Skip to content

Instantly share code, notes, and snippets.

@jamilbk
Last active December 26, 2015 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamilbk/7077341 to your computer and use it in GitHub Desktop.
Save jamilbk/7077341 to your computer and use it in GitHub Desktop.
example of encrypted pgp-style message sending involving two recipients
// handle signed numbers
var toHex = function(decimalInt) {
if (decimalInt < 0) {
decimalInt += 0xFFFFFFFF + 1;
}
return decimalInt.toString(16).toUpperCase();
};
var set1, set2, set3, pair1, pair2, sym_key='';
var msg = 'Super-secret message! Tell no one!';
var pass1 = 'password1'
, pass2 = 'password2';
while (typeof set1 === 'undefined') {
set1 = sjcl.ecc.ecdsa.generateKeys();
}
while (typeof set2 === 'undefined') {
set2 = sjcl.ecc.ecdsa.generateKeys();
}
while (typeof set3 === 'undefined') {
set3 = sjcl.ecc.ecdsa.generateKeys();
}
// create hex-based representation of symmetric key
sym_key = _.reduce(set3.sec.get(), function (sum, key) { return sum + toHex(key); }, '');
var emsg = sjcl.encrypt(sym_key, msg);
var rec1 = sjcl.encrypt(pass1, sym_key);
var rec2 = sjcl.encrypt(pass2, sym_key);
console.log('symmetric key: ' + sym_key);
console.log('encrypted message: ' + emsg);
console.log('encrypted symmetric key with pass1: ' + rec1);
console.log('encrypted symmetric key with pass2: ' + rec2);
// Now, store emsg, rec1, rec2 on the server, then...
var dec_sym_key = sjcl.decrypt(pass1, rec1);
var msg1 = sjcl.decrypt(dec_sym_key, emsg);
var msg2 = sjcl.decrypt(dec_sym_key, emsg);
console.log('original message: ' + msg);
console.log('decrypted message1: ' + msg1);
console.log('decrypted message2: ' + msg2);
@jamilbk
Copy link
Author

jamilbk commented Oct 21, 2013

Requires sjcl library and lodash / underscore. In prod, you would encrypt pair1 and pair2 with pass1 and pass2 respectively. Then back this up and use pair1 / pair2 private key for decryption.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment