nodejs 加密解密有什么问题? [英] What's wrong with nodejs crypto decipher?

查看:17
本文介绍了nodejs 加密解密有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下加密数据:

U2FsdGVkX1+21O5RB08bavFTq7Yq/gChmXrO3f00tvJaT55A5pPvqw0zFVnHSW1o

解密的通行证是:password

(这是来自 gibberish-aes 的示例)

(it's the example from gibberish-aes)

在命令行中使用 openssl:

In the command line using openssl:

echo "U2FsdGVkX1+21O5RB08bavFTq7Yq/gChmXrO3f00tvJaT55A5pPvqw0zFVnHSW1o" |openssl enc -d -aes-256-cbc -a -k 密码

输出为:

用乱码制作

Made with Gibberish

使用我的 NodeJS 应用程序:

With my NodeJS application:

  var decipher = crypto.createDecipher('aes-256-cbc', "password");
  var dec = decipher.update("U2FsdGVkX1+21O5RB08bavFTq7Yq/gChmXrO3f00tvJaT55A5pPvqw0zFVnHSW1o",
     'base64', 'utf8');
  dec += decipher.final('utf8');

我在 decipher.final 行出现以下错误 TypeError: DecipherFinal fail.

I have the following error TypeError: DecipherFinal fail at the decipher.final line.

我错过了什么吗?谢谢.

Am I missing something ? Thanks.

推荐答案

加密后的数据以 8 字节的magic"开头,表示有盐("Salted__" 的 ASCII 编码).然后接下来的 8 个字节是盐.现在坏消息是:Node.js 似乎没有为 EVP_BytesToKey 方法使用盐:

The encrypted data starts with a 8 byte "magic" indicating that there is a salt (the ASCII encoding of "Salted__"). Then the next 8 bytes is the salt. Now the bad news: Node.js does not seem to use the salt for the EVP_BytesToKey method:

int key_len = EVP_BytesToKey(cipher, EVP_md5(), NULL,
  (unsigned char*) key_buf, key_buf_len, 1, key, iv);

那个 NULL 就是盐.

这已使用 Java 测试应用程序(使用正确的盐)进行了验证 - 结果字符串已返回.

This has been verified using a Java test application (using the right salt) - the result string was returned.

请使用 OpenSSL -nosalt 开关忽略盐,然后重试.

Please leave out the salt using the OpenSSL -nosalt switch and try again.

[例子]

OpenSSL CLI:

OpenSSL CLI:

openssl enc -aes-256-cbc -nosalt -a -k password
owlstead
Mh5yxIyZH+fSMTkSgkLa5w==

NodeJS 加密:

var crypto=require('crypto')
var cipher=crypto.createDecipher('aes-256-cbc', "password")
var enc = cipher.update("Mh5yxIyZH+fSMTkSgkLa5w==", 'base64', 'utf8')
enc += cipher.final('utf8')

<小时>

[后期编辑] 请注意,使用带盐和大工作系数的密钥派生可能对安全性至关重要.您最好使用一个非常独特的高熵密码,否则您的加密数据可能会受到威胁.


[LATE EDIT] Note that using secret key derivation with a salt and large work factor may be paramount to security. You'd better use a very unique, high entropy password otherwise your encrypted data may be at risk.

[REALLY LATE EDIT] OpenSSL 1.1.0c 更改了一些内部组件中使用的摘要算法.以前用的是MD5,1.1.0改用SHA256.请注意,更改不会影响 EVP_BytesToKey 和诸如 openssl enc 之类的命令.

[REALLY LATE EDIT] OpenSSL 1.1.0c changed the digest algorithm used in some internal components. Formerly, MD5 was used, and 1.1.0 switched to SHA256. Be careful the change is not affecting you in both EVP_BytesToKey and commands like openssl enc.

这篇关于nodejs 加密解密有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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