问题
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