Skip to content

Instantly share code, notes, and snippets.

@bellbind
Last active July 7, 2018 19:38
Show Gist options
  • Save bellbind/8554970 to your computer and use it in GitHub Desktop.
Save bellbind/8554970 to your computer and use it in GitHub Desktop.
[nodejs]Hashcash example
// see: http://en.wikipedia.org/wiki/Hashcash
var crypto = require("crypto");
var table = "0123456789/:" + "abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var next = function (array) {
for (i = array.length - 1; i >= 0; i--) {
if (array[i] < table.length - 1) {
array[i] += 1;
return true;
} else {
array[i] = 0;
}
}
return false; // overflow
};
var toSuffix = function (array) {
return array.map(function (v) {
return table[v];
}).join("");
};
var hash = function (data) {
var alg = crypto.createHash("sha1");
alg.update(data);
return alg.digest("hex");
};
var find = function (data) {
for (var l = 0; l < 25; l++) {
var array = Array(l);
for (var i = 0; i < l; i++) array[i] = 0;
do {
var challenge = data + toSuffix(array);
var cash = hash(challenge);
if (cash.match(/^0{5}/)) {
console.log(cash + " " + challenge);
return challenge;
}
} while (next(array));
}
};
var data = "1:40:1303030600:[email protected]::";
find(data);
// result
// 000007767c31164bd2931d8b6941974e348c3cd7 1:40:1303030600:[email protected]::lY6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment