Specify Cipher.getInstance() arguments?

47,757

Solution 1

Another 'short answer', but I believe AES-GCM is more secure that CBC mode and been around for a couple of years however if you want to use in Android you'll need to include spongycastle

Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

Solution 2

Short answer:

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

Long Answer

Solution 3

This is how I did it:

keyGenerator.init(new
                KeyGenParameterSpec.Builder(KEY_NAME,
                KeyProperties.PURPOSE_ENCRYPT |
                        KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                .setUserAuthenticationRequired(true)
                .setEncryptionPaddings(
                        KeyProperties.ENCRYPTION_PADDING_PKCS7)
                .build());

cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
Share:
47,757
user291701
Author by

user291701

Updated on July 09, 2022

Comments

  • user291701
    user291701 almost 2 years

    I'm using the following in an android app and a standalone java app:

    private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(clear);
        ...
    

    I get different encrypted strings on android vs my standalone java app (both using the same code and key). I get the same exception (javax.crypto.BadPaddingException: Blocktype mismatch: 0) as in this question:

    RSA Encryption: Difference between Java and Android

    And the suggested solution is to specify the padding strategy like:

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    

    but I'm using "AES", not "RSA", and am not sure how to specify the padding in combination with AES. How would I construct the string passed to Cipher.getInstance() in that case? I gave this a try:

    Cipher cipher = Cipher.getInstance("AES/PKCS1Padding");
    

    but get an exception about that being invalid.

    Thanks

  • user1811107
    user1811107 almost 10 years
    In my case, I was calling a cipher.update when it should have been cipher.doFinal.
  • alphaguy
    alphaguy about 4 years
    java.security.NoSuchAlgorithmException: AES/GCM/NoPadding SecretKeyFactory not available I am getting this error