解密文件的代码非常简单(三重DES加密):
FileStream fin = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
TripleDES tdes = new TripleDESCryptoServiceProvider();
CryptoStream cs = new CryptoStream(fin, tdes.CreateDecryptor(key, iv),CryptoStreamMode.Read); //<---- Exceptions
它不起作用。'cs' 无效,无法从中读取。创建 CryptoStream 时有一些例外:
Length = 'cs.Length' threw an exception of type 'System.NotSupportedException'
base {System.SystemException} = {"Stream does not support seeking."}
为什么我无法创建加密流并从中读取以及如何解决此问题?
[添加]
感谢您的回复,现在对我来说更清楚了。但是 - 仍然无法从“cs”中读取。
加密:
FileStream fout = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Write);
TripleDES tdes = new TripleDESCryptoServiceProvider();
CryptoStream cs = new CryptoStream(fout, tdes.CreateEncryptor(key, iv), CryptoStreamMode.Write);
byte[] d = Encoding.ASCII.GetBytes(Data);
cs.Write(d, 0, d.Length);
cs.WriteByte(0);
cs.Close();
fout.Close();
在其他地方定义了 iv 和 key。并且,解密 - 整个方法:
FileStream fin = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
TripleDES tdes = new TripleDESCryptoServiceProvider();
CryptoStream cs = new CryptoStream(fin, tdes.CreateDecryptor(key, iv),CryptoStreamMode.Read);
StringBuilder SB = new StringBuilder();
int ch;
for (int i = 0; i < fin.Length; i++)
{
ch = cs.ReadByte(); //Exception - CryptographicException: Bad data
if (ch == 0)
break;
SB.Append(Convert.ToChar(ch));
}
cs.Close();
fin.Close();
如您所见,与加密代码中的密钥和 iv 相同。但是仍然无法从“cs”流中读取 - 抛出异常。你怎么看 - 这里有什么问题?
这是我的钥匙,我用过:
public static byte[] key = { 21, 10, 64, 10, 100, 40, 200, 4,
21, 54, 65, 246, 5, 62, 1, 54,
54, 6, 8, 9, 65, 4, 65, 9};
private static byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0 };