0
我已經使用DES Encryption解密文件的代碼,儘管我在密鑰解密加密方式不同時輸入密鑰,但我仍然繼續收到該文件。但是我得到了錯誤。解密文件有錯誤的數據,如果有錯誤的數據
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;
是的,我確實使用8個字符,我的意思是如果我嘗試在解密過程中插入密鑰不同於我的加密時出現錯誤:錯誤的數據。 – sloqye
我沒有在解密參數中使用輸出目標文件,如果你的意思是這個問題? – sloqye
我已經完成了。但在同一行中有相同的錯誤。我發佈了我的ecrypt代碼。 – sloqye