Skip to content

Instantly share code, notes, and snippets.

@Romain-P
Created October 9, 2017 11:02
Show Gist options
  • Select an option

  • Save Romain-P/9f0774302633bd91b1a38daad50e8de9 to your computer and use it in GitHub Desktop.

Select an option

Save Romain-P/9f0774302633bd91b1a38daad50e8de9 to your computer and use it in GitHub Desktop.
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 = "-----BEGIN RSA PRIVATE KEY-----\n"
+ config.authentication.rsa.privateKey
+ "\n-----END RSA PRIVATE KEY-----";
this.publicKey = "-----BEGIN RSA PUBLIC KEY-----\n"
+ config.authentication.rsa.publicKey
+ "\n-----END RSA PUBLIC KEY-----";
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')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment