Skip to content

Instantly share code, notes, and snippets.

@samermurad
Last active January 10, 2020 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samermurad/700a3653d49a7d5e583562bc689fed42 to your computer and use it in GitHub Desktop.
Save samermurad/700a3653d49a7d5e583562bc689fed42 to your computer and use it in GitHub Desktop.
Nodejs Basic aes256 encrypt decrypt implementation
const crypto = require('crypto');
const TAG = 'cryptor || '
/**
* @typedef CryptResult
* @property {string} iv
* @property {string} crypt
*/
/**
* @description AES256 Encryption
* @param {string} key Secret Key
* @param {string} plain utf8 text to encrypt
* @return {Promise<CryptResult>}
*/
exports.encrypt = async (key, plain) => new Promise((resolve, reject) => {
const funcName = 'encrypt';
try {
const _key = Buffer.from(key).toString('hex').slice(0, 32);
const iv = crypto.randomBytes(16).toString('hex').slice(0, 16);
const cipher = crypto.createCipheriv('aes256', _key, iv);
let crypt = cipher.update(plain, 'utf8', 'hex');
crypt += cipher.final('hex');
resolve({
crypt,
iv,
});
} catch (e) {
console.log(TAG, funcName, e);
reject(e);
}
});
/**
* @description AES256 Decryption
* @param {string} key Secret Key
* @param {string} iv Encrypted IV from the corespondent encryption
* @param {string} crypt Encrypted data
* @return {Promise<string>}
*/
exports.decrypt = async (key, iv, crypt) => new Promise((resolve, reject) => {
const funcName = 'decrypt';
try {
const _key = Buffer.from(key).toString('hex').slice(0, 32);
const chiper = crypto.createDecipheriv('aes256', _key, iv);
let decoded = chiper.update(crypt, 'hex', 'utf8');
decoded += chiper.final('utf8');
resolve(decoded);
} catch (e) {
console.log(TAG, funcName, e);
reject(e);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment