更新时间:2023-02-17 17:06:33
我遇到了类似的问题。我正在使用Angular 4 / Angular-Cli 1.0.0。对我有用的东西:
I had a similar issue. I'm using Angular 4/Angular-Cli 1.0.0. What worked for me:
npm install crypto-js --save
npm install @types/crypto-js --save
在这两个命令之后,请参考下面的 crypto-js 库
After these two commands, reference the crypto-js library in the angular-cli.json file, in the "scripts" array. In my case:
"scripts": [
"../node_modules/crypto-js/crypto-js.js"
]
您会注意到,在 node_modules / @类型目录,您将拥有一个crypto-js子目录。因此,请在代码中使用
You'll notice that in the node_modules/@types directory, you'll have a crypto-js subdirectory. So put a reference to the node_modules/@types/crypto-js/index.d.ts file in your code, using a triple-slash directive, so the compliler knows that the typings file is necessary to compile that module file:
/// <reference path="relative_path_to_cypto_folder/index.d.ts" />
或者,您也可以使用 types属性代替 path,因为在node_modules / @ types内部的类型定义:
Alternatively, you can also use "types" attribute instead of "path", since you're referencing a typings definition inside node_modules/@types:
/// <reference types="crypto-js" />
之后,您可以按原样使用代码:
After that you can use your code exactly as it is:
/// <reference types="crypto-js" />
import * as CryptoJS from 'crypto-js';
var key = CryptoJS.enc.Utf8.parse('7061737323313233');
var iv = CryptoJS.enc.Utf8.parse('7061737323313233');
var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse("It works"), key,
{
keySize: 128 / 8,
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
keySize: 128 / 8,
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
console.log('Encrypted :' + encrypted);
console.log('Key :' + encrypted.key);
console.log('Salt :' + encrypted.salt);
console.log('iv :' + encrypted.iv);
console.log('Decrypted : ' + decrypted);
console.log('utf8 = ' + decrypted.toString(CryptoJS.enc.Utf8));