干得好:
string s = "The brown fox jumped over the green frog";
string k = "urieurut";
byte[] enc = EncryptString(s, k);
string dec = DecryptString(enc, k);
您不能尝试将加密的字节串解释为 Unicode 字符串。将它们保留为字节。解密后的版本可以转换回字符串。
另请注意以下一次性物品的处理。如果您没有正确释放某些资源,则可能会导致某些资源被保留太长时间或泄漏using()
or Dispose()
.
public static byte[] EncryptString(string stringToEncrypt, string encryptionKey)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(encryptionKey);
using (RijndaelManaged RMCrypto = new RijndaelManaged())
using (MemoryStream ms = new MemoryStream())
using (ICryptoTransform encryptor = RMCrypto.CreateEncryptor(key, key))
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
byte[] encryptedString = UE.GetBytes(stringToEncrypt);
cs.Write(encryptedString, 0, encryptedString.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
}
public static string DecryptString(byte[] stringToDecrypt, string encryptionKey)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(encryptionKey);
using (RijndaelManaged RMCrypto = new RijndaelManaged())
using (MemoryStream ms = new MemoryStream())
using (ICryptoTransform decryptor = RMCrypto.CreateDecryptor(key, key))
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
{
cs.Write(stringToDecrypt, 0, stringToDecrypt.Length);
cs.FlushFinalBlock();
return UE.GetString(ms.ToArray());
}
}