[英]AES Encryption in c#
我嘗試使用示例MSDN https://msdn.microsoft.com/ru-ru/library/system.security.cryptography.aes(v=vs.110).aspx加密文件。當我加密.txt文件時,那么一切都很好,但是當我嘗試加密其他文件(.bmp,.pdf ...)時,該文件不會被解密。 錯誤在哪里?
我修改了代碼以下載文件
internal static void EncryptAes(string pathData, string pathEnCrypt)
{
string plainText;
using (StreamReader sr = new StreamReader(pathData))
plainText = sr.ReadToEnd();
byte[] encrypted;
// Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.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(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
using (FileStream fstream = new FileStream(pathEnCrypt, FileMode.Create))
fstream.Write(encrypted, 0, encrypted.Length);
}
}
StreamReader應該使用特殊編碼的文本數據。 因此,您不能將其用於二進制數據。
如果文件不是很大,則可以將文件內容讀取到MemmoryStream中,然后將其用於AES。
像字符串一樣對十六進制/二進制數據進行操作,將導致數據丟失,因此您將無法完全恢復它。 為了讓你可以想看看一個/多個想法此 ,它說明你想為VB.NET做什么
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.