0

I have the following BASH script to encrypt and decrypt a string given a password.

$ echo 'some-data' | openssl enc -base64 -e -aes-256-cbc -nosalt -pass pass:some-password

luYWG/C5uryBVtPHilO6Pg==

$ echo 'luYWG/C5uryBVtPHilO6Pg==' | openssl enc -base64 -d -aes-256-cbc -nosalt -pass pass:some-password

some-data

As you can see I'm able to enter some-password to encrypt and decrypt another string using openssl and AES-256

The problem came when I want to replicate this in Java using java.crypto because some-password don't complies the Key requirements apparently, I have this code:

public static String decrypt(String data, String secret)
            throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secret.getBytes(), "AES"));
        return new String(cipher.doFinal(Base64.getDecoder().decode(data)));
}

When I run it with those same inputs I get the following exception

java.security.InvalidKeyException: Invalid AES key length: ...

Is there a way that I can make it work? I'm guessing that openssl is able to take my desired string password and convert it to a valid one

William Añez
  • 730
  • 6
  • 25
  • Not Java, but definitely relevant: https://stackoverflow.com/questions/9488919/password-to-key-function-compatible-with-openssl-commands. – Oliver Charlesworth May 30 '18 at 19:54
  • Dupe https://stackoverflow.com/questions/14695766/java-aes-with-cbc-using-passphrase and https://stackoverflow.com/questions/22085107/perl-cbc-des-equivalent-in-java and https://stackoverflow.com/questions/11783062/how-to-decrypt-an-encrypted-file-in-java-with-openssl-with-aes and https://stackoverflow.com/questions/31947256/how-to-decode-a-string-encoded-with-openssl-aes-128-cbc-using-java and https://stackoverflow.com/questions/29151211/how-to-decrypt-an-encrypted-aes-256-string-from-cryptojs-using-java which _are_ Java but (all?) for the less-awful salted variant so you'll need to tweak. – dave_thompson_085 May 30 '18 at 21:40

0 Answers0