我在DES加密中解密文件的代码,即使我在密钥以不同的方式解密加密时输入密钥,我也会尝试继续获取文件。但我得到了错误。
while ((data = cryptostreamDecr.ReadByte()) != -1) // Message Error : Bad Data.
我应该添加或更改哪些代码才能使进程保持解密状态?
private static void DecryptFile(string sInputFilename, string sKey)
{
var DES = new DESCryptoServiceProvider();
DES.Key = Encoding.ASCII.GetBytes(sKey);
DES.IV = Encoding.ASCII.GetBytes(sKey);
ICryptoTransform desdecrypt = DES.CreateDecryptor();
using (var fsread = new FileStream(sInputFilename, FileMode.Open,
FileAccess.ReadWrite))
{
using (var cryptostreamDecr = new CryptoStream(fsread,
desdecrypt,
CryptoStreamMode.Read))
{
int data;
fsread.Flush();
using (var ms = new MemoryStream())
{
while ((data = cryptostreamDecr.ReadByte()) != -1)
{
ms.WriteByte((byte)data);
}
cryptostreamDecr.Close();
using (var fsWrite = new FileStream(sInputFilename, FileMode.Truncate))
{
ms.WriteTo(fsWrite);
ms.Flush();
}
}
}
}
}
加密代码:
public static void EncryptFile(string sInputFilename, string sKey)
{
FileStream fsInput = new FileStream(sInputFilename,
FileMode.Open,
FileAccess.ReadWrite);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fsInput,
desencrypt,
CryptoStreamMode.Write);
byte[] bytearrayinput = new byte[fsInput.Length];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
fsInput.SetLength(0);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.FlushFinalBlock();
cryptostream.Close();
fsInput.Close();
}
[编辑] :在Encypt中删除:
cryptostream.FlushFinalBlock();
并添加解密
DES.Padding = PaddingMode.None;
答案 0 :(得分:2)
64位是DES加密算法的唯一有效密钥大小。 8位等于一个ASCII字符表示64位等于8个字符。
如果您只发送8个字符,请选中此项(C# "Bad Data" exception when decrypting encrypted file)。它可以解决你的问题。
<强> [编辑] 强>
在DES.Padding = PaddingMode.None;
中添加DecryptFile
。