I am using the javascript WebCrypto API window.crypto.subtle.deriveKey()
API to generate HMAC keys like this:
this.key = await window.crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt: someSalt,
iterations: 50000,
hash: "SHA-1"
},
keyMaterial,
// default length value!
{ name: "HMAC", hash:"SHA-256"},
true,
[ "sign", "verify" ]
);
now, here is what the documentation on the MDN site https://developer.mozilla.org/en-US/docs/Web/API/HmacKeyGenParams mentions about the key length:
HmacKeyGenParams
The HmacKeyGenParams dictionary of the Web Crypto API represents the object that should be passed as the algorithm parameter into SubtleCrypto.generateKey(), when generating a key for the HMAC algorithm.
Properties
name
A DOMString. This should be set to HMAC.
hash
A DOMString representing the name of the digest function to use. You can pass any of SHA-1, SHA-256, SHA-384, or SHA-512 here.
length Optional
A Number — the length in bits of the key.
If this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen.
Unless you have a good reason to use a different length, omit this property and use the default.
It basically says that the default length of the key is the length of the digest (in bits).
I was expecting a key length equal to 256 bits assuming that the digest size in bits for SHA256 is 256. However, dumping the object returned by deriveKey()
into the developer console reveals a length of 512 bits (both for chrome and firefox - pretty recent versions).
Leaving apart that this kind of issues are difficult to discover and debug (since initially you see that some message digest computed somewhere else does not match the one computed in the browser), after fixing the issue (by using an explicit length of 256 bits) there are some things which I still do not understand:
- Which standard recommends the key length for HMAC based signing, authentication aso?
- Is there a bug in the WebCrypto API documentation or in its implementation?
- Which is the optimal/recommended key length for HMAC(SHA256) based signing?
deriveKey()
is documented here on the MDN site:
https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/deriveKey