简体   繁体   中英

JAVA: AES Decryption

I'm currently running into problems decrypting my data. The base64 of the encoded string is being stored in the database. So, I'm printing out the encoded string and then trying to run it back through with "DECRYPT" instead of "ENCRYPT". However, I never get a value that the Decrypter method likes, it always gives me an error about parameters or the value not being 16 bytes.

public class crypto {
    public static void main(String [] args) {
        String s = args[0];
        String s1 = args[1];
        String ivkey = "thisisasecretkey";
        byte[] ivraw = ivkey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(ivraw, "AES");

        if (s.equalsIgnoreCase("ENCRYPT")) {
            try {
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
                byte[] encrypted = cipher.doFinal(s1.getBytes());
                System.out.println(new String(Base64.encodeBase64(encrypted)));

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            try {
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                cipher.init(Cipher.DECRYPT_MODE, skeySpec);
                byte[] encrypted = cipher.doFinal(s1.getBytes());
                System.out.println(new String(Base64.decodeBase64(encrypted)));

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return;
    };
}

command: crypto "ENCRYPT" "password"
output: 5eQvSzPG1TE2AybgCmeV6A==

command: crytpo "DECRYPT" "5eQvSzPG1TE2AybgCmeV6A=="
output: java.security.InvalidKeyException: Parameters missing

I'm aware of the security flaws, that's not what I'm asking about and I would prefer answers/comments not get cluttered with best practices.

您应该进行base 64 解码 ,并且应该解密之前进行

You are not including the initialization vector (IV). AES in CBC mode has both a 16 byte IV and the 16 byte symmetric key.

String IV = "AAAAAAAAAAAAAAAA"; // generate this randomly
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(IV.getBytes()));
byte[] encrypted = cipher.doFinal(s.getBytes());

Edit: as it turns out, encryption does not require a IV to be provided (as owlstead pointed out), but decryption does. The best bet would be to be explicit and use IV in both encryption and decryption. Change your decryption function to include the IV, and you will run into the other error in your code that owlstead pointed out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM