Search code examples
javascriptcryptojs

JavaScript, CryptoJS is not defined?


I'm trying to run the following simple JS code in multiple websites but all throw same error:

var _finalScore = 9; // Final Score
var _tapCount = 3; // Clicks

_tapCount *= 73;

var key = CryptoJS.enc.Utf8.parse('4512631236589784');
var iv = CryptoJS.enc.Utf8.parse('4512631236589784');

console.log(CryptoJS.AES.encrypt(_finalScore.toString(), key, { iv: iv }).toString())
console.log(CryptoJS.AES.encrypt(_tapCount.toString()))

which is:

    var key = CryptoJS.enc.Utf8.parse('4512631236589784');
          ^

ReferenceError: CryptoJS is not defined
    at Object.<anonymous> (/tmp/YA2n3rCQMJ.js:6:11)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Why is that? How can I fix it I didn't find any special command to include CryptoJS...


Solution

  • Did you include the library? Either install it on your server, or use a CDN. Here is the code using a CDN:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js" integrity="sha512-E8QSvWZ0eCLGk4km3hxSsNmGWbLtSCSUcewDQPQWZF6pEU8GlT8a5fF32wOl1i8ftdMhssTrF/OhyGWwonTcXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    (from https://cdnjs.com/libraries/crypto-js)

    Edit:

    Working example based on your code: (Note: I did not check if your code as applied correctly)

    var _finalScore = 9; // Final Score
    var _tapCount = 3; // Clicks
    
    _tapCount *= 73;
    
    var key = CryptoJS.enc.Utf8.parse('4512631236589784');
    var iv = CryptoJS.enc.Utf8.parse('4512631236589784');
    
    console.log('start');
    console.log(CryptoJS.AES.encrypt(_finalScore.toString(), key, { iv: iv }).toString());
    console.log(CryptoJS.AES.encrypt(_tapCount.toString(), key, { iv: iv }).toString());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.3.0/crypto-js.min.js" integrity="sha512-e2c+O0PvytekkdJLc82DHfa6La8TPKzO2/DFA97YeHTbiDCwKMzloupJM6Llf/W4K19+N21gFyplVkvzL4pZxQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>