简体   繁体   English

crypto-js模块已导入,但无法按预期工作

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

I work on a project wich use typescript and es6 syntax. 我正在使用打字稿和es6语法的项目中工作。 I have installed the module crypto-js npm install crypto-js and his typescript type npm install @types/crypto-js . 我已经安装了crypto-js模块npm install crypto-js和他的打字稿类型npm install @types/crypto-js

I import it then into my file like this :` 然后将其导入到我的文件中,如下所示:

import * as CryptoJS from 'crypto-js';

But when i tried to use it like in the documentation : 但是当我尝试像文档中那样使用它时:

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

It show me an Object structure instead of an unreadable string : 它显示了一个对象结构而不是一个不可读的字符串:

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

What am I forgetting? 我忘记了什么?

In your code, you reference the output from calling the MD5 function which, when passed to typeof returns its type as 'object'. 在您的代码中,您引用了调用MD5函数的输出,该函数在传递给typeof返回其类型为“对象”。

Though it seems poorly documented, you can reach the string representation of the MD5 value using: 尽管似乎文献记载不充分,但是您可以使用以下命令来获取MD5值的字符串表示形式:

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

which produces: "8ba6c19dc1def5702ff5acbf2aeea5aa" 产生: "8ba6c19dc1def5702ff5acbf2aeea5aa"

If you plan to run your code using NodeJS, you might consider its native crypto module rather than crypto-js . 如果计划使用NodeJS运行代码,则可以考虑使用其本机crypto模块,而不是crypto-js

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

which also prints: "8ba6c19dc1def5702ff5acbf2aeea5aa" 其中还会显示: "8ba6c19dc1def5702ff5acbf2aeea5aa"

The benefit of using NodeJS' native crypto module here is that, like all native modules, it is bundled into the NodeJS runtime and so doesn't need to be loaded in from an external module. 在这里使用NodeJS的本机加密模块的好处是,像所有本机模块一样,它被捆绑到NodeJS运行时中,因此不需要从外部模块加载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM