0
votes

I have written the following two methods that encrypt and decrypt a given token:

private static final String ALGORITHM_TYPE = "AES";
private static final String CIPHER_TRANSFORMATION = "AES/CBC/PKCS5Padding";
private static byte[] INITIALIZATION_VECTOR = new byte[] {
    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
};
public String encrypt(String token) {
    Cipher cipher = null;
    SecretKey key = null;
    String tokenAsHex = null;
    byte[] encryptedToken = null;
    byte[] sksKey = getKeyAsByteArray(KEY); // SecretKeySpec key.

    try {
        key = new SecretKeySpec(sksKey, ALGORITHM_TYPE);
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(INITIALIZATION_VECTOR);
        cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        encryptedToken = cipher.doFinal(Base64.encodeBase64(token.getBytes("UTF-8")));
    } catch (Exception e) {
        throw new EncryptionException(e);
    }
    return Base64.encodeBase64String(encryptedToken).toLowerCase();
}

public String decrypt(String token) throws EncryptionException {
    Cipher cipher = null;
    SecretKey key = null;
    byte[] decryptedToken = null;
    byte[] sksKey = getKeyAsByteArray(KEY); // SecretKeySpec key.
    try {
        key = new SecretKeySpec(sksKey, ALGORITHM_TYPE);            
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(INITIALIZATION_VECTOR);
        cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        decryptedToken = cipher.doFinal(Base64.decodeBase64(token));
    } catch(Exception e){
        throw new EncryptionException(e);    
    }
    if (decryptedToken == null) {
         throw new EncryptionException("Unable to decrypt the following token: " + token);
    }
    return Base64.encodeBase64String(decryptedToken);
}

However, I am unable to successfully decrypt any string encrypted with with the encrypt method. I searched for similar issues and the closest found is here: Encrypt and decrypt with AES and Base64 encoding. Even after using a similar strategy, I am still unable to decrypt the encrypted string. Any help is appreciated diagnosing what the issue maybe.

Also, I am encoding the encrypted/decrypted byte array using Base64 instead of creating a new String as the latter results in a unsafe URL string.

1

1 Answers

1
votes

You're encrypting a base64-encoding, and then re-base64-encoding it, and decrypting a base64-decoding, and then for some reason base64-encoding that. It doesn't make sense. You should be:

  1. base64-encoding the encryption, i.e. essentially return Base64.encode(cipher.doFinal(...))
  2. Decrypting the base64-decoding of (1), i.e. essentially return cipher.doFinal(Base64.decode(...))