文件的加密和解密

时间:2013-09-20 09:54:04

标签: encryption des

我正在尝试加密和解密文件。该文件可以是任何文件,如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();

1 个答案:

答案 0 :(得分:0)

您正在将IV写入CryptoStream,因此它将转换为密文。 IV应该以普通的密文为前缀,它不应该是密文的一部分。