Search code examples
c#encryptionaesbouncycastle

Encrypt AES cipher in CCM with Bouncy Castle in C#


I want to use AES/CCM encryption using Bouncy Castle and I don't know what I am doing wrong in the following code (key and iv are obtained from their HEXA representation):

using System;
using System.Linq;
using System.Text;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;

namespace Crypto.Tests {
    class MainClass {
        public static void Main (string[] args) {
            var key = "D44EDA90DDCFA90216BDAC1559D704D336D371A3DA943E935315964D27CC91DC".ToByteArray();
            var iv = "7B13E1A17861356401A3C15F4F0525C3".ToByteArray();
            var nonSecretPayload = new byte[] { };
            var plainText = Encoding.UTF8.GetBytes("Secret message!!!");

            var cipher = new CcmBlockCipher(new AesFastEngine());
            var parameters = new CcmParameters(
                new KeyParameter(key), 64, iv, nonSecretPayload);
            cipher.Init(true, parameters);

            var cipherText = new byte[cipher.GetOutputSize(plainText.Length)];
            var len = cipher.ProcessBytes(plainText, 0, plainText.Length, cipherText, 0);
            cipher.DoFinal(cipherText, len);

            Console.WriteLine(Convert.ToBase64String(cipherText));

            Console.Read();
        }
    }

    public static class StringExtentions {
        public static byte[] ToByteArray(this string toTransform) {
            return Enumerable
                .Range(0, toTransform.Length / 2)
                .Select(i => Convert.ToByte(toTransform.Substring(i * 2, 2), 16))
                .ToArray();
        }
    }
}

Executing the above code results in the following exception:

Unhandled Exception: System.ArgumentException: Destination array was not long enough. 
Check destIndex and length, and the array's lower bounds.
  at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length, Boolean reliable)
  at Org.BouncyCastle.Crypto.Modes.CcmBlockCipher.ProcessPacket(Byte[] input, Int32 inOff, Int32 inLen)
  at Org.BouncyCastle.Crypto.Modes.CcmBlockCipher.DoFinal(Byte[] outBytes, Int32 outOff)
  at Crypto.Tests.MainClass.Main(String[] args) in c:\Users\Emi\Documents\Projects\Crypto\Crypto.Tests\Main.cs:line 23

Solution

  • It was crashing in bouncy castle when it was trying to generate a counter IV from your nonce, because it's expecting a nonce that is (BlockSize - 1) or less such as an incremental number. If you remove one byte from your iv it works.

       var iv = "7B13E1A17861356401A3C15F4F0525".ToByteArray();