'use strict'; | |
const crypto = require('crypto'); | |
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY; // Must be 256 bits (32 characters) | |
const IV_LENGTH = 16; // For AES, this is always 16 | |
function encrypt(text) { | |
let iv = crypto.randomBytes(IV_LENGTH); | |
let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_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('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv); | |
let decrypted = decipher.update(encryptedText); | |
decrypted = Buffer.concat([decrypted, decipher.final()]); | |
return decrypted.toString(); | |
} | |
module.exports = { decrypt, encrypt }; |
Thanks @vlucas - If anyone having trouble using code, I did the following.
npm install crypto
Get your 32 character passkey, you can type it yourself or go here and generate it > make sure you change Password length to 32 https://passwordsgenerator.net/
Copy paste that 32 character string into your .env file
In your .env file, put
ENCRYPTION_KEY = 'paste your 32 character string here'
Now Cut and paste all code from above into a js file eg file.js
In the file you want to use the encrypt and decrypt, use import the code like as follows
const { decrypt, encrypt } = require('./file') // path to your code that was cut and paste
and to use it test it out
let data = encrypt('hello') console.log(data) // you will see the encrypted string let dataD = decrypt(data) console.log(dataD) // you will see the decrypted string 'hello'
Link Updated Password Generator: http://passwordsgenerators.net/
The password generator that you included doesn't load anymore. You can try this one.
https://passwords-generator.org
I am unable to run the code.....whenever I am entering the string.....it gives me an error...
made this package a while ago for server side encrypted payloads to use for backend only: https://www.npmjs.com/package/encryption.js
@music2code Any luck on your problem? I am in same situation.