gtludwig
gtludwig

Reputation: 5611

How to ensure crypted data to be properly decrypted?

I need to send some crypted data over REST. My crypter / decrypter class is as follows:

public class AesCrypter {
    static String IV = "AAAAAAAAAAAAAAAA";
    static String aesKey = "0123456789abcdef";

    public static byte[] encrypt(String unecryptedText) throws Exception {
        Cipher encrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
        SecretKeySpec key = new SecretKeySpec(aesKey.getBytes("UTF-8"), "AES");
        encrypt.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
        return encrypt.doFinal(unecryptedText.getBytes("UTF-8"));
    }

    public static String decrypt(String cryptedText) throws Exception{
        byte[] bytes = cryptedText.getBytes(StandardCharsets.UTF_8);
        Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
        SecretKeySpec key = new SecretKeySpec(aesKey.getBytes("UTF-8"), "AES");
        decrypt.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
        return new String(decrypt.doFinal(bytes),"UTF-8"); // this line
    }
}

But I'm getting a javax.crypto.BadPaddingException: Given final block not properly padded on the decrypt method, console points out error to be on the line I commented with // this line.

What am I missing out here?

Upvotes: 0

Views: 285

Answers (1)

SkyWalker
SkyWalker

Reputation: 29168

Actual Scenerio of PKCS5-Padding causes javax.crypto.BadPaddingException

If you try to decrypt PKCS5-padded data with the wrong key, and then unpad it (which is done by the Cipher class automatically), you most likely will get the BadPaddingException (with probably of slightly less than 255/256, around 99.61%), because the padding has a special structure which is validated during unpad and very few keys would produce a valid padding.

So, if you get this exception, catch it and treat it as "wrong key".

This also can happen when you provide a wrong password, which then is used to get the key from a keystore, or which is converted into a key using a key generation function.

Of course, bad padding can also happen if your data is corrupted in transport.

So you can follow Base64:

import org.apache.commons.codec.binary.Base64;


 public static String base64Encode(String token) {
    byte[] encodedBytes = Base64.encode(token.getBytes());
    return new String(encodedBytes, Charset.forName("UTF-8"));
}


public static String base64Decode(String token) {
    byte[] decodedBytes = Base64.decode(token.getBytes());
    return new String(decodedBytes, Charset.forName("UTF-8"));
}

Resource Link:

  1. Base64 Encoding in Java

Upvotes: 1

Related Questions