我使用此代碼來加密字符串(基本上,這是對Rijndael class on MSDN給出的示例):編碼用來字節轉換數組字符串,反之亦然
public static String AESEncrypt(String str2Encrypt, Byte[] encryptionKey, Byte[] IV)
{
Byte[] encryptedText;
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
// Use the provided key and IV
rijAlg.Key = encryptionKey;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption
using (MemoryStream msEncrypt = new MemoryStream())
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
// Write all data to the stream
swEncrypt.Write(str2Encrypt);
}
encryptedText = msEncrypt.ToArray();
}
}
return Encoding.Default.GetString(encryptedText);
}
我使用Encoding.Default
轉換一個字節數組轉換爲字符串,但我不確定這是一個好的解決方案。我的目標是將加密的文本(如密碼......)存儲在文件中。我應該繼續使用Encoding.Default
還是使用Encoding.UTF8Encoding
或其他?
當我嘗試加密和解密它們時,如果文件被移動到不同的操作系統上,會對存儲值產生負面影響嗎?
感謝喬恩。將我從嚴重的錯誤中拯救出來。 – Otiel
另請參閱[菲爾哈克的帖子在此擴展](http://feeds.haacked.com/~r/haacked/~3/5hyXGYRO0Bo/hazards-of-converting-binary-data-to-a-string.aspx) –
另請參閱http://stackoverflow.com/questions/646974/is-there-a-standard-technique-for-packing-binary-data-into-a-utf-16-string –