Kiran Shinde
Kiran Shinde

Reputation: 5982

Use node crypto in angular 9

My project was in Angular 6 and it had following lines of code

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

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. 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.

Note: Encryption is happening on server side using crypto only as they have nodejs.

Thanks in advance.

Upvotes: 5

Views: 18449

Answers (4)

MishkuMoss
MishkuMoss

Reputation: 118

I was using Angular 16 & used crypto inside a method and it worked. I didn't used any packages.

My requirement was to get some random numbers.

private getRandomNumbers(){
const array = new Uint32Array(10);
crypto.getRandomValues(array);

for (const num of array) {
  console.log(num);
}
}

Upvotes: 0

Rafael Pizao
Rafael Pizao

Reputation: 841

Depending on the desired hash, the best option for me was 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)

Upvotes: 0

ImFarhad
ImFarhad

Reputation: 3189

I recently acheived this in my MEAN Stack app. After installing crypto-js with following command:

npm i crypto-js --save

Following service in Angular-9 which can be used through out the project for encryption and decryption.

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:

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);
}

Upvotes: 1

Kiran Shinde
Kiran Shinde

Reputation: 5982

After 3-4 days I am finally able to resolve this.

  1. I installed crypto-browserify.
  2. Delete node_modules folder and then again installed all dependencies by using npm-install

crypto-browserify provides same features as crypto

Upvotes: 5

Related Questions