Last active
July 4, 2019 09:43
-
-
Save chonlatee/2c18d3dacc7c4dde38a36dbcdafae444 to your computer and use it in GitHub Desktop.
encrypt decrypt message with nodejs with algorithm aes-256-cbc
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 ALGORITHM_NAME = 'aes-256-cbc' | |
const ENCRYPT_KEY = 'e916e810f3858bffc8751581ca81a748' | |
const IV_LENGTH = 16 | |
const NONCE_LENGTH = 4 | |
const encryptString = (plainText) => { | |
const nonce = crypto.randomBytes(NONCE_LENGTH) | |
const iv = crypto.randomBytes(IV_LENGTH) | |
const cipher = crypto.createCipheriv(ALGORITHM_NAME, ENCRYPT_KEY, iv) | |
let encrypted = cipher.update(plainText, 'utf8', 'hex') | |
encrypted += cipher.final('hex') | |
const cipherText = Buffer.concat([iv, nonce, Buffer.from(encrypted, 'hex')]) | |
return cipherText.toString('hex') | |
} | |
const decryptString = (cipherText) => { | |
const cipherByte = Buffer.from(cipherText, 'hex') | |
const iv = cipherByte.slice(0, IV_LENGTH) | |
const originalText = cipherByte.slice(IV_LENGTH + NONCE_LENGTH, cipherByte.length) | |
let decipher = crypto.createDecipheriv(ALGORITHM_NAME, ENCRYPT_KEY, iv) | |
let decrypted = decipher.update(originalText.toString('hex'), 'hex', 'utf8') | |
decrypted += decipher.final('utf8') | |
return decrypted | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment