Reputation: 29
I try to encrypt a file using the example MSDN https://msdn.microsoft.com/ru-ru/library/system.security.cryptography.aes(v=vs.110).aspx When I encrypt a .txt file, then everything is fine, but when I try to encrypt other files (.bmp, .pdf ...), then the file is not decrypted. Where is the error there?
I modified the code to download the file
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);
}
}
Upvotes: 0
Views: 591
Reputation:
Acting on hex/binary data as if it was a string, will result in loss in data and so you won't be able to recover it fully. To get an/more idea you may want to check out this, it explains what you would like to do for VB.NET
Upvotes: 0
Reputation: 860
StreamReader is supposed to work with text data in particular encoding. Hence you can't use it for binary data.
If file is not huge, you can read file contents into MemmoryStream and use it latter for AES.
Upvotes: 2