Skip to content

Instantly share code, notes, and snippets.

@swordfeng
Last active August 29, 2018 07:33
Show Gist options
  • Save swordfeng/949329d2c7286e5ae59d51738dd939c2 to your computer and use it in GitHub Desktop.
Save swordfeng/949329d2c7286e5ae59d51738dd939c2 to your computer and use it in GitHub Desktop.
#!/usr/bin/node
var targetEntropy = parseFloat(process.argv[2]);
var charSet = process.argv[3] && process.argv[3].toLowerCase();
var testStrength = parseInt(process.argv[4]) || 16384;
var filter = () => true;
switch (charSet) {
case 'alphanum': filter = isAlphaNum; break;
}
var crypto = require('crypto');
function getOneChar() {
while (true) {
var t = crypto.randomBytes(1)[0];
if (t >= 95 * 2) continue;
var c = String.fromCharCode(t % 95 + 32);
if (!filter(c)) continue;
return c;
}
}
// entropy calculate
var tot = 114514;
var counts = {};
for (var i = 0; i < tot; i++) {
var c = getOneChar();
counts[c] = counts[c] || 0;
counts[c]++;
}
var entropy = 0;
for (var c in counts) {
var p = counts[c] / tot;
entropy += p * (-Math.log2(p));
}
var output = '';
var curEntropy = 0;
var rem = 0;
while (curEntropy < targetEntropy) {
var c = getOneChar();
output += c;
curEntropy += entropy;
}
process.stdout.write(output);
console.error('\nentropy:', curEntropy);
function isAlphaNum(c) {
if (c >= '0' && c <= '9') return true;
if (c >= 'A' && c <= 'Z') return true;
if (c >= 'a' && c <= 'z') return true;
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment