Search code examples
javaandroidencryptionbase64initialization-vector

Removing characters from decrypted Base64 string in Java


In relation to this question; Java (Android) Decrypting msg with IV attached

My message decrypts fine but with the unwanted IV byte data.
I try to remove the attached IV, yet it does not delete all the characters and some character always remain behind. I'm not sure how I should be calculating the length of the encoded IV to remove the non-required characters.

public String decrypt(String cipherText, byte[] encryptionKey) throws Exception {
    SecretKeySpec key = new SecretKeySpec(encryptionKey, "AES");          
    cipher.init(Cipher.DECRYPT_MODE, key, iV);
    String decrypt = new String(cipher.doFinal( Base64.decode(cipherText, Base64.DEFAULT)));

    byte[] decryptData = new byte[decrypt.getBytes().length - iV.getIV().length];
    System.arraycopy(decrypt.getBytes(), iV.getIV().length, decryptData, 0, decrypt.getBytes().length - iV.getIV().length);

    Log.d("decrypt = ", decrypt);

    decrypt = new String(decryptData, "UTF-8");

    return decrypt;
}   

Solution

  • You need to remove the IV before decryption not after it, because it is a parameter of the decryption. Since the IV is prepended to the ciphertext there is no need to save it somewhere else (no need for your iV reference).

    byte[] ciphertextBytes = Base64.decode(cipherText, Base64.DEFAULT);
    IvParameterSpec iv = new IvParameterSpec(ciphertextBytes, 0, 16);
    ciphertextBytes = Arrays.copyOfRange(ciphertextBytes, 16, ciphertextBytes.length);
    
    SecretKeySpec key = new SecretKeySpec(encryptionKey, "AES");          
    cipher.init(Cipher.DECRYPT_MODE, key, iv);
    String decrypt = new String(cipher.doFinal(ciphertextBytes), "UTF-8");