Last active
September 2, 2022 12:35
-
-
Save reegodev/d2da073df3959f5a2bb259873fa19e71 to your computer and use it in GitHub Desktop.
Node encryption/decryption with aes-256-gcm
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 assert = require('assert'); | |
const algorithm = 'aes-256-gcm'; | |
// From env | |
const password = 'CDcmzxwnDgJ581XYOJqBqWdbVDcdsSGr'; | |
const encrypt = (message, salt) => { | |
const iv = crypto.randomBytes(16); | |
// computationally expensive, if we could generate this before looping env variables | |
// it would make the process much faster | |
const key = crypto.scryptSync(password, salt, 32); | |
const cipher = crypto.createCipheriv(algorithm, key, iv); | |
const encrypted = cipher.update(message, 'utf8', 'hex') + cipher.final('hex'); | |
const authTag = cipher.getAuthTag(); | |
// Attach "iv" and "authTag" to the returned payload because they are needed for the decryption. | |
// They are not secret so they can safely be exposed. | |
return iv.toString('hex') + '|' + encrypted + '|' + authTag.toString('hex'); | |
}; | |
const decrypt = (payload, salt) => { | |
const [ iv, value, authTag ] = payload.split('|'); | |
// computationally expensive, if we could generate this before looping env variables | |
// it would make the process much faster | |
const key = crypto.scryptSync(password, salt, 32); | |
const decipher = crypto.createDecipheriv(algorithm, key, Buffer.from(iv, 'hex')); | |
decipher.setAuthTag(Buffer.from(authTag, 'hex')); | |
const decrypted = decipher.update(value, 'hex', 'utf8') + decipher.final('utf8'); | |
return decrypted; | |
}; | |
// User id | |
const salt = '18486db8-572f-4ad9-a22f-4ab18bca658c'; | |
const message = 'Hello world!'; | |
const encrypted = encrypt(message, password, salt); | |
const decrypted = decrypt(encrypted, password, salt); | |
assert.equal(message, decrypted); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment