Node.js keyObject.asymmetricKeyType Property
The keyObject.asymmetricKeyType property identifies the key type for us. The key type is essentially the name of the algorithm used to construct the key instance.
The crypto module in Node.js allows us to create a crypto key instance and corresponding key object with the help of various cryptographic algorithms.
Assuming the “RSA” algorithm is used to generate the asymmetric key (public and private key), this property returns RSA.
Syntax: The following is the syntax for the keyObject.asymmetricKeyType property. This property works on the crypto key objects.
To demonstrate the use of this property we will create a crypto key object using the keyObject() method.
The following are the necessary steps to know the type of key object:
Step 1: Generate the cryptographic keys using the subtle.generateKey() method. This method generates symmetric or asymmetric keys based on the specified algorithm.
The following is the syntax for generating a crypto key instance:
const key = generateKey( algorithm : Object, extractable : boolean, keyUsages : array );
- Algorithm: The object specifies the type of key to generate and other algorithm details.
- Extractable: A boolean variable that indicates whether the key can be exported using a particular technique such as SubtleCrypto.exportKey(). If true, keys cannot be exported.
- Keyusages: An array listing instructions for using the generated key.
Returns: Crypto Key Instance.
Step 2: Convert this crypto key instance into KeyObject using the KeyObject.from(key) method. This method takes a single key instance either a public or a private key from the group of asymmetric keys and generates a corresponding KeyObject. The following is the syntax for this method:
keyObject.form( key );
- Key: a single key instance. ( symmetric or asymmetric key)
Step 3: Now we have created a KeyObject and can use the keyObject.asymmetricKeyType on the generated KeyObject to get the type of the generated KeyObject.
The following is the syntax for the keyObject.asymmetricKeyType property:
Returns: This property returns a string telling us the type of the key.
Let’s understand the topic with the examples:
Example 1: In this example, the ‘RSA-PSS’ algorithm is used to generate the crypto key instances. This algorithm requires two keys – public and private keys. Following the above-discussed steps – generating crypto key instances, converting crypto key instances into KeyObject, and applying the property keyObject_name.asymmetricKeyType:
The key is of type RSA which means RSA cryptographic algorithm is used to generate the key instance.
Example 2: In this example, the ‘ECDSA’ algorithm is used to generate the crypto key instances
privet_key_object.asymmetricKeyType: ec public_key_object.asymmetricKeyType: ec
The key is of type EC (Elliptic curve) which means the Elliptic curve cryptographic algorithm is used to generate the key instance.
Please Login to comment...