Skip to content

Instantly share code, notes, and snippets.

@jedie
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jedie/14f5b342ac44418368f9 to your computer and use it in GitHub Desktop.
Save jedie/14f5b342ac44418368f9 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>WebCrypto PBKDF2 test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script>
function hex(buffer) {
// from example here:
// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
var hexCodes = [];
var view = new DataView(buffer);
for (var i = 0; i < view.byteLength; i += 4) {
// Using getUint32 reduces the number of iterations needed (we process 4 bytes each time)
var value = view.getUint32(i)
// toString(16) will give the hex representation of the number without padding
var stringValue = value.toString(16)
// We use concatenation and slice for padding
var padding = '00000000'
var paddedValue = (padding + stringValue).slice(-padding.length)
hexCodes.push(paddedValue);
}
return hexCodes.join(""); // Join all the hex strings into one
}
if (!window.crypto) {
alert("ERROR: Your browser does not support the Web Cryptography API!");
}
if(window.crypto.webkitSubtle){
window.crypto.subtle = window.crypto.webkitSubtle; //for Safari
}
function hexlify_pbkdf2(password, salt, iterations, dklen) {
password = new TextEncoder("utf-8").encode(password);
return window.crypto.subtle.importKey(
"raw", password, {name: "PBKDF2"},
false, //whether the key is extractable (i.e. can be used in exportKey)
["deriveBits"] // ["deriveKey", "deriveBits"] //can be any combination of "deriveKey" and "deriveBits"
).then(function(key){
salt = new TextEncoder("utf-8").encode(salt);
return window.crypto.subtle.deriveBits(
{
"name": "PBKDF2",
salt: salt,
iterations: iterations,
hash: {name: "SHA-1"},
},
key, dklen
).then(function(hash){
return hex(hash);
})
})
}
var password="password";
var salt="salt";
var iterations=1000;
var dklen=16*8;
hexlify_pbkdf2(password, salt, iterations, dklen).then(function(hex_hash){
alert("hexlify pbkdf2:"+hex_hash); // should display: 6e88be8bad7eae9d9e10aa061224034f
})
</script>
</head>
<body>
<h1>Web Cryptography - PBKDF2 test</h1>
<p>Open javascript console if alert box doesn't pop up.</p>
</body>
</html>
# same in python:
import hashlib
import binascii
dk = hashlib.pbkdf2_hmac('sha1', b'password', b'salt', 1000, dklen=16)
print(binascii.hexlify(dk)) # b'6e88be8bad7eae9d9e10aa061224034f'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment