Recently I needed to store an encrypted value in a database table for a Cloudflare Worker. A simple way to do this was with AES and a passphrase.
Install dependency
crypto-js is required:
npm install crypto-js
Encryption
const cryptoJS = require('crypto-js');
const encrypt = (stringValue) => {
const passphrase = "sssh-its-a-secret";
return cryptoJS.AES.encrypt(stringValue, passphrase).toString();
};
Decryption
const cryptoJS = require('crypto-js');
const decrypt = (ciphertext) => {
const passphrase = "sssh-its-a-secret";
const bytes = cryptoJS.AES.decrypt(ciphertext, passphrase);
return bytes.toString(cryptoJS.enc.Utf8);
};
Example
const ciphertext = encrypt("don't be evil");
console.log(ciphertext);
// U2FsdGVkX1+WBqXF5xgowgP5ZubzrDBGYofLloWaafU=
const stringValue = decrypt(ciphertext);
console.log(stringValue)
// don't be evil
A non-dependency approach
Modern Node.js ships with a native Crypto module. A future post will show how to use that to achieve a similar result as above.