Skip to content

Instantly share code, notes, and snippets.

@chj1768
Last active December 16, 2022 07:20
Show Gist options
  • Save chj1768/2830869aeba8908c366ad261e118c302 to your computer and use it in GitHub Desktop.
Save chj1768/2830869aeba8908c366ad261e118c302 to your computer and use it in GitHub Desktop.
RSA encryption / decryption example (nodejs)
openssl key pair generate
//client - using meteor.js
const nodersa = Npm.require('node-rsa');
import { HTTP } from 'meteor/http';
const syncPost = Meteor.wrapAsync( HTTP.post, HTTP );
encryptStringWithRsaPublicKey( data ) {
const absolutePath = Assets.absoluteFilePath( "public.key" ); //public key file path
const publicKey = fs.readFileSync( absolutePath, "utf8" );
const key = new nodersa( publicKey );
const encrypted = key.encrypt( data, 'base64' );
const remote = 'url:8000'; //example
return syncPost( remote, { data : { 'value' : encrypted } } );
}
...
//example server
'use strict';
const express = require('express');
const fs = require('fs');
const nodersa = require('node-rsa');
const bodyParser = require('body-parser');
let app = express();
app.use(bodyParser.urlencoded({ extended : false }));
app.use(bodyParser.json());
app.post('/', (req, res)=>{
let value = req.body.value;
const privateKey = fs.readFileSync('./store/privateKey.pem', 'utf8');
const original = new nodersa(privateKey).decrypt(value, 'utf8');
res.end(original);
});
app.listen(8000, ()=>{
console.log('on 8000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment