Search code examples
javascriptangularjsencryptioncryptojs

Include CryptoJS in AngularJS application - Can't find variable: CryptoJS


I want to use CryptoJS in my AngularJS application, but I get this error: Can't find variable: CryptoJS.

I included this in my index.html:

<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/rc4.js"></script>

And tried to encrypt something:

var encrypted = CryptoJS.RC4Drop.encrypt("Message", "Secret Passphrase");

Any help would be greatly appreciated.


Solution

  • Preface:

    This one took me a bit to sort out. I'm using the SHA1 library, but the implementation should be the same. I'm also using bower to manage my dependencies, but that shouldn't change anything on your end.

    Solution:

    In it's simplest implementation, you want to include the Crypto dependency after all your NG dependencies are wired (this is typically at the end of your index.html). For me I include

    <script src="https://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js"></script> 
    

    after my last NG dependency which is

    <script src="bower_components/angular-route/angular-route.js"></script>
    

    Then I add all my angular scripts (controllers, services, etc).

    If you're using Bower, you can install the crypto library via

    bower install https://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js --save
    

    from there you can call CryptoJS.SHA1('some string');

    note that the value you pass in has to be a string

    You can call CryptoJS.SHA1('some string').toString(); to get the hashed value.

    Pro tip:

    You can also create a factory that you can inject into all your controls to better manage your dependencies. In my case, I went from MD5 to SHA-1 in about 20min, and this saved a ton of time.

    angular.module('someApp')
    .factory('crypt', function () {
        return {
            hash: function (value) {
                var str = JSON.stringify(value);
                return CryptoJS.SHA1(str).toString();
            }
        };
    });
    

    For testing:

    If you're using karma and jasmine to test your app, don't forget to include the path of the crypto library to your karma.conf file in the files section. Otherwise you'll get a persistent Can't find variable: CryptoJS error.