Encrypting any file using AES

拜拜、爱过 提交于 2019-12-11 13:46:45

问题


I'm using some code like this to encrypt a file.

            FileStream fsInput = new FileStream(ifile_path,
              FileMode.Open,
              FileAccess.Read);

            FileStream fsEncrypted = new FileStream(ofile_path,
               FileMode.Create,
               FileAccess.Write);
            AesCryptoServiceProvider AES = new AesCryptoServiceProvider();
            AES.Mode = CipherMode.CBC;
            AES.KeySize = 256;
            iv = AES.IV;
            AES.Key = key;
            ICryptoTransform aesencrypt = AES.CreateEncryptor();
            CryptoStream cryptostream = new CryptoStream(fsEncrypted,
               aesencrypt,
               CryptoStreamMode.Write);

            byte[] bytearrayinput = new byte[fsInput.Length];
            fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Close();
            fsInput.Close();
            fsEncrypted.Close();

However, while this code successfully encrypts .txt and .xml files, it doesn't work on other file types such as .docx, or image file formats. What changes can I make to the code to extend the functionality to all such file types?


回答1:


You want to use a BinaryReader and BinaryWriter for doing the file I/O. The normal StreamReader will attempt to read the bytes using a particular encoding as it implements TextReader and will mangle primitive data types. This is why plain text .txt and .xml work while .docx files do not.



来源:https://stackoverflow.com/questions/23374121/encrypting-any-file-using-aes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!