使用Bouncy Castle AES/CBC/PKCS7加密字符串

27

我一直在寻找如何使用Bouncy Castle框架加密一个简单字符串的示例代码,该加密方式在标题中提到。

这段代码将运行在Windows通用项目上。 我之前尝试使用内置API进行加密,但在服务器上无法解密。

我尝试了以下代码:给我一个类似于下面的字符串:

4pQUfomwVVsl68oQqWoWYNRmRM+Cp+vNFXBNdkN6dZPQ34VZ35vsKn9Q7QGTDVOj+w5mqVYHnGuAOFOgdgl8kA==

s = String.Format("{0}_{1}", s, DateTime.Now.ToString("ddMMyyyyHmmss"));
SymmetricKeyAlgorithmProvider algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
IBuffer keymaterial = CryptographicBuffer.ConvertStringToBinary("[Key]", BinaryStringEncoding.Utf8);
CryptographicKey KEY = algorithm.CreateSymmetricKey(keymaterial);
IBuffer IV = CryptographicBuffer.ConvertStringToBinary("[IV]", BinaryStringEncoding.Utf8);
IBuffer data = CryptographicBuffer.ConvertStringToBinary(s, BinaryStringEncoding.Utf8);
IBuffer output = CryptographicEngine.Encrypt(KEY, data, IV);
return CryptographicBuffer.EncodeToBase64String(output);

服务器使用加密/解密功能

public static string Encrypt(string text, byte[] key, byte[] iv, int keysize = 128, int blocksize = 128, CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7)
{
    AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
    aes.BlockSize = blocksize;
    aes.KeySize = keysize;
    aes.Mode = cipher;
    aes.Padding = padding;

    byte[] src = Encoding.UTF8.GetBytes(text);
    using (ICryptoTransform encrypt = aes.CreateEncryptor(key, iv))
    {
        byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
        encrypt.Dispose();
        return Convert.ToBase64String(dest);
    }
}

public static string Decrypt(string text, byte[] key, byte[] iv, int keysize = 128, int blocksize = 128, CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7)
{
    AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
    aes.BlockSize = blocksize;
    aes.KeySize = keysize;
    aes.Mode = cipher;
    aes.Padding = padding;

    byte[] src = Convert.FromBase64String(text);
    using (ICryptoTransform decrypt = aes.CreateDecryptor(key, iv))
    {
        byte[] dest = decrypt.TransformFinalBlock(src, 0, src.Length);
        decrypt.Dispose();
        return Encoding.UTF8.GetString(dest); //Padding is invalid and cannot be removed. 
    }
}

但是它失败了,因为:

填充无效,无法移除。

这就是为什么我想尝试 Bouncy Castle,但我找不到任何合适的示例代码。

编辑

我尝试使用答案中提供的代码使用 Bouncy Castle。 现在我收到了错误消息:

初始向量的长度必须与块大小相同。

byte[] inputBytes = Encoding.UTF8.GetBytes(s);
byte[] IV = Encoding.UTF8.GetBytes("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
byte[] key = Encoding.UTF8.GetBytes("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");

//Set up
AesEngine engine = new AesEngine();
CbcBlockCipher blockCipher = new CbcBlockCipher(engine);
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding());
Debug.WriteLine(IV.Length); //32
Debug.WriteLine(cipher.GetBlockSize()); //16
KeyParameter keyParam = new KeyParameter(key);
ParametersWithIV keyParamWithIv = new ParametersWithIV(keyParam, IV);


cipher.Init(true, keyParamWithIv); //Error Message thrown
byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)]; //cip
int length = cipher.ProcessBytes(inputBytes, outputBytes, 0);
cipher.DoFinal(outputBytes, length); //Do the final block
string encryptedInput = Convert.ToBase64String(outputBytes);
服务器上的长度为128。我该如何强制它相等且长度相同?

编辑了问题,附上了我尝试的内容。 - timr
你能用更安全的方式替换加密吗? - CodesInChaos
@CodesInChaos,您能解释一下您的意思吗? - timr
你的密钥和IV初始化看起来很奇怪。假设每个X代表一个字符,你有一个十六进制编码的AES128密钥和IV,但你没有解码十六进制表示。因此,密钥和IV太长了。 - Robert
你得到了什么结果?你应该得到什么结果? - vrwim
2个回答

20

