Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Difference in key lengths between crypto.pbkdf2 (node.js) and PBEKeySpec

Difference in key lengths between crypto.pbkdf2 (node.js) and PBEKeySpec

Problem

I'm working on some interoperable code for encrypting/decrypting strings between Java and node.js and have managed to get node.js to decrypt what Java has encrypted with this being the final part to successful decryption: the secret key.

To derive a secret key in Java, we write:

private static Key deriveSecretKey(String secretKeyAlgorithm, String secretKey, String salt) throws Exception {

  SecretKeyFactory factory = SecretKeyFactory.getInstance(SECRET_KEY_FACTORY_ALGORITHM);
  KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), char2byte(salt), 65536, 128);
  SecretKey tmp = factory.generateSecret(spec);
  SecretKey secret = new SecretKeySpec(tmp.getEncoded(), secretKeyAlgorithm);

  return secret;
}

Notice the key Length passed to PBEKeySpec() is 128 here. In node.js, however, I get an "Invalid key length" if I try to use 128 and actually have to use 16 here instead:

crypto.pbkdf2(key_value, salt_value, 65536, 16, function(err, key) {
   var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);

   // decipher.setAutoPadding(false);
   var decoded = decipher.update(ciphertext, 'binary', 'utf8');
   decoded += decipher.final('utf8');

   console.log('Result: ' + decoded);
});

Console output:

Result: Super secret stuff -- right here.

Curious as to why the difference when specifying Key Lengths between these two functions. Thanks!

Problem courtesy of: rdev5

Solution

Normally, key sizes are defined in bits. However, most cryptographic libraries don't handle bit sizes that cannot be divided by 8 particularly well - the output is almost always in octets (8-bit bytes). So it is up to the designer of the API if the user has to specify the size in bits, or in the number of octets in the octet string (byte array).

The only way to really know why bits or bytes are being chosen is to ask the person who designed the library. In my own code, I do try to keep to (ad-hoc) standards - so bits for key sizes. If it's unclear from the context which is which, it is probably best to use names such as blockSizeBits or blockSizeBytes. Documentation may be of help too of course, but using specific identifiers is best in my opinion.

Solution courtesy of: Maarten Bodewes

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Difference in key lengths between crypto.pbkdf2 (node.js) and PBEKeySpec

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×