Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSA Encrypt/Decrypt in TypeScript

I'm using Angular 4 to make the front end of my application. I have implemented OAuth2 on my backend (developed with Spring in Java), so people using my application must be authenticated.

The thing is that we can see clearly the passwords from the backend server logs and it could be caught by a MITM until I add a SSL.

That's why I decided to encrypt the sent password with RSA. My backend is already ready, but I don't find any up-to-date libraries that provide a decent API for encrypt/decrypt from a RSA key-pair.

Also seen crypto module, but no longer usable on ECMAS6. The crypto-js one only provides AES and some hashing such as MD5/SHA.

like image 336
Romeortec Avatar asked Oct 09 '17 08:10

Romeortec


Video Answer


1 Answers

Finally found a way, after installed some.

npm install buffer
npm install crypto-browserify

Then use it

import {config} from "../app.config";
import {Buffer} from 'buffer/';
import * as crypto from "crypto-browserify";

export class RsaService {
  private privateKey: string;
  private publicKey: string;
  private enabled: boolean;

  constructor() {
    this.privateKey = config.authentication.rsa.privateKey;
    this.publicKey = config.authentication.rsa.publicKey;
    this.enabled = config.authentication.rsa.enabled;
  }

  isEnabled(): boolean {
    return this.enabled;
  }

  encrypt(plaintext: string): string {
    if (!this.enabled)
      return plaintext;

    let buffer = new Buffer(plaintext);
    let encrypted = crypto.privateEncrypt(this.privateKey, buffer);

    return encrypted.toString('base64');
  }

  decrypt(cypher: string): string {
    if (!this.enabled)
      return cypher;

    let buffer = Buffer.from(cypher, 'base64');
    let plaintext = crypto.publicDecrypt(this.publicKey, buffer);

    return plaintext.toString('utf8')
  }
}
like image 60
Romeortec Avatar answered Oct 16 '22 19:10

Romeortec