简体   繁体   English

Crypto-JS 哈希函数返回对象

[英]Crypto-JS hash functions return object

I'm trying to hash a string using the crypto-js library in a react/typescript project.我正在尝试在 react/typescript 项目中使用 crypto-js 库对字符串进行哈希处理。 I'm using crypto-js 3.1.9 and @types/crypto-js 3.1.33.我正在使用 crypto-js 3.1.9 和 @types/crypto-js 3.1.33。

Here's some code:这是一些代码:

import CryptoJS = require("crypto-js");

export const hashString= (str: string): string => {
  const hash = CryptoJS.MD5(str);
  return hash;
}

I expect hash to be of type string, as specified in the documentation of the crypto-js implementation.我希望hash是 string 类型,如 crypto-js 实现的文档中所指定。 But the function returns an object, that contains a wordarray.但该函数返回一个对象,其中包含一个 wordarray。

I also tried calling我也试过打电话

hash.toString(CryptoJS.enc.Hex) 

but that didn't work, because typescript also assumes that hash will be a string.但这不起作用,因为打字稿还假定hash将是一个字符串。 So a parameterized toString function is not allowed.所以不允许使用参数化的toString函数。

What am I doing wrong?我做错了什么?

I know this is an old question, but I had this question recently and in case someone is looking for an answer, I just cast the result to a string.我知道这是一个老问题,但我最近遇到了这个问题,如果有人正在寻找答案,我只是将结果转换为字符串。 Seems to work fine for me.对我来说似乎工作正常。

 console.log(typeof CryptoJS.MD5('hello')); console.log("String() => ", String(CryptoJS.MD5('hello')));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>

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

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