Rijndael如何从字符串和byte []返回不同的结果?

时间:2013-01-22 11:31:38

标签: c# .net aes rijndael rijndaelmanaged

这是我的代码,首先是字符串:

byte[] concatBytes = Encoding.ASCII.GetBytes(key);
byte[] keyBytes = Encoding.ASCII.GetBytes(key);
for (int i = 0; i < 3; i++)
{
         concatBytes = Encrypt(Encoding.ASCII.GetString(concatBytes), keyBytes);
         //Console.WriteLine(Transform.Hexa(concatBytes));
} 

public byte[] Encrypt(string plainText, byte[] key)
    {
        byte[] encrypted;
        using (var rijndael = new RijndaelManaged())
        {
            rijndael.Mode = CipherMode.ECB;
            rijndael.KeySize = 128;
            rijndael.BlockSize = 128;
            rijndael.Padding = PaddingMode.Zeros;
            rijndael.Key = key;
            //rijndael.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

            ICryptoTransform transform = rijndael.CreateEncryptor(rijndael.Key, rijndael.IV);

            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write))
                {
                    using (var streamWriter = new StreamWriter(cryptoStream))
                    {
                        streamWriter.Write(plainText);
                    }
                    encrypted = memoryStream.ToArray();
                }
            }
        }
        return encrypted;
    }

如果我将方法参数plainText更改为byte[],那么我的结果会完全不同。我在这里失踪了什么?此外,我们使用OpenSSLRijndael AES加密有不同的结果。我有什么建议可以解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

StreamWriter(Stream)

  

使用UTF-8编码和默认缓冲区大小为指定的流初始化StreamWriter类的新实例。

由于您使用的是不同的编码(UTF-8而不是ASCII),因此您会得到不同的结果并不奇怪。