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中文網其他相關文章!