2017-02-28 5 views
0

私は単純な文字列の暗号化と復号化しようとしたとき、すべてが完璧に罰金行きでは動作しません。..C#ラインダール復号化はJPGのみ

をしかし、私はByteArrayのにJPGをコード化し、それとまったく同じことをしたときbytearray、復号化はもはや動作しませんでした(bytearrayは元のものとは全く異なり、もう表示できません)...

bytearrayが大きすぎますか?

誰かが私の問題の解決策を持っていますか?

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Security.Cryptography; 
using System.Text; 
using System.Threading.Tasks; 

namespace Encrypter2 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      try 
      { 

       Console.WriteLine(); 
       // Create a new instance of the Rijndael 
       // class. This generates a new key and initialization 
       // vector (IV). 
       byte[] originalFile = File.ReadAllBytes(@"C:/Users/Elron/Documents/Visual Studio 2015/Projects/FileEncrypt/FileEncrypt/bin/Debug/harambe.jpg"); 
       using (Rijndael myRijndael = Rijndael.Create()) 
       { 
       //  Encrypt the string to an array of bytes 
       // Encrypted byte[] 
       byte[] encrypted = EncryptStringToBytes(originalFile, myRijndael.Key, myRijndael.IV); 
        using (FileStream fs = File.Create(@"C:/Users/Elron/Documents/Visual Studio 2015/Projects/FileEncrypt/FileEncrypt/bin/Debug/harambeEncrypted.jpg")) 
        { 
         //Add some information to the file. 
         fs.Write(encrypted, 0, encrypted.Length); 
        } 
       //  Decrypted byte[] 
       byte[] roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV); 
        using (FileStream fs = File.Create(@"C:/Users/Elron/Documents/Visual Studio 2015/Projects/FileEncrypt/FileEncrypt/bin/Debug/harambeDecrypted.jpg")) 
        { 
         //Add some information to the file. 
         fs.Write(roundtrip, 0, roundtrip.Length); 
        } 
       // Display the original data and the decrypted data. 
       // Encrypted string 
        Console.ReadKey(); 
      } 

      } 
      catch (Exception e) 
      { 
       Console.WriteLine("Error: {0}", e.Message); 
      } 
     } 

     static byte[] EncryptStringToBytes(byte[] plainText, byte[] Key, byte[] IV) 
     { 
      // Check arguments. 
      if (plainText == null || plainText.Length <= 0) 
       throw new ArgumentNullException("plainText"); 
      if (Key == null || Key.Length <= 0) 
       throw new ArgumentNullException("Key"); 
      if (IV == null || IV.Length <= 0) 
       throw new ArgumentNullException("IV"); 
      byte[] encrypted; 
      // Create an Rijndael object 
      // with the specified key and IV. 
      using (Rijndael rijAlg = Rijndael.Create()) 
      { 
       rijAlg.Key = Key; 
       rijAlg.IV = IV; 

       // Create an encryptor to perform the stream transform. 
       ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV); 

       // Create the streams used for encryption. 
       using (MemoryStream msEncrypt = new MemoryStream()) 
       { 
        using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) 
        { 
         using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) 
         { 

          //Write all data to the stream. 
          string toEncrypt = Encoding.Default.GetString(plainText); 
          swEncrypt.Write(toEncrypt); 
         } 
         encrypted = msEncrypt.ToArray(); 
        } 
       } 
      } 


      // Return the encrypted bytes from the memory stream. 
      return encrypted; 

     } 

     static byte[] DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV) 
     { 
      // Check arguments. 
      if (cipherText == null || cipherText.Length <= 0) 
       throw new ArgumentNullException("cipherText"); 
      if (Key == null || Key.Length <= 0) 
       throw new ArgumentNullException("Key"); 
      if (IV == null || IV.Length <= 0) 
       throw new ArgumentNullException("IV"); 

      // Declare the string used to hold 
      // the decrypted text. 
      string plaintext = null; 
      byte[] returnText; 

      // Create an Rijndael object 
      // with the specified key and IV. 
      using (Rijndael rijAlg = Rijndael.Create()) 
      { 
       rijAlg.Key = Key; 
       rijAlg.IV = IV; 

       // Create a decryptor to perform the stream transform. 
       ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); 

       // Create the streams used for decryption. 
       using (MemoryStream msDecrypt = new MemoryStream(cipherText)) 
       { 
        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) 
        { 
         using (StreamReader srDecrypt = new StreamReader(csDecrypt)) 
         { 
          // Read the decrypted bytes from the decrypting stream 
          // and place them in a string. 
          plaintext = srDecrypt.ReadToEnd(); 


          ASCIIEncoding asc = new ASCIIEncoding(); 
          returnText = asc.GetBytes(plaintext); 
         } 
        } 
       } 
      } 
      return returnText; 
     } 
    } 
} 
+2

バイナリデータのテキスト用のStreamReaderとStreamWriterを使用することは意味がありません。どこからこのコードをコピーして貼り付けたのですか?それが何をしているのか理解していますか?最初に解決しようとしている問題は何ですか? – CodeCaster

+1

MSDNのページからそれをコピーし、後で多くのストリームチュートリアルを見て、それを理解しようとしました。 – Mreifenberger

