Last active
January 10, 2020 13:57
-
-
Save samermurad/700a3653d49a7d5e583562bc689fed42 to your computer and use it in GitHub Desktop.
Nodejs Basic aes256 encrypt decrypt implementation
This file contains hidden or 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 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