尝试使用AES Managed解密字符串

时间:2017-02-24 15:27:54

标签: c#

我正在尝试编写代码来解密字符串。

我在python中获得了一个等价物,我正在尝试创建相同的内容。 NET

的Python:

//Initialization vector is just a string of 16 null bytes
iv = '\x00' * 16

//Create new AES object using the key and init vector
aes = AES.new(key, AES.MODE_CBC, iv)

//Decrypt password and remove padding
result = aes.decrypt(myString).rstrip('\x0b\x08\x07')

return result

这是我的尝试:

byte[] iv = new byte[16];
byte[] rawPlaintext = Convert.FromBase64String("MyBase64String");
byte[] key = // Read from common source

using (Aes aes = new AesManaged())
            {
                aes.Padding = PaddingMode.None;
                aes.KeySize = 128;          // in bits
                aes.Key = new byte[128 / 8];  // 16 bytes for 128 bit encryption
                aes.IV = new byte[128 / 8];   // AES needs a 16-byte IV
                // Should set Key and IV here.  Good approach: derive them from 
                // a password via Cryptography.Rfc2898DeriveBytes 
                byte[] cipherText = key;
                byte[] plainText = iv;

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(rawPlaintext, 0, rawPlaintext.Length);
                    }

                    cipherText = ms.ToArray();
                }


                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherText, 0, cipherText.Length);
                    }

                    plainText = ms.ToArray();
                }
                string s = System.Text.Encoding.Unicode.GetString(plainText);
                Console.WriteLine(s);
            }

它似乎不适用于结果是一串符号。

可能的问题:
- 我看到了CBC的一种模式。我不确定那个等效设置在哪里。我试过玩PaddingMode。
- 我的iv字节[]可能导致问题吗?是默认的null还是0?

编辑: - 从我正在阅读的内容来看,AesManaged在CBC模式下使用AES,因此应该不是问题。

1 个答案:

答案 0 :(得分:0)

尝试替换它:

string s = System.Text.Encoding.Unicode.GetString(plainText);

为:

string s = System.Text.Encoding.UTF8.GetString(plainText);