Node crypto.createCipheriv() Method
Last Updated :
15 Jan, 2024
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:
- algorithm: It is a string-type value that dependent on OpenSSL. The examples are aes192, aes256, etc.
- key: It is the raw key that is used by the algorithm and iv.
- iv: It is an initialization vector that must be uncertain and very unique. However, an ideal iv will be cryptographically random. It don’t need to be secret.
- options: It is an optional parameter that is used to control stream behavior. It is optional except when a cipher is used in CCM or OCB mode(e.g. ‘aes-128-ccm’).
Return Value: It returns Cipher object.
Example 1: Below examples illustrate the use of crypto.createCipheriv() method in NodeJs:
Javascript
const crypto = require( 'crypto' );
const algorithm = 'aes-256-cbc' ;
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
function encrypt(text) {
let cipher = crypto.createCipheriv(
'aes-256-cbc' , Buffer.from(key), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return {
iv: iv.toString( 'hex' ),
encryptedData: encrypted.toString( 'hex' )
};
}
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:
Javascript
const crypto = require( 'crypto' );
const algorithm = 'aes-192-cbc' ;
const password = 'bncaskdbvasbvlaslslasfhj' ;
const key = crypto.scryptSync(password, 'GfG' , 24);
const iv = Buffer.alloc(16, 0);
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = '' ;
cipher.on( 'readable' , () => {
let chunk;
while ( null !== (chunk = cipher.read())) {
encrypted += chunk.toString( 'base64' );
}
});
cipher.on( 'end' , () => {
console.log(encrypted);
});
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...