2012-01-13 27 views
0

私はここでAES暗号化/復号化のために見つけたクラスを使用しています。それは私のために正しく動作しますが、EncryptToStringメソッドを使って文字列を暗号化すると、暗号化には数字だけが含まれます。私はそれが数字、文字、記号を含むことを期待していた。それがなぜ数字だけを含むのか知っていますか?おかげ双方向AES暗号化

これは私が参照していたコードである:それは、文字列およびその逆として整数値(3桁)とを連結するthoesとしてバイトをコード

public class AESEncryption 
{ 
    // These can be anything I desire but must be less than or equal to 255 
    private byte[] Key = { 222, 237, 16, 14, 28, 26, 85, 45, 114, 184, 27, 192, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 105, 29, 24, 26, 17, 218, 131, 236, 53, 209 }; 
    private byte[] Vector = { 146, 64, 101, 111, 23, 32, 113, 119, 231, 121, 211, 11, 99, 32, 104, 156 }; 


    private ICryptoTransform EncryptorTransform, DecryptorTransform; 
    private System.Text.UTF8Encoding UTFEncoder; 

    public AESEncryption() 
    { 
     //This is our encryption method 
     RijndaelManaged rm = new RijndaelManaged(); 

     //Create an encryptor and a decryptor using our encryption method, key, and vector. 
     EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector); 
     DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector); 

     //Used to translate bytes to text and vice versa 
     UTFEncoder = new System.Text.UTF8Encoding(); 
    } 

    /// -------------- Two Utility Methods (not used but may be useful) ----------- 
    /// Generates an encryption key. 
    static public byte[] GenerateEncryptionKey() 
    { 
     //Generate a Key. 
     RijndaelManaged rm = new RijndaelManaged(); 
     rm.GenerateKey(); 
     return rm.Key; 
    } 

    /// Generates a unique encryption vector 
    static public byte[] GenerateEncryptionVector() 
    { 
     //Generate a Vector 
     RijndaelManaged rm = new RijndaelManaged(); 
     rm.GenerateIV(); 
     return rm.IV; 
    } 


    /// ----------- The commonly used methods ------------------------------  
    /// Encrypt some text and return a string suitable for passing in a URL. 
    public string EncryptToString(string TextValue) 
    { 
     return ByteArrToString(Encrypt(TextValue)); 
    } 

    /// Encrypt some text and return an encrypted byte array. 
    public byte[] Encrypt(string TextValue) 
    { 
     //Translates our text value into a byte array. 
     Byte[] bytes = UTFEncoder.GetBytes(TextValue); 

     //Used to stream the data in and out of the CryptoStream. 
     MemoryStream memoryStream = new MemoryStream(); 

     /* 
     * We will have to write the unencrypted bytes to the stream, 
     * then read the encrypted result back from the stream. 
     */ 
     #region Write the decrypted value to the encryption stream 
     CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write); 
     cs.Write(bytes, 0, bytes.Length); 
     cs.FlushFinalBlock(); 
     #endregion 

     #region Read encrypted value back out of the stream 
     memoryStream.Position = 0; 
     byte[] encrypted = new byte[memoryStream.Length]; 
     memoryStream.Read(encrypted, 0, encrypted.Length); 
     #endregion 

     //Clean up. 
     cs.Close(); 
     memoryStream.Close(); 

     return encrypted; 
    } 

    /// The other side: Decryption methods 
    public string DecryptString(string EncryptedString) 
    { 
     return Decrypt(StrToByteArray(EncryptedString)); 
    } 

    /// Decryption when working with byte arrays.  
    public string Decrypt(byte[] EncryptedValue) 
    { 
     #region Write the encrypted value to the decryption stream 
     MemoryStream encryptedStream = new MemoryStream(); 
     CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write); 
     decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length); 
     decryptStream.FlushFinalBlock(); 
     #endregion 

     #region Read the decrypted value from the stream. 
     encryptedStream.Position = 0; 
     Byte[] decryptedBytes = new Byte[encryptedStream.Length]; 
     encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length); 
     encryptedStream.Close(); 
     #endregion 
     return UTFEncoder.GetString(decryptedBytes); 
    } 

    /// Convert a string to a byte array. NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so). 
    //  System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); 
    //  return encoding.GetBytes(str); 
    // However, this results in character values that cannot be passed in a URL. So, instead, I just 
    // lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100). 
    public byte[] StrToByteArray(string str) 
    { 
     if (str.Length == 0) 
      throw new Exception("Invalid string value in StrToByteArray"); 

     byte val; 
     byte[] byteArr = new byte[str.Length/3]; 
     int i = 0; 
     int j = 0; 
     do 
     { 
      val = byte.Parse(str.Substring(i, 3)); 
      byteArr[j++] = val; 
      i += 3; 
     } 
     while (i < str.Length); 
     return byteArr; 
    } 

    // Same comment as above. Normally the conversion would use an ASCII encoding in the other direction: 
    //  System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); 
    //  return enc.GetString(byteArr);  
    public string ByteArrToString(byte[] byteArr) 
    { 
     byte val; 
     string tempStr = ""; 
     for (int i = 0; i <= byteArr.GetUpperBound(0); i++) 
     { 
      val = byteArr[i]; 
      if (val < (byte)10) 
       tempStr += "00" + val.ToString(); 
      else if (val < (byte)100) 
       tempStr += "0" + val.ToString(); 
      else 
       tempStr += val.ToString(); 
     } 
     return tempStr; 
    } 
} 
+0

'数字のみ'で、バイト配列を意味しますか? – Jodrell

+0

バイトを整数値(3桁)としてエンコードし、文字列として連結します。逆の場合も同様です... – Yahia

+5

__one_秒の 'ByteArrToString'メソッドを見ましたか?あなたの答えはそこにあります(そして 'StrToByteArray'メソッドのコメント)。 – Nuffin

答えて

2

...

からコードとコメントあなたが掲示:

/// Convert a string to a byte array. NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so). 
//  System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); 
//  return encoding.GetBytes(str); 
// However, this results in character values that cannot be passed in a URL. So, instead, I just 
// lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100). 
public byte[] StrToByteArray(string str) 

と、逆の方法

// Same comment as above. Normally the conversion would use an ASCII encoding in the other direction: 
//  System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); 
//  return enc.GetString(byteArr);  
public string ByteArrToString(byte[] byteArr) 
+0

3桁またはそれ以上の数値は、256未満です。 – Jodrell

0

AESアルゴリズムは、バイト配列(byte[])、すなわち8ビット数のセットを受け取り、返します。

これは、データ型がどのようなものであっても、stringImageintなどのように、コンピュータ内部のすべてのデータを格納するものです。あなたが見る通り、この行

は、「クリア」文字列を「クリア」バイト配列に変換し、暗号化アルゴリズムを実行します。暗号化の後、バイト配列はもはや文字列(暗号化のポイント)にデコードできません。

これを文字列として保存したい場合は、base64でエンコードすることができますので、それはパーサーフレンドリーですが、人間にとっては読めないゴミとなります。

あなたはこの

File.WriteAllBytes("C:\MyTestFile.txt", Encrypt("My Clear Text")); 

ようEncryptからの出力とFile.WriteAllBytes機能を使用する場合は、テキストファイルにバイトを格納します。次に、 "C:\ MyTestFile.txt"を任意のテキストエディタで開くと、ファイルには印刷と非印刷の両方の文字スタイルが含まれていることがわかります。

あなたはそれらのバイト戻って、元の文字列として

return UTFEncoder.GetString(decryptedBytes); 

リターンを見ることができるようにkeyvector、復号化コードは、バック「クリア」バイトに暗号化されたバイトを回すとなり、右を使用と仮定。

これが意味をなさない場合は、申し訳ありませんが、私は単純なままにしておきました。おそらく一歩前に戻り、byteが何であるかを考えてみましょう。

+0

意味があります。ありがとう –

+0

もう1つ質問があります。何かを暗号化してデータベースに格納しようとすると、それをバイト配列として暗号化してバイトを書き出すことができますか、それは印刷文字と非印字文字を含むので動作しませんか? –

+0

@RichardKeslar 十分な大きさのBLOBに保存しても機能しますが、以前にテキスト文字列として保存していた場合は、新しい(一時的な)列を作成するか、テキストに基数64として格納する必要がありますフィールド私は推測する。 –