NodeJS 如何在vanilla JavaScript或基于节点的JavaScript项目中导入crypto.js

3z6pesqy  于 2023-04-20  发布在  Node.js
关注(0)|答案(3)|浏览(190)

我曾做过一件

npm install --save crypto-js

在当前项目中。它显示在package.json中:

$grep crypto package.json
  "crypto-js": "^4.0.0",

然后在一个本地项目javascript文件中,我试图使用它,但没有弄清楚。以下是尝试:

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

我还尝试在将aes.js下载到同一个本地目录后使用import方法:

<script type="text/javascript" src="aes.js"></script>

这导致:
未捕获引用错误:require未在my-project-worker.js中定义:1

Uncaught ReferenceError: CryptoJS is not defined
    at encrypt (audio-clips-worker.js:168)
    at audio-clips-worker.js:235
    at Set.forEach (<anonymous>)
    at onmessage (audio-clips-worker.js:229)

最后我试着留下一个绝对URL:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>

这给出了相同的“CryptoJS is not defined”错误。这里的 * 工作 * 选项是什么-缺少哪些步骤或需要以不同的方式完成?

arknldoa

arknldoa1#

对我有用。也许您的包包含不正确:
https://jsfiddle.net/rLt7haxc/6/

var message = "café";
var key = "something";

var encrypted = CryptoJS.AES.encrypt(message, key);
//equivalent to CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(message), key);
var decrypted = CryptoJS.AES.decrypt(encrypted, key);

$('#1').text("Encrypted: "+encrypted);
$('#2').text("Decrypted: "+decrypted.toString(CryptoJS.enc.Utf8));
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="1"></div>
<div id="2"></div>

npm项目的CodeSandbox演示:
https://codesandbox.io/s/prod-glade-6j2rw

var CryptoJS = require("crypto-js/core");
CryptoJS.AES = require("crypto-js/aes");
var encrypted = CryptoJS.AES.encrypt(message, key);
var decrypted = CryptoJS.AES.decrypt(encrypted, key);
console.log(encrypted, decrypted);

有一个CryptoES项目更符合模块标准。

xkrw2x1b

xkrw2x1b2#

“require is not defined”意味着你没有在nodejs上下文中运行它。要在vanilla环境中运行,你只需要包含带有绝对路径的脚本,并将你的js更改为不使用'require'而是使用'CryptoJS',如下所示:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
<script>
console.log('whats up!')
console.log('encrypted', CryptoJS.AES.encrypt('themessage', 'thekey'))
</script>
mm9b1k5b

mm9b1k5b3#

对于任何新手来说,你必须在项目JS文件上方声明Crypto JS URL才能工作,就像这样:

<!-- JavaScript and other scripts here -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
    <script src="script.js"></script>

如果你用下面方式声明它,你会得到一个错误caught ReferenceError: CryptoJS is not defined

<!-- JavaScript and other scripts here -->
    <script src="script.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>

相关问题