2017-04-13 22 views
0

I Mはファイルを復号化するためにコードを使用しています。しかし、出力ファイルに書き戻しをしているときにエラーを表示しています:バッドデータ例外がスローされました:mscorlib.dllの 'System.Security.Cryptography.CryptographicException'追加情報:不正なデータ

以下は私のコード提供です。

ALSO ENCYPTIONで同じGETBYTEを使用した
public static void DecryptFile(string sInputFilename, string sOutputFilename, string sKey) 
    { 
     try 
     { 
      DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); 
      //A 64 bit key and IV is required for this provider. 
      //Set secret key For DES algorithm. 
      DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey); 
      //Set initialization vector. 
      DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey); 
      //Create a DES decryptor from the DES instance. 
      ICryptoTransform desdecrypt = DES.CreateDecryptor(); 

      //Create a file stream to read the encrypted file back. 
      using (FileStream fsread = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read)) 
      { 

       //Create crypto stream set to read and do a 
       //DES decryption transform on incoming bytes. 
       using (CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read)) 
       { 
        fsread.Flush(); 
        //Print the contents of the decrypted file. 
        StreamWriter fsDecrypted = new StreamWriter(sOutputFilename); 

        ////----ERROR IN THIS LINE----//// 
        fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd()); 
        fsDecrypted.Flush(); 
        fsDecrypted.Close(); 
       } 
      } 
     } 
     catch(XamlParseException XEx) 
     { 
      //throw XEx; 
      System.Windows.MessageBox.Show(XEx.Message.ToString()); 
     } 
    } 

暗号化コード

public static void EncryptFile(string sInputFilename,string sOutputFilename,string sKey) 
    { 
     FileStream fsInput = new FileStream(sInputFilename,FileMode.Open,FileAccess.Read); 

     FileStream fsEncrypted = new FileStream(sOutputFilename,FileMode.Create,FileAccess.Write); 

     DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); 

     DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey); 
     DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey); 

     ICryptoTransform desencrypt = DES.CreateEncryptor(); 
     CryptoStream cryptostream = new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write); 

     byte[] bytearrayinput = new byte[fsInput.Length - 1]; 
     fsInput.Read(bytearrayinput, 0, bytearrayinput.Length); 
     cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length); 
    } 

答えて

0

最も可能性が高い理由は、あなたがsKeyバイトのDES.IVを初期化していることです。ここでは、dyring暗号化を使用したのと同じ初期化ベクトルを使用する必要があります。

+0

暗号化に同じを使用 私は上記のコードを編集しました – Shantnu

+0

使用している暗号化方法であなたの投稿を更新してください。おそらく、暗号化ルーチンと復号化ルーチンの間には多少の不一致があります。 – CodeFuller

+0

コメントにも暗号化コードが更新されました – Shantnu

関連する問題