Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Last active February 13, 2018 06:10
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save xeoncross/d5a9482e5231db62fb87 to your computer and use it in GitHub Desktop.
Save xeoncross/d5a9482e5231db62fb87 to your computer and use it in GitHub Desktop.
Javascript Hashcash tests using CryptoJS
<form id="feedback">
Username: <input name="username">
<input type="hidden" class="nounce" value="foobar">
<input type="hidden" class="time" value="123456789">
</form>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha256.js"></script>
<script>
function sha256(string) {
return CryptoJS.SHA256(string).toString(CryptoJS.enc.Hex);
}
function Hashcash(text, zeroes) {
var count = 0;
var pad = '0000000000000000000'.substring(0, zeroes);
return function(iterations) {
while(iterations > 0) {
var hash = sha256(text + count);
if(pad == hash.substring(0, zeroes)) {
return count;
}
count++;
iterations--;
}
return false;
};
}
// Thanks to Mike Ash for his HashcashBG/setTimeout idea
function HashcashBG(text, zeroes, callback) {
var iterations = 100;
var delay = 1;
var processor = Hashcash(text, zeroes);
var f = function() {
var count = processor(iterations);
if(count) {
callback(count);
return;
}
setTimeout(f, delay);
};
f();
}
function HashcashForm(form, nounce)
{
var nounce = form.getElementsByClassName(nounce);
// We only care about forms with a nounce to hash
if(nounce.length) {
HashcashBG(nounce[0].value, 3, function(count) {
console.log(sha256(nounce[0].value + count), count);
var input = document.createElement("input");
input.value = count;
input.className = "hashcash";
input.type = "hidden";
console.log(input);
form.appendChild(input);
});
}
}
// On page load, or AJAX request complete
//HashcashForm();
var forms = document.getElementsByTagName('form');
for (i = 0; i < forms.length; ++i) {
HashcashForm(forms[i], 'nounce');
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment