简体   繁体   English

如何在 Angular 6 中加密和解密

[英]How to Encrypt and Decrypt in Angular 6

Login Response登录响应

{
  code: 200,
  id: 4,
  msg: "success",
  user: "Sourav"
}

I have a issue like i want to store id and user in Local Storage as Encrypted format.How can i do it using Angular 6?我有一个问题,比如我想将本地存储中的 id 和用户存储为加密格式。我如何使用 Angular 6 来做到这一点?

In one our project, we have used 'crypto-js' library.在我们的一个项目中,我们使用了“crypto-js”库。 http://github.com/brix/crypto-js http://github.com/brix/crypto-js

import * as CryptoJS from 'crypto-js';

encryptData(data) {

    try {
      return CryptoJS.AES.encrypt(JSON.stringify(data), this.encryptSecretKey).toString();
    } catch (e) {
      console.log(e);
    }
  }

  decryptData(data) {

    try {
      const bytes = CryptoJS.AES.decrypt(data, this.encryptSecretKey);
      if (bytes.toString()) {
        return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
      }
      return data;
    } catch (e) {
      console.log(e);
    }
  }

The technical solution for encrypting things on client side is probably to use some third party library.在客户端加密事物的技术解决方案可能是使用一些第三方库。 Quoting such libraries leads to opinionated answers and that's not very desirable here.引用此类库会导致固执己见的答案,这在这里并不是很理想。

However, if the use case is to hide some backend data from the user (which seems to be the case when I read your question), it makes no sense to encrypt, since the key would be either stored in JavaScript code or sent through network.但是,如果用例是对用户隐藏一些后端数据(当我阅读您的问题时似乎就是这种情况),那么加密是没有意义的,因为密钥要么存储在 JavaScript 代码中,要么通过网络发送. In both cases it's impossible to obfuscate.在这两种情况下,都无法混淆。

Some examples of valid use cases for client-side encryption:客户端加密的一些有效用例示例:

  • Allow the user to encrypt things with a key they own.允许用户使用他们拥有的密钥加密事物。
  • Use some public key to encrypt a message for a system that owns the corresponding private key使用一些公钥为拥有相应私钥的系统加密消息
  • ... ...

Though it's not perfect, window.btoa() will provide basic base-64 encoding, to avoid everyone reading the user data.虽然它并不完美,但window.btoa()将提供基本base-64编码,以避免每个人都读取用户数据。 This could be your quickest solution.这可能是您最快的解决方案。 As encryption on the client side is not secured, because everything that comes to the browser can be seen by the end user (Your code or Ajax call, etc), even your encryption key.由于客户端的加密不安全,因为最终用户可以看到浏览器的所有内容(您的代码或 Ajax 调用等),甚至您的加密密钥。

You can use crypto.js to encrypt data.您可以使用crypto.js来加密数据。 See this if you don't know how to use it with Angular.如果您不知道如何将其与 Angular 一起使用,请参阅内容。

Next, you put the encrypted data into your local storage.接下来,将加密数据放入本地存储。 See this tutorial .请参阅本教程

You can also use secure-ls .您也可以使用secure-ls No need to maintain the decryption key at client side.无需在客户端维护解密密钥。

import * as SecureLS from 'secure-ls';
export class StorageService { 

  private _ls = new SecureLS({ encodingType: 'aes' });
  constructor() {
  }

  set(key: string, value: any, expired: number = 0) {
    this._ls.set(key, value);
  }

  remove(key: string) {
    this._ls.remove(key);
  }

  get(key: string) {
    return this._ls.get(key);
  }

  clear() {
    this._ls.removeAll();
  }
}

Simply use the built-in function as follows:只需使用内置函数,如下所示:

const encodedData = btoa('Hello, world'); // encode a string        
localStorage.setItem("token", encodedData );

let accessToken = localStorage.getItem("token");
const decodedData = atob(accessToken ); // decode the string

This is how I did encryption/decryption in Angular:这就是我在 Angular 中进行加密/解密的方式:

//profile-detail.component.ts //profile-detail.component.ts

 var userIdVal = this._AESEncryptDecryptService.get(this.Auth[0].UserID); this._AESEncryptDecryptService.encryptData(this.eCode); var UserIdEncrpt = this._AESEncryptDecryptService.encryptData(userIdVal);

//EncryptDecryptService.service.ts //EncryptDecryptService.service.ts

 export class AESEncryptDecryptServiceService { secretKey = 'YourSecretKeyForEncryption&Descryption' constructor() { } // QA/UAT secret key encryptSecretKey = 'mySecretKeyHere' tokenFromUI: string = '123456$#@$^@1ERF' // Prod secret key // encryptSecretKey = 'b14ca3428a4e1840bbce2ea2315a1814' // tokenFromUI: string = '7891@$#@$^@1@ERF' // 7891@230456$#@$^@1257@ERF //adding secret key //Data Encryption Function encryptData(msg) { var keySize = 256 var salt = crypto.lib.WordArray.random(16) var key = crypto.PBKDF2(this.encryptSecretKey, salt, { keySize: keySize / 32, iterations: 100, }) var iv = crypto.lib.WordArray.random(128 / 8) var encrypted = crypto.AES.encrypt(msg, key, { iv: iv, padding: crypto.pad.Pkcs7, mode: crypto.mode.CBC, }) var result = crypto.enc.Base64.stringify( salt.concat(iv).concat(encrypted.ciphertext) ) return result } decryptData(txt) { var key = crypto.enc.Base64.parse(this.encryptSecretKey) var iv = crypto.lib.WordArray.create([0x00, 0x00, 0x00, 0x00]) var decrypted = crypto.AES.decrypt(txt, key, { iv: iv }) return decrypted.toString(crypto.enc.Utf8) } // ======================================================== encrypted: any = '' decrypted: string set(value) { var key = crypto.enc.Utf8.parse(this.tokenFromUI) var iv = crypto.enc.Utf8.parse(this.tokenFromUI) var encrypted = crypto.AES.encrypt( crypto.enc.Utf8.parse(value.toString()), key, { keySize: 128 / 8, iv: iv, mode: crypto.mode.CBC, padding: crypto.pad.Pkcs7, } ) return encrypted.toString() } //The get method is use for decrypt the value. get(value) { var key = crypto.enc.Utf8.parse(this.tokenFromUI) var iv = crypto.enc.Utf8.parse(this.tokenFromUI) var decrypted = crypto.AES.decrypt(value, key, { keySize: 128 / 8, iv: iv, mode: crypto.mode.CBC, padding: crypto.pad.Pkcs7, }) return decrypted.toString(crypto.enc.Utf8) } decryptUsingAES256(value) { let _key = crypto.enc.Utf8.parse(this.tokenFromUI) let _iv = crypto.enc.Utf8.parse(this.tokenFromUI) var decrpted = crypto.AES.decrypt(value, _key, { keySize: 128 / 8, iv: _iv, mode: crypto.mode.CBC, padding: crypto.pad.Pkcs7, }).toString(crypto.enc.Utf8) return decrpted } }`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM