解密文件真的很简单(三重加密):
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'流中读取 - 抛出异常。你怎么想 - 这里有什么不对?
这是我的关键并使用了iv:
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 };
答案 0 :(得分:1)
对我来说,你正在观看视觉工作室工具中的sc.Length
属性,专门用于检查变量,并在那里获得例外。如果是这样,只要忽略它们,如果在代码中使用Length
,它们就会相关。流不支持需要了解内部所有数据的功能,这是很正常的。
修改
首先,您假设加密文件的长度等于解密数据的长度。我想这可能是真的,但我对此表示怀疑。
尝试:
var textReader = new StreamReader(cs);// you might need to specify encoding
var text = textReader.ReadToEnd();
请注意,这会将整个文件读入内存,这对于大文件来说是个问题。
如果我要编写此代码,我会使用StreamWritter
写入CryptoStream
和StreamReader
以便从中读取代码是正确的。
答案 1 :(得分:0)
您的代码在我的机器上没有错误(VS2010,.NET 4,Windows)。您运行此客户端配置文件/平台是什么?该错误表明您的FileStream是一种不支持搜索的类型,是正常的.NET FileStream吗?