.NET MAUI .NET8 跨平台简易字符串加解密方法咨询
跨平台.NET字符串加解密与安全存储方案
一、跨平台AES对称加解密实现
如果你需要和原WinForm代码类似的直接调用式加解密,推荐使用AES对称加密算法——它在.NET的所有平台(Android、iOS、Windows)都原生支持,调用方式和你原来的Encrypt/Decrypt函数几乎一致。
以下是封装好的工具类代码:
using System.Security.Cryptography; using System.Text; public static class CryptoHelper { // 自定义盐值(请务必替换为你自己的唯一值) private static readonly byte[] DefaultSalt = Encoding.UTF8.GetBytes("YourUniqueSalt_2024"); private const int Iterations = 10000; private const int KeySize = 256; // AES-256加密 public static string Encrypt(string plainText, string? password = null) { if (string.IsNullOrEmpty(plainText)) throw new ArgumentNullException(nameof(plainText)); var passwordBytes = string.IsNullOrEmpty(password) ? Encoding.UTF8.GetBytes("YourSecureDefaultKey") // 生产环境建议强制要求传入密码 : Encoding.UTF8.GetBytes(password); // 通过PBKDF2从密码生成安全密钥 using var pbkdf2 = new Rfc2898DeriveBytes(passwordBytes, DefaultSalt, Iterations, HashAlgorithmName.SHA256); var key = pbkdf2.GetBytes(KeySize / 8); using var aes = Aes.Create(); aes.Key = key; aes.GenerateIV(); using var encryptor = aes.CreateEncryptor(aes.Key, aes.IV); using var ms = new MemoryStream(); ms.Write(aes.IV, 0, aes.IV.Length); // 先写入IV,解密时需要读取 using var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); using var sw = new StreamWriter(cs); sw.Write(plainText); return Convert.ToBase64String(ms.ToArray()); } public static string Decrypt(string cipherText, string? password = null) { if (string.IsNullOrEmpty(cipherText)) throw new ArgumentNullException(nameof(cipherText)); var cipherBytes = Convert.FromBase64String(cipherText); // 提取IV(AES固定IV长度为16字节) var iv = new byte[16]; Array.Copy(cipherBytes, 0, iv, 0, iv.Length); var dataBytes = new byte[cipherBytes.Length - iv.Length]; Array.Copy(cipherBytes, iv.Length, dataBytes, 0, dataBytes.Length); var passwordBytes = string.IsNullOrEmpty(password) ? Encoding.UTF8.GetBytes("YourSecureDefaultKey") : Encoding.UTF8.GetBytes(password); using var pbkdf2 = new Rfc2898DeriveBytes(passwordBytes, DefaultSalt, Iterations, HashAlgorithmName.SHA256); var key = pbkdf2.GetBytes(KeySize / 8); using var aes = Aes.Create(); aes.Key = key; aes.IV = iv; using var decryptor = aes.CreateDecryptor(aes.Key, aes.IV); using var ms = new MemoryStream(dataBytes); using var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read); using var sr = new StreamReader(cs); return sr.ReadToEnd(); } }
使用示例
// 加密 var encryptedPwd = CryptoHelper.Encrypt("mySecurePassword123", "userSecretKey"); // 解密 var decryptedPwd = CryptoHelper.Decrypt(encryptedPwd, "userSecretKey");
注意:生产环境请替换默认盐值和默认密钥,不要使用硬编码的默认密码,最好让用户提供自定义密码。
二、封装SecureStorage为简易调用函数
如果更倾向于系统级的安全存储(由各平台原生安全组件托管:Android Keystore、iOS Keychain、Windows Credential Locker),可以把SecureStorage封装成极简调用的函数,避免直接处理复杂的API:
using Microsoft.Maui.Storage; public static class SecureStorageHelper { // 存储字符串到安全存储 public static async Task StoreSecureString(string storageKey, string plainText) { await SecureStorage.Default.SetAsync(storageKey, plainText); } // 从安全存储读取字符串 public static async Task<string?> GetSecureString(string storageKey) { return await SecureStorage.Default.GetAsync(storageKey); } // 删除安全存储中的字符串 public static bool RemoveSecureString(string storageKey) { return SecureStorage.Default.Remove(storageKey); } }
使用示例
// 存储密码 await SecureStorageHelper.StoreSecureString("user_login_password", "mySecurePassword123"); // 获取密码 var storedPwd = await SecureStorageHelper.GetSecureString("user_login_password");
这个方案不需要自己管理加密逻辑,由系统负责密钥的安全存储,比自定义加密更可靠,封装后调用复杂度和你原来的WinForm函数差不多。
内容的提问来源于stack exchange,提问作者Hưng Nguyễn
相关产品推荐
相关产品推荐

