2012-02-16 66 views
1

さて、この奇妙な、私に。私はこのコードを使っています。CryptoStream:復号化するデータの長さが無効です。同じコードで同じデータにエラーが発生しません

using (MemoryStream memStream = new MemoryStream(inBytes)) 
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) 
using (CryptoStream cs = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read)) 
{ 
    byte[] buffer; 
    if (inBytes.Length < (1024 * 10)) buffer = new byte[inBytes.Length]; 
    else buffer = new byte[(1024 * 10)]; 
    long readBytes = 0; 
    long totalBytes = inStream.Length; 
    int currBytes; 

    while (readBytes < totalBytes) 
    { 
     currBytes = cs.Read(buffer, 0, buffer.Length); 
     fs.Write(buffer, 0, currBytes); 
     readBytes += currBytes; 
    } 
} 

これは、暗号化されたデータをファイルに書き出します。

それは(戻り)への書き込みを除き、その後、私は、まったく同じことを行い、このコードを持っているMemoryStream:行で

using(MemoryStream memStream = new MemoryStream(inBytes)) 
using(MemoryStream ms = new MemoryStream()) 
using (CryptoStream cs = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read)) 
{ 
    byte[] buffer; 
    if (inBytes.Length < (1024 * 10)) buffer = new byte[inBytes.Length]; 
    else buffer = new byte[(1024 * 10)]; 
    long readBytes = 0; 
    long totalBytes = inStream.Length; 
    int currBytes; 

    while (readBytes < totalBytes) 
    { 
     currBytes = cs.Read(buffer, 0, buffer.Length); 
     ms.Write(buffer, 0, currBytes); 
     readBytes += currBytes; 
    } 

    return ms; 
} 

私は解読するために、データの誤り」長さを受け取るcurrBytes = cs.Read(buffer, 0, buffer.Length)されます無効 "であるが、最初のセットではなく、2番目のセットのみである。 ICryptoTransform "decryptor"は共通の方法で作成されており、同じ鍵を使用していることがわかります。

誰も私に最初のインスタンスでこのエラーが表示されない理由を教えてもらえますが、2番目のエラーメッセージが表示され、さらに重要なのは修正方法です。

そして、はい、私はDESがこれまで最高の暗号化方法ではないことを知っています。これは、プロダクション環境での日の光を決して見ることのできない、概念実証の性質上のものです。

+0

愚かな質問かもしれませんが、どちらの場合でも入力(inBytes)が同じであることを100%確信していますか? –

+0

はい。私は実際にこれを確実にするために私の呼び出しコードに変更を加えました(とにかくあったはずですが、私は先に進んで疑いを取り除きました)。 – AllenG

+0

'inStream'はどこに定義されていますか?この行は 'long totalBytes = inStream.Length;' 'long totalBytes = memStream.Length; 'とするべきでしょうか? – rsbarro

答えて

0

これらのチェックを両方のコードに追加してみてください。私は強く、1疑われる、またはこれらの両方が失敗します。

if (inStream.Length != inBytes.Length) 
    throw new Exception("inBytes read incorrectly"); 
if (inBytes.Length % 8 == 0) 
    throw new Exception("inBytes is not a valid DES encryption"); 
+0

それを試して、それは動作しませんでした。 – AllenG

1

私は今日、このエラーに遭遇し、それは私が1つの関数にASCIIを使用してバイト配列と内にBase64を使用して他に1元の文字列を変換していたことが判明異なる機能。

入力が正しい長さでも、同じエンコードを使用していない可能性があります。

関連する問題