crypto-js 模块已导入但未按预期工作

crypto-js module is imported but does not work as expected

我从事一个使用 typescript 和 es6 语法的项目。我已经安装了模块 crypto-js npm install crypto-js 和他的打字稿类型 npm install @types/crypto-js.

然后我将它导入到我的文件中,如下所示:`

import * as CryptoJS from 'crypto-js';

但是当我尝试像文档中那样使用它时:

console.log(CryptoJS.MD5('my message'));

它向我展示了一个对象结构而不是不可读的字符串:

WordArray.init {words: Array(4), sigBytes: 16}
sigBytes: 16
words: Array(4)
    0: -1952005731
    1: -1042352784
    2: 804629695
    3: 720283050
    length: 4
__proto__: Array(0)
__proto__: Object

我忘记了什么?

在您的代码中,您引用了调用 MD5 函数的输出,该函数在传递给 typeof returns 时其类型为 'object'。

虽然文档似乎很少,但您可以使用以下方法获得 MD5 值的字符串表示形式:

console.log(CryptoJS.MD5('my message').toString())

产生:"8ba6c19dc1def5702ff5acbf2aeea5aa"

如果您打算 运行 您的代码使用 NodeJS,您可以考虑其原生 crypto 模块而不是 crypto-js

const crypto = require('crypto')
const h = crypto.createHash('md5')
h.update('my message')
console.log(h.digest('hex'))

也打印:"8ba6c19dc1def5702ff5acbf2aeea5aa"

在这里使用 NodeJS 的原生 crypto module 的好处是,与所有原生模块一样,它被捆绑到 NodeJS 运行time 中,因此不需要从外部模块。