当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js cipher.getAuthTag()用法及代码示例


cipher.getAuthTag() 方法返回一个缓冲区,其中包含根据给定数据计算出的身份验证标签。该方法应该在使用final方法之后调用。

Buffer 对象用于表示固定长度的字节序列。

用法:

cipher.getAuthTag()

Parameters: 该方法不接受任何参数。

返回值:此方法返回一个缓冲区,其中包含根据给定数据计算出的身份验证标记。

示例 1:在下面的示例中,我们将在控制台屏幕上打印缓冲区。

Javascript


const crypto = require('crypto'),
    algorithm = 'aes-256-gcm',
    password = '3zTvzr3p67VC61jmV54rIYu1545x4TlY',
    // Do not use a global iv for production, 
    // generate a new one for each encryption
    iv = '60iP0h6vJoEa'
function encrypt(text) {
    let cipher = crypto.createCipheriv(algorithm, password, iv)
    let encrypted = cipher.update(text, 'utf8', 'hex')
    encrypted += cipher.final('hex');
    let tag = cipher.getAuthTag();
    return {
        content: encrypted,
        tag: tag
    };
}
let output = encrypt("GeeksforGeeks")
//  Here, we are printing the tag and content.
// Content is Encrypted 
console.log(output);

输出:

{
    content: '57e625f9675b265c32a86966eb',
     tag: <Buffer df e6 cc ff 9e 70 47 2e 66 4a f0 ba 08 53 17 b5>
}

示例2:在下面的示例中,我们将在最终方法之前调用getAuthTag()方法。

Javascript


const crypto = require('crypto'),
    algorithm = 'aes-256-gcm',
    password = '3zTvzr3p67VC61jmV54rIYu1545x4TlY',
    // Do not use a global iv for production, 
    // generate a new one for each encryption
    iv = '60iP0h6vJoEa'
function encrypt(text) {
    let cipher = crypto.createCipheriv(algorithm, password, iv)
    let encrypted = cipher.update(text, 'utf8', 'hex')
    let tag = cipher.getAuthTag();
    encrypted += cipher.final('hex');
    return {
        content: encrypted,
        tag: tag
    };
}
let output = encrypt("GeeksforGeeks")
//  Here, we are printing the tag and content. 
// Content is Encrypted 
console.log(output);

输出:在此示例中,我们将收到如下错误。

node:internal/crypto/cipher:213
 throw new ERR_CRYPTO_INVALID_STATE('getAuthTag');
 

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



相关用法


注:本文由纯净天空筛选整理自neeraj3304大神的英文原创作品 Node.js cipher.getAuthTag() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。