0

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); } } 
6
  • 2
    "when I try to encrypt other files (.bmp, .pdf ...), then the file is not decrypted." Did you mean "then the file is not ENcrypted"? Or is it really the decryption afterwards that fails? Commented May 24, 2016 at 14:26
  • it is encrypted as it is strange, the size of the file is increased by half. And then it can decrypt, but to open it still will not work Commented May 24, 2016 at 14:32
  • 1
    Can you try just use BinaryReader and BinaryWriter instead (not StreamReader and StreamWriter) since bmp etc. are binary files... Commented May 24, 2016 at 14:32
  • The comment and code do not match: decrytor and CreateEncryptor. // Create a decrytor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(((aesAlg.Key, aesAlg.IV); Commented May 24, 2016 at 14:40
  • This might help you: stackoverflow.com/questions/4816121/… Commented May 24, 2016 at 14:40

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.