Search code examples
javascriptblazorcryptojs

How to use CryptoJs in the Javascript


I installed crypto-js like so in my Blazor project

PM> npm install crypto-js

then in the index.html, I used it like so

<script>
    
    ... OTHER FUNCTIONS

    function encryptMessage(message, key) {
        const keyOffSet = 10;
        const data = CryptoJS.enc.Utf8.parse(message);
        const keyLength = 24
        
    }
</script>

How come that I get an error of

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: CryptoJS is not defined
ReferenceError: CryptoJS is not defined

Solution

  • You need to import CryptoJS by adding CryptoJS CDN. Add the following code before your script tag which contains the logic.

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


    Note: If you still get error, check details of the GET request performed in Dev Tool's Network tab, it would probably have to do with CORS or some other network policy.