Node.js keyObject.equals() Method
Last Updated :
14 Apr, 2023
The keyObject.equals() of the crypto module in Node.js, which allows you to compare two key objects. By default, this method returns a boolean indicating whether the keyObject passed is equal to the key object the method is applied to. This method makes decisions based on the key’s type, value, and parameters.
Syntax:
keyObject.equals(KeyObject);
Return Value: This method returns a boolean indicating whether the keyObject passed is equal to the key object the method is applied to.
We will now see some examples of keyObject.equals(otherKeyObject) method.
Example 1: Let’s create one more keyObject with the same Algorithm and attributes and compares the above one and this newly created keyObject using the keyObject.equals() method.
Javascript
const {
webcrypto: { subtle }, KeyObject
} = require( 'node:crypto' );
(async function () {
const k1 = await subtle.generateKey({
name: 'AES-CBC' ,
length: 192,
},
false ,
[ 'encrypt' , 'decrypt' ]);
const keyObject1 = KeyObject.from(k1);
const keyObject2 = KeyObject.from(k1);
result = keyObject1.equals(keyObject2);
console.log(result);
})();
|
Output: In the example above, two key objects were created using the same cryptographic key instance. Then I applied keyObject.equals() method to check if the two key objects are equal or not. The result is true because both the keyObjects are generated using the same crypto key instance. All the parameters and values are the same for both key Objects.
true
Example 2: Let’s create one more keyObject with different attributes and values. Compare both the keyObject.
Javascript
const {
webcrypto: { subtle }, KeyObject
} = require( 'node:crypto' );
(async function () {
const k1 = await subtle.generateKey({
name: 'AES-CBC' ,
length: 192,
},
false ,
[ 'encrypt' , 'decrypt' ]);
const k2 = await subtle.generateKey(
{
name: "HMAC" ,
hash: "SHA-256" ,
length: 256,
},
true ,
[ "sign" , "verify" ]
);
const keyObject1 = KeyObject.from(k1);
const keyObject2 = KeyObject.from(k2);
result = keyObject1.equals(keyObject2);
console.log(result);
})();
|
Output: In the above example, we have created two different key objects using two different crypto key Instances. We have used the AES algorithm to generate the first crypto key instance and the HMAC algorithm to generate the second key Instance. All the parameters and values are different for both the key objects so this method returns false.
false
Reference: https://nodejs.org/api/crypto.html#keyobjectequalsotherkeyobject
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...