双向AES加密

时间:2012-01-13 17:13:02

标签: c# encryption aes

我正在使用我在这里找到的用于AES加密/解密的类。它对我来说可以正常工作,但是当我使用EncryptToString方法加密字符串时,加密只包含数字。我期待它包含数字,字母和符号。你知道它为什么只包含数字吗?谢谢

这是我所指的代码:

 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;
    }
}

2 个答案:

答案 0 :(得分:2)

它将字节编码为整数值(3位数)并将字符串连接为字符串,反之亦然......

根据您发布的代码和评论:

/// 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)

答案 1 :(得分:0)

AES算法获取并返回一个字节数组(byte[]),即一组8位数字。

这就是计算机内的所有数据都存储为的内容,无论数据类型是stringImageint还是其他任何数据类型。如你所见,这一行

//Translates our text value into a byte array.
Byte[] bytes = UTFEncoder.GetBytes(TextValue);

将'clear'字符串转换为'clear'字节数组,然后通过加密算法运行它。加密后,字节数组不能再被解码为字符串(这是加密点)。

如果你想将它存储为一个字符串,你可以使用base64编码,这样它就是解析器友好的,但对于人类来说,它将是不可读的垃圾。

如果您使用File.WriteAllBytes函数和Encrypt的输出

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

它会将字节存储到文本文件中。如果您随后使用您选择的文本编辑器打开“C:\ MyTestFile.txt”,您将看到该文件实际上包含所有类型的字符,包括打印和非打印。

假设你使用了正确的keyvector,解密代码会将加密的字节变回'clear'字节,正如你所看到的那样

return UTFEncoder.GetString(decryptedBytes);

将这些字节作为原始字符串返回。

如果这一切都没有任何意义,那么抱歉,我试图保持简单,也许退后一步考虑byte是什么,然后是类型如何工作。