Skip to content

Instantly share code, notes, and snippets.

@getify
Created October 20, 2020 15:51
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 getify/57eee7451984e947d66388a2292fa7b8 to your computer and use it in GitHub Desktop.
Save getify/57eee7451984e947d66388a2292fa7b8 to your computer and use it in GitHub Desktop.
troubles with pbkdf2 between node and browser

In the code below, I generate a PBKDF2 key from my password using the same salt/iterations, first in node, then in the browser.

I'm not using any libraries on either side. I'm using the built-in crypto module in node, and the SubtleCrypto web API in the browser.

I'm trying to get both sides to generate the same base64 string of the derived key. Here's what I get:

Node:    UJ3XzqSfs1IjU3/1USt8jPb9Z9jnhevBy3TPCAPGzHPbwXI0jVk+0LoVO7zYmb1BVEtajPmkcuLUPpwju+x+IQ==
Browser: UJ3XzqSfs1IjU3_1USt8jPb9Z9jnhevBy3TPCAPGzHM

As you can see, it's sort of tantalizingly almost the same. The / in one is a _ in the other, and the browser one diverges at the 43rd character which is also the end of that one.

So what's going on here? What am I missing?

// in node:
var crypto = require("crypto");
async function generatePBKDF2(password) {
var pwSalt = "SumYxGzTe3lMtfteF+l00yEF7IQuzL/ARHnJp4hCHDAfO9p1aB";
return (await crypto.pbkdf2(password,pwSalt,250000,64,"sha512")).toString("base64");
}
generatePBKDF2("-- my password here --")
.then(console.log);
// UJ3XzqSfs1IjU3/1USt8jPb9Z9jnhevBy3TPCAPGzHPbwXI0jVk+0LoVO7zYmb1BVEtajPmkcuLUPpwju+x+IQ==
// *********************************************************
// in browser:
async function generatePBKDF2(password) {
var pwSalt = "SumYxGzTe3lMtfteF+l00yEF7IQuzL/ARHnJp4hCHDAfO9p1aB";
var encoder = new TextEncoder();
var keyMaterial = await crypto.subtle.importKey(
"raw",
encoder.encode(password),
"PBKDF2",
false,
["deriveBits","deriveKey",],
);
var key = await crypto.subtle.deriveKey(
{
"name": "PBKDF2",
salt: encoder.encode(pwSalt),
"iterations": 250000,
"hash": "SHA-512",
},
keyMaterial,
{ "name": "AES-GCM", "length": 256, },
true,
[ "encrypt", "decrypt" ]
);
return (
(await crypto.subtle.exportKey("jwk",key)).k
);
}
generatePBKDF2("-- my password here --")
.then(console.log);
// UJ3XzqSfs1IjU3_1USt8jPb9Z9jnhevBy3TPCAPGzHM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment