Sign HmacSHA256 - is algorithm irrelevant?

Luís Soares :

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).

Karol Dowbecki :

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;

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=144204&siteId=1