Reputation: 6222
Why does this always work regardless of the second parameter of SecretKeySpec
? shouldn't it be a valid algorithm name? thanks
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "it does not matter what I put here. why?");
sha256_HMAC.init(secret_key);
String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
the question is: why the thing that I pass is irrelevant? the code always works properly regardless of what I pass as second argument (the algorithm name).
Upvotes: 2
Views: 216
Reputation: 5636
If you look at the code you will see that
public SecretKeySpec(byte[] key, String algorithm) {
...
this.algorithm = algorithm;
and on the header
@throws IllegalArgumentException
* if the key data or the algorithm name is null or if the key
* data is empty.
So SecretKeySpec
don't care the algorithm.
And when you init the MAC you will get error only
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this MAC.
public final void init(Key key) throws InvalidKeyException {
Upvotes: 1
Reputation: 44970
I suppose that this is just a coincidence because Java Cryptographic Architecture is based on the concept of providers. It looks like the default JDK providers for Mac
don't check the algorithm from SecretKeySpec
and depend entirely on the algorithm saved in Mac.algorithm
field.
You still should set the right algorithm in SecretKeySpec
because nothing stops a provider to check the key's algorithm. For example if you look at Mac.chooseProvider(Key key, AlgorithmParameterSpec params)
private method it passes the key to external code:
// if provider says it does not support this key, ignore it
if (s.supportsParameter(key) == false) {
continue;
}
Upvotes: 2