Search code examples
javaandroidbouncycastle

Android AES/ECB/PKCS7PADDING generate key bouncy castle


I want to generate Random key using AES/ECB/PKCS7PADDING but java does not support PKCS7 padding and in my algo I have to use the same padding, bouncy castle does support PKCS7PADDING but I am unable to understand how to generate key using that

My code :

Security.addProvider(new BouncyCastleProvider());


private byte[] generateSessionKey() throws NoSuchAlgorithmException, NoSuchProviderException {
        KeyGenerator kgen = KeyGenerator.getInstance("AES/ECB/PKCS7PADDING", "BC");
        kgen.init(SYMMETRIC_KEY_SIZE);
        SecretKey key = kgen.generateKey();
        return key.getEncoded();
}

I am receiving error of no such algorithm


Solution

  • Key generation for AES does not have to do anything with padding. Padding is required for some modes of operation such as ECB and CBC. But the key itself doesn't rely on the mode or the padding. So you should just use:

    KeyGenerator kgen = KeyGenerator.getInstance("AES", "BC");
    

    which will undoubtedly work.


    Do not use PKCS#7 padding, substitute "PKCS5Padding" for "PKCS7Padding".

    Please take a look here to understand the difference between the padding mechanisms and here for the difference in Java.

    I guess Android is using a stripped down Bouncy Castle provider (it was one of the reasons that SpongyCastle was lounged), which would explain the differences between Android and the Java SE provider.