Node.js cipher.getAuthTag() 方法
该方法返回一个缓冲区,其中包含从给定数据计算得出的身份验证标签。此方法应在使用最终方法之后调用。
Buffer对象用于表示字节序列的固定长度。
语法:
cipher.getAuthTag()
参数: 该方法不接受任何参数。
返回值: 该方法返回一个缓冲区,该缓冲区包含从给定数据计算出的身份验证标签。
示例1: 在下面的示例中,我们将在控制台屏幕上打印输出缓冲区。
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()方法。
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);
输出: 在这个示例中,我们将得到以下错误。
“`javascript
node:internal/crypto/cipher:213
throw new ERR_CRYPTO_INVALID_STATE('getAuthTag');
“`
参考: https://nodejs.org/api/crypto.html#ciphergetauthtag