SHA256 未定义

SHA256 is undefined

我在试验 CryptoJS 库时遇到了我导入的哈希函数在 class 中不可见的问题。这是我的代码:

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());

[已解决]感谢您的回答!

在您的代码中,您导入了 CryptoJs 模块和 SHA256 函数,但没有导入 SHA512 函数。

尝试添加:

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

在脚本之上