Open In App
Related Articles

Node.js cipher.final() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

The cipher.final() method in Node.js is used to signal to the cipher object that the encryption or decryption process is complete. This method must be called after all data has been passed to the cipher object using the cipher.update() method.

The cipher.final() method returns the remaining encrypted or decrypted data as a Buffer object. If the outputEncoding parameter was specified when creating the cipher object, the returned Buffer will be automatically encoded using the specified encoding.

Syntax:

const cipher.final([outputEncoding])

Parameters: This method takes the output encoding as a parameter.

Return Value: This method returns the object of the buffer containing the cipher value.

Example 1: Filename: index.js

Javascript

// Node.js program to demonstrate the
// cipher.final() method
 
// Importing crypto module
const crypto = require('crypto');
 
// Creating and initializing algorithm and password
const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
 
// Getting key for the cipher object
const key = crypto.scryptSync(password, 'salt', 24);
 
// Creating and initializing the static iv
const iv = Buffer.alloc(16, 0);
 
// Creating and initializing the cipher object
const cipher = crypto.createCipheriv(algorithm, key, iv);
 
// Getting buffer value
// by using final() method
let value = cipher.final('hex');
 
// Display the result
console.log("buffer :- " + value);

                    

Output:

buffer :- b9be42878310d599e4e49e040d1badb9

Example 2: Filename: index.js

Javascript

// Node.js program to demonstrate the
// cipher.final() method
 
// Importing crypto module
const crypto = require('crypto');
 
// Creating and initializing algorithm and password
const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
 
// Getting key for cipher object
crypto.scrypt(password, 'salt', 24,
    { N: 512 }, (err, key) => {
 
        if (err) throw err;
 
        // Creating and initializing the static iv
        const iv = Buffer.alloc(16, 0);
 
        // Creating and initializing the cipher object
        const cipher = crypto
            .createCipheriv(algorithm, key, iv);
 
        // Getting buffer value
        // by using final() method
        let value = cipher.final('hex');
 
        // Display the result
        console.log("buffer :- " + value);
    });

                    

Output:

buffer :- 726cccfc7d80ca473d8d4de1a0a42675

Run the index.js file using the following command:

node index.js

Reference: https://nodejs.org/dist/latest-v12.x/docs/api/crypto.html#crypto_cipher_final_outputencoding



Last Updated : 15 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads