失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > CryptoJS aes加密(不要求密钥长度) 解密为空字符串的问题

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

时间:2022-12-23 04:53:12

相关推荐

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()); //实际的加密密钥// 7b1ed7478780b0b07a60e79e0abce02ec4652471bae608c2d62a8bafd8060cc7console.log(res.ciphertext.toString( /* CryptoJS.enc.Hex (默认)*/ )); //加密后的密文,默认输出hex编码// 1a1822ee6683b0b6fb6796ee0b213e63console.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// f3b27ca7d9399448console.log(res.iv.toString()); //派生的向量(解密时用不到)// 73aa96806b6b0b995403f72b6a88fe2d// 以上输出每次运行都不相同let cipher = CryptoJS.lib.CipherParams.create({salt: res.salt, //派生的saltciphertext: 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:官方文档的例子直接点复制去运行可能会报错,因为代码中夹杂了某些空白的字符

如果觉得《CryptoJS aes加密(不要求密钥长度) 解密为空字符串的问题》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。