Skip to content

Instantly share code, notes, and snippets.

@Ugarz
Last active March 13, 2018 14:39
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 Ugarz/f01681e86125467c8cec211006045f15 to your computer and use it in GitHub Desktop.
Save Ugarz/f01681e86125467c8cec211006045f15 to your computer and use it in GitHub Desktop.
Using Crypto, the Node js module to encrypt passwords

How to use the Crypto module from Node js

This is a simple example, please consider using createHash instead for passwords in production

const crypto = require('crypto');
const passwordToEncrypt = "AP34IOUR+&"
const salt = "My Awesome Salt"

function encryptData(salt, passwordToEncrypt){
  const cipher = crypto.createCipher('aes256', salt);
  let encrypted = cipher.update(passwordToEncrypt, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return encrypted;
}


function decryptData(salt, encryptedPassword){
  const decipher = crypto.createDecipher('aes256', salt);
  let decrypted = decipher.update(encryptedPassword, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted
}

const encryptedData = encryptData(salt, passwordToEncrypt)
console.log('Encrypted Data :', encryptedData)

const decryptedData = decryptData(salt, encryptedPassword)
console.log('Decrypted Data :', decryptedData)

How to use the Crypto module from Node js

This is a simple example using createHash

// TODO
const crypto = require('crypto');
const salt = 'aZerTy!Osef'
const password = 'myAwesomePassword'
/**
* Encrypt Password with aes256 and salt
* @param {String} passwordToEncrypt Le password à encrypter
* @return {String} Le password encrypté
*/
function encryptPassword(passwordToEncrypt) {
console.log('** Encrypt with aes256')
const cipher = crypto.createCipher('aes256', salt);
let encrypted = cipher.update(passwordToEncrypt, 'utf8', 'hex');
console.log('** Encrypt with aes256', encrypted)
encrypted += cipher.final('hex');
console.log('** Final hex', encrypted)
return encrypted;
}
/**
* Decrypt Password with aes256 and the salt
* @param {String} encryptedPassword Le password à décrypter
* @return {String} Le password décrypté
*/
function decryptPassword(encryptedPassword) {
console.log('** Decrypt with aes256')
const decipher = crypto.createDecipher('aes256', salt);
let decrypted = decipher.update(encryptedPassword, 'hex', 'utf8');
console.log('** Decrypt with aes256', decrypted)
decrypted += decipher.final('utf8');
console.log('** Final utf8', decrypted)
return decrypted;
}
console.log('\n Original password :', password)
const encrypted = encryptPassword(password)
console.log('\n Password encrypted :', encrypted)
const decrypted = decryptPassword(encrypted)
console.log('\n Password decrypted :', decrypted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment