Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crypto-JS hash functions return object

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?

like image 523
Androidicus Avatar asked Jul 13 '17 13:07

Androidicus


People also ask

Can you hash an object in JavaScript?

The most common example of a Hash Table in JavaScript is the Object data type, where you can pair the object's property value with a property key. But JavaScript's Object type is a special kind of Hash Table implementation for two reasons: It has properties added by the Object class.

What is CryptoJS HmacSHA256?

HmacSHA256(CryptoJS. enc. Hex. parse(mess), key)) generates an HMAC using the SHA256 digest. Thereby the message is hex decoded and the key UTF8 encoded.

What is the use of CryptoJS?

CryptoJS is a growing collection of standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns. They are fast, and they have a consistent and simple interface.

How do you use CryptoJS in Reactjs?

To encrypt and decrypt data, simply use encrypt() and decrypt() function from an instance of crypto-js. var bytes = CryptoJS. AES. decrypt(ciphertext, 'my-secret-key@123');


1 Answers

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>
like image 138
Abraham Labkovsky Avatar answered Sep 20 '22 15:09

Abraham Labkovsky