Include CryptoJS in AngularJS Application - Unable to find variable: CryptoJS
I want to use AngularJS CryptoJS in its application, but I get this error: Can't find variable: CryptoJS
.
I have included this in mine 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.
source to share
Introduction:
It took me a little to figure it out. I am using SHA1 library but the implementation should be the same. I also use bower to manage my dependencies, but that shouldn't change anything on your end.
Decision:
It has the simplest implementation, you want to include the Crypto dependency after all your NG dependencies are included (this is usually at the end of yours 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 dependency on NG which
<script src="bower_components/angular-route/angular-route.js"></script>
Then I add all my angular scripts (controllers, services, etc.).
If you are 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 are passing must 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 can be injected into all of your controls to better manage your dependencies. In my case, I went from MD5 to SHA-1 in about 20 minutes and it 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 are using karma and jasmine to test your application, be sure to include the crypto library path in your karma.conf
file under files
. Otherwise, you will get a permanent error Can't find variable: CryptoJS
.
source to share