Open In App

Node.js keyObject.type Class

Last Updated : 06 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In NodeJS, the KeyObject class represents algorithm-specific keys and contains built-in functions or methods for working with cryptographic key instances.

KeyObject.from(key): This is a static method built into the keyObject class. Used to generate a key object from a cryptographic key or key pair.

Syntax: The syntax for converting a cryptographic key instance to key object form is:

keyObject.form( key )
  • key: symmetric or asymmetric key
  • keyObject.type: KeyObject’s type method Indicates whether the generated key is private, public, or private. For symmetric keys, the keyObject.type returns secret because the same key is used for both encryption and decryption. When using asymmetric keys, two different keys (public and private) are used for encryption and decryption. The public key is known to everyone, but the private key is kept private, so this method returns type private for the private key keyObject and public for the public key keyObject.

Step 1: Run the following command in your terminal to set up your Node.js project package.json:

npm init

Step 2: Create an app.js file that describes the code.

Step 3: Now import the required classes or packages from the crypto module NodeJS. 

Step 4: The Subtle.generateKey() method returns a cryptographic key (either a symmetric key or an asymmetric key pair).

Syntax: The following is the syntax for subtle.generateKey() method:

const key = generateKey(algorithm : Object , extractable : boolean , keyUsages : array);

Parameters:

  • Algorithm: An object specifies the kind of key we want to generate as well as further algorithmic details.
  • Extractable: A boolean variable that represents whether or not the key may be exported by specific techniques such as SubtleCrypto.exportKey (). The key cannot be exported if true.
  • Keyusages: An array that lists the steps that must be taken in order to use the created key. 

These are the potential values:

Index

Values

Description

1 [‘sign’] It indicates that the key can be used to generate the digital signature.
2 [‘verify’] It indicates key will be used to verify the digital signature.
3 [‘encrypt’] It indicates key will be used to encrypt the conversation.
4 [‘decrypt’] It indicates key will be used to decrypt the conversation.
5 [‘deriveKey’] It indicates key will be used to derive the secret key.
6 [‘deriveBits’] It indicates key will be used to derive an array of bits.
7 [‘wrapKey’] It indicates exportable key will be in encrypted form.
8 [‘unwrapKey’] Itindicates exportable key will be in decrypted form.

Returns: An object contains the result value along with some additional information.

Step 5: Use the KeyObject.from(key) method and pass the generated cryptographic key value to this method to generate the keyObject.

Example 1: In this example, we will generate an encryption key using the “AES-CBS” algorithm, convert this encryption key to a keyObject, and check the type of this keyObject.

App.js

Javascript




//Importing the crypto module
const {
    webcrypto: { subtle }, KeyObject
} = require('node:crypto');
 
// Generating the crypto key that is
// not a keyObject.
(async function () {
    const k = await subtle.generateKey({
        // algorithm name
        name: 'AES-CBC',
        // length of key in bits.
        length: 192,
    },
        // not exportable.
        false,
        // key can be used in encryption and decryption.
        ['encrypt', 'decrypt']);
 
    // Converting cryptographic key into keyObject.
    const key_obj = KeyObject.from(k);
 
    // printing the type of keyObject.
    console.log(key_obj.type)
 
})();


Output: 

secret

Example 2: In this example, we will be generating Crypto key pairs of the public and private keys using the RSASSA-PKCS1-V1_5 Algorithm and for each crypto key – public and private running keyObject.type method.

Javascript




//Importing the crypto module
const { Console } = require('node:console');
const {
    webcrypto: { subtle }, KeyObject
} = require('node:crypto');
 
 
// async function
(async function () {
 
    // generating the crypto key
    // RSA Algorithm
    const k = await subtle.generateKey(
        {
            // Algorithm name.
            name: "RSASSA-PKCS1-v1_5",
            // Length of RSA modulus in bits (number of bits).      
            modulusLength: 4096,
            // Unit8Array -  consists of 8-bit unsigned integers.
            publicExponent: new Unit8Array([4, 5, 2]),
            // digital hash function
            hash: "SHA-256"
 
        }
        // Key is not exportable.
        , false,
        // Key can be used for generating and verifying
        // the digital signature.
        ['sign', 'verify']
    );
 
 
    // Generating keyObject for private Key
    const private_key_object = KeyObject.from(k.privateKey);
 
    // printing the type of private KeyObject
    console.log(private_key_object.type);
 
    // Generating keyObject for public Key
    const public_key_object = KeyObject.from(k.publicKey);
 
    // printing the type of public KeyObject
    console.log(public_key_object.type);
 
})();


Output:

private
public

Reference: https://nodejs.org/api/crypto.html#class-keyobject



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads