Created
July 17, 2017 07:38
-
-
Save kvhnuke/62178532d02dd3f68df05d34dfafd9ec to your computer and use it in GitHub Desktop.
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
var crypto = require("crypto"); | |
var eccrypto = require("eccrypto"); | |
var privKeyA = '8331f0e81f21947c516d07d520392cbc3ee891c47fad573904ea2902fe0ecd1b'; | |
var privKeyB = '5aae22750dbf28402d1aad60bb11bffcac2d1fb0cb604d8789c8fd7216af42ee'; | |
var privateKeyA = new Buffer(privKeyA, 'hex'); | |
var publicKeyA = eccrypto.getPublic(privateKeyA); | |
var privateKeyB = new Buffer(privKeyB, 'hex'); | |
var publicKeyB = eccrypto.getPublic(privateKeyB); | |
let hexify = function(obj) { | |
return { | |
iv: obj.iv.toString('hex'), | |
ephemPublicKey: obj.ephemPublicKey.toString('hex'), | |
ciphertext: obj.ciphertext.toString('hex'), | |
mac: obj.mac.toString('hex') | |
} | |
} | |
let deHexify = function(obj) { | |
return { | |
iv: new Buffer(obj.iv, 'hex'), | |
ephemPublicKey: new Buffer(obj.ephemPublicKey, 'hex'), | |
ciphertext: new Buffer(obj.ciphertext, 'hex'), | |
mac: new Buffer(obj.mac, 'hex') | |
} | |
} | |
let decrypt = function(encrypted, hexPrivKeyA, hexPrivKeyB, cb) { | |
let privKeyA = new Buffer(hexPrivKeyA, 'hex'); | |
let privKeyB = new Buffer(hexPrivKeyB, 'hex'); | |
encrypted = JSON.parse(encrypted); | |
encryptedMsg = deHexify(encrypted); | |
eccrypto.decrypt(privKeyB, encryptedMsg).then(function(_encryptedMsg) { | |
_encryptedMsg = JSON.parse(_encryptedMsg.toString()); | |
_encryptedMsg = deHexify(_encryptedMsg); | |
eccrypto.decrypt(privKeyA, _encryptedMsg).then(function(plaintext) { | |
cb(plaintext.toString()); | |
}); | |
}); | |
} | |
let encrypt = function(msg, hexPubKeyA, hexPubKeyB, cb) { | |
let pubKeyA = new Buffer(hexPubKeyA, 'hex'); | |
let pubKeyB = new Buffer(hexPubKeyB, 'hex'); | |
msg = Buffer(msg); | |
eccrypto.encrypt(pubKeyA, msg).then(function(encryptedOnce) { | |
eccrypto.encrypt(pubKeyB, JSON.stringify(hexify(encryptedOnce))).then(function(encrypted) { | |
cb(JSON.stringify(hexify(encrypted))); | |
}); | |
}); | |
} | |
encrypt("This is a super long msg", publicKeyA.toString('hex'), publicKeyB.toString('hex'), function(encrypted) { | |
decrypt(encrypted, privKeyA, privKeyB, function(decrypted) { | |
console.log(decrypted); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment