2012-08-24 53 views
0

實在是簡單的代碼來解密文件(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 }; 

回答

1

這接縫,我認爲你是看在致力於檢查變量,你會得到異常有視覺工作室工具sc.Length財產。如果是這樣,只是忽略它們,如果你在你的代碼中使用Length,它們將是相關的。流不支持需要了解所有內部數據的功能是非常正常的。

編輯

首先你承擔加密的文件,它的長度等於解密的數據的長度。我想這可能是事實,但我懷疑它。

嘗試:

var textReader = new StreamReader(cs);// you might need to specify encoding 
var text = textReader.ReadToEnd(); 

注意,這將讀取整個文件到內存中,這將是大文件的問題。

如果我要寫這段代碼,我會用StreamWritter寫入CryptoStreamStreamReader來讀取它的代碼是向前走的。

0

您的代碼在我的機器上(VS2010,.NET 4,Windows)沒有提供任何錯誤。您正在運行的是哪種客戶端配置文件/平臺?該錯誤表明您的FileStream是不支持查找的類型,是正常的.NET FileStream?