Skip to content

Instantly share code, notes, and snippets.

@munkiepus
Created April 17, 2019 12:56
Show Gist options
  • Save munkiepus/6b95964c8bed345d9e5cc016ef1a3cae to your computer and use it in GitHub Desktop.
Save munkiepus/6b95964c8bed345d9e5cc016ef1a3cae to your computer and use it in GitHub Desktop.
// need to include https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js
password = "hello";
alert(encodePassword(password));
// return b64 encoded like symfony encodePassword
function encodePassword(stringInput, iterations = 5000) {
return btoa(hashPassword(stringInput, iterations));
}
// does the hashing to sha512 with iterations
function hashPassword(stringInput, iterations = 5000){
hashWordArray = CryptoJS.SHA512(stringInput);
uint8array = convertWordArrayToUint8Array(hashWordArray);
binaryString = convertUint8ArrayToBinaryString(uint8array);
for (var i=1; i<iterations; i++) {
wordArrayFromString = CryptoJS.enc.Latin1.parse(binaryString+stringInput);
hashWordArray = CryptoJS.SHA512(wordArrayFromString);
uint8array = convertWordArrayToUint8Array(hashWordArray);
binaryString = convertUint8ArrayToBinaryString(uint8array);
}
return binaryString;
}
// binary transform functions from
// https://gist.github.com/getify/7325764
function convertWordArrayToUint8Array(wordArray) {
var len = wordArray.words.length,
u8_array = new Uint8Array(len << 2),
offset = 0, word, i
;
for (i=0; i<len; i++) {
word = wordArray.words[i];
u8_array[offset++] = word >> 24;
u8_array[offset++] = (word >> 16) & 0xff;
u8_array[offset++] = (word >> 8) & 0xff;
u8_array[offset++] = word & 0xff;
}
return u8_array;
}
function convertUint8ArrayToBinaryString(u8Array) {
var i, len = u8Array.length, b_str = "";
for (i=0; i<len; i++) {
b_str += String.fromCharCode(u8Array[i]);
}
return b_str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment