Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
27
rated 0 times [  30] [ 3]  / answers: 1 / hits: 29699  / 4 Years ago, wed, july 15, 2020, 12:00:00

I have (succesfully) done an


 npm install --save crypto-js

in the current project. It shows up in package.json:


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

Then in a local project javascript file I am trying to use it and have not figured it out.
The following has been attempted:


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

I have also tried to use the import approach after downloading the aes.js to the same local directory:


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

This results in:



Uncaught ReferenceError: require is not defined
at 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)

Finally I tried leaving an absolute url:


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

That gave the same "CryptoJS is not defined" error. What are working options here - and what steps are missing or need to be done differently?


More From » node.js

 Answers
22

Works for me. Maybe your package inclusion isn't correct:


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>




CodeSandbox demo of npm project:

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

There's a CryptoES project that is more conformant to module standards.


[#50796] Thursday, July 9, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deanna

Total Points: 84
Total Questions: 86
Total Answers: 107

Location: Cyprus
Member since Wed, Dec 8, 2021
3 Years ago
;