【问题标题】:Please help me to fix the AES CTR mode Bouncy Castle code in C#请帮我修复 C# 中的 AES CTR 模式 Bouncy Castle 代码
【发布时间】:2019-10-30 06:29:33
【问题描述】:

Bouncy Castle CRT Csharp, Decrypt 获取纯文本失败

测试失败

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

Plain:这是一个测试字符串

Base64加密:71WVSPK31A+QrCUyqppI56fQixMV

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

--->解密与纯文本不一样:)

【问题讨论】:

  • 你不应该使用 ASCII,因为它只支持 128 个基本的拉丁字母、数字和符号。改用 UTF8 来支持所有 100,000+ Unicode 字符。

标签: c# encryption aes bouncycastle


【解决方案1】:

问题是您缺少将 base64 转换回原始字节数组的过程。

代替:

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

你需要:

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

MSDN

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    相关资源
    最近更新 更多