Why is SecretKeySpec necessary when retrieving a key from a Java password?

What is the difference between SecretKey vs SecretKeySpec in Java?

The SecretKeySpec documentation says:

it can be used to create SecretKey from an array of bytes

In this code, if I type secretKey.getEncoded() or secret.getEncoded() in hexadecimal, both give the same output. So why do we need SecretKeySpec ?

 final String password = "test"; int pswdIterations = 65536 ; int keySize = 256; byte[] ivBytes; byte[] saltBytes = {0,1,2,3,4,5,6}; SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); PBEKeySpec spec = new PBEKeySpec( password.toCharArray(), saltBytes, pswdIterations, keySize ); SecretKey secretKey = factory.generateSecret(spec); SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(),"AES"); 

Here is the output of both calls to getEncoded() :

00367171843C185C043DDFB90AA97677F11D02B629DEAFC04F935419D832E697

+7
java cryptography jce secret-key
source share
3 answers

Each SecretKey has an associated algorithm name. You cannot use SecretKey with the "DES" in a context where, for example, an AES key is required.

In your code, the following line creates SecretKey :

 SecretKey secretKey = factory.generateSecret(spec); 

However, at this point, the key is not an AES key. If you were to call secretKey.getAlgorithm() , the result would be "PBKDF2WithHmacSHA1" . You need to somehow tell Java that this is actually an AES key.

The easiest way to do this is to create a new SecretKeySpec object using the key's original data and explicitly specifying the algorithm name:

 SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(),"AES"); 

Note. I would personally declare a secret as SecretKey , since I do not think that after that you will need to take care of a specific implementation.

+10
source share

SecretKey is just an interface that requires implementation of a specific provider. SecretKeySpec is a concrete class that makes it easy to create SecretKey from existing key material. So, to get SecretKey, you need to use the corresponding factory class or SecretKeySpec as a shortcut.

+7
source share

SecretKey is the interface, and SecretKeySpec is the implementation of SecretKey

+3
source share

All Articles