實在是簡單的代碼來解密文件(Triple DES加密):無法創建CryptoStream的讀取距離 - System.NotSupportedException
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和關鍵定義的其他地方。並且,解密 - 整個方法:
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 };