1
0
mirror of https://github.com/moparisthebest/mail synced 2024-11-29 04:12:18 -05:00

Refactor pgp service to use promises

This commit is contained in:
Tankred Hase 2014-11-29 16:28:51 +01:00
parent f9f086d622
commit 01e0529854

View File

@ -10,7 +10,9 @@ var util = openpgp.util,
/** /**
* High level crypto api that handles all calls to OpenPGP.js * High level crypto api that handles all calls to OpenPGP.js
*/ */
function PGP() { function PGP($q) {
this._q = $q;
openpgp.config.prefer_hash_algorithm = openpgp.enums.hash.sha256; openpgp.config.prefer_hash_algorithm = openpgp.enums.hash.sha256;
openpgp.initWorker(config.workerPath + '/openpgp.worker.min.js'); openpgp.initWorker(config.workerPath + '/openpgp.worker.min.js');
} }
@ -18,29 +20,31 @@ function PGP() {
/** /**
* Generate a key pair for the user * Generate a key pair for the user
*/ */
PGP.prototype.generateKeys = function(options, callback) { PGP.prototype.generateKeys = function(options) {
var userId, passphrase; var userId, passphrase;
if (!util.emailRegEx.test(options.emailAddress) || !options.keySize) { if (!util.emailRegEx.test(options.emailAddress) || !options.keySize) {
callback(new Error('Crypto init failed. Not all options set!')); return this._q(function(resolve, reject) {
return; reject(new Error('Crypto init failed. Not all options set!'));
});
} }
// generate keypair // generate keypair
userId = 'Whiteout User <' + options.emailAddress + '>'; userId = 'Whiteout User <' + options.emailAddress + '>';
passphrase = (options.passphrase) ? options.passphrase : undefined; passphrase = (options.passphrase) ? options.passphrase : undefined;
openpgp.generateKeyPair({
return openpgp.generateKeyPair({
keyType: 1, // (keytype 1=RSA) keyType: 1, // (keytype 1=RSA)
numBits: options.keySize, numBits: options.keySize,
userId: userId, userId: userId,
passphrase: passphrase passphrase: passphrase
}).then(function(keys) { }).then(function(keys) {
callback(null, { return {
keyId: keys.key.primaryKey.getKeyId().toHex().toUpperCase(), keyId: keys.key.primaryKey.getKeyId().toHex().toUpperCase(),
privateKeyArmored: keys.privateKeyArmored, privateKeyArmored: keys.privateKeyArmored,
publicKeyArmored: keys.publicKeyArmored publicKeyArmored: keys.publicKeyArmored
}); };
}).catch(callback); });
}; };
/** /**
@ -142,152 +146,164 @@ PGP.prototype.extractPublicKey = function(privateKeyArmored) {
/** /**
* Import the user's key pair * Import the user's key pair
*/ */
PGP.prototype.importKeys = function(options, callback) { PGP.prototype.importKeys = function(options) {
var pubKeyId, privKeyId, self = this; var self = this;
return self._q(function(resolve, reject) {
var pubKeyId, privKeyId;
// check options // check options
if (!options.privateKeyArmored || !options.publicKeyArmored) { if (!options.privateKeyArmored || !options.publicKeyArmored) {
callback(new Error('Importing keys failed. Not all options set!')); reject(new Error('Importing keys failed. Not all options set!'));
return; return;
} }
function resetKeys() { function resetKeys() {
self._publicKey = undefined; self._publicKey = undefined;
self._privateKey = undefined; self._privateKey = undefined;
} }
// read armored keys // read armored keys
try { try {
this._publicKey = openpgp.key.readArmored(options.publicKeyArmored).keys[0]; self._publicKey = openpgp.key.readArmored(options.publicKeyArmored).keys[0];
this._privateKey = openpgp.key.readArmored(options.privateKeyArmored).keys[0]; self._privateKey = openpgp.key.readArmored(options.privateKeyArmored).keys[0];
} catch (e) { } catch (e) {
resetKeys(); resetKeys();
callback(new Error('Importing keys failed. Parsing error!')); reject(new Error('Importing keys failed. Parsing error!'));
return; return;
} }
// decrypt private key with passphrase // decrypt private key with passphrase
if (!this._privateKey.decrypt(options.passphrase)) { if (!self._privateKey.decrypt(options.passphrase)) {
resetKeys(); resetKeys();
callback(new Error('Incorrect passphrase!')); reject(new Error('Incorrect passphrase!'));
return; return;
} }
// check if keys have the same id // check if keys have the same id
pubKeyId = this._publicKey.primaryKey.getKeyId().toHex(); pubKeyId = self._publicKey.primaryKey.getKeyId().toHex();
privKeyId = this._privateKey.primaryKey.getKeyId().toHex(); privKeyId = self._privateKey.primaryKey.getKeyId().toHex();
if (!pubKeyId || !privKeyId || pubKeyId !== privKeyId) { if (!pubKeyId || !privKeyId || pubKeyId !== privKeyId) {
resetKeys(); resetKeys();
callback(new Error('Key IDs dont match!')); reject(new Error('Key IDs dont match!'));
return; return;
} }
callback(); resolve();
});
}; };
/** /**
* Export the user's key pair * Export the user's key pair
*/ */
PGP.prototype.exportKeys = function(callback) { PGP.prototype.exportKeys = function() {
if (!this._publicKey || !this._privateKey) { var self = this;
callback(new Error('Could not export keys!')); return self._q(function(resolve, reject) {
return; if (!self._publicKey || !self._privateKey) {
} reject(new Error('Could not export keys!'));
return;
}
callback(null, { resolve({
keyId: this._publicKey.primaryKey.getKeyId().toHex().toUpperCase(), keyId: self._publicKey.primaryKey.getKeyId().toHex().toUpperCase(),
privateKeyArmored: this._privateKey.armor(), privateKeyArmored: self._privateKey.armor(),
publicKeyArmored: this._publicKey.armor() publicKeyArmored: self._publicKey.armor()
});
}); });
}; };
/** /**
* Change the passphrase of an ascii armored private key. * Change the passphrase of an ascii armored private key.
*/ */
PGP.prototype.changePassphrase = function(options, callback) { PGP.prototype.changePassphrase = function(options) {
var privKey, packets, newPassphrase, newKeyArmored; return this._q(function(resolve, reject) {
var privKey, packets, newPassphrase, newKeyArmored;
// set undefined instead of empty string as passphrase // set undefined instead of empty string as passphrase
newPassphrase = (options.newPassphrase) ? options.newPassphrase : undefined; newPassphrase = (options.newPassphrase) ? options.newPassphrase : undefined;
if (!options.privateKeyArmored) { if (!options.privateKeyArmored) {
callback(new Error('Private key must be specified to change passphrase!')); reject(new Error('Private key must be specified to change passphrase!'));
return; return;
}
if (options.oldPassphrase === newPassphrase ||
(!options.oldPassphrase && !newPassphrase)) {
callback(new Error('New and old passphrase are the same!'));
return;
}
// read armored key
try {
privKey = openpgp.key.readArmored(options.privateKeyArmored).keys[0];
} catch (e) {
callback(new Error('Importing key failed. Parsing error!'));
return;
}
// decrypt private key with passphrase
if (!privKey.decrypt(options.oldPassphrase)) {
callback(new Error('Old passphrase incorrect!'));
return;
}
// encrypt key with new passphrase
try {
packets = privKey.getAllKeyPackets();
for (var i = 0; i < packets.length; i++) {
packets[i].encrypt(newPassphrase);
} }
newKeyArmored = privKey.armor();
} catch (e) {
callback(new Error('Setting new passphrase failed!'));
return;
}
// check if new passphrase really works if (options.oldPassphrase === newPassphrase ||
if (!privKey.decrypt(newPassphrase)) { (!options.oldPassphrase && !newPassphrase)) {
callback(new Error('Decrypting key with new passphrase failed!')); reject(new Error('New and old passphrase are the same!'));
return; return;
} }
callback(null, newKeyArmored); // read armored key
try {
privKey = openpgp.key.readArmored(options.privateKeyArmored).keys[0];
} catch (e) {
reject(new Error('Importing key failed. Parsing error!'));
return;
}
// decrypt private key with passphrase
if (!privKey.decrypt(options.oldPassphrase)) {
reject(new Error('Old passphrase incorrect!'));
return;
}
// encrypt key with new passphrase
try {
packets = privKey.getAllKeyPackets();
for (var i = 0; i < packets.length; i++) {
packets[i].encrypt(newPassphrase);
}
newKeyArmored = privKey.armor();
} catch (e) {
reject(new Error('Setting new passphrase failed!'));
return;
}
// check if new passphrase really works
if (!privKey.decrypt(newPassphrase)) {
reject(new Error('Decrypting key with new passphrase failed!'));
return;
}
resolve(newKeyArmored);
});
}; };
/** /**
* Encrypt and sign a pgp message for a list of receivers * Encrypt and sign a pgp message for a list of receivers
*/ */
PGP.prototype.encrypt = function(plaintext, publicKeysArmored, callback) { PGP.prototype.encrypt = function(plaintext, publicKeysArmored) {
var publicKeys; var self = this;
return self._q(function(resolve, reject) {
var publicKeys;
// check keys // check keys
if (!this._privateKey) { if (!self._privateKey) {
callback(new Error('Error encrypting. Keys must be set!')); reject(new Error('Error encrypting. Keys must be set!'));
return; return;
}
// parse armored public keys
try {
if (publicKeysArmored && publicKeysArmored.length) {
publicKeys = [];
publicKeysArmored.forEach(function(pubkeyArmored) {
publicKeys = publicKeys.concat(openpgp.key.readArmored(pubkeyArmored).keys);
});
} }
} catch (err) { // parse armored public keys
callback(new Error('Error encrypting plaintext!')); try {
return; if (publicKeysArmored && publicKeysArmored.length) {
} publicKeys = [];
publicKeysArmored.forEach(function(pubkeyArmored) {
publicKeys = publicKeys.concat(openpgp.key.readArmored(pubkeyArmored).keys);
});
}
} catch (err) {
reject(new Error('Error encrypting plaintext!'));
return;
}
resolve(publicKeys);
if (publicKeys) { }).then(function(publicKeys) {
// encrypt and sign the plaintext if (publicKeys) {
openpgp.signAndEncryptMessage(publicKeys, this._privateKey, plaintext).then(callback.bind(null, null)).catch(callback); // encrypt and sign the plaintext
} else { return openpgp.signAndEncryptMessage(publicKeys, self._privateKey, plaintext);
// if no public keys are available encrypt for myself } else {
openpgp.signAndEncryptMessage([this._publicKey], this._privateKey, plaintext).then(callback.bind(null, null)).catch(callback); // if no public keys are available encrypt for myself
} return openpgp.signAndEncryptMessage([self._publicKey], self._privateKey, plaintext);
}
});
}; };
/** /**
@ -296,35 +312,42 @@ PGP.prototype.encrypt = function(plaintext, publicKeysArmored, callback) {
* @param {String} publicKeyArmored The public key used to sign the message * @param {String} publicKeyArmored The public key used to sign the message
* @param {Function} callback(error, plaintext, signaturesValid) signaturesValid is undefined in case there are no signature, null in case there are signatures but the wrong public key or no key was used to verify, true if the signature was successfully verified, or false if the signataure verification failed. * @param {Function} callback(error, plaintext, signaturesValid) signaturesValid is undefined in case there are no signature, null in case there are signatures but the wrong public key or no key was used to verify, true if the signature was successfully verified, or false if the signataure verification failed.
*/ */
PGP.prototype.decrypt = function(ciphertext, publicKeyArmored, callback) { PGP.prototype.decrypt = function(ciphertext, publicKeyArmored) {
var publicKeys, message; var self = this;
return self._q(function(resolve, reject) {
var publicKeys, message;
// check keys // check keys
if (!this._privateKey) { if (!self._privateKey) {
callback(new Error('Error decrypting. Keys must be set!')); reject(new Error('Error decrypting. Keys must be set!'));
return; return;
}
// read keys and ciphertext message
try {
if (publicKeyArmored) {
// parse public keys if available ...
publicKeys = openpgp.key.readArmored(publicKeyArmored).keys;
} else {
// use own public key to know if signatures are available
publicKeys = [this._publicKey];
} }
message = openpgp.message.readArmored(ciphertext); // read keys and ciphertext message
} catch (err) { try {
callback(new Error('Error parsing encrypted PGP message!')); if (publicKeyArmored) {
return; // parse public keys if available ...
} publicKeys = openpgp.key.readArmored(publicKeyArmored).keys;
} else {
// use own public key to know if signatures are available
publicKeys = [self._publicKey];
}
message = openpgp.message.readArmored(ciphertext);
} catch (err) {
reject(new Error('Error parsing encrypted PGP message!'));
return;
}
resolve(publicKeys, message);
// decrypt and verify pgp message }).then(function(publicKeys, message) {
openpgp.decryptAndVerifyMessage(this._privateKey, publicKeys, message).then(function(decrypted) { // decrypt and verify pgp message
return openpgp.decryptAndVerifyMessage(self._privateKey, publicKeys, message);
}).then(function(decrypted) {
// return decrypted plaintext // return decrypted plaintext
callback(null, decrypted.text, checkSignatureValidity(decrypted.signatures)); return {
}).catch(callback); decrypted: decrypted.text,
signaturesValid: checkSignatureValidity(decrypted.signatures)
};
});
}; };
/** /**
@ -333,34 +356,37 @@ PGP.prototype.decrypt = function(ciphertext, publicKeyArmored, callback) {
* @param {String} publicKeyArmored The public key used to signed the message * @param {String} publicKeyArmored The public key used to signed the message
* @param {Function} callback(error, signaturesValid) signaturesValid is undefined in case there are no signature, null in case there are signatures but the wrong public key or no key was used to verify, true if the signature was successfully verified, or false if the signataure verification failed. * @param {Function} callback(error, signaturesValid) signaturesValid is undefined in case there are no signature, null in case there are signatures but the wrong public key or no key was used to verify, true if the signature was successfully verified, or false if the signataure verification failed.
*/ */
PGP.prototype.verifyClearSignedMessage = function(clearSignedText, publicKeyArmored, callback) { PGP.prototype.verifyClearSignedMessage = function(clearSignedText, publicKeyArmored) {
var publicKeys, var self = this;
message; return self._q(function(resolve, reject) {
var publicKeys, message;
// check keys // check keys
if (!this._privateKey) { if (!self._privateKey) {
callback(new Error('Error verifying signed PGP message. Keys must be set!')); reject(new Error('Error verifying signed PGP message. Keys must be set!'));
return; return;
}
// read keys and ciphertext message
try {
if (publicKeyArmored) {
// parse public keys if available ...
publicKeys = openpgp.key.readArmored(publicKeyArmored).keys;
} else {
// use own public key to know if signatures are available
publicKeys = [this._publicKey];
} }
message = openpgp.cleartext.readArmored(clearSignedText); // read keys and ciphertext message
} catch (err) { try {
callback(new Error('Error verifying signed PGP message!')); if (publicKeyArmored) {
return; // parse public keys if available ...
} publicKeys = openpgp.key.readArmored(publicKeyArmored).keys;
} else {
// use own public key to know if signatures are available
publicKeys = [self._publicKey];
}
message = openpgp.cleartext.readArmored(clearSignedText);
} catch (err) {
reject(new Error('Error verifying signed PGP message!'));
return;
}
resolve(publicKeys, message);
openpgp.verifyClearSignedMessage(publicKeys, message).then(function(result) { }).then(function(publicKeys, message) {
callback(null, checkSignatureValidity(result.signatures)); return openpgp.verifyClearSignedMessage(publicKeys, message);
}).catch(callback); }).then(function(result) {
return checkSignatureValidity(result.signatures);
});
}; };
/** /**
@ -370,39 +396,40 @@ PGP.prototype.verifyClearSignedMessage = function(clearSignedText, publicKeyArmo
* @param {String} publicKeyArmored The public key used to signed the message * @param {String} publicKeyArmored The public key used to signed the message
* @param {Function} callback(error, signaturesValid) signaturesValid is undefined in case there are no signature, null in case there are signatures but the wrong public key or no key was used to verify, true if the signature was successfully verified, or false if the signataure verification failed. * @param {Function} callback(error, signaturesValid) signaturesValid is undefined in case there are no signature, null in case there are signatures but the wrong public key or no key was used to verify, true if the signature was successfully verified, or false if the signataure verification failed.
*/ */
PGP.prototype.verifySignedMessage = function(message, pgpSignature, publicKeyArmored, callback) { PGP.prototype.verifySignedMessage = function(message, pgpSignature, publicKeyArmored) {
var publicKeys; var self = this;
return self._q(function(resolve, reject) {
var publicKeys, signatures;
// check keys // check keys
if (!this._privateKey) { if (!self._privateKey) {
callback(new Error('Error verifying signed PGP message. Keys must be set!')); reject(new Error('Error verifying signed PGP message. Keys must be set!'));
return; return;
} }
// read keys and ciphertext message
// read keys and ciphertext message try {
try { if (publicKeyArmored) {
if (publicKeyArmored) { // parse public keys if available ...
// parse public keys if available ... publicKeys = openpgp.key.readArmored(publicKeyArmored).keys;
publicKeys = openpgp.key.readArmored(publicKeyArmored).keys; } else {
} else { // use own public key to know if signatures are available
// use own public key to know if signatures are available publicKeys = [self._publicKey];
publicKeys = [this._publicKey]; }
} catch (err) {
reject(new Error('Error verifying signed PGP message!'));
return;
}
// check signatures
try {
var msg = openpgp.message.readSignedContent(message, pgpSignature);
signatures = msg.verify(publicKeys);
} catch (err) {
reject(new Error('Error verifying signed PGP message!'));
return;
} }
} catch (err) {
callback(new Error('Error verifying signed PGP message!'));
return;
}
var signatures; resolve(checkSignatureValidity(signatures));
try { });
var msg = openpgp.message.readSignedContent(message, pgpSignature);
signatures = msg.verify(publicKeys);
} catch (err) {
callback(new Error('Error verifying signed PGP message!'));
return;
}
callback(null, checkSignatureValidity(signatures));
}; };
/** /**