如何使用Javascript中的AES-128-CBC算法加密字符串? [英] How can I encrypt a string with AES-128-CBC algorithm in Javascript?

查看:1669
本文介绍了如何使用Javascript中的AES-128-CBC算法加密字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下使用openssl加密字符串的shell脚本:

I have the following shell script which uses openssl to encrypt string:

API_KEY="qrBprgc/3dTjrrD@4t!9FcNjwT3_Ra"
DATE="Mon, 19 Mar 2018 12:45:05 EET"

aesivkey=$(echo -n "$DATE" | openssl dgst -sha256 -hmac "$API_KEY" -r)
aes128cbciv=${aesivkey:0:32}
aes128cbckey=${aesivkey:32:32}

private_key="test"
encrypted_private_key=`echo -e $private_key | openssl aes-128-cbc -base64 -nosalt -K $aes128cbckey -iv $aes128cbciv`

我是试图在javascript中实现相同的功能(在邮递员中使用)。目前我有以下代码:

I am trying to make the same function in javascript(to use it in postman). At the moment I have the following code:

var dateString = "Mon, 19 Mar 2018 12:45:05 EET";
var api_key="qrBprgc/3dTjrrD@4t!9FcNjwT3_Ra"

//aesivkey=$(echo -n "$DATE" | openssl dgst -sha256 -hmac "$API_KEY" -r)
var aesivkey = (CryptoJS.HmacSHA256(dateString, api_key)).toString();
//aes128cbciv=${aesivkey:0:32}
var aes128cbciv = aesivkey.substring(0, 32);
//aes128cbckey=${aesivkey:32:32}
var aes128cbckey = aesivkey.substring(aesivkey.length - 32);

var private_key="test"

//encrypted_private_key=`echo -e $private_key | openssl aes-128-cbc -base64 -nosalt -K $aes128cbckey -iv $aes128cbciv`
var encrypted_private_key = CryptoJS.AES.encrypt(private_key, aes128cbckey,
{
    keySize: 128 / 8,
    iv: aes128cbciv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
});

有人可以解释我在做什么错吗?

Could someone please explain what I am doing wrong?

shell脚本中的结果:HSMD8RaXNbRrN4c1NzFXvQ ==

Result in shell script: HSMD8RaXNbRrN4c1NzFXvQ==

javascript中的结果:U2FsdGVkX1 + uapLKV00iSOtj8eVpjfY4onoqQmoPPFh =

Result in javascript: U2FsdGVkX1+uapLKV00iSOtj8eVpjfY4onoqQmoPPF4=

解决方案

当前结果为 Salted __ (请参见base 64编码的ASCII内容,前8个字节将拼写该单词),即使用密码加密。这可能是因为您的密钥和IV需要在使用前从十六进制解码为 WordArray 。如果密钥是字符串而不是 WordArray ,它将被解释为密码,并且将派生密钥。

Currently the result is Salted__ (see the ASCII contents of the base 64 encoding, the first 8 bytes spell this word), i.e. it uses password encryption. This is probably because your key and IV need to be decoded from hexadecimals to a WordArray before use. If the key is a string instead of a WordArray it will be interpreted as being a password, and the key will be derived.

例如:

CryptoJS.enc.Hex.parse(aes128cbckey)

iv: CryptoJS.enc.Hex.parse(aes128cbciv)






注意:


Notes:


  • 在配置参数中指定 keySize 很好,如果您提供密码,但是如果直接指定密钥,则可能不应该使用它。

  • Specifying the keySize in the configuration parameters is nice if you provide a password, but if you specify the key directly you should probably not use it.

创建CryptoJS的开发人员应该真的真的没有重载 encrypt 函数。

The developer that created CryptoJS should really really really not have overloaded the encrypt function.

这篇关于如何使用Javascript中的AES-128-CBC算法加密字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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