答えて

0

私は、あなたが文字列として任意のバイト配列を扱うことができない、あなたの暗号化と復号化の方法で

static byte[] DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV) 
{ 
    ... 
    ASCIIEncoding asc = new ASCIIEncoding(); 
    returnText = asc.GetBytes(plaintext); 
    ... 
} 

そして

static byte[] EncryptStringToBytes(byte[] plainText, byte[] Key, byte[] IV) 
    { 
     ... 
     string toEncrypt = Encoding.Default.GetString(plainText); 
     swEncrypt.Write(toEncrypt); 
     ... 
    } 
+0

副題として、ファイル - >バイト[] - >文字列 - >暗号化 - >文字列 - >バイト[] 'は、エラーを避けるために簡単です – bradbury9

+0

よく感謝私はそれを見ている!私がそれをしなかったとき、私はちょうどSystem.Byte []を返しました。それは当時は役に立たなかった...そして、私が直接変換しようとしていなかったときには、書き込み操作に文字列が必要で、正しく変換できないなどのエラーが発生しました。 – Mreifenberger

+0

注:エンコーディング問題だった!どうもありがとう! – Mreifenberger

3

を別のエンコーディングを使用していると思います。バイトを取り込んで文字列に変換した後、文字列をStreamWriterに書き込んで、文字列をバイトに戻します。これは、任意のバイトの束に対して損失の多い操作になります。

あなたのメソッドEncryptStringToBytesは間違った概念です。文字列には関係しないメソッドEncryptBytes(およびDecryptBytes)が必要です。バイト配列を渡してCryptoStreamに直接フィードすることができます。これらのバイトがどのように解釈されるかは、暗号化アルゴリズムの関心事ではありません。次のように

つまり、あなたの方法を微調整することもできます

static byte[] EncryptBytes(byte[] bytes, byte[] Key, byte[] IV) 
{ 
    // Check arguments. 
    if (bytes == null || bytes.Length <= 0) 
     throw new ArgumentNullException("bytes"); 
    if (Key == null || Key.Length <= 0) 
     throw new ArgumentNullException("Key"); 
    if (IV == null || IV.Length <= 0) 
     throw new ArgumentNullException("IV"); 
    // Create an Rijndael object 
    // with the specified key and IV. 
    using (Rijndael rijAlg = Rijndael.Create()) 
    { 
     rijAlg.Key = Key; 
     rijAlg.IV = IV; 

     // Create an encryptor to perform the stream transform. 
     ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV); 

     // Create the streams used for encryption. 
     using (MemoryStream msEncrypt = new MemoryStream()) 
     { 
      using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, 
        CryptoStreamMode.Write)) 
      { 
       csEncrypt.Write(bytes,0,bytes.Length); 
       csEncrypt.FlushFinalBlock(); 
       return msEncrypt.ToArray(); 
      } 
     } 
    } 
} 

static byte[] DecryptBytes(byte[] encryptedBytes, byte[] Key, byte[] IV) 
{ 
    // Check arguments. 
    if (encryptedBytes == null || encryptedBytes.Length <= 0) 
     throw new ArgumentNullException("encryptedBytes"); 
    if (Key == null || Key.Length <= 0) 
     throw new ArgumentNullException("Key"); 
    if (IV == null || IV.Length <= 0) 
     throw new ArgumentNullException("IV"); 

    // Create an Rijndael object 
    // with the specified key and IV. 
    using (Rijndael rijAlg = Rijndael.Create()) 
    { 
     rijAlg.Key = Key; 
     rijAlg.IV = IV; 

     // Create a decryptor to perform the stream transform. 
     ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); 

     // Create the streams used for decryption. 
     using (MemoryStream msDecrypt = new MemoryStream()) 
     { 
      using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, 
        CryptoStreamMode.Write)) 
      { 
       csDecrypt.Write(encryptedBytes,0,encryptedBytes.Length); 
       csDecrypt.FlushFinalBlock(); 
       return msDecrypt.ToArray(); 
      } 
     } 
    } 

} 

はその後、往復でテスト:

using(var rijndael = Rijndael.Create()) 
{ 
    var stringToEncrypt = "foobar"; 
    var bytesToEncrypt = Encoding.UTF8.GetBytes(stringToEncrypt); 
    var encryptedBytes = EncryptBytes(bytesToEncrypt, rijndael.Key, rijndael.IV); 
    var decryptedBytes = DecryptBytes(encryptedBytes, rijndael.Key, rijndael.IV); 
    var originalString = Encoding.UTF8.GetString(decryptedBytes); 
    Debug.Assert(string.Equals(stringToEncrypt, originalString, 
           StringComparison.InvariantCulture)); 
} 

うまくいけば、この時点で、それはどのように明らかです私たちは、暗号化からの文字列エンコーディングの問題を解消し、これらのメタ任意の種類のバイナリデータ用のods。

+0

私はあまりにも経験がないと思う....これは単なるMSDNコードなので、私は自分のアプリケーションに適合させようとしました。 – Mreifenberger

+0

@Mreifenberger私の編集をご覧ください。 – spender

+0

@Mreifenberger上記のコードには問題があります...今すぐ作業してください。 – spender

関連する問題