Created
October 12, 2021 10:59
-
-
Save ismummy/f3db08dfc56b8a62cf06f74292009ca0 to your computer and use it in GitHub Desktop.
AES-ENCRYPTION-DESCRIPTION IN NODEJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const crypto = require('crypto'); | |
const ENCRYPTION_KEY = ''//16/32 characters | |
const IV_KEY = '' //16 charactere | |
function getAlgorithm(key) { | |
switch (key.length) { | |
case 16: | |
return 'aes-128-cbc'; | |
case 32: | |
return 'aes-256-cbc'; | |
} | |
throw new Error('Invalid key length: ' + key.length); | |
} | |
function encrypt(text) { | |
const key = new Buffer.from(ENCRYPTION_KEY) | |
const iv = new Buffer.from(IV_KEY) | |
let cipher = crypto.createCipheriv(getAlgorithm(ENCRYPTION_KEY), key, iv); | |
let encrypted = cipher.update(text); | |
encrypted = Buffer.concat([encrypted, cipher.final()]); | |
return iv.toString('hex') + ':' + encrypted.toString('hex'); | |
} | |
function decrypt(text) { | |
let textParts = text.split(':'); | |
let iv = Buffer.from(textParts.shift(), 'hex'); | |
let encryptedText = Buffer.from(textParts.join(':'), 'hex'); | |
let decipher = crypto.createDecipheriv(getAlgorithm(ENCRYPTION_KEY), new Buffer.from(ENCRYPTION_KEY), iv); | |
let decrypted = decipher.update(encryptedText); | |
decrypted = Buffer.concat([decrypted, decipher.final()]); | |
return decrypted.toString(); | |
} | |
console.log(encrypt('hello')) | |
console.log(decrypt(encrypt('hello'))) | |
module.exports = {decrypt, encrypt}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment