const crypto = require('crypto'); | |
const Salt = { | |
/** | |
* Length. | |
* @const int | |
*/ | |
LENGTH: 128, | |
/** | |
* Characters. | |
* @const string | |
*/ | |
CHARACTERS: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/', | |
/** | |
* Generate. | |
* @param {Int} length? | |
* @param {Int} bitsPerChar? | |
* @param {Bool} opt_translate? | |
* @return {String} | |
* @see https://github.com/php/php-src/blob/master/ext/session/session.c#L267,#L326 | |
*/ | |
generate: function(length, bitsPerChar, opt_translate) | |
{ | |
let len = length || this.LENGTH; // output length | |
let bpc = bitsPerChar || 6; // 4=hex chars, 5=base36 chars, 6=base64 chars | |
let bytes = crypto.randomBytes(parseInt(Math.ceil(len * bpc / 8))); | |
let p = 0, q = bytes.length; | |
let w = 0, have = 0, mask = (1 << bpc) - 1, byte; | |
let out = ''; | |
while (len--) { | |
if (have < bpc) { | |
if (p < q) { | |
byte = bytes[p++]; | |
w |= (byte << have); | |
have += 8; | |
} else { | |
break; | |
} | |
} | |
// consume bpc bits | |
out += this.CHARACTERS[w & mask]; | |
w >>= bpc; | |
have -= bpc; | |
} | |
if (opt_translate) { | |
out = out.replace(/\+/g, '-').replace(/\//g, '_'); | |
} | |
return out; | |
} | |
}; | |
module.exports = Salt; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment