NodeJs - subtleCrypto.decrypt() Method


The NodeJS subtle.decrypt() method is used for decrypting the encrypted data with the help of cryptographic algorithms and returns a Promise that resolves with the data decrypted.

The output data format may depend on the input and the algorithm used for decryption. It may be a string, byte array, or any other format that is defined by the decryption algorithm.

Usually, this method is used in web applications to manage data that cannot be disclosed to other users such as passwords or private messages.

Syntax

Following is the syntax of the NodeJs SubtleCrypto.decrypt() method −

SubtleCrypto.decrypt(algorithm, key, data)

Parameters

This method accepts three parameters listed below −

  • algorithm: This parameter specifies the cryptographic algorithm that used for decryption.
  • key: This is the cryptographic key used for decryption. The key should match the one used for encryption.
  • data: The encrypted data that needs to be decrypted. This will be in the form of a byte array or a buffer.

Return value

This method returns a 'Promise' that resolves with the decrypted data as an ArrayBuffer.

Example

Following is the program of NodeJs SubtleCrypto.decrypt() Method is designed to decrypt data that was previously encrypted using the AES-GCM algorithm. It uses a 256-bit secret key (provided in hexadecimal format), an initialization vector (IV) (also in hexadecimal format), and optional associated data (AAD) for decryption.

const crypto = require('crypto');

async function decryptAesGcm(ciphertext, key, iv, aad) {
   try {
      console.log('Key:', key);
      console.log('Key length (hex characters):', key.length);
      
      const keyBuffer = Buffer.from(key, 'hex');
      const ivBuffer = Buffer.from(iv, 'hex');
      const aadBuffer = Buffer.from(aad, 'hex');
      
      if (keyBuffer.length !== 32) {
          throw new Error(`Invalid key length. Key must be 32 bytes (256 bits). Current length: ${keyBuffer.length} bytes.`);
      }
      
      if (ivBuffer.length !== 12) {
          throw new Error('Invalid initialization vector length. IV must be 12 bytes.');
      }
      
      const ciphertextBuffer = Buffer.from(ciphertext, 'hex');
      const authTag = ciphertextBuffer.slice(-16);
      const encryptedData = ciphertextBuffer.slice(0, -16);
      
      const decipher = crypto.createDecipheriv('aes-256-gcm', keyBuffer, ivBuffer);
      decipher.setAAD(aadBuffer);
      decipher.setAuthTag(authTag);
      
      const decryptedText = Buffer.concat([
          decipher.update(encryptedData),
          decipher.final()
      ]).toString('utf8');
   
       return decryptedText;
   } catch (error) {
      console.error('Error during decryption:', error.message);
      throw error; 
   }
}

const ciphertext = '1232tutorialspoint1321332'; 
const key = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; // Your secret key (hex format), should be 64 hex characters (32 bytes)
const iv = '1234567890abcdef12345678'; 
const aad = '...'; // Associated data (hex format)

(async () => {
    try {
        const decryptedText = await decryptAesGcm(ciphertext, key, iv, aad);
        console.log('Decrypted text:', decryptedText);
    } catch (error) {
        console.error('Decryption failed:', error.message);
    }
})();

Output

The above program produces the following output −

Key: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
Key length (hex characters): 64

Error during decryption: Invalid authentication tag length: 2
Decryption failed: Invalid authentication tag length: 2
nodejs_crypto.htm
Advertisements