简体   繁体   English

在 angular 9 中使用节点加密

[英]Use node crypto in angular 9

My project was in Angular 6 and it had following lines of code我的项目在 Angular 6 中,它有以下几行代码

const crypto = require('crypto-js');
const Buffer = require('buffer').Buffer;
const decrypt = new Buffer(data.result.encr, 'base64');
const privatekey = Buffer.from(data.result.pk, 'base64');
this.decrypted = crypto.privateDecrypt(privatekey, decrypt).toString('utf-8');
return this.decrypted;

Which was working fine.哪个工作正常。

Now I migrated my code to Angular 9. And I find out that crypto has no longer support from NPM现在我将我的代码迁移到 Angular 9。我发现crypto不再支持加密

https://www.npmjs.com/package/crypto https://www.npmjs.com/package/crypto

It says that I have to use inbuild library of crypto.它说我必须使用内置的加密库。 But I have no idea how to use it.但我不知道如何使用它。

I thought crypto-js would help me.我认为crypto-js会帮助我。 But it didn't.但它没有。

If someone knows how to use crypto in Angular 9 or how to convert upper lines for crypto-js then it would be great.如果有人知道如何在 Angular 9 中使用crypto或如何为crypto-js转换上行,那就太好了。

Note: Encryption is happening on server side using crypto only as they have nodejs.注意:加密是在服务器端使用加密进行的,因为它们只有 nodejs。

Thanks in advance.提前致谢。

After 3-4 days I am finally able to resolve this. 3-4天后,我终于能够解决这个问题。

  1. I installed crypto-browserify .我安装了crypto-browserify
  2. Delete node_modules folder and then again installed all dependencies by using npm-install删除 node_modules 文件夹,然后使用npm-install再次安装所有依赖项

crypto-browserify provides same features as crypto crypto-browserify提供与crypto相同的功能

I recently acheived this in my MEAN Stack app.我最近在我的 MEAN Stack 应用程序中实现了这一点。 After installing crypto-js with following command:使用以下命令安装 crypto-js 后:

npm i crypto-js --save

Following service in Angular-9 which can be used through out the project for encryption and decryption. Angular-9中的以下服务,可以在整个项目中用于加密和解密。

import { Injectable } from '@angular/core';
import * as CryptoJS from 'crypto-js';
import { environment } from 'src/environments/environment';

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

  constructor() { }

  get jsonFormatter() {
    return {
      stringify: (cipherParams: any) => {
        const jsonObj = { ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64), iv: null, s: null };
        if (cipherParams.iv) {
          jsonObj.iv = cipherParams.iv.toString();
        }
        if (cipherParams.salt) {
          jsonObj.s = cipherParams.salt.toString();
        }
        return JSON.stringify(jsonObj);
      },
      parse: (jsonStr) => {
        const jsonObj = JSON.parse(jsonStr);
        // extract ciphertext from json object, and create cipher params object
        const cipherParams = CryptoJS.lib.CipherParams.create({
          ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
        });
        if (jsonObj.iv) {
          cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv);
        }
        if (jsonObj.s) {
          cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s);
        }
        return cipherParams;
      }
    };
  }
  /* Method for Encryption */
  encrypt(value: any) {
    const key =  environment.crypto_js_key; // SECRET KEY FOR ENCRYPTION 
    value = value instanceof String ? value : JSON.stringify(value);
    const encrypted = CryptoJS.AES.encrypt(value,key, 
      { format: this.jsonFormatter, mode: CryptoJS.mode.CBC }).toString();
    return encrypted;
  }

  /* Method for Decryption */
  decrypt(value: any): any {
    const key = environment.crypto_js_key; //SECRET KEY FOR ENCRYPTION
    const decrypted = CryptoJS.AES.decrypt(value, key, {format: this.jsonFormatter }).toString(CryptoJS.enc.Utf8);
    return JSON.parse(decrypted);
  }
}

In Nodejs , following utility could be used through out the app:Nodejs中,可以在整个应用程序中使用以下实用程序:

var CryptoJS = require('crypto-js');
var config = require('../config/environment');

module.exports.encrypt = function(value){
  var JsonFormatter = {
    stringify: function(cipherParams){
      var jsonObj = { ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64) };
      if (cipherParams.iv) {
        jsonObj.iv = cipherParams.iv.toString();
      }
      if (cipherParams.salt) {
        jsonObj.s = cipherParams.salt.toString();
      }
      return JSON.stringify(jsonObj);
    },
    parse: function(jsonStr) {
      var jsonObj = JSON.parse(jsonStr);
      // extract ciphertext from json object, and create cipher params object
      var cipherParams = CryptoJS.lib.CipherParams.create({
        ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
      });
      if (jsonObj.iv) {
        cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv);
      }
      if (jsonObj.s) {
        cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s);
      }
      return cipherParams;
    }
  }
  value = value instanceof String ? value: JSON.stringify(value);
  var encrypted = CryptoJS.AES.encrypt(value, config.crypto_js_key, {
    format: JsonFormatter, mode: CryptoJS.mode.CBC
  }).toString();
  return encrypted;
}

module.exports.decrypt = function(value) {
  return CryptoJS.AES.decrypt(value, config.crypto_js_key, {format: JsonFormatter }).toString(CryptoJS.enc.Utf8);
}

Depending on the desired hash, the best option for me was ts-md5 lib.根据所需的 hash,对我来说最好的选择是ts-md5 lib。

import {Md5} from 'ts-md5/dist/md5';
...
Md5.hashStr('blah blah blah'); // hex:string
Md5.hashStr('blah blah blah', true); // raw:Int32Array(4)
Md5.hashAsciiStr('blah blah blah'); // hex:string
Md5.hashAsciiStr('blah blah blah', true); // raw:Int32Array(4)

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

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