Skip to content

Instantly share code, notes, and snippets.

@quilicicf
Created May 27, 2020 07:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quilicicf/5b69fe665e81714d2c220a50949f04b5 to your computer and use it in GitHub Desktop.
Save quilicicf/5b69fe665e81714d2c220a50949f04b5 to your computer and use it in GitHub Desktop.
NodeJS AES encryption/decryption service with IV
const crypto = require('crypto');
const ALGORITHM = 'aes256';
const DECRYPTED_ENCODING = 'utf8';
const ENCRYPTED_ENCODING = 'hex';
// Makes sure to have a secret with the right size by hashing it and taking a substring of the hash.
// I'm not sure whether this is cryptographically secure, don't use in production.
const hashSecret = secret => crypto
.createHash('sha256')
.update(String(secret))
.digest('base64')
.substr(0, 32);
module.exports = {
encrypt (content, secret) {
const ivBuffer = crypto.randomBytes(16);
const secretHash = hashSecret(secret);
const cipher = crypto.createCipheriv(ALGORITHM, secretHash, ivBuffer);
return {
password: cipher.update(content, DECRYPTED_ENCODING, ENCRYPTED_ENCODING) + cipher.final(ENCRYPTED_ENCODING),
iv: ivBuffer.toString(ENCRYPTED_ENCODING),
};
},
decrypt ({ password, iv }, secret) {
const ivBuffer = Buffer.from(iv, ENCRYPTED_ENCODING);
const secretHash = hashSecret(secret);
const decipher = crypto.createDecipheriv(ALGORITHM, secretHash, ivBuffer);
return decipher.update(password, ENCRYPTED_ENCODING, DECRYPTED_ENCODING) + decipher.final(DECRYPTED_ENCODING);
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment