Created
September 14, 2017 11:12
-
-
Save DomNomNom/f9a5c22e742687ecd7dc30840303fac1 to your computer and use it in GitHub Desktop.
Hiding a private key by using JS scopes and closures
This file contains hidden or 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 rp = require('request-promise-native'); | |
const crypto = require('crypto'); | |
const assert = require('assert'); | |
const signatureMethod = 'RSA-SHA256' | |
const protocolVersion = '0.0.1'; | |
const signatureEncoding = 'base64'; | |
class RpcClient { | |
// note: RpcClient takes ownership of the keyPair and makes | |
// keyPair.private hard to access. | |
constructor(keyPair, validateKeyPair=true) { | |
if (!keyPair.hasOwnProperty('private') || !keyPair.hasOwnProperty('public')) { | |
throw new Error( | |
`Bad keyPair: Expected {public: '...', private: '...'} ` + | |
`but got this instead: ${JSON.stringify(keyPair)}` | |
); | |
} | |
this.keyPair = { public: keyPair.public }; | |
{ // Create a closure over the privateKey, making it harder to access | |
const privateKey = keyPair.private + ''; | |
delete keyPair.private; | |
this._signWithPrivateKey = (stringToSign) => { | |
const signer = crypto.createSign(signatureMethod); | |
signer.update(stringToSign); | |
return signer.sign(privateKey).toString(signatureEncoding); | |
} | |
} | |
if (validateKeyPair) { // Check that we have a valid keyPair | |
const testString = 'foo 42'; | |
const signatureOfFoo = this.sign(testString); | |
const verifyer = crypto.createVerify(signatureMethod); | |
verifyer.update(testString); | |
const isVerified = verifyer.verify( | |
this.keyPair.public, | |
signatureOfFoo, | |
signatureEncoding | |
); | |
assert(isVerified, 'In the keyPair, the publicKey does not match the privateKey'); | |
} | |
} | |
sign(stringToSign) { | |
return this._signWithPrivateKey(stringToSign); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment