6

I'm trying to hash a string using the crypto-js library in a react/typescript project. I'm using crypto-js 3.1.9 and @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. But the function returns an object, that contains a 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. So a parameterized toString function is not allowed.

What am I doing wrong?

4
  • 1
    hash.toString(CryptoJS.enc.Hex) should be correct, but you can also try hash.toString() Commented Jul 13, 2017 at 19:17
  • Did you solved it by adding toString() or else ways? Commented May 25, 2018 at 11:30
  • @NeriusJok I was never able to solve it and implemented by own MD5 Commented Jun 4, 2018 at 9:14
  • hash.toString() is working fine for me. Commented Jul 18, 2022 at 9:49

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.