请帮助我修复C#中的AES CTR模式Bouncy Castle代码

时间:2019-06-16 10:53:38

标签: c# encryption aes bouncycastle

Bouncy Castle CRT Csharp,解密无法获得纯文本

测试失败

   static void Main(string[] args) {
        string toEncrypt = "This is a test string";
        byte[] key = Encoding.ASCII.GetBytes("0123456789abcdef");            
        byte[] iv = { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff };

        Console.Write("\n Plain: " + toEncrypt); 

        // create AES cipher
        IBufferedCipher cipher = CipherUtilities.GetCipher("AES/CTR/NoPadding");
        cipher.Init(true, new ParametersWithIV(ParameterUtilities.CreateKeyParameter("AES", key), iv));

        // encrypted
        byte[] input = Encoding.ASCII.GetBytes(toEncrypt);
        byte[] encryptedBytes = cipher.DoFinal(input);
        string base64EncryptedOutputString = Convert.ToBase64String(encryptedBytes);
        Console.Write("\n Base64Encrypted:" + base64EncryptedOutputString);

        // decrypted
        byte[] toDecrypt = Encoding.ASCII.GetBytes(base64EncryptedOutputString);
        cipher.Init(false, new ParametersWithIV(ParameterUtilities.CreateKeyParameter("AES", key), iv));
        byte[] plainBytes = cipher.DoFinal(toDecrypt);
        Console.WriteLine("\n Decrypted:" + Encoding.ASCII.GetString(plainBytes));
    }

简单:这是一个测试字符串

Base64Encrypted:71WVSPK31A + QrCUyqppI56fQixMV

解密:?? m ????? z ?? = ???? 4G ??? e?w?

--->用PLAIN Text解密的内容不一样:)

1 个答案:

答案 0 :(得分:1)

问题是您缺少从 base64到原始字节数组的转换。

代替:

byte[] toDecrypt = Encoding.ASCII.GetBytes(base64EncryptedOutputString);

您需要:

byte[] toDecrypt = Convert.FromBase64String(base64EncryptedOutputString);

请参见MSDN