试图用加密js打印六角字符串

发布于 2025-01-28 09:17:41 字数 341 浏览 0 评论 0原文

我正在尝试使用cryptojs加密某些内容,然后生成加密文本的十六进制字符串。

function EncryptAES(text, key) {
  var encrypted = CryptoJS.AES.encrypt(text, key);
  return CryptoJS.enc.Hex.stringify(encrypted);
}

var encrypted = EncryptAES("Hello, World!", "SuperSecretPassword");

console.log(encrypted);

但是,将空白行打印到控制台上,而不是十六进制的字符串。我在做什么错?

I am trying to use CryptoJS to encrypt something and then generate a hexadecimal string of the encrypted text.

function EncryptAES(text, key) {
  var encrypted = CryptoJS.AES.encrypt(text, key);
  return CryptoJS.enc.Hex.stringify(encrypted);
}

var encrypted = EncryptAES("Hello, World!", "SuperSecretPassword");

console.log(encrypted);

However, instead of a hexadecimal string, a blank line is printed to the console. What am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱本泡沫多脆弱 2025-02-04 09:17:41

cryptojs.aes.encrypt()返回cipherparams对象将几个数据封装,包括ciphertext as wordarray(s。在这里)。默认情况下,.toString()返回WordArray的十六进制数据

function EncryptAES(text, key) {
    var encrypted = CryptoJS.AES.encrypt(text, key);
    return encrypted.ciphertext.toString()
}

var encrypted = EncryptAES("Hello, World!", "SuperSecretPassword");

console.log(encrypted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>

请注意,在您的示例中,关键材料以字符串的形式传递,因此被解释为密码(s。在这里),通过键推导函数推断键和IV,并与a andan> Random 8字节盐结合使用,这就是为什么Ciphertext每次在相同的输入数据中每次更改的原因。

因此,解密不仅需要密文,还需要盐,这也封装在cipherparams对象中。
对于cipherparams对象,.toString()返回基本64编码的openssl格式中的数据,该格式由ASCII编码salted> salted __的编码,然后是8字节盐和实际的密文,因此包含解密所需的所有信息。

CryptoJS.AES.encrypt() returns a CipherParams object that encapsulates several data, including the ciphertext as WordArray (s. here). By default, .toString() returns the hex encoded data for a WordArray:

function EncryptAES(text, key) {
    var encrypted = CryptoJS.AES.encrypt(text, key);
    return encrypted.ciphertext.toString()
}

var encrypted = EncryptAES("Hello, World!", "SuperSecretPassword");

console.log(encrypted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>

Note that in your example the key material is passed as string and therefore interpreted as passphrase (s. here), inferring key and IV via a key derivation function in conjunction with a random 8 bytes salt, which is why the ciphertext changes each time for the same input data.
Therefore, decryption requires not only the ciphertext but also the salt, which is also encapsulated in the CipherParams object.
For a CipherParams object, .toString() returns the data in the Base64 encoded OpenSSL format consisting of the ASCII encoding of Salted__ followed by the 8 bytes salt and the actual ciphertext, and thus contains all the information needed for decryption.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文