Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use AES CCM with Bouncycastle JCE provider - CCMParameters

Is it possible to use JCE to perform CCM?

I see lots of examples on the Internet using the non-JCE bouncycastle classes. In particular, I see them calling init passing in a CCMParameters object.

Trouble is, this CCMParameters object doesn't derive from AlgorthmParameters or AlgorithmParameterSpec, so there seems to be no way to pass it into Cipher.init() (after getting a Cipher object with Cipher.getInstance("AES/CCM/NoPadding")).

How does one do this?

like image 281
nsayer Avatar asked Nov 08 '22 13:11

nsayer


1 Answers

Hi here is sample code for AES-CCM algo where all usual names are input params. take care about HEX data bytes and all other things

import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CCMBlockCipher;
import org.bouncycastle.crypto.params.CCMParameters;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Hex;

public class AesCcm {
    public static void main(String[] args) throws IllegalStateException, InvalidCipherTextException {
    int macSize = 125;
    byte[] key = new byte[32];
    byte[] keybyte = "test123".getBytes();
    byte[] inputNouc = "abcdefghijklm".getBytes();
    for (int I = 0; I < keybyte.length; I++) {
        key[I] = keybyte[I];
    }

//      Input data in HEX format
    String input = "ed88fe7b95fa0ffa190b7ab33933fa";

    byte[] inputData= Hex.decode(input);

    BlockCipher engine = new AESEngine();
    CCMParameters params = new CCMParameters(new KeyParameter(key),
            macSize, inputNouc, null);

    CCMBlockCipher cipher = new CCMBlockCipher(engine);
    cipher.init(true, params);
    byte[] outputText = new byte[cipher.getOutputSize(inputData.length)];
    int outputLen = cipher.processBytes(inputData, 0, inputData.length,
            outputText , 0);
    cipher.doFinal(outputText, outputLen);

//      outputText and mac are in bytes 
    System.out.println(outputText);
    System.out.println(cipher.getMac());
    }
}
like image 67
Ashu Kanaujia Avatar answered Nov 14 '22 21:11

Ashu Kanaujia