CryptoJS aes加密(不要求密钥长度),解密为空字符串的问题

不要求密钥长度的aes加密

crypto-js 是浏览器和node端都能用的,本文的加密解密演示没有额外的配置,全都是默认的。

说明

官方文档有介绍

The Cipher Input
For the plaintext message, the cipher algorithms accept either strings or instances of CryptoJS.lib.WordArray.
For the key, when you pass a string, it’s treated as a passphrase and used to derive an actual key and IV. Or you can pass a WordArray that represents the actual key. If you pass the actual key, you must also pass the actual IV.
For the ciphertext, the cipher algorithms accept either strings or instances of CryptoJS.lib.CipherParams. A CipherParams object represents a collection of parameters such as the IV, a salt, and the raw ciphertext itself. When you pass a string, it’s automatically converted to a CipherParams object according to a configurable format strategy.
The Cipher Output
The plaintext you get back after decryption is a WordArray object. See Hashing’s Output for more detail.
The ciphertext you get back after encryption isn’t a string yet. It’s a CipherParams object. A CipherParams object gives you access to all the parameters used during encryption. When you use a CipherParams object in a string context, it’s automatically converted to a string according to a format strategy. The default is an OpenSSL-compatible format.

软件翻译一下大概是这样
文档
下面边做边解释,node端

const CryptoJS = require('crypto-js')

let key = 'hwft5j' //长度不足且不是8的倍数的密钥
let res = CryptoJS.AES.encrypt('string', key)
console.log(res.key.toString()); //实际的加密密钥
// 7b1ed7478780b0b07a60e79e0abce02ec4652471bae608c2d62a8bafd8060cc7
console.log(res.ciphertext.toString( /* CryptoJS.enc.Hex (默认)*/ )); //加密后的密文,默认输出hex编码
// 1a1822ee6683b0b6fb6796ee0b213e63
console.log(res.ciphertext.toString(CryptoJS.enc.Base64)); //base64编码
// Ghgi7maDsLb7Z5buCyE+Yw==
//console.log(res.ciphertext.toString(CryptoJS.enc.(Utf8/Utf16/...))); //其他编码
console.log(res.salt.toString()); //派生的salt(解密时需要) #1
// f3b27ca7d9399448
console.log(res.iv.toString()); //派生的向量(解密时用不到)
// 73aa96806b6b0b995403f72b6a88fe2d

// 以上输出每次运行都不相同

let cipher = CryptoJS.lib.CipherParams.create({
  salt: res.salt, //派生的salt
  ciphertext: CryptoJS.enc.Hex.parse(res.ciphertext.toString()) //密文,注意是CryptoJS.lib.WordArray格式,这里这样写是为了演示编码转换,这里因为在上下文中所以可以直接用res.ciphertext
})
console.log(CryptoJS.AES.decrypt(cipher, key).toString(CryptoJS.enc.Utf8)); //解密并以Utf8编码输出
// string

#1解释:
密钥
我们传递的简短的字符串并不是用于加密的密钥,而是根据这个字符串生成了实际的密钥、盐和向量用于加密。
所以并不是知道这个字符串就能解密,还得知道生成的盐值才行。
具体操作看代码就好了,有问题可以评论。

说明1:这个密码短语肯定是需要保密的,但是盐值并不需要,前后端配合时直接和密文一起传

说明2:官方文档的例子直接点复制去运行可能会报错,因为代码中夹杂了某些空白的字符

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值