这里是我使用的代码片段。它使用默认内置的 System.Security.Cryptography。它不需要 BC。

    /// <summary>
    /// Encrypt a byte array using AES 128
    /// </summary>
    /// <param name="key">128 bit key</param>
    /// <param name="secret">byte array that need to be encrypted</param>
    /// <returns>Encrypted array</returns>
    public static byte[] EncryptByteArray(byte[] key, byte[] secret)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            using (AesManaged cryptor = new AesManaged())
            {
                cryptor.Mode = CipherMode.CBC;
                cryptor.Padding = PaddingMode.PKCS7;
                cryptor.KeySize = 128;
                cryptor.BlockSize = 128;

                //We use the random generated iv created by AesManaged
                byte[] iv = cryptor.IV;

                using (CryptoStream cs = new CryptoStream(ms, cryptor.CreateEncryptor(key, iv), CryptoStreamMode.Write))
                {
                    cs.Write(secret, 0, secret.Length);
                }
                byte[] encryptedContent = ms.ToArray();

                //Create new byte array that should contain both unencrypted iv and encrypted data
                byte[] result = new byte[iv.Length + encryptedContent.Length];

                //copy our 2 array into one
                System.Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
                System.Buffer.BlockCopy(encryptedContent, 0, result, iv.Length, encryptedContent.Length);

                return result;
            }
        }
    }

    /// <summary>
    /// Decrypt a byte array using AES 128
    /// </summary>
    /// <param name="key">key in bytes</param>
    /// <param name="secret">the encrypted bytes</param>
    /// <returns>decrypted bytes</returns>
    public static byte[] DecryptByteArray(byte[] key, byte[] secret)
    {
        byte[] iv = new byte[16]; //initial vector is 16 bytes
        byte[] encryptedContent = new byte[secret.Length - 16]; //the rest should be encryptedcontent

        //Copy data to byte array
        System.Buffer.BlockCopy(secret, 0, iv, 0, iv.Length);
        System.Buffer.BlockCopy(secret, iv.Length, encryptedContent, 0, encryptedContent.Length);

        using (MemoryStream ms = new MemoryStream())
        {
            using (AesManaged cryptor = new AesManaged())
            {
                cryptor.Mode = CipherMode.CBC;
                cryptor.Padding = PaddingMode.PKCS7;
                cryptor.KeySize = 128;
                cryptor.BlockSize = 128;

                using (CryptoStream cs = new CryptoStream(ms, cryptor.CreateDecryptor(key, iv), CryptoStreamMode.Write))
                {
                    cs.Write(encryptedContent, 0, encryptedContent.Length);

                }
                return ms.ToArray();
            }
        }
    }

如果您真的需要BC,请看我设法根据https://github.com/bcgit/bc-csharp/blob/master/crypto/test/src/crypto/test/AESFastTest.cs测试套件编写的快速测试。 您可以根据自己的需求进行调整。

    private static void TestBC()
    {
        //Demo params
        string keyString = "jDxESdRrcYKmSZi7IOW4lw==";   

        string input = "abc";
        byte[] inputBytes = Encoding.UTF8.GetBytes(input);            
        byte[] iv = new byte[16]; //for the sake of demo

        //Set up
        AesEngine engine = new AesEngine();
        CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher); //Default scheme is PKCS5/PKCS7
        KeyParameter keyParam = new KeyParameter(Convert.FromBase64String(keyString));
        ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16);

        // Encrypt
        cipher.Init(true, keyParamWithIV);
        byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)];
        int length = cipher.ProcessBytes(inputBytes, outputBytes, 0);
        cipher.DoFinal(outputBytes, length); //Do the final block
        string encryptedInput = Convert.ToBase64String(outputBytes);

        Console.WriteLine("Encrypted string: {0}", encryptedInput);

        //Decrypt            
        cipher.Init(false, keyParamWithIV);
        byte[] comparisonBytes = new byte[cipher.GetOutputSize(outputBytes.Length)];
        length = cipher.ProcessBytes(outputBytes, comparisonBytes, 0);
        cipher.DoFinal(comparisonBytes, length); //Do the final block

        Console.WriteLine("Decrypted string: {0}",Encoding.UTF8.GetString(comparisonBytes)); //Should be abc
    }

1
嗯,我喜欢你的努力,但是AesManaged在Windows Universal上不可用(如果我错了,请纠正我)。 你的Bouncy Castle代码中,我没有看到填充PKCS7、IV或输出字符串。我只需要加密后的字符串。 - timr
PaddedBufferedBlockCipher默认使用PKCS5/PKCS7(http://www.cs.berkeley.edu/~jonah/bc/org/bouncycastle/crypto/paddings/PaddedBufferedBlockCipher.html)。 对于IV,您可以将keyParameter包装在ParametersWithIV中。 输出字符串可以通过将输出字节转换为Base64来获得。 - Eledra Nguyen
已将BC部分编辑为PKCS7 + IV +输出字符串。不过还没有尝试过Windows Universal。 - Eledra Nguyen
AES 128的IV应该只有128位=16字节。只需确保传递一个16字节的数组即可。 如果您真的需要强制执行此操作: ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16); - Eledra Nguyen
这个有效吗?我应该授予奖励吗?还是让它过期?@SeaSharp 你遇到了什么问题?能告诉我们你看到了什么,期望得到什么结果吗? - vrwim

-1

在此输入链接描述

        byte[] k; //32 byte
        string para; // plaintext
        string msgRefNo; // 16byte

        byte[] inputBytes = Encoding.UTF8.GetBytes(para);
        byte[] IV = Encoding.UTF8.GetBytes(msgRefNo);
        byte[] key = k;


        AesEngine engine = new AesEngine();
        CbcBlockCipher blockCipher = new CbcBlockCipher(engine);
        PaddedBufferedBlockCipher cipher1 = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding());

        KeyParameter keyParam = new KeyParameter(key);
        ParametersWithIV keyParamWithIv = new ParametersWithIV(keyParam, IV);


        cipher1.Init(true, keyParamWithIv); //Error Message thrown
        byte[] outputBytes = new byte[cipher1.GetOutputSize(inputBytes.Length)]; //cip
        int length = cipher1.ProcessBytes(inputBytes, outputBytes, 0);
        cipher1.DoFinal(outputBytes, length); //Do the final block
        string encryptedInput = Convert.ToBase64String(outputBytes);
        return encryptedInput;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接