crypto 32 characers encryption node js
const crypto = require('crypto');
function encrypt(text, key) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return iv.toString('hex') + ':' + encrypted.toString('hex');
}
function decrypt(text, key) {
const textParts = text.split(':');
const iv = Buffer.from(textParts.shift(), 'hex');
const encryptedText = Buffer.from(textParts.join(':'), 'hex');
const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
const secretMessage = 'This is a secret message!';
const encryptionKey = 'MySuperSecretKey';
const encryptedMessage = encrypt(secretMessage, encryptionKey);
console.log('Encrypted:', encryptedMessage);
const decryptedMessage = decrypt(encryptedMessage, encryptionKey);
console.log('Decrypted:', decryptedMessage);
Explanation:
Import the
crypto
module in Node.js to access cryptographic functionalities.Create an
encrypt
function that takes plaintext and a key as input parameters. Inside the function: a. Generate a random initialization vector (IV) usingcrypto.randomBytes(16)
. IVs are used to ensure different ciphertexts are generated even if the same plaintext is encrypted multiple times with the same key. b. Create a cipher object usingcrypto.createCipheriv
with the 'aes-256-cbc' algorithm, passing the key and IV as parameters. c. Encrypt the plaintext using the cipher'supdate
method and concatenate it with the final ciphertext obtained from thefinal
method. d. Return a string that combines the IV and encrypted text in hexadecimal format, separated by a colon.Create a
decrypt
function that takes the encrypted text and a key as input parameters. Inside the function: a. Split the inputtext
into two parts using the colon (':') separator to separate the IV and encrypted text. b. Convert the IV string to a Buffer usingBuffer.from
with 'hex' encoding. c. Convert the encrypted text string to a Buffer usingBuffer.from
with 'hex' encoding. d. Create a decipher object usingcrypto.createDecipheriv
with the 'aes-256-cbc' algorithm, passing the key and IV as parameters. e. Decrypt the encrypted text using the decipher'supdate
method and concatenate it with the final decrypted plaintext obtained from thefinal
method. f. Return the decrypted plaintext as a string.Define a
secretMessage
and anencryptionKey
.Encrypt the
secretMessage
using theencrypt
function with theencryptionKey
and log the encrypted message to the console.Decrypt the encrypted message using the
decrypt
function with theencryptionKey
and log the decrypted message to the console.