Open In App

Node.js cipher.getAuthTag() Method

Last Updated : 28 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The cipher.getAuthTag() method returns a buffer containing the authentication tag that has been computed from the given data. This method should be called after using the final method.

The Buffer objects are used for representing the fixed length of the sequence of bytes.

Syntax:

cipher.getAuthTag()

Parameters: This method does not accept any parameter.

Return Value: This method returns a buffer that contains the authentication tag that has been computed from the given data.

Example 1: In the below example, we will print the buffer on the console screen.

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


Output:

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

Example 2:  In the below example, We will be called the getAuthTag() method before the final method. 

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


Output: In this example, we will get an error as follow.  

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

Reference: https://nodejs.org/api/crypto.html#ciphergetauthtag



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads