我正在尝试加密和解密文件。该文件可以是任何文件,如 txt、jpg、doc、pdf。IV 附加在密文之前。但是在解密时,如果我读取前 8 个字节,它给我的值与加密时 IV 的值不同。
这是我加密文件的代码
fsOut = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.Write);
des = new DESCryptoServiceProvider();
des.Key = ASCIIEncoding.ASCII.GetBytes(secretkey);
des.GenerateIV();
desencrypt = des.CreateEncryptor();
cryptoStream = new CryptoStream(fsOut, desencrypt, CryptoStreamMode.Write);
//write the IV to beginning of encrypted data
BinaryWriter bw = new BinaryWriter(cryptoStream);
bw.Write(des.IV, 0, des.IV.Length);
// Now will initialize a buffer and will be
// processing the input file in chunks.
// This is done to avoid reading the whole file (which can be
// huge) into memory.
int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int bytesRead;
do
{
// read a chunk of data from the input file
bytesRead = filestream.Read(buffer, 0, bufferLen);
// Encrypt it
cryptoStream.Write(buffer, 0, bytesRead);
}
while (bytesRead != 0);
cryptoStream.FlushFinalBlock();
这会在指定位置生成一个加密文件。
现在下面是我的解密代码
des = new DESCryptoServiceProvider();
des.Key = Encoding.ASCII.GetBytes(secretkey);
byte[] iv = new byte[8];
sourcefile.Read(iv, 0, 8);
des.IV = iv;
desdecrypt = des.CreateDecryptor();
msOut = new MemoryStream();
cryptoStream = new CryptoStream(sourcefile, desdecrypt, CryptoStreamMode.Read);
StreamWriter fsDecrypted = new StreamWriter("D:\\tempDecrypted.jpg");
fsDecrypted.Write(new StreamReader(cryptoStream).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();