Im trying to figure out why should I use createSecretKey
in crypto module instead of string.
What difference between this:
const secret = crypto.createSecretKey('mysupersecret'); // Creates SecretKeyObject
hmac = crypto.createHmac('sha256', secret);
hash = hmac.update('somemessage').digest('hex');
console.log(hash);
and this:
const secret = 'mysupersecret'; // just string
hmac = crypto.createHmac('sha256', secret);
hash = hmac.update('somemessage').digest('hex');
console.log(hash);
Both output: 81a86a988a751d4523ebc1ccb3150b094ef7d51a0fbe111600d1832c6de68f9f
Does SecretKeyObject
provides any benefits?
Using createSecretKey
improves security of my code?
The createSecretKey
adds additional security benefits by returning an instance of the KeyObject
class.
From the documentation https://nodejs.org/api/crypto.html#:~:text=Class%3A-,KeyObject,-%23
Node.js uses a KeyObject class to represent a symmetric or asymmetric key, and each kind of key exposes different functions. The crypto.createSecretKey() ... KeyObject objects are not to be created directly using the new keyword.
One example is of a benefit of using the KeyObject class: