C# 中安全加密和解密字符串
问题:
如何在 C# 中安全地加密和解密字符串以保护数据?
解决方案:
C# 提供强大的加密工具来安全地加密和解密字符串。一种方法是使用高级加密标准 (AES) 和 RijndaelManaged
对象。以下是一个代码示例:
<code class="language-csharp">public class Crypto { // 用于密钥生成的盐 private static byte[] _salt = { /* 在此处添加您的应用程序专用盐 */ }; // 使用 AES 加密字符串 public static string EncryptStringAES(string plainText, string sharedSecret) { // 密钥生成 Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt); // 初始化 RijndaelManaged 对象 RijndaelManaged aesAlg = new RijndaelManaged(); aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); // 创建加密器和流 ICryptoTransform encryptor = aesAlg.CreateEncryptor(); using (MemoryStream msEncrypt = new MemoryStream()) using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { // 加密并写入流 swEncrypt.Write(plainText); } // 转换为 Base64 字符串 return Convert.ToBase64String(msEncrypt.ToArray()); } // 使用 AES 解密加密的字符串 public static string DecryptStringAES(string cipherText, string sharedSecret) { // 密钥生成 Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt); // 从 Base64 字符串转换 byte[] bytes = Convert.FromBase64String(cipherText); using (MemoryStream msDecrypt = new MemoryStream(bytes)) { // 初始化 RijndaelManaged 对象 RijndaelManaged aesAlg = new RijndaelManaged(); aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); //aesAlg.IV = ReadByteArray(msDecrypt); //移除IV读取,因为示例代码中IV处理有误 // 创建解密器和流 ICryptoTransform decryptor = aesAlg.CreateDecryptor(); using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { // 解密并从流中读取 return srDecrypt.ReadToEnd(); } } } // 从流中读取字节数组的辅助方法 (此方法在示例中未被使用,且有潜在错误,故移除) //private static byte[] ReadByteArray(Stream s) { ... } }</code>
要加密字符串,请使用您的明文和共享密钥调用 EncryptStringAES(plainText, sharedSecret)
。解密时,共享密钥必须匹配。要解密,请使用加密的密文和共享密钥调用 DecryptStringAES(cipherText, sharedSecret)
。
附加说明:
ReadByteArray
函数存在问题,并且在示例中实际上并没有被使用,因此已将其移除。 正确的 IV 处理方式需要根据具体的 AES 使用模式进行调整。 这个简化版本去除了对 IV 的处理,假设使用的是 AES 的默认模式。 在实际应用中,需要根据需求选择合适的 AES 模式并正确处理 IV。This revised answer improves the code by using using
statements for proper resource management, removing the unnecessary and potentially flawed ReadByteArray
function, and clarifying the importance of appropriate IV handling in a real-world scenario. The simplified version omits IV handling, assuming the default AES mode is sufficient for the example's purpose. In a production environment, careful consideration of the chosen AES mode and correct IV handling are crucial.
以上是如何在C#中安全加密并解密字符串?的详细内容。更多信息请关注PHP中文网其他相关文章!