0

I was experimenting with CryptoJS library and came across with the problem that my imported hash function isn't visible inside a class. Here's my code:

CryptoJS = require('crypto-js');
SHA256 = require('crypto-js/sha256');

class trCrypt {
  constructor(input,key) {
this.input = input;
this.key = SHA512(key).toString();
  }
  encrypt(){
    this.step1 = CryptoJS.AES.encrypt(this.input,this.key);
    return this.step1.toString()
  }
  decrypt(){
    const bytes =  CryptoJS.AES.decrypt(this.step1);
    this.dec1 = bytes.toString(CryptoJS.enc.Utf8);
    return this.dec1
  }
}
a = new trCrypt('hello','world');
console.log(a.encrypt());
console.log(a.decrypt());

[SOLVED] Thanks for answer!

Paul Losev
  • 969
  • 1
  • 12
  • 17
  • 2
    SHA256 is defined, but not SHA512 – Juan Elfers Aug 21 '18 at 17:09
  • You are importing `SHA256` but using `SHA512`. Also, you shouldn't be declaring variables globally. (Using `var` or `const` in your case is preferred) – bradcush Aug 21 '18 at 17:10
  • 1
    The real question here is why do you think SHA256 module can handle SHA512 encryption? Remember, do one thing, but do it well... – TGrif Aug 21 '18 at 21:04

1 Answers1

2

In your code you've imported the CryptoJs module and the SHA256 function, but you've not imported the SHA512 function.

Try adding:

SHA512 = require('crypto-js/sha512');

On top of the script

Martín Zaragoza
  • 1,717
  • 8
  • 19