I am trying to encrypt and decrypt a file. The file can be any file like txt, jpg, doc, pdf. The IV is prepended to the cipher text. but while decrypting if i read first 8 bytes it gives me different value then the value of IV while encryption.
Here is my code to encrypt the file
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();
This produces an encrypted file to the specified location.
Now below is my decryption code
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();