Open In App

Node crypto.createCipheriv() Method

The crypto.createCipheriv() method is an inbuilt application programming interface of the crypto module which is used to create a Cipher object, with the stated algorithm, key, and initialization vector (iv).
Syntax: 

crypto.createCipheriv( algorithm, key, iv, options )

Parameters: This method accepts four parameters as mentioned above and described below:  



Return Value: It returns Cipher object.

Example 1: Below examples illustrate the use of crypto.createCipheriv() method in NodeJs:






// Node.js program to demonstrate the    
// crypto.createCipheriv() method
 
// Includes crypto module
const crypto = require('crypto');
 
// Defining algorithm
const algorithm = 'aes-256-cbc';
 
// Defining key
const key = crypto.randomBytes(32);
 
// Defining iv
const iv = crypto.randomBytes(16);
 
// An encrypt function
function encrypt(text) {
 
    // Creating Cipheriv with its parameter
    let cipher = crypto.createCipheriv(
        'aes-256-cbc', Buffer.from(key), iv);
 
    // Updating text
    let encrypted = cipher.update(text);
 
    // Using concatenation
    encrypted = Buffer.concat([encrypted, cipher.final()]);
 
    // Returning iv and encrypted data
    return {
        iv: iv.toString('hex'),
        encryptedData: encrypted.toString('hex')
    };
}
 
// Displays output
var output = encrypt("GeeksforGeeks");
console.log(output);

Output: 

{ iv: 'fb1f4b0a7daaada6cae678df32fad0f0',
encryptedData: '41aad2618892aa3d1850d336ad15b50e' }

Example 2: Below examples illustrate the use of crypto.createCipheriv() method in NodeJs:




// Node.js program to demonstrate the    
// crypto.createCipheriv() method
 
// Includes crypto module
const crypto = require('crypto');
 
// Defining algorithm
const algorithm = 'aes-192-cbc';
 
// Defining password
const password = 'bncaskdbvasbvlaslslasfhj';
 
// Defining key
const key = crypto.scryptSync(password, 'GfG', 24);
 
// Defininf iv
const iv = Buffer.alloc(16, 0);
 
// Creating cipher
const cipher = crypto.createCipheriv(algorithm, key, iv);
 
// Declaring encrypted
let encrypted = '';
 
// Reading data
cipher.on('readable', () => {
    let chunk;
    while (null !== (chunk = cipher.read())) {
        encrypted += chunk.toString('base64');
    }
});
 
// Handling end event
cipher.on('end', () => {
    console.log(encrypted);
});
 
// Writing data
cipher.write('CS-Portal');
cipher.end();
console.log("done");

Output: 

done
MfHwhG/WPv+TIbG/qM78qA==

We have a Cheat Sheet on Nodejs crypto methods where we covered all the crypto methods to check those please go through Node Crypto Module Complete Reference this article.


Article Tags :