Skip to content

Instantly share code, notes, and snippets.

@themonti
Forked from konstantinzolotarev/Symfony2PasswordEncode.js
Last active February 14, 2019 12:46
Show Gist options
  • Save themonti/ad607e79b38cf3f7b43f0364c11c4708 to your computer and use it in GitHub Desktop.
Save themonti/ad607e79b38cf3f7b43f0364c11c4708 to your computer and use it in GitHub Desktop.
Function for node.js that will encrypt password exactly like Symfony2 PHP framework. So all passwords from Symfony2 will work in your node.js application
'use strict';
var CryptoJS = require("crypto-js");
/**
* Will encrypt password in Symfony2 way using a given salt with CryptoJS.
*
* @param {string} password
* @param {string} salt
* @returns {string}
*/
function encryptPassword(password, salt){
var salted = password + '{' + salt + '}';
if (!salt){
salted = password;
}
var digest = CryptoJS.SHA512(salted);
for (var i = 1; i < 5000; i++) {
digest = CryptoJS.SHA512(digest.concat(CryptoJS.enc.Utf8.parse(salted)));
}
return (digest.toString(CryptoJS.enc.Base64));
};
'use strict';
var crypto = require('crypto');
var _ = require('lodash');
/**
* Will encrypt password in Symfony2 way using a given salt.
*
* @param {string} password
* @param {string} salt
* @returns {string}
*/
function encryptPassword(password, salt){
var salted = password + '{' + salt + '}';
if (!salt){
salted = password;
}
var digest = crypto.createHash('sha512').update(salted).digest('binary');
for (var i = 1; i < 5000; i++){
digest = crypto.createHash('sha512').update(digest + salted).digest('binary');
}
return (new Buffer(digest, 'binary')).toString('base64');
};
@themonti
Copy link
Author

themonti commented Feb 6, 2019

var encryptPassword=function(password, salt){
var salted = password + '{' + salt + '}';
if (!salt){
salted = password;
}
var digest = crypto.createHash('sha512').update(salted).digest('binary');
for (var i = 1; i < 5000; i++){
digest = crypto.createHash('sha512').update(Buffer.concat([Buffer.from(digest, 'binary'), Buffer.from(salted, 'utf8')]) ).digest('binary');
}
return (Buffer.from(digest, 'binary')).toString('base64');
};
console.log("Password2: "+ encryptPassword("password", "salt"));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment