Skip to content

Instantly share code, notes, and snippets.

@Oschangkai
Last active October 2, 2019 05:56
Show Gist options
  • Save Oschangkai/ce54ac92b0285a3f6313111f721dbd56 to your computer and use it in GitHub Desktop.
Save Oschangkai/ce54ac92b0285a3f6313111f721dbd56 to your computer and use it in GitHub Desktop.
Using Certificates Encryption and Decryption hash with Node.js crypto Package
const fs = require('fs'),
crypto = require('crypto');
function loadKey(file) {
return fs.readFileSync(file, 'utf8');
}
let
prvKey = loadKey('./privateKey.pem'),
pubKey = loadKey('./publicKey.pem'),
message = crypto.createHash('sha512').update('Hello').digest('base64');
console.log('message: ' + message);
const encryptOptions = {
key: prvKey,
padding: crypto.constants.RSA_PKCS1_PADDING
}
let enc_by_prv = crypto.privateEncrypt(encryptOptions, Buffer.from(message, 'base64'));
console.log('encrypted by private key: ' + enc_by_prv.toString('base64'));
const decryptOptions = {
key: pubKey,
padding: crypto.constants.RSA_PKCS1_PADDING
}
let dec_by_pub = crypto.publicDecrypt(decryptOptions, Buffer.from(enc_by_prv, 'base64'));
console.log('decrypted by public key: ' + dec_by_pub.toString('base64'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment