crypto.pbkdf2(node.js)和PBEKeySpec之间的密钥长度差异 [英] Difference in key lengths between crypto.pbkdf2 (node.js) and PBEKeySpec

查看:76
本文介绍了crypto.pbkdf2(node.js)和PBEKeySpec之间的密钥长度差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一些可互操作的代码,用于对Java和node.js之间的字符串进行加密/解密,并设法使node.js解密Java加密的内容,这是成功解密的最后一部分:秘密密钥.

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.

要获取Java中的秘密密钥,我们编写:

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;
}

请注意,此处传递给PBEKeySpec()的密钥长度为128.但是,在node.js中,如果尝试使用128,而实际上必须在此处使用16,则会得到无效的密钥长度":

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);
});

控制台输出:

结果:超级秘密的东西-就在这里.

好奇为什么在指定这两个功能之间的键长时会有区别.谢谢!

Curious as to why the difference when specifying key lengths between these two functions. Thanks!

推荐答案

通常,密钥大小以位为单位定义.但是,大多数密码库不能很好地处理不能除以8的位大小-输出几乎总是以八位位组(8位字节)为单位.因此,如果用户必须指定位的大小或八位位组字符串(字节数组)中八位位组的数目,则取决于API的设计者.

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).

真正知道为什么选择位或字节的唯一方法是询问设计库的人.在我自己的代码中,我确实尝试遵守(即席)标准-密钥长度的位数.如果从上下文中不清楚是哪个,则最好使用诸如 blockSizeBits blockSizeBytes 之类的名称.文档当然也可能有所帮助,但是我认为最好使用特定的标识符.

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.

这篇关于crypto.pbkdf2(node.js)和PBEKeySpec之间的密钥长度差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