Skip to content

Instantly share code, notes, and snippets.

@volodalexey
Created April 9, 2019 11:46
Show Gist options
  • Save volodalexey/23aa2774c82e4b95ac9b7ffe83033cfd to your computer and use it in GitHub Desktop.
Save volodalexey/23aa2774c82e4b95ac9b7ffe83033cfd to your computer and use it in GitHub Desktop.
Encrypt or decrypt text with NodeJS
const crypto = require('crypto');

const ALGORITM = 'aes-256-cbc';
const RAW_ENCODING = 'utf8';
const ENCRYPTED_ENCODING = 'hex';

function encryptAsync(password, data) {
  return new Promise((resolve, reject) => {
    try {
      const strData = JSON.stringify(data);
      const cipher = crypto.createCipher(ALGORITM, password);
      const encrypted = [
        cipher.update(strData, RAW_ENCODING, ENCRYPTED_ENCODING),
        cipher.final(ENCRYPTED_ENCODING)
      ].join('');
      resolve(encrypted)
    } catch (err) {
      reject(err);
    }
  });
}

function decryptAsync(password, strData) {
  return new Promise((resolve, reject) => {
    try {
      const decipher = crypto.createDecipher(ALGORITM, password);
      const decrypted = [
        decipher.update(strData, ENCRYPTED_ENCODING, RAW_ENCODING),
        decipher.final(RAW_ENCODING),
      ].join('');
      resolve(JSON.parse(decrypted));
    } catch (err) {
      reject(err);
    }
  });
}

const password = 'dd';
encryptAsync(password, 'fofof')
  .then(encrypted => {
    console.log('encrypted', encrypted)
    return decryptAsync(password, encrypted).then(decripted => {
      console.log(decripted)
    })
  }).catch(err => {
    console.error(err);
    process.exit(1)
  })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment