Last active
October 2, 2019 05:56
-
-
Save Oschangkai/ce54ac92b0285a3f6313111f721dbd56 to your computer and use it in GitHub Desktop.
Using Certificates Encryption and Decryption hash with Node.js crypto Package
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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