• 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.