• Node.js Video Tutorials

Node.js - subtleCrypto.decrypt() 方法


NodeJS 的subtle.decrypt() 方法用于使用加密算法解密加密数据,并返回一个 Promise,该 Promise 解析为解密后的数据。

输出数据的格式可能取决于输入和用于解密的算法。它可以是字符串、字节数组或解密算法定义的任何其他格式。

通常,此方法用于 Web 应用程序中管理不能泄露给其他用户的数据,例如密码或私人消息。

语法

以下是 NodeJS SubtleCrypto.decrypt() 方法的语法:

SubtleCrypto.decrypt(algorithm, key, data)

参数

此方法接受以下三个参数:

  • algorithm:此参数指定用于解密的加密算法。
  • key:这是用于解密的加密密钥。密钥应与用于加密的密钥匹配。
  • data:需要解密的加密数据。这将采用字节数组或缓冲区的形式。

返回值

此方法返回一个 Promise,该 Promise 解析为一个 ArrayBuffer 形式的解密数据。

示例

以下程序演示了NodeJS SubtleCrypto.decrypt() 方法,该方法旨在解密先前使用 AES-GCM 算法加密的数据。它使用 256 位密钥(以十六进制格式提供)、初始化向量 (IV)(也以十六进制格式提供)和可选的关联数据 (AAD) 进行解密。

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);
    }
})();

输出

上述程序产生以下输出:

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
广告
© . All rights reserved.