前端 crypto-js aes 加解密

由於開發項目的數據較為敏感,為了防止資料在傳輸過程中,可能被中間人竊走,

之後在資料傳遞上,以下加密規則。

首先先建立兩個service文件,utils和aesKeys

aes-keys.service.ts

建立傳遞參數的加密規則

import { Injectable } from '@angular/core';
import * as CryptoJS from 'crypto-js';
@Injectable({
  providedIn: 'root'
})
export class AesKeysService {

  constructor() { }

  public GetKey() {
    const NowDate = new Date();
    const key = CryptoJS.MD5('AES' + NowDate.getFullYear() + NowDate.getMonth() + NowDate.getDay() + NowDate.getHours()).toString();
    return key;
  }
}

utils.service.ts

import { Injectable } from '@angular/core';
import * as CryptoJS from 'crypto-js';//引用AES源码js
import { by } from 'protractor';

@Injectable({
  providedIn: 'root'
})
export class UtilsService {

  constructor() { }
//加密方法
  public encrypt(secret, key) {
    try {
      const encrypted = CryptoJS.AES.encrypt(secret, key);
      return encrypted.toString();
    } catch (e) {
      console.error(e);
      return '';
    }
  }
//解密方法
  public decrypt(encrypted, key) {
    try {
      const bytes = CryptoJS.AES.decrypt(encrypted,key);
      const decrypted = bytes.toString(CryptoJS.enc.Utf8);
      return decrypted.toString();
    } catch (e) {
      console.error(e);
      return '';
    }
  }
}

然後我們在新建的http.service.ts裡面導入這兩個服務,在constructor加入

import { AesKeysService } from 'src/app/share/security/aes-keys.service';

import { UtilsService} from 'src/app/share/security/utils.service';

import { HttpClient } from '@angular/common/http';

import { HttpHeaders } from '@angular/common/http';

Injectable({
  providedIn: 'root'
})

export class HttpService {

 constructor(

    private http: HttpClient,

    private AesKeysService : AesKeysService ,

    private UtilsService: UtilsService,

  ) { }

    getData(){

         //這邊加入了token的驗證,可以不加

         var token = localStorage.getItem("Token");

            if (!token) {

              token = '';

            }

            this.httpOptions = {

              headers: new HttpHeaders({

                // 'Content-Type':  'application/json',

                'Authorization': token

              })

            };

        //URL為與後端交互的地址

        const URL = 'http://*******'

        //param 前端加密數據

        const param = this.UtilsService.encrypt('aaa', this.RfqkeyService.GetKey());

        const data= URL +'aaa?empno='+encodeURIComponent(params)

        var res = await this.http.get(URL, this.httpOptions).toPromise();

        if(res.result.secret){

           res = JSON.parse(this.UtilsService.decrypt(res.result.secret, 
                
           this.AesKeysService .GetKey()));

        }
       
    }
  
}

於此同時,後端也加上相應的加解密配置,得到的結果如果有加密的數據就解密。

後端我用的是nodeJs,如下配置,和前端類似

同樣是這兩個文件

utils.js

const CryptoJS = require('crypto-js');

module.exports = {
  encrypt(secret, key) {
    try {
      const encrypted = CryptoJS.AES.encrypt(secret, key);
      return encrypted.toString();
    } catch (e) {
      console.error(e);
      return '';
    }
  },

  decrypt(encrypted, key) {
    try {
      const bytes = CryptoJS.AES.decrypt(encrypted, key);
      const decrypted = bytes.toString(CryptoJS.enc.Utf8);
      return decrypted.toString();
    } catch (e) {
      console.error(e);
      return '';
    }
  },
};

aeskeys.js

/* eslint-disable new-cap */
const CryptoJS = require('crypto-js');

module.exports = {
  getKey() {
    const NowDate = new Date();
    const key = CryptoJS.MD5('RFQ' + NowDate.getFullYear() + NowDate.getMonth() + NowDate.getDay() + NowDate.getHours()).toString();
    return key;
  },
};
  1. 調整return

例如,原本:

     例如,原本:

     return  { code:1, data: result}

      調整為

          return {

            secret:utils.encrypt(JSON.stringify(

              { code:1, data: result,}

              ),aeskeys.GetKey())

          };

你可能感兴趣的:(angular,前端,javascript,angular,node.js,加密解密)