Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const logger = require('mii-logger.js');
const RSA_BITS = 2048 * 2;
const LOCATION = __dirname+'/rsa_keys';
const SEC_KEY = 'sec_key.pem';
const PUB_KEY = 'pub_key.pem';
module.exports = RSA = class{
constructor(){
this.isReady = false;
this.createNewRSAKeys();
if( this.isReady )
console.ok(' #RSA: ready ...');
}
decrypt( payload ){
try{
if( !this.isReady )
return {code: 400, msg: 'RSA: is not ready ...'};
const sec_key = fs.readFileSync( LOCATION+'/'+SEC_KEY,'utf-8' );
const dec_data = crypto.privateDecrypt( sec_key, Buffer.from(payload, 'hex'));
return {code: 200, msg: 'OK', data: dec_data.toString('utf-8')};
}catch(e){
console.warn(' #RSA: decrypt: '+e.message );
console.error( e );
return {code: 500, msg: e.message};
}
}
encrypt( payload ){
try{
if( !this.isReady )
return {code: 400, msg: 'RSA: is not ready ...'};
const pub_key = fs.readFileSync( LOCATION+'/'+PUB_KEY, 'utf-8' );
const enc_data = crypto.publicEncrypt( pub_key, Buffer.from(payload,'utf-8'));
return {code: 200, msg: 'OK', data: enc_data.toString('hex')};
}catch(e){
console.warn(' #RSA: encrypt: '+e.message );
console.error( e );
return {code: 500, msg: e.message};
}
}
createNewRSAKeys(){
if( console.isFile( LOCATION+'/'+SEC_KEY ) || console.isFile( LOCATION+'/'+PUB_KEY ) ){
// console.warn(' #RSA: Keys already generated. Aborting ...');
this.isReady = true;
return;
}
try{
console.log(' #RSA: Generating new keys');
const RSAKeys = crypto.generateKeyPairSync('rsa', {
modulusLength: RSA_BITS,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem', }
});
const sec_key_file = path.join( LOCATION, 'sec_key.pem');
const pub_ke_filey = path.join( LOCATION, 'pub_key.pem');
fs.writeFileSync( sec_key_file, RSAKeys.privateKey, 'ascii' );
fs.writeFileSync( pub_ke_filey, RSAKeys.publicKey, 'ascii' );
this.isReady = true;
console.ok(' #RSA: Generating new keys: done ...');
}catch(e){
console.error(' #RSA: createNewRSAKeys: '+e.message);
console.error( e );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment