在AngularJS应用程序中包含CryptoJS - 找不到变量:CryptoJS

use*_*602 4 javascript encryption angularjs cryptojs

我想在我的AngularJS应用程序中使用CryptoJS,但是我收到了这个错误:Can't find variable: CryptoJS.

我把它包括在我的index.html:

<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/rc4.js"></script>
Run Code Online (Sandbox Code Playgroud)

并试图加密一些东西:

var encrypted = CryptoJS.RC4Drop.encrypt("Message", "Secret Passphrase");
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

Sha*_*rty 14

前言:

这个让我有点理清.我正在使用SHA1库,但实现应该是相同的.我也使用bower来管理我的依赖项,但这不应该改变你的任何东西.

解:

在它最简单的实现中,您希望在所有NG依赖关系都连接之后包含加密依赖关系(这通常在您的最后index.html).对我来说,我包括

<script src="https://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js"></script> 
Run Code Online (Sandbox Code Playgroud)

在我最后的NG依赖之后

<script src="bower_components/angular-route/angular-route.js"></script>
Run Code Online (Sandbox Code Playgroud)

然后我添加所有角度脚本(控制器,服务等).

如果您正在使用Bower,则可以通过以下方式安装加密库

bower install https://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js --save
Run Code Online (Sandbox Code Playgroud)

从那里你可以打电话 CryptoJS.SHA1('some string');

请注意,您传入的值必须是字符串

您可以调用CryptoJS.SHA1('some string').toString();以获取散列值.

专家提示:

您还可以创建一个可以注入所有控件的工厂,以便更好地管理依赖项.在我的情况下,我在大约20分钟内从MD5转到SHA-1,这节省了大量时间.

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

用于检测:

如果您正在使用karma和jasmine来测试您的应用,请不要忘记karma.conf在该files部分中将加密库的路径包含到您的文件中.否则你会得到持久性Can't find variable: CryptoJS错误.

  • 关闭Google代码后,您可能希望将此依赖关系安装为:`bower install https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/sha1.js --save` (2认同)