Encrypt the string In Typescript And Decrypt In C# using Advanced Encryption Standard Algorithm(AES)

≡放荡痞女 提交于 2019-12-03 00:36:34

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

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

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

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));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!