简体   繁体   中英

Java AES - message digest for the key

I recently searched for Java code to encrypt data with AES and found this piece of code on the net:

        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.update(getSecretKey().getBytes("UTF-8"));
        byte[] keyBytes = new byte[16];
        System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);
        Key aesKey = new SecretKeySpec(keyBytes, "AES");

        // Then encrypt
        byte[] iv = initIV();
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(iv));
        byte[] encrypted = cipher.doFinal(value.getBytes(encoding));

I'd like to understand why the developer used a MessageDigest with the secret key. What are the benefits of such an approach, instead of writing:

        Key aesKey = new SecretKeySpec(getSecretKey().getBytes("UTF-8"), "AES");

        // Then encrypt
        byte[] iv = initIV();
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(iv));
        byte[] encrypted = cipher.doFinal(value.getBytes(encoding));

Many thanks in advance

Gilles

By taking the SHA-256 hash of getSecretKey().getBytes("UTF-8") you are guaranteed to get a 256-bit AES key no matter the size of the String returned by getSecretKey() . This is a useful property. The programmer is essentially using SHA-256 as an ad-hoc key derivation function (KDF). However, there are carefully designed KDFs designed by cryptographers that are better choices. For example, if the value returned by getSecretKey() is a password or something like a password then a password hashing algorithm like PBKDF2 , bcrypt , or argon2 would be a better choice.

The significant difference is, that in the above code a hash (SHA-256) of getSecretKey() is applied to construct the AES-key.

In the below code getSecretKey() is taken raw/applied directly.

...the above i would consider as "more secure";)

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