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
1 changed files with 230 additions and 203 deletions

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,12 +146,14 @@ 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;
} }
@ -158,66 +164,71 @@ PGP.prototype.importKeys = function(options, callback) {
// 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) {
if (!self._publicKey || !self._privateKey) {
reject(new Error('Could not export keys!'));
return; 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) {
return this._q(function(resolve, reject) {
var privKey, packets, newPassphrase, newKeyArmored; 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 || if (options.oldPassphrase === newPassphrase ||
(!options.oldPassphrase && !newPassphrase)) { (!options.oldPassphrase && !newPassphrase)) {
callback(new Error('New and old passphrase are the same!')); reject(new Error('New and old passphrase are the same!'));
return; return;
} }
@ -225,13 +236,13 @@ PGP.prototype.changePassphrase = function(options, callback) {
try { try {
privKey = openpgp.key.readArmored(options.privateKeyArmored).keys[0]; privKey = openpgp.key.readArmored(options.privateKeyArmored).keys[0];
} catch (e) { } catch (e) {
callback(new Error('Importing key failed. Parsing error!')); reject(new Error('Importing key failed. Parsing error!'));
return; return;
} }
// decrypt private key with passphrase // decrypt private key with passphrase
if (!privKey.decrypt(options.oldPassphrase)) { if (!privKey.decrypt(options.oldPassphrase)) {
callback(new Error('Old passphrase incorrect!')); reject(new Error('Old passphrase incorrect!'));
return; return;
} }
@ -243,31 +254,33 @@ PGP.prototype.changePassphrase = function(options, callback) {
} }
newKeyArmored = privKey.armor(); newKeyArmored = privKey.armor();
} catch (e) { } catch (e) {
callback(new Error('Setting new passphrase failed!')); reject(new Error('Setting new passphrase failed!'));
return; return;
} }
// check if new passphrase really works // check if new passphrase really works
if (!privKey.decrypt(newPassphrase)) { if (!privKey.decrypt(newPassphrase)) {
callback(new Error('Decrypting key with new passphrase failed!')); reject(new Error('Decrypting key with new passphrase failed!'));
return; return;
} }
callback(null, newKeyArmored); 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 self = this;
return self._q(function(resolve, reject) {
var publicKeys; 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 // parse armored public keys
try { try {
if (publicKeysArmored && publicKeysArmored.length) { if (publicKeysArmored && publicKeysArmored.length) {
@ -277,17 +290,20 @@ PGP.prototype.encrypt = function(plaintext, publicKeysArmored, callback) {
}); });
} }
} catch (err) { } catch (err) {
callback(new Error('Error encrypting plaintext!')); reject(new Error('Error encrypting plaintext!'));
return; return;
} }
resolve(publicKeys);
}).then(function(publicKeys) {
if (publicKeys) { if (publicKeys) {
// encrypt and sign the plaintext // encrypt and sign the plaintext
openpgp.signAndEncryptMessage(publicKeys, this._privateKey, plaintext).then(callback.bind(null, null)).catch(callback); return openpgp.signAndEncryptMessage(publicKeys, self._privateKey, plaintext);
} else { } else {
// if no public keys are available encrypt for myself // if no public keys are available encrypt for myself
openpgp.signAndEncryptMessage([this._publicKey], this._privateKey, plaintext).then(callback.bind(null, null)).catch(callback); return openpgp.signAndEncryptMessage([self._publicKey], self._privateKey, plaintext);
} }
});
}; };
/** /**
@ -296,15 +312,16 @@ 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 self = this;
return self._q(function(resolve, reject) {
var publicKeys, message; 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 // read keys and ciphertext message
try { try {
if (publicKeyArmored) { if (publicKeyArmored) {
@ -312,19 +329,25 @@ PGP.prototype.decrypt = function(ciphertext, publicKeyArmored, callback) {
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 = [this._publicKey]; publicKeys = [self._publicKey];
} }
message = openpgp.message.readArmored(ciphertext); message = openpgp.message.readArmored(ciphertext);
} catch (err) { } catch (err) {
callback(new Error('Error parsing encrypted PGP message!')); reject(new Error('Error parsing encrypted PGP message!'));
return; return;
} }
resolve(publicKeys, message);
}).then(function(publicKeys, message) {
// decrypt and verify pgp message // decrypt and verify pgp message
openpgp.decryptAndVerifyMessage(this._privateKey, publicKeys, message).then(function(decrypted) { 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,16 +356,16 @@ 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 // read keys and ciphertext message
try { try {
if (publicKeyArmored) { if (publicKeyArmored) {
@ -350,17 +373,20 @@ PGP.prototype.verifyClearSignedMessage = function(clearSignedText, publicKeyArmo
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 = [this._publicKey]; publicKeys = [self._publicKey];
} }
message = openpgp.cleartext.readArmored(clearSignedText); message = openpgp.cleartext.readArmored(clearSignedText);
} catch (err) { } catch (err) {
callback(new Error('Error verifying signed PGP message!')); reject(new Error('Error verifying signed PGP message!'));
return; 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,15 +396,16 @@ 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) {
@ -386,23 +413,23 @@ PGP.prototype.verifySignedMessage = function(message, pgpSignature, publicKeyArm
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 = [this._publicKey]; publicKeys = [self._publicKey];
} }
} catch (err) { } catch (err) {
callback(new Error('Error verifying signed PGP message!')); reject(new Error('Error verifying signed PGP message!'));
return; return;
} }
// check signatures
var signatures;
try { try {
var msg = openpgp.message.readSignedContent(message, pgpSignature); var msg = openpgp.message.readSignedContent(message, pgpSignature);
signatures = msg.verify(publicKeys); signatures = msg.verify(publicKeys);
} catch (err) { } catch (err) {
callback(new Error('Error verifying signed PGP message!')); reject(new Error('Error verifying signed PGP message!'));
return; return;
} }
callback(null, checkSignatureValidity(signatures)); resolve(checkSignatureValidity(signatures));
});
}; };
/** /**