Node.js cipher.setAAD() 方法

Node.js cipher.setAAD() 方法

cipher.setAAD() 方法用于在Node.js中为加密/解密流设置附加身份验证数据(AAD)。AAD是一块经过身份验证但未加密的数据块。它对于发送与加密消息并需进行身份验证但不需保密的数据很有用。

语法:

cipher.setAAD(aad[, options]);

参数: cipher.setAAD() 方法接受两个参数:

  • aad: 一个包含额外认证数据的缓冲区或TypedArray。
  • options: (可选)一个包含设置AAD选项的对象。该对象可以包含plaintextLength属性,指定将要加密的明文数据的长度(以字节为单位)。

示例1: 在下面的示例中,cipher.setAAD() 方法用于将额外认证数据设置为已认证但未加密的数据。当数据被加密时,AAD将被认证但不包含在加密输出中。

const crypto = require('crypto'); 
const iv = Buffer.alloc(16, 0); 
const key = Buffer.alloc(32, 1); 
const aad = Buffer.from('authenticated but not encrypted data'); 
  
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); 
cipher.setAAD(aad); 
  
const encrypted = 
    cipher.update('some secret data', 'utf8', 'hex') + cipher.final('hex'); 
console.log(encrypted);

输出:

02c5112376449247c35e9c3cea4242fd

示例2: 这个示例使用aes-256-gcm算法创建一个新的 cipher 对象,并使用 setAAD() 方法设置一些额外的认证数据(AAD)。然后使用 getAuthTag() 方法加密一些数据并生成身份验证标签。该示例使用utf8编码来处理输入和输出数据,但根据您的需求,您可以使用任何支持的编码选项(如hex、base64等)。

const crypto = require('crypto'); 
  
async function main() { 
    // Generate a random key and iv 
    const key = crypto.randomBytes(32); 
    const iv = crypto.randomBytes(16); 
  
    // Create a new cipher object 
    const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); 
  
    // Set the AAD (additional authenticated data) 
    cipher.setAAD(Buffer.from('some additional data')); 
  
    // Encrypt some data 
    const encrypted = cipher.update 
        ('some data to encrypt', 'utf8', 'hex'); 
    encrypted += cipher.final('hex'); 
  
    // Generate the authentication tag 
    const tag = cipher.getAuthTag(); 
  
    // Create a new decipher object 
    const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv); 
  
    // Set the AAD and authentication tag 
    decipher.setAAD(Buffer.from('some additional data')); 
    decipher.setAuthTag(tag); 
  
    // Decrypt the data 
    const decrypted = decipher.update(encrypted, 'hex', 'utf8'); 
    decrypted += decipher.final('utf8'); 
  
    console.log(decrypted); 
} 
  
main();

输出:

some data to encrypt

参考: https://nodejs.org/api/crypto.html

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程