Add timeparameter to signing and encryption

This commit is contained in:
KAYLukas
2018-02-15 12:51:41 +01:00
parent be7973b904
commit 7e66ea20db
7 changed files with 577 additions and 76 deletions

View File

@@ -68,22 +68,26 @@ CleartextMessage.prototype.getSigningKeyIds = function() {
/**
* Sign the cleartext message
* @param {Array<module:key~Key>} privateKeys private keys with decrypted secret key data for signing
* @param {Signature} signature (optional) any existing detached signature
* @param {Date} creationDate The creation time of the signature that should be created
* @return {module:message~CleartextMessage} new cleartext message with signed content
*/
CleartextMessage.prototype.sign = async function(privateKeys) {
return new CleartextMessage(this.text, await this.signDetached(privateKeys));
CleartextMessage.prototype.sign = async function(privateKeys, signature = null, creationDate = new Date()) {
return new CleartextMessage(this.text, await this.signDetached(privateKeys, signature, creationDate));
};
/**
* Sign the cleartext message
* @param {Array<module:key~Key>} privateKeys private keys with decrypted secret key data for signing
* @param {Signature} signature (optional) any existing detached signature
* @param {Date} creationDate The creation time of the signature that should be created
* @return {module:signature~Signature} new detached signature of message content
*/
CleartextMessage.prototype.signDetached = async function(privateKeys) {
CleartextMessage.prototype.signDetached = async function(privateKeys, signature = null, creationDate = new Date()) {
const literalDataPacket = new packet.Literal();
literalDataPacket.setText(this.text);
return new Signature(await createSignaturePackets(literalDataPacket, privateKeys));
return new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, creationDate));
};
/**

View File

@@ -301,19 +301,20 @@ Key.prototype.armor = function() {
* Returns first key packet or key packet by given keyId that is available for signing or signature verification
* @param {module:type/keyid} keyId, optional
* @param {Boolean} allowExpired allows signature verification with expired keys
* @param {Date} currentDate the current date
* @return {(module:packet/secret_subkey|module:packet/secret_key|null)} key packet or null if no signing key has been found
*/
Key.prototype.getSigningKeyPacket = function(keyId, allowExpired=false) {
Key.prototype.getSigningKeyPacket = function(keyId, allowExpired=false, currentDate = new Date()) {
const primaryUser = this.getPrimaryUser(allowExpired);
if (primaryUser && (!keyId || this.primaryKey.getKeyId().equals(keyId)) &&
isValidSigningKeyPacket(this.primaryKey, primaryUser.selfCertificate, allowExpired)) {
isValidSigningKeyPacket(this.primaryKey, primaryUser.selfCertificate, allowExpired, currentDate)) {
return this.primaryKey;
}
if (this.subKeys) {
for (let i = 0; i < this.subKeys.length; i++) {
if (!keyId || this.subKeys[i].subKey.getKeyId().equals(keyId)) {
for (let j = 0; j < this.subKeys[i].bindingSignatures.length; j++) {
if (isValidSigningKeyPacket(this.subKeys[i].subKey, this.subKeys[i].bindingSignatures[j], allowExpired)) {
if (isValidSigningKeyPacket(this.subKeys[i].subKey, this.subKeys[i].bindingSignatures[j], allowExpired, currentDate)) {
return this.subKeys[i].subKey;
}
}
@@ -323,7 +324,7 @@ Key.prototype.getSigningKeyPacket = function(keyId, allowExpired=false) {
return null;
};
function isValidEncryptionKeyPacket(keyPacket, signature, allowExpired=false) {
function isValidEncryptionKeyPacket(keyPacket, signature, allowExpired=false, currentDate = new Date()) {
return keyPacket.algorithm !== enums.read(enums.publicKey, enums.publicKey.dsa) &&
keyPacket.algorithm !== enums.read(enums.publicKey, enums.publicKey.rsa_sign) &&
keyPacket.algorithm !== enums.read(enums.publicKey, enums.publicKey.ecdsa) &&
@@ -331,43 +332,44 @@ function isValidEncryptionKeyPacket(keyPacket, signature, allowExpired=false) {
(!signature.keyFlags ||
(signature.keyFlags[0] & enums.keyFlags.encrypt_communication) !== 0 ||
(signature.keyFlags[0] & enums.keyFlags.encrypt_storage) !== 0) &&
(allowExpired || (!signature.isExpired() &&
(allowExpired || (!signature.isExpired(currentDate) &&
// check expiration time of V3 key packet
!(keyPacket.version === 3 && keyPacket.expirationTimeV3 !== 0 &&
Date.now() > (keyPacket.created.getTime() + keyPacket.expirationTimeV3*24*3600*1000)) &&
+currentDate > (keyPacket.created.getTime() + keyPacket.expirationTimeV3*24*3600*1000)) &&
// check expiration time of V4 key packet
!(keyPacket.version === 4 && signature.keyNeverExpires === false &&
Date.now() > (keyPacket.created.getTime() + signature.keyExpirationTime*1000))));
+currentDate > (keyPacket.created.getTime() + signature.keyExpirationTime*1000))));
}
function isValidSigningKeyPacket(keyPacket, signature, allowExpired=false) {
function isValidSigningKeyPacket(keyPacket, signature, allowExpired=false, currentDate = new Date()) {
return keyPacket.algorithm !== enums.read(enums.publicKey, enums.publicKey.rsa_encrypt) &&
keyPacket.algorithm !== enums.read(enums.publicKey, enums.publicKey.elgamal) &&
keyPacket.algorithm !== enums.read(enums.publicKey, enums.publicKey.ecdh) &&
(!signature.keyFlags ||
(signature.keyFlags[0] & enums.keyFlags.sign_data) !== 0) &&
(allowExpired || (!signature.isExpired() &&
(allowExpired || (!signature.isExpired(currentDate) &&
// check expiration time of V3 key packet
!(keyPacket.version === 3 && keyPacket.expirationTimeV3 !== 0 &&
Date.now() > (keyPacket.created.getTime() + keyPacket.expirationTimeV3*24*3600*1000)) &&
+currentDate > (keyPacket.created.getTime() + keyPacket.expirationTimeV3*24*3600*1000)) &&
// check expiration time of V4 key packet
!(keyPacket.version === 4 && signature.keyNeverExpires === false &&
Date.now() > (keyPacket.created.getTime() + signature.keyExpirationTime*1000))));
+currentDate > (keyPacket.created.getTime() + signature.keyExpirationTime*1000))));
}
/**
* Returns first key packet or key packet by given keyId that is available for encryption or decryption
* @param {module:type/keyid} keyId, optional
* @param {Date} currentDate optional
* @returns {(module:packet/public_subkey|module:packet/secret_subkey|module:packet/secret_key|module:packet/public_key|null)} key packet or null if no encryption key has been found
*/
Key.prototype.getEncryptionKeyPacket = function(keyId) {
Key.prototype.getEncryptionKeyPacket = function(keyId, currentDate = new Date()) {
// V4: by convention subkeys are preferred for encryption service
// V3: keys MUST NOT have subkeys
if (this.subKeys) {
for (let i = 0; i < this.subKeys.length; i++) {
if (!keyId || this.subKeys[i].subKey.getKeyId().equals(keyId)) {
for (let j = 0; j < this.subKeys[i].bindingSignatures.length; j++) {
if (isValidEncryptionKeyPacket(this.subKeys[i].subKey, this.subKeys[i].bindingSignatures[j])) {
if (isValidEncryptionKeyPacket(this.subKeys[i].subKey, this.subKeys[i].bindingSignatures[j], false, currentDate)) {
return this.subKeys[i].subKey;
}
}
@@ -377,7 +379,7 @@ Key.prototype.getEncryptionKeyPacket = function(keyId) {
// if no valid subkey for encryption, evaluate primary key
const primaryUser = this.getPrimaryUser();
if (primaryUser && (!keyId || this.primaryKey.getKeyId().equals(keyId)) &&
isValidEncryptionKeyPacket(this.primaryKey, primaryUser.selfCertificate)) {
isValidEncryptionKeyPacket(this.primaryKey, primaryUser.selfCertificate, false, currentDate)) {
return this.primaryKey;
}
return null;

View File

@@ -239,9 +239,10 @@ Message.prototype.getText = function() {
* @param {Array<String>} passwords (optional) password(s) for message encryption
* @param {Object} sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String }
* @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs
* @param {Date} creationDate (optional) the current date of encryption
* @return {Message} new message with encrypted content
*/
Message.prototype.encrypt = function(keys, passwords, sessionKey, wildcard = false) {
Message.prototype.encrypt = function(keys, passwords, sessionKey, wildcard = false, creationDate = new Date()) {
let symAlgo;
let msg;
let symEncryptedPacket;
@@ -264,7 +265,7 @@ Message.prototype.encrypt = function(keys, passwords, sessionKey, wildcard = fal
sessionKey = crypto.generateSessionKey(symAlgo);
}
msg = await encryptSessionKey(sessionKey, symAlgo, keys, passwords, wildcard);
msg = await encryptSessionKey(sessionKey, symAlgo, keys, passwords, wildcard, creationDate);
if (config.aead_protect) {
symEncryptedPacket = new packet.SymEncryptedAEADProtected();
@@ -296,16 +297,17 @@ Message.prototype.encrypt = function(keys, passwords, sessionKey, wildcard = fal
* @param {Array<Key>} publicKeys (optional) public key(s) for message encryption
* @param {Array<String>} passwords (optional) for message encryption
* @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs
* @param {Date} creationDate (optional) the date used to encrypt
* @return {Message} new message with encrypted content
*/
export function encryptSessionKey(sessionKey, symAlgo, publicKeys, passwords, wildcard=false) {
export function encryptSessionKey(sessionKey, symAlgo, publicKeys, passwords, wildcard=false, creationDate = new Date()) {
const packetlist = new packet.List();
return Promise.resolve().then(async () => {
if (publicKeys) {
const results = await Promise.all(publicKeys.map(async function(key) {
await key.verifyPrimaryUser();
const encryptionKeyPacket = key.getEncryptionKeyPacket();
const encryptionKeyPacket = key.getEncryptionKeyPacket(undefined, creationDate);
if (!encryptionKeyPacket) {
throw new Error('Could not find valid key packet for encryption in key ' + key.primaryKey.getKeyId().toHex());
}
@@ -358,11 +360,12 @@ export function encryptSessionKey(sessionKey, symAlgo, publicKeys, passwords, wi
/**
* Sign the message (the literal data packet of the message)
* @param {Array<module:key~Key>} privateKey private keys with decrypted secret key data for signing
* @param {Array<module:key~Key>} privateKeys private keys with decrypted secret key data for signing
* @param {Signature} signature (optional) any existing detached signature to add to the message
* @param {Date} creationDate} (optional) the creation date of the signature used for creating a new signature
* @return {module:message~Message} new message with signed content
*/
Message.prototype.sign = async function(privateKeys=[], signature=null) {
Message.prototype.sign = async function(privateKeys=[], signature=null, creationDate = new Date()) {
const packetlist = new packet.List();
const literalDataPacket = this.packets.findPacket(enums.packet.literal);
@@ -397,7 +400,7 @@ Message.prototype.sign = async function(privateKeys=[], signature=null) {
throw new Error('Need private key for signing');
}
await privateKey.verifyPrimaryUser();
const signingKeyPacket = privateKey.getSigningKeyPacket();
const signingKeyPacket = privateKey.getSigningKeyPacket(undefined, undefined, creationDate);
if (!signingKeyPacket) {
throw new Error('Could not find valid key packet for signing in key ' +
privateKey.primaryKey.getKeyId().toHex());
@@ -416,7 +419,7 @@ Message.prototype.sign = async function(privateKeys=[], signature=null) {
});
packetlist.push(literalDataPacket);
packetlist.concat(await createSignaturePackets(literalDataPacket, privateKeys, signature));
packetlist.concat(await createSignaturePackets(literalDataPacket, privateKeys, signature, creationDate));
return new Message(packetlist);
};
@@ -443,26 +446,30 @@ Message.prototype.compress = function(compression) {
/**
* Create a detached signature for the message (the literal data packet of the message)
* @param {Array<module:key~Key>} privateKey private keys with decrypted secret key data for signing
* @param {Array<module:key~Key>} privateKeys private keys with decrypted secret key data for signing
* @param {Signature} signature (optional) any existing detached signature
* @param {Date} creationDate (optional) the creation date to sign the message with
* @return {module:signature~Signature} new detached signature of message content
*/
Message.prototype.signDetached = async function(privateKeys=[], signature=null) {
Message.prototype.signDetached = async function(privateKeys=[], signature=null, creationDate = new Date()) {
const packetlist = new packet.List();
const literalDataPacket = this.packets.findPacket(enums.packet.literal);
if (!literalDataPacket) {
throw new Error('No literal data packet to sign.');
}
return new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature));
return new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, creationDate));
};
/**
* Create signature packets for the message
* @param {module:packet/literal} the literal data packet to sign
* @param {Array<module:key~Key>} privateKey private keys with decrypted secret key data for signing
* @param {module:packet/literal} literalDataPacket the literal data packet to sign
* @param {Array<module:key~Key>} privateKeys private keys with decrypted secret key data for signing
* @param {Signature} signature (optional) any existing detached signature to append
* @param {Date} creationDate (optional) the creation date to sign the message with
* @return {module:packet/packetlist} list of signature packets
*/
export async function createSignaturePackets(literalDataPacket, privateKeys, signature=null) {
export async function createSignaturePackets(literalDataPacket, privateKeys, signature=null, creationDate = new Date()) {
const packetlist = new packet.List();
const literalFormat = enums.write(enums.literal, literalDataPacket.format);
@@ -474,14 +481,14 @@ export async function createSignaturePackets(literalDataPacket, privateKeys, sig
throw new Error('Need private key for signing');
}
await privateKey.verifyPrimaryUser();
const signingKeyPacket = privateKey.getSigningKeyPacket();
const signingKeyPacket = privateKey.getSigningKeyPacket(undefined, undefined, creationDate);
if (!signingKeyPacket) {
throw new Error('Could not find valid key packet for signing in key ' + privateKey.primaryKey.getKeyId().toHex());
}
if (!signingKeyPacket.isDecrypted) {
throw new Error('Private key is not decrypted.');
}
const signaturePacket = new packet.Signature();
const signaturePacket = new packet.Signature(creationDate);
signaturePacket.signatureType = signatureType;
signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;
signaturePacket.hashAlgorithm = getPreferredHashAlgo(privateKey);
@@ -626,11 +633,12 @@ export function readSignedContent(content, detachedSignature) {
* creates new message object from text
* @param {String} text
* @param {String} filename (optional)
* @param {Date} creationDate (optional)
* @return {module:message~Message} new message object
* @static
*/
export function fromText(text, filename) {
const literalDataPacket = new packet.Literal();
export function fromText(text, filename, creationDate = new Date()) {
const literalDataPacket = new packet.Literal(creationDate);
// text will be converted to UTF8
literalDataPacket.setText(text);
if (filename !== undefined) {
@@ -645,15 +653,16 @@ export function fromText(text, filename) {
* creates new message object from binary data
* @param {Uint8Array} bytes
* @param {String} filename (optional)
* @param {Date} creationDate (optional)
* @return {module:message~Message} new message object
* @static
*/
export function fromBinary(bytes, filename) {
export function fromBinary(bytes, filename, creationDate = new Date()) {
if (!util.isUint8Array(bytes)) {
throw new Error('Data must be in the form of a Uint8Array');
}
const literalDataPacket = new packet.Literal();
const literalDataPacket = new packet.Literal(creationDate);
if (filename) {
literalDataPacket.setFilename(filename);
}

View File

@@ -202,33 +202,34 @@ export function decryptKey({ privateKey, passphrase }) {
* @param {Signature} signature (optional) a detached signature to add to the encrypted message
* @param {Boolean} returnSessionKey (optional) if the unencrypted session key should be added to returned object
* @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs
* @param {Date} creationDate (optional) the creation date used to encrypt and sign the message
* @return {Promise<Object>} encrypted (and optionally signed message) in the form:
* {data: ASCII armored message if 'armor' is true,
* message: full Message object if 'armor' is false, signature: detached signature if 'detached' is true}
* @static
*/
export function encrypt({ data, publicKeys, privateKeys, passwords, sessionKey, filename, compression = config.compression, armor = true, detached = false, signature = null, returnSessionKey = false, wildcard = false}) {
export function encrypt({ data, publicKeys, privateKeys, passwords, sessionKey, filename, compression = config.compression, armor = true, detached = false, signature = null, returnSessionKey = false, wildcard = false, creationDate = new Date()}) {
checkData(data); publicKeys = toArray(publicKeys); privateKeys = toArray(privateKeys); passwords = toArray(passwords);
if (!nativeAEAD() && asyncProxy) { // use web worker if web crypto apis are not supported
return asyncProxy.delegate('encrypt', { data, publicKeys, privateKeys, passwords, sessionKey, filename, armor, detached, signature, returnSessionKey, wildcard });
return asyncProxy.delegate('encrypt', { data, publicKeys, privateKeys, passwords, sessionKey, filename, armor, detached, signature, returnSessionKey, wildcard, creationDate });
}
const result = {};
return Promise.resolve().then(async function() {
let message = createMessage(data, filename);
let message = createMessage(data, filename, creationDate);
if (!privateKeys) {
privateKeys = [];
}
if (privateKeys.length || signature) { // sign the message only if private keys or signature is specified
if (detached) {
const detachedSignature = await message.signDetached(privateKeys, signature);
const detachedSignature = await message.signDetached(privateKeys, signature, creationDate);
result.signature = armor ? detachedSignature.armor() : detachedSignature;
} else {
message = await message.sign(privateKeys, signature);
message = await message.sign(privateKeys, signature, creationDate);
}
}
message = message.compress(compression);
return message.encrypt(publicKeys, passwords, sessionKey, wildcard);
return message.encrypt(publicKeys, passwords, sessionKey, wildcard, creationDate);
}).then(encrypted => {
if (armor) {
@@ -291,20 +292,21 @@ export function decrypt({ message, privateKeys, passwords, sessionKeys, publicKe
* @param {Key|Array<Key>} privateKeys array of keys or single key with decrypted secret key data to sign cleartext
* @param {Boolean} armor (optional) if the return value should be ascii armored or the message object
* @param {Boolean} detached (optional) if the return value should contain a detached signature
* @param {Date} creationDate (optional) the creation date used to sign the message
* @return {Promise<Object>} signed cleartext in the form:
* {data: ASCII armored message if 'armor' is true,
* message: full Message object if 'armor' is false, signature: detached signature if 'detached' is true}
* @static
*/
export function sign({
data, privateKeys, armor=true, detached=false
data, privateKeys, armor=true, detached=false, creationDate = new Date()
}) {
checkData(data);
privateKeys = toArray(privateKeys);
if (asyncProxy) { // use web worker if available
return asyncProxy.delegate('sign', {
data, privateKeys, armor, detached
data, privateKeys, armor, detached, creationDate
});
}
@@ -313,10 +315,10 @@ export function sign({
let message = util.isString(data) ? new CleartextMessage(data) : messageLib.fromBinary(data);
if (detached) {
const signature = await message.signDetached(privateKeys);
const signature = await message.signDetached(privateKeys, undefined, creationDate);
result.signature = armor ? signature.armor() : signature;
} else {
message = await message.sign(privateKeys);
message = await message.sign(privateKeys, undefined, creationDate);
if (armor) {
result.data = message.armor();
} else {
@@ -493,14 +495,15 @@ function toArray(param) {
* Creates a message obejct either from a Uint8Array or a string.
* @param {String|Uint8Array} data the payload for the message
* @param {String} filename the literal data packet's filename
* @param {Date} creationDate the creation date of the package
* @return {Message} a message object
*/
function createMessage(data, filename) {
function createMessage(data, filename, creationDate = new Date()) {
let msg;
if (util.isUint8Array(data)) {
msg = messageLib.fromBinary(data, filename);
msg = messageLib.fromBinary(data, filename, creationDate);
} else if (util.isString(data)) {
msg = messageLib.fromText(data, filename);
msg = messageLib.fromText(data, filename, creationDate);
} else {
throw new Error('Data must be of type String or Uint8Array');
}

View File

@@ -31,10 +31,10 @@ import enums from '../enums.js';
/**
* @constructor
*/
export default function Literal() {
export default function Literal(creationDate = new Date()) {
this.tag = enums.packet.literal;
this.format = 'utf8'; // default format for literal data packets
this.date = new Date();
this.date = creationDate;
this.data = new Uint8Array(0); // literal data representation
this.filename = 'msg.txt';
}

View File

@@ -41,7 +41,7 @@ import type_keyid from '../type/keyid.js';
/**
* @constructor
*/
export default function Signature() {
export default function Signature(creationDate = new Date()) {
this.tag = enums.packet.signature;
this.version = 4;
this.signatureType = null;
@@ -52,7 +52,7 @@ export default function Signature() {
this.unhashedSubpackets = null;
this.signedHashValue = null;
this.created = new Date();
this.created = creationDate;
this.signatureExpirationTime = null;
this.signatureNeverExpires = true;
this.exportable = null;
@@ -663,9 +663,9 @@ Signature.prototype.verify = async function (key, data) {
* Verifies signature expiration date
* @return {Boolean} true if expired
*/
Signature.prototype.isExpired = function () {
Signature.prototype.isExpired = function (currentDate = new Date()) {
if (!this.signatureNeverExpires) {
return Date.now() > (this.created.getTime() + this.signatureExpirationTime*1000);
return +currentDate > (this.created.getTime() + this.signatureExpirationTime*1000);
}
return false;
};