From fb3d23427dd00f251865204fd39768bfc54a69f9 Mon Sep 17 00:00:00 2001 From: Daniel Huigens Date: Thu, 14 May 2020 13:38:08 +0200 Subject: [PATCH] Allow dead code elimination --- package-lock.json | 29 ++- package.json | 4 +- rollup.config.js | 4 + src/cleartext.js | 14 +- src/crypto/pkcs1.js | 2 +- src/crypto/pkcs5.js | 2 +- src/enums.js | 12 +- src/index.js | 2 +- src/key/factory.js | 16 +- src/key/helper.js | 68 ++++--- src/key/key.js | 60 +++--- src/key/subkey.js | 52 ++--- src/key/user.js | 50 ++--- src/message.js | 109 ++++++---- src/openpgp.js | 14 +- src/packet/all_packets.js | 90 +++++---- .../{compressed.js => compressed_data.js} | 86 ++++---- src/packet/index.js | 14 +- src/packet/{literal.js => literal_data.js} | 26 +-- src/packet/marker.js | 8 +- src/packet/one_pass_signature.js | 24 +-- src/packet/packet.js | 10 +- src/packet/packetlist.js | 28 +-- src/packet/public_key.js | 32 +-- .../public_key_encrypted_session_key.js | 18 +- src/packet/public_subkey.js | 14 +- src/packet/secret_key.js | 34 ++-- src/packet/secret_subkey.js | 14 +- src/packet/signature.js | 42 ++-- ...s => sym_encrypted_aead_protected_data.js} | 30 ++- ...sym_encrypted_integrity_protected_data.js} | 28 ++- src/packet/sym_encrypted_session_key.js | 14 +- ...ted.js => symmetrically_encrypted_data.js} | 30 ++- src/packet/trust.js | 6 +- src/packet/user_attribute.js | 14 +- src/packet/userid.js | 14 +- src/signature.js | 10 +- test/general/key.js | 16 +- test/general/openpgp.js | 34 ++-- test/general/packet.js | 190 +++++++++--------- test/security/message_signature_bypass.js | 4 +- test/security/preferred_algo_mismatch.js | 2 +- test/security/subkey_trust.js | 6 +- test/security/unsigned_subpackets.js | 6 +- 44 files changed, 682 insertions(+), 600 deletions(-) rename src/packet/{compressed.js => compressed_data.js} (69%) rename src/packet/{literal.js => literal_data.js} (87%) rename src/packet/{sym_encrypted_aead_protected.js => sym_encrypted_aead_protected_data.js} (89%) rename src/packet/{sym_encrypted_integrity_protected.js => sym_encrypted_integrity_protected_data.js} (85%) rename src/packet/{symmetrically_encrypted.js => symmetrically_encrypted_data.js} (82%) diff --git a/package-lock.json b/package-lock.json index 7575ccc1..2d9dfbd2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -722,6 +722,15 @@ "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", "dev": true }, + "commander": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.8.1.tgz", + "integrity": "sha1-Br42f+v9oMMwqh4qBy09yXYkJdQ=", + "dev": true, + "requires": { + "graceful-readlink": ">= 1.0.0" + } + }, "commondir": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", @@ -2815,9 +2824,8 @@ } }, "pako": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.6.tgz", - "integrity": "sha512-lQe48YPsMJAig+yngZ87Lus+NF+3mtu7DVOBu6b/gHO1YpKwIj5AWjZ/TOS7i46HD/UixzWb1zeWDZfGZ3iYcg==", + "version": "github:openpgpjs/pako#f38f7368a5fa511e54b95add2f04444c3a9d803f", + "from": "github:openpgpjs/pako#f38f7368a5fa511e54b95add2f04444c3a9d803f", "dev": true }, "parse-json": { @@ -3168,22 +3176,11 @@ "dev": true }, "seek-bzip": { - "version": "github:openpgpjs/seek-bzip#6187fc025851d35c4e104a25ea15a10b9b8d6f7d", - "from": "github:openpgpjs/seek-bzip#6187fc025851d35c4e104a25ea15a10b9b8d6f7d", + "version": "github:openpgpjs/seek-bzip#4b89457f20c0e1921b4689106a31c99782c29829", + "from": "github:openpgpjs/seek-bzip#4b89457f20c0e1921b4689106a31c99782c29829", "dev": true, "requires": { "commander": "~2.8.1" - }, - "dependencies": { - "commander": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.8.1.tgz", - "integrity": "sha1-Br42f+v9oMMwqh4qBy09yXYkJdQ=", - "dev": true, - "requires": { - "graceful-readlink": ">= 1.0.0" - } - } } }, "semver": { diff --git a/package.json b/package.json index c63312f3..9fe1ff99 100644 --- a/package.json +++ b/package.json @@ -62,10 +62,10 @@ "jsdoc": "github:openpgpjs/jsdoc#0f1816eb4553856647b4ca9561b9307b11ec4f9e", "mocha": "^5.0.0", "nyc": "^14.1.1", - "pako": "^1.0.6", + "pako": "github:openpgpjs/pako#f38f7368a5fa511e54b95add2f04444c3a9d803f", "rollup": "^2.7.2", "rollup-plugin-terser": "^5.3.0", - "seek-bzip": "github:openpgpjs/seek-bzip#6187fc025851d35c4e104a25ea15a10b9b8d6f7d", + "seek-bzip": "github:openpgpjs/seek-bzip#4b89457f20c0e1921b4689106a31c99782c29829", "sinon": "^4.3.0", "text-encoding-utf-8": "^1.0.2", "tweetnacl": "github:openpgpjs/tweetnacl-js#3dae25bd3eaa77173f3405676b595721dde92eec", diff --git a/rollup.config.js b/rollup.config.js index 4fa16b21..7c8364fe 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -20,6 +20,10 @@ const terserOptions = { ecma: 2017, compress: { unsafe: true + }, + output: { + comments: '/^(?:!|#__)/', + preserve_annotations: true } }; diff --git a/src/cleartext.js b/src/cleartext.js index 8d8b57a6..92b03dfe 100644 --- a/src/cleartext.js +++ b/src/cleartext.js @@ -27,7 +27,7 @@ import armor from './encoding/armor'; import enums from './enums'; import util from './util'; -import packet from './packet'; +import { PacketList, LiteralDataPacket, SignaturePacket } from './packet'; import { Signature } from './signature'; import { createVerificationObjects, createSignaturePackets } from './message'; @@ -47,7 +47,7 @@ export function CleartextMessage(text, signature) { if (signature && !(signature instanceof Signature)) { throw new Error('Invalid signature input'); } - this.signature = signature || new Signature(new packet.List()); + this.signature = signature || new Signature(new PacketList()); } /** @@ -86,7 +86,7 @@ CleartextMessage.prototype.sign = async function(privateKeys, signature = null, * @async */ CleartextMessage.prototype.signDetached = async function(privateKeys, signature = null, date = new Date(), userIds = []) { - const literalDataPacket = new packet.Literal(); + const literalDataPacket = new LiteralDataPacket(); literalDataPacket.setText(this.text); return new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, date, userIds, true)); @@ -112,7 +112,7 @@ CleartextMessage.prototype.verify = function(keys, date = new Date()) { */ CleartextMessage.prototype.verifyDetached = function(signature, keys, date = new Date()) { const signatureList = signature.packets; - const literalDataPacket = new packet.Literal(); + const literalDataPacket = new LiteralDataPacket(); // we assume that cleartext signature is generated based on UTF8 cleartext literalDataPacket.setText(this.text); return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true); @@ -157,8 +157,8 @@ export async function readArmored(armoredText) { if (input.type !== enums.armor.signed) { throw new Error('No cleartext signed message.'); } - const packetlist = new packet.List(); - await packetlist.read(input.data); + const packetlist = new PacketList(); + await packetlist.read(input.data, { SignaturePacket }); verifyHeaders(input.headers, packetlist); const signature = new Signature(packetlist); return new CleartextMessage(input.text, signature); @@ -167,7 +167,7 @@ export async function readArmored(armoredText) { /** * Compare hash algorithm specified in the armor header with signatures * @param {Array} headers Armor headers - * @param {module:packet.List} packetlist The packetlist with signature packets + * @param {PacketList} packetlist The packetlist with signature packets * @private */ function verifyHeaders(headers, packetlist) { diff --git a/src/crypto/pkcs1.js b/src/crypto/pkcs1.js index 6a46eb27..a7f50a39 100644 --- a/src/crypto/pkcs1.js +++ b/src/crypto/pkcs1.js @@ -19,7 +19,7 @@ * @fileoverview Provides EME-PKCS1-v1_5 encoding and decoding and EMSA-PKCS1-v1_5 encoding function * @see module:crypto/public_key/rsa * @see module:crypto/public_key/elliptic/ecdh - * @see module:packet.PublicKeyEncryptedSessionKey + * @see PublicKeyEncryptedSessionKeyPacket * @requires crypto/random * @requires crypto/hash * @requires util diff --git a/src/crypto/pkcs5.js b/src/crypto/pkcs5.js index 23c93b2d..4f826b74 100644 --- a/src/crypto/pkcs5.js +++ b/src/crypto/pkcs5.js @@ -17,7 +17,7 @@ /** * @fileoverview Functions to add and remove PKCS5 padding - * @see module:packet.PublicKeyEncryptedSessionKey + * @see PublicKeyEncryptedSessionKeyPacket * @module crypto/pkcs5 */ diff --git a/src/enums.js b/src/enums.js index 39520cf1..48b8a76a 100644 --- a/src/enums.js +++ b/src/enums.js @@ -196,17 +196,17 @@ export default { secretKey: 5, publicKey: 6, secretSubkey: 7, - compressed: 8, - symmetricallyEncrypted: 9, + compressedData: 8, + symmetricallyEncryptedData: 9, marker: 10, - literal: 11, + literalData: 11, trust: 12, - userid: 13, + userID: 13, publicSubkey: 14, userAttribute: 17, - symEncryptedIntegrityProtected: 18, + symEncryptedIntegrityProtectedData: 18, modificationDetectionCode: 19, - symEncryptedAEADProtected: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1 + symEncryptedAEADProtectedData: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1 }, /** Data types in the literal packet diff --git a/src/index.js b/src/index.js index 862da8b9..9acd3990 100644 --- a/src/index.js +++ b/src/index.js @@ -51,7 +51,7 @@ export { default as util } from './util'; * @see module:packet * @name module:openpgp.packet */ -export { default as packet } from './packet'; +export * from './packet'; /** * @see module:type/mpi diff --git a/src/key/factory.js b/src/key/factory.js index 64ddf310..f9b92b37 100644 --- a/src/key/factory.js +++ b/src/key/factory.js @@ -27,7 +27,7 @@ * @module key/factory */ -import packet from '../packet'; +import { PacketList, UserIDPacket, SignaturePacket } from '../packet'; import Key from './key'; import * as helper from './helper'; import enums from '../enums'; @@ -147,7 +147,7 @@ async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options) { } })); - const packetlist = new packet.List(); + const packetlist = new PacketList(); packetlist.push(secretKeyPacket); @@ -165,13 +165,13 @@ async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options) { return algos; } - const userIdPacket = new packet.Userid(); + const userIdPacket = new UserIDPacket(); userIdPacket.format(userId); const dataToSign = {}; dataToSign.userId = userIdPacket; dataToSign.key = secretKeyPacket; - const signaturePacket = new packet.Signature(options.date); + const signaturePacket = new SignaturePacket(options.date); signaturePacket.signatureType = enums.signature.certGeneric; signaturePacket.publicKeyAlgorithm = secretKeyPacket.algorithm; signaturePacket.hashAlgorithm = await helper.getPreferredHashAlgo(null, secretKeyPacket); @@ -270,8 +270,8 @@ async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options) { * @static */ export async function read(data) { - const packetlist = new packet.List(); - await packetlist.read(data); + const packetlist = new PacketList(); + await packetlist.read(data, helper.allowedKeyPackets); return new Key(packetlist); } @@ -299,8 +299,8 @@ export async function readArmored(armoredKey) { */ export async function readAll(data) { const keys = []; - const packetlist = new packet.List(); - await packetlist.read(data); + const packetlist = new PacketList(); + await packetlist.read(data, helper.allowedKeyPackets); const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); if (keyIndex.length === 0) { throw new Error('No key packet found'); diff --git a/src/key/helper.js b/src/key/helper.js index cbe2a574..640fcb2f 100644 --- a/src/key/helper.js +++ b/src/key/helper.js @@ -7,14 +7,32 @@ * @module key/helper */ -import packet from '../packet'; +import { + PublicKeyPacket, + PublicSubkeyPacket, + SecretKeyPacket, + SecretSubkeyPacket, + UserIDPacket, + UserAttributePacket, + SignaturePacket +} from '../packet'; import enums from '../enums'; import config from '../config'; import crypto from '../crypto'; import util from '../util'; +export const allowedKeyPackets = { + PublicKeyPacket, + PublicSubkeyPacket, + SecretKeyPacket, + SecretSubkeyPacket, + UserIDPacket, + UserAttributePacket, + SignaturePacket +}; + export async function generateSecretSubkey(options) { - const secretSubkeyPacket = new packet.SecretSubkey(options.date); + const secretSubkeyPacket = new SecretSubkeyPacket(options.date); secretSubkeyPacket.packets = null; secretSubkeyPacket.algorithm = enums.read(enums.publicKey, options.algorithm); await secretSubkeyPacket.generate(options.rsaBits, options.curve); @@ -22,7 +40,7 @@ export async function generateSecretSubkey(options) { } export async function generateSecretKey(options) { - const secretKeyPacket = new packet.SecretKey(options.date); + const secretKeyPacket = new SecretKeyPacket(options.date); secretKeyPacket.packets = null; secretKeyPacket.algorithm = enums.read(enums.publicKey, options.algorithm); await secretKeyPacket.generate(options.rsaBits, options.curve); @@ -31,9 +49,9 @@ export async function generateSecretKey(options) { /** * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future. - * @param {Array} signatures List of signatures + * @param {Array} signatures List of signatures * @param {Date} date Use the given date instead of the current time - * @returns {Promise} The latest valid signature + * @returns {Promise} The latest valid signature * @async */ export async function getLatestValidSignature(signatures, primaryKey, signatureType, dataToVerify, date = new Date()) { @@ -76,15 +94,15 @@ export function isDataExpired(keyPacket, signature, date = new Date()) { /** * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1} - * @param {module:packet.SecretSubkey} subkey Subkey key packet - * @param {module:packet.SecretKey} primaryKey Primary key packet + * @param {SecretSubkeyPacket} subkey Subkey key packet + * @param {SecretKeyPacket} primaryKey Primary key packet * @param {Object} options */ export async function createBindingSignature(subkey, primaryKey, options) { const dataToSign = {}; dataToSign.key = primaryKey; dataToSign.bind = subkey; - const subkeySignaturePacket = new packet.Signature(options.date); + const subkeySignaturePacket = new SignaturePacket(options.date); subkeySignaturePacket.signatureType = enums.signature.subkeyBinding; subkeySignaturePacket.publicKeyAlgorithm = primaryKey.algorithm; subkeySignaturePacket.hashAlgorithm = await getPreferredHashAlgo(null, subkey); @@ -107,7 +125,7 @@ export async function createBindingSignature(subkey, primaryKey, options) { /** * Returns the preferred signature hash algorithm of a key * @param {module:key.Key} key (optional) the key to get preferences from - * @param {module:packet.SecretKey|module:packet.SecretSubkey} keyPacket key packet used for signing + * @param {SecretKeyPacket|SecretSubkeyPacket} keyPacket key packet used for signing * @param {Date} date (optional) use the given date for verification instead of the current time * @param {Object} userId (optional) user ID * @returns {Promise} @@ -125,10 +143,10 @@ export async function getPreferredHashAlgo(key, keyPacket, date = new Date(), us } } switch (Object.getPrototypeOf(keyPacket)) { - case packet.SecretKey.prototype: - case packet.PublicKey.prototype: - case packet.SecretSubkey.prototype: - case packet.PublicSubkey.prototype: + case SecretKeyPacket.prototype: + case PublicKeyPacket.prototype: + case SecretSubkeyPacket.prototype: + case PublicSubkeyPacket.prototype: switch (keyPacket.algorithm) { case 'ecdh': case 'ecdsa': @@ -182,8 +200,8 @@ export async function getPreferredAlgo(type, keys, date = new Date(), userIds = /** * Create signature packet * @param {Object} dataToSign Contains packets to be signed - * @param {module:packet.SecretKey| - * module:packet.SecretSubkey} signingKeyPacket secret key packet for signing + * @param {SecretKeyPacket| + * SecretSubkeyPacket} signingKeyPacket secret key packet for signing * @param {Object} signatureProperties (optional) properties to write on the signature packet before signing * @param {Date} date (optional) override the creationtime of the signature * @param {Object} userId (optional) user ID @@ -195,7 +213,7 @@ export async function createSignaturePacket(dataToSign, privateKey, signingKeyPa if (!signingKeyPacket.isDecrypted()) { throw new Error('Private key is not decrypted.'); } - const signaturePacket = new packet.Signature(date); + const signaturePacket = new SignaturePacket(date); Object.assign(signaturePacket, signatureProperties); signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; signaturePacket.hashAlgorithm = await getPreferredHashAlgo(privateKey, signingKeyPacket, date, userId); @@ -231,15 +249,15 @@ export async function mergeSignatures(source, dest, attr, checkFn) { /** * Checks if a given certificate or binding signature is revoked - * @param {module:packet.SecretKey| - * module:packet.PublicKey} primaryKey The primary key packet - * @param {Object} dataToVerify The data to check - * @param {Array} revocations The revocation signatures to check - * @param {module:packet.Signature} signature The certificate or signature to check - * @param {module:packet.PublicSubkey| - * module:packet.SecretSubkey| - * module:packet.PublicKey| - * module:packet.SecretKey} key, optional The key packet to check the signature + * @param {SecretKeyPacket| + * PublicKeyPacket} primaryKey The primary key packet + * @param {Object} dataToVerify The data to check + * @param {Array} revocations The revocation signatures to check + * @param {SignaturePacket} signature The certificate or signature to check + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} key, optional The key packet to check the signature * @param {Date} date Use the given date instead of the current time * @returns {Promise} True if the signature revokes the data * @async diff --git a/src/key/key.js b/src/key/key.js index 5d857a08..ac82caf4 100644 --- a/src/key/key.js +++ b/src/key/key.js @@ -26,7 +26,12 @@ */ import armor from '../encoding/armor'; -import packet from '../packet'; +import { + PacketList, + PublicKeyPacket, + PublicSubkeyPacket, + SignaturePacket +} from '../packet'; import enums from '../enums'; import util from '../util'; import User from './user'; @@ -37,13 +42,13 @@ import * as helper from './helper'; * @class * @classdesc Class that represents an OpenPGP key. Must contain a primary key. * Can contain additional subkeys, signatures, user ids, user attributes. - * @param {module:packet.List} packetlist The packets that form this key - * @borrows module:packet.PublicKey#getKeyId as Key#getKeyId - * @borrows module:packet.PublicKey#getFingerprint as Key#getFingerprint - * @borrows module:packet.PublicKey#hasSameFingerprintAs as Key#hasSameFingerprintAs - * @borrows module:packet.PublicKey#getAlgorithmInfo as Key#getAlgorithmInfo - * @borrows module:packet.PublicKey#getCreationTime as Key#getCreationTime - * @borrows module:packet.PublicKey#isDecrypted as Key#isDecrypted + * @param {PacketList} packetlist The packets that form this key + * @borrows PublicKeyPacket#getKeyId as Key#getKeyId + * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint + * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs + * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo + * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime + * @borrows PublicKeyPacket#isDecrypted as Key#isDecrypted */ export default function Key(packetlist) { if (!(this instanceof Key)) { @@ -71,7 +76,7 @@ Object.defineProperty(Key.prototype, 'primaryKey', { /** * Transforms packetlist to structured key data - * @param {module:packet.List} packetlist The packets that form a key + * @param {PacketList} packetlist The packets that form a key */ Key.prototype.packetlist2structure = function(packetlist) { let user; @@ -87,7 +92,7 @@ Key.prototype.packetlist2structure = function(packetlist) { this.keyPacket = packetlist[i]; primaryKeyId = this.getKeyId(); break; - case enums.packet.userid: + case enums.packet.userID: case enums.packet.userAttribute: user = new User(packetlist[i]); this.users.push(user); @@ -149,10 +154,10 @@ Key.prototype.packetlist2structure = function(packetlist) { /** * Transforms structured key data to packetlist - * @returns {module:packet.List} The packets that form a key + * @returns {PacketList} The packets that form a key */ Key.prototype.toPacketlist = function() { - const packetlist = new packet.List(); + const packetlist = new PacketList(); packetlist.push(this.keyPacket); packetlist.concat(this.revocationSignatures); packetlist.concat(this.directSignatures); @@ -169,8 +174,8 @@ Key.prototype.toPacketlist = function() { */ Key.prototype.clone = async function(deep = false) { if (deep) { - const packetlist = new packet.List(); - await packetlist.read(this.toPacketlist().write()); + const packetlist = new PacketList(); + await packetlist.read(this.toPacketlist().write(), helper.allowedKeyPackets); return new Key(packetlist); } return new Key(this.toPacketlist()); @@ -245,7 +250,7 @@ Key.prototype.isPrivate = function() { * @returns {module:key.Key} new public Key */ Key.prototype.toPublic = function() { - const packetlist = new packet.List(); + const packetlist = new PacketList(); const keyPackets = this.toPacketlist(); let bytes; let pubKeyPacket; @@ -254,13 +259,13 @@ Key.prototype.toPublic = function() { switch (keyPackets[i].tag) { case enums.packet.secretKey: bytes = keyPackets[i].writePublicKey(); - pubKeyPacket = new packet.PublicKey(); + pubKeyPacket = new PublicKeyPacket(); pubKeyPacket.read(bytes); packetlist.push(pubKeyPacket); break; case enums.packet.secretSubkey: bytes = keyPackets[i].writePublicKey(); - pubSubkeyPacket = new packet.PublicSubkey(); + pubSubkeyPacket = new PublicSubkeyPacket(); pubSubkeyPacket.read(bytes); packetlist.push(pubSubkeyPacket); break; @@ -395,7 +400,7 @@ Key.prototype.getDecryptionKeys = async function(keyId, date = new Date(), userI * Encrypts all secret key and subkey packets matching keyId * @param {String|Array} passphrases - if multiple passphrases, then should be in same order as packets each should encrypt * @param {module:type/keyid} keyId - * @returns {Promise>} + * @returns {Promise>} * @async */ Key.prototype.encrypt = async function(passphrases, keyId = null) { @@ -516,12 +521,11 @@ Key.prototype.clearPrivateParams = function () { /** * Checks if a signature on a key is revoked - * @param {module:packet.SecretKey| - * @param {module:packet.Signature} signature The signature to verify - * @param {module:packet.PublicSubkey| - * module:packet.SecretSubkey| - * module:packet.PublicKey| - * module:packet.SecretKey} key, optional The key to verify the signature + * @param {SignaturePacket} signature The signature to verify + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} key, optional The key to verify the signature * @param {Date} date Use the given date instead of the current time * @returns {Promise} True if the certificate is revoked * @async @@ -602,7 +606,7 @@ Key.prototype.getExpirationTime = async function(capabilities, keyId, userId) { * @param {Date} date (optional) use the given date for verification instead of the current time * @param {Object} userId (optional) user ID to get instead of the primary user, if it exists * @returns {Promise<{user: module:key.User, - * selfCertification: module:packet.Signature}>} The primary user and the self signature + * selfCertification: SignaturePacket}>} The primary user and the self signature * @async */ Key.prototype.getPrimaryUser = async function(date = new Date(), userId = {}) { @@ -750,7 +754,7 @@ Key.prototype.revoke = async function({ Key.prototype.getRevocationCertificate = async function(date = new Date()) { const dataToVerify = { key: this.keyPacket }; const revocationSignature = await helper.getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date); - const packetlist = new packet.List(); + const packetlist = new PacketList(); packetlist.push(revocationSignature); return armor.encode(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate'); }; @@ -765,8 +769,8 @@ Key.prototype.getRevocationCertificate = async function(date = new Date()) { */ Key.prototype.applyRevocationCertificate = async function(revocationCertificate) { const input = await armor.decode(revocationCertificate); - const packetlist = new packet.List(); - await packetlist.read(input.data); + const packetlist = new PacketList(); + await packetlist.read(input.data, { SignaturePacket }); const revocationSignature = packetlist.findPacket(enums.packet.signature); if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) { throw new Error('Could not find revocation signature packet'); diff --git a/src/key/subkey.js b/src/key/subkey.js index 672c3377..082a31e9 100644 --- a/src/key/subkey.js +++ b/src/key/subkey.js @@ -7,17 +7,17 @@ import enums from '../enums'; import * as helper from './helper'; -import packet from '../packet'; +import { PacketList } from '../packet'; /** * @class * @classdesc Class that represents a subkey packet and the relevant signatures. - * @borrows module:packet.PublicSubkey#getKeyId as SubKey#getKeyId - * @borrows module:packet.PublicSubkey#getFingerprint as SubKey#getFingerprint - * @borrows module:packet.PublicSubkey#hasSameFingerprintAs as SubKey#hasSameFingerprintAs - * @borrows module:packet.PublicSubkey#getAlgorithmInfo as SubKey#getAlgorithmInfo - * @borrows module:packet.PublicSubkey#getCreationTime as SubKey#getCreationTime - * @borrows module:packet.PublicSubkey#isDecrypted as SubKey#isDecrypted + * @borrows PublicSubkeyPacket#getKeyId as SubKey#getKeyId + * @borrows PublicSubkeyPacket#getFingerprint as SubKey#getFingerprint + * @borrows PublicSubkeyPacket#hasSameFingerprintAs as SubKey#hasSameFingerprintAs + * @borrows PublicSubkeyPacket#getAlgorithmInfo as SubKey#getAlgorithmInfo + * @borrows PublicSubkeyPacket#getCreationTime as SubKey#getCreationTime + * @borrows PublicSubkeyPacket#isDecrypted as SubKey#isDecrypted */ export default function SubKey(subKeyPacket) { if (!(this instanceof SubKey)) { @@ -30,10 +30,10 @@ export default function SubKey(subKeyPacket) { /** * Transforms structured subkey data to packetlist - * @returns {module:packet.List} + * @returns {PacketListPacket} */ SubKey.prototype.toPacketlist = function() { - const packetlist = new packet.List(); + const packetlist = new PacketList(); packetlist.push(this.keyPacket); packetlist.concat(this.revocationSignatures); packetlist.concat(this.bindingSignatures); @@ -42,13 +42,13 @@ SubKey.prototype.toPacketlist = function() { /** * Checks if a binding signature of a subkey is revoked - * @param {module:packet.SecretKey| - * module:packet.PublicKey} primaryKey The primary key packet - * @param {module:packet.Signature} signature The binding signature to verify - * @param {module:packet.PublicSubkey| - * module:packet.SecretSubkey| - * module:packet.PublicKey| - * module:packet.SecretKey} key, optional The key to verify the signature + * @param {SecretKeyPacket| + * PublicKeyPacket} primaryKey The primary key packet + * @param {SignaturePacket} signature The binding signature to verify + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} key, optional The key to verify the signature * @param {Date} date Use the given date instead of the current time * @returns {Promise} True if the binding signature is revoked * @async @@ -66,9 +66,9 @@ SubKey.prototype.isRevoked = async function(primaryKey, signature, key, date = n /** * Verify subkey. Checks for revocation signatures, expiration time * and valid binding signature. Throws if the subkey is invalid. - * @param {module:packet.SecretKey| - * module:packet.PublicKey} primaryKey The primary key packet - * @param {Date} date Use the given date instead of the current time + * @param {SecretKeyPacket| + * PublicKeyPacket} primaryKey The primary key packet + * @param {Date} date Use the given date instead of the current time * @returns {Promise} * @async */ @@ -89,9 +89,9 @@ SubKey.prototype.verify = async function(primaryKey, date = new Date()) { /** * Returns the expiration time of the subkey or Infinity if key does not expire * Returns null if the subkey is invalid. - * @param {module:packet.SecretKey| - * module:packet.PublicKey} primaryKey The primary key packet - * @param {Date} date Use the given date instead of the current time + * @param {SecretKeyPacket| + * PublicKeyPacket} primaryKey The primary key packet + * @param {Date} date Use the given date instead of the current time * @returns {Promise} * @async */ @@ -110,9 +110,9 @@ SubKey.prototype.getExpirationTime = async function(primaryKey, date = new Date( /** * Update subkey with new components from specified subkey - * @param {module:key~SubKey} subKey Source subkey to merge - * @param {module:packet.SecretKey| - module:packet.SecretSubkey} primaryKey primary key used for validation + * @param {module:key~SubKey} subKey Source subkey to merge + * @param {SecretKeyPacket| + SecretSubkeyPacket} primaryKey primary key used for validation * @returns {Promise} * @async */ @@ -151,7 +151,7 @@ SubKey.prototype.update = async function(subKey, primaryKey) { /** * Revokes the subkey - * @param {module:packet.SecretKey} primaryKey decrypted private primary key for revocation + * @param {SecretKeyPacket} primaryKey decrypted private primary key for revocation * @param {Object} reasonForRevocation optional, object indicating the reason for revocation * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation diff --git a/src/key/user.js b/src/key/user.js index 80cfdaa3..16647d49 100644 --- a/src/key/user.js +++ b/src/key/user.js @@ -8,7 +8,7 @@ import enums from '../enums'; import util from '../util'; -import packet from '../packet'; +import { PacketList } from '../packet'; import { mergeSignatures, isDataRevoked, createSignaturePacket } from './helper'; /** @@ -19,7 +19,7 @@ export default function User(userPacket) { if (!(this instanceof User)) { return new User(userPacket); } - this.userId = userPacket.tag === enums.packet.userid ? userPacket : null; + this.userId = userPacket.tag === enums.packet.userID ? userPacket : null; this.userAttribute = userPacket.tag === enums.packet.userAttribute ? userPacket : null; this.selfCertifications = []; this.otherCertifications = []; @@ -28,10 +28,10 @@ export default function User(userPacket) { /** * Transforms structured user data to packetlist - * @returns {module:packet.List} + * @returns {PacketList} */ User.prototype.toPacketlist = function() { - const packetlist = new packet.List(); + const packetlist = new PacketList(); packetlist.push(this.userId || this.userAttribute); packetlist.concat(this.revocationSignatures); packetlist.concat(this.selfCertifications); @@ -41,8 +41,8 @@ User.prototype.toPacketlist = function() { /** * Signs user - * @param {module:packet.SecretKey| - * module:packet.PublicKey} primaryKey The primary key packet + * @param {SecretKeyPacket| + * PublicKeyPacket} primaryKey The primary key packet * @param {Array} privateKeys Decrypted private keys for signing * @returns {Promise} New user with new certificate signatures * @async @@ -74,13 +74,13 @@ User.prototype.sign = async function(primaryKey, privateKeys) { /** * Checks if a given certificate of the user is revoked - * @param {module:packet.SecretKey| - * module:packet.PublicKey} primaryKey The primary key packet - * @param {module:packet.Signature} certificate The certificate to verify - * @param {module:packet.PublicSubkey| - * module:packet.SecretSubkey| - * module:packet.PublicKey| - * module:packet.SecretKey} key, optional The key to verify the signature + * @param {SecretKeyPacket| + * PublicKeyPacket} primaryKey The primary key packet + * @param {SignaturePacket} certificate The certificate to verify + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} key, optional The key to verify the signature * @param {Date} date Use the given date instead of the current time * @returns {Promise} True if the certificate is revoked * @async @@ -98,9 +98,9 @@ User.prototype.isRevoked = async function(primaryKey, certificate, key, date = n /** * Verifies the user certificate. Throws if the user certificate is invalid. - * @param {module:packet.SecretKey| - * module:packet.PublicKey} primaryKey The primary key packet - * @param {module:packet.Signature} certificate A certificate of this user + * @param {SecretKeyPacket| + * PublicKeyPacket} primaryKey The primary key packet + * @param {SignaturePacket} certificate A certificate of this user * @param {Array} keys Array of keys to verify certificate signatures * @param {Date} date Use the given date instead of the current time * @returns {Promise} status of the certificate @@ -137,8 +137,8 @@ User.prototype.verifyCertificate = async function(primaryKey, certificate, keys, /** * Verifies all user certificates - * @param {module:packet.SecretKey| - * module:packet.PublicKey} primaryKey The primary key packet + * @param {SecretKeyPacket| + * PublicKeyPacket} primaryKey The primary key packet * @param {Array} keys Array of keys to verify certificate signatures * @param {Date} date Use the given date instead of the current time * @returns {Promise} Status of user + * @param {SecretKeyPacket| + * PublicKeyPacket} primaryKey The primary key packet + * @param {Date} date Use the given date instead of the current time + * @returns {Promise} Status of user * @async */ User.prototype.verify = async function(primaryKey, date = new Date()) { @@ -201,9 +201,9 @@ User.prototype.verify = async function(primaryKey, date = new Date()) { /** * Update user with new components from specified user - * @param {module:key.User} user Source user to merge - * @param {module:packet.SecretKey| - * module:packet.SecretSubkey} primaryKey primary key used for validation + * @param {module:key.User} user Source user to merge + * @param {SecretKeyPacket| + * SecretSubkeyPacket} primaryKey primary key used for validation * @returns {Promise} * @async */ diff --git a/src/message.js b/src/message.js index 40e53a92..ca3e84ca 100644 --- a/src/message.js +++ b/src/message.js @@ -36,7 +36,18 @@ import config from './config'; import crypto from './crypto'; import enums from './enums'; import util from './util'; -import packet from './packet'; +import { + PacketList, + LiteralDataPacket, + CompressedDataPacket, + SymEncryptedAEADProtectedDataPacket, + SymEncryptedIntegrityProtectedDataPacket, + SymmetricallyEncryptedDataPacket, + PublicKeyEncryptedSessionKeyPacket, + SymEncryptedSessionKeyPacket, + OnePassSignaturePacket, + SignaturePacket +} from './packet'; import { Signature } from './signature'; import { getPreferredHashAlgo, getPreferredAlgo, isAeadSupported, createSignaturePacket } from './key'; @@ -45,7 +56,7 @@ import { getPreferredHashAlgo, getPreferredAlgo, isAeadSupported, createSignatur * @class * @classdesc Class that represents an OpenPGP message. * Can be an encrypted message, signed message, compressed message or literal message - * @param {module:packet.List} packetlist The packets that form this message + * @param {module:PacketList} packetlist The packets that form this message * See {@link https://tools.ietf.org/html/rfc4880#section-11.3} */ @@ -53,7 +64,7 @@ export function Message(packetlist) { if (!(this instanceof Message)) { return new Message(packetlist); } - this.packets = packetlist || new packet.List(); + this.packets = packetlist || new PacketList(); } /** @@ -104,9 +115,9 @@ Message.prototype.decrypt = async function(privateKeys, passwords, sessionKeys, const keyObjs = sessionKeys || await this.decryptSessionKeys(privateKeys, passwords); const symEncryptedPacketlist = this.packets.filterByTag( - enums.packet.symmetricallyEncrypted, - enums.packet.symEncryptedIntegrityProtected, - enums.packet.symEncryptedAEADProtected + enums.packet.symmetricallyEncryptedData, + enums.packet.symEncryptedIntegrityProtectedData, + enums.packet.symEncryptedAEADProtectedData ); if (symEncryptedPacketlist.length === 0) { @@ -137,7 +148,7 @@ Message.prototype.decrypt = async function(privateKeys, passwords, sessionKeys, } const resultMsg = new Message(symEncryptedPacket.packets); - symEncryptedPacket.packets = new packet.List(); // remove packets after decryption + symEncryptedPacket.packets = new PacketList(); // remove packets after decryption return resultMsg; }; @@ -162,8 +173,8 @@ Message.prototype.decryptSessionKeys = async function(privateKeys, passwords) { await Promise.all(passwords.map(async function(password, i) { let packets; if (i) { - packets = new packet.List(); - await packets.read(symESKeyPacketlist.write()); + packets = new PacketList(); + await packets.read(symESKeyPacketlist.write(), { SymEncryptedSessionKeyPacket }); } else { packets = symESKeyPacketlist; } @@ -249,7 +260,7 @@ Message.prototype.decryptSessionKeys = async function(privateKeys, passwords) { */ Message.prototype.getLiteralData = function() { const msg = this.unwrapCompressed(); - const literal = msg.packets.findPacket(enums.packet.literal); + const literal = msg.packets.findPacket(enums.packet.literalData); return (literal && literal.getBytes()) || null; }; @@ -259,7 +270,7 @@ Message.prototype.getLiteralData = function() { */ Message.prototype.getFilename = function() { const msg = this.unwrapCompressed(); - const literal = msg.packets.findPacket(enums.packet.literal); + const literal = msg.packets.findPacket(enums.packet.literalData); return (literal && literal.getFilename()) || null; }; @@ -269,7 +280,7 @@ Message.prototype.getFilename = function() { */ Message.prototype.getText = function() { const msg = this.unwrapCompressed(); - const literal = msg.packets.findPacket(enums.packet.literal); + const literal = msg.packets.findPacket(enums.packet.literalData); if (literal) { return literal.getText(); } @@ -324,19 +335,19 @@ Message.prototype.encrypt = async function(keys, passwords, sessionKey, wildcard let symEncryptedPacket; if (aeadAlgorithm) { - symEncryptedPacket = new packet.SymEncryptedAEADProtected(); + symEncryptedPacket = new SymEncryptedAEADProtectedDataPacket(); symEncryptedPacket.aeadAlgorithm = aeadAlgorithm; } else if (config.integrityProtect) { - symEncryptedPacket = new packet.SymEncryptedIntegrityProtected(); + symEncryptedPacket = new SymEncryptedIntegrityProtectedDataPacket(); } else { - symEncryptedPacket = new packet.SymmetricallyEncrypted(); + symEncryptedPacket = new SymmetricallyEncryptedDataPacket(); } symEncryptedPacket.packets = this.packets; await symEncryptedPacket.encrypt(algorithm, sessionKeyData, streaming); msg.packets.push(symEncryptedPacket); - symEncryptedPacket.packets = new packet.List(); // remove packets after encryption + symEncryptedPacket.packets = new PacketList(); // remove packets after encryption return msg; }; @@ -354,12 +365,12 @@ Message.prototype.encrypt = async function(keys, passwords, sessionKey, wildcard * @async */ export async function encryptSessionKey(sessionKey, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard = false, date = new Date(), userIds = []) { - const packetlist = new packet.List(); + const packetlist = new PacketList(); if (publicKeys) { const results = await Promise.all(publicKeys.map(async function(publicKey) { const encryptionKey = await publicKey.getEncryptionKey(undefined, date, userIds); - const pkESKeyPacket = new packet.PublicKeyEncryptedSessionKey(); + const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket(); pkESKeyPacket.publicKeyId = wildcard ? type_keyid.wildcard() : encryptionKey.getKeyId(); pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm; pkESKeyPacket.sessionKey = sessionKey; @@ -383,7 +394,7 @@ export async function encryptSessionKey(sessionKey, algorithm, aeadAlgorithm, pu const sum = (accumulator, currentValue) => accumulator + currentValue; const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) { - const symEncryptedSessionKeyPacket = new packet.SymEncryptedSessionKey(); + const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(); symEncryptedSessionKeyPacket.sessionKey = sessionKey; symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm; if (aeadAlgorithm) { @@ -420,9 +431,9 @@ export async function encryptSessionKey(sessionKey, algorithm, aeadAlgorithm, pu * @async */ Message.prototype.sign = async function(privateKeys = [], signature = null, date = new Date(), userIds = [], streaming = false) { - const packetlist = new packet.List(); + const packetlist = new PacketList(); - const literalDataPacket = this.packets.findPacket(enums.packet.literal); + const literalDataPacket = this.packets.findPacket(enums.packet.literalData); if (!literalDataPacket) { throw new Error('No literal data packet to sign.'); } @@ -437,7 +448,7 @@ Message.prototype.sign = async function(privateKeys = [], signature = null, date existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); for (i = existingSigPacketlist.length - 1; i >= 0; i--) { const signaturePacket = existingSigPacketlist[i]; - const onePassSig = new packet.OnePassSignature(); + const onePassSig = new OnePassSignaturePacket(); onePassSig.signatureType = signaturePacket.signatureType; onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm; onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm; @@ -454,7 +465,7 @@ Message.prototype.sign = async function(privateKeys = [], signature = null, date throw new Error('Need private key for signing'); } const signingKey = await privateKey.getSigningKey(undefined, date, userIds); - const onePassSig = new packet.OnePassSignature(); + const onePassSig = new OnePassSignaturePacket(); onePassSig.signatureType = signatureType; onePassSig.hashAlgorithm = await getPreferredHashAlgo(privateKey, signingKey.keyPacket, date, userIds); onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm; @@ -483,11 +494,11 @@ Message.prototype.compress = function(compression) { return this; } - const compressed = new packet.Compressed(); + const compressed = new CompressedDataPacket(); compressed.packets = this.packets; compressed.algorithm = enums.read(enums.compression, compression); - const packetList = new packet.List(); + const packetList = new PacketList(); packetList.push(compressed); return new Message(packetList); @@ -504,7 +515,7 @@ Message.prototype.compress = function(compression) { * @async */ Message.prototype.signDetached = async function(privateKeys = [], signature = null, date = new Date(), userIds = [], streaming = false) { - const literalDataPacket = this.packets.findPacket(enums.packet.literal); + const literalDataPacket = this.packets.findPacket(enums.packet.literalData); if (!literalDataPacket) { throw new Error('No literal data packet to sign.'); } @@ -513,18 +524,18 @@ Message.prototype.signDetached = async function(privateKeys = [], signature = nu /** * Create signature packets for the message - * @param {module:packet.Literal} literalDataPacket the literal data packet to sign + * @param {LiteralDataPacket} literalDataPacket the literal data packet to sign * @param {Array} privateKeys private keys with decrypted secret key data for signing * @param {Signature} signature (optional) any existing detached signature to append * @param {Date} date (optional) override the creationtime of the signature * @param {Array} userIds (optional) user IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] * @param {Boolean} detached (optional) whether to create detached signature packets * @param {Boolean} streaming (optional) whether to process data as a stream - * @returns {Promise} list of signature packets + * @returns {Promise} list of signature packets * @async */ export async function createSignaturePackets(literalDataPacket, privateKeys, signature = null, date = new Date(), userIds = [], detached = false, streaming = false) { - const packetlist = new packet.List(); + const packetlist = new PacketList(); // If data packet was created from Uint8Array, use binary, otherwise use text const signatureType = literalDataPacket.text === null ? @@ -558,7 +569,7 @@ export async function createSignaturePackets(literalDataPacket, privateKeys, sig */ Message.prototype.verify = async function(keys, date = new Date(), streaming) { const msg = this.unwrapCompressed(); - const literalDataList = msg.packets.filterByTag(enums.packet.literal); + const literalDataList = msg.packets.filterByTag(enums.packet.literalData); if (literalDataList.length !== 1) { throw new Error('Can only verify message with one literal data packet.'); } @@ -610,7 +621,7 @@ Message.prototype.verify = async function(keys, date = new Date(), streaming) { */ Message.prototype.verifyDetached = function(signature, keys, date = new Date()) { const msg = this.unwrapCompressed(); - const literalDataList = msg.packets.filterByTag(enums.packet.literal); + const literalDataList = msg.packets.filterByTag(enums.packet.literalData); if (literalDataList.length !== 1) { throw new Error('Can only verify message with one literal data packet.'); } @@ -620,8 +631,8 @@ Message.prototype.verifyDetached = function(signature, keys, date = new Date()) /** * Create object containing signer's keyid and validity of signature - * @param {module:packet.Signature} signature signature packets - * @param {Array} literalDataList array of literal data packets + * @param {SignaturePacket} signature signature packets + * @param {Array} literalDataList array of literal data packets * @param {Array} keys array of keys to verify signatures * @param {Date} date Verify the signature against the given date, * i.e. check signature creation time < date < expiration time @@ -663,7 +674,7 @@ async function createVerificationObject(signature, literalDataList, keys, date = })(), signature: (async () => { const sig = await signaturePacket; - const packetlist = new packet.List(); + const packetlist = new PacketList(); packetlist.push(sig); return new Signature(packetlist); })() @@ -681,8 +692,8 @@ async function createVerificationObject(signature, literalDataList, keys, date = /** * Create list of objects containing signer's keyid and validity of signature - * @param {Array} signatureList array of signature packets - * @param {Array} literalDataList array of literal data packets + * @param {Array} signatureList array of signature packets + * @param {Array} literalDataList array of literal data packets * @param {Array} keys array of keys to verify signatures * @param {Date} date Verify the signature against the given date, * i.e. check signature creation time < date < expiration time @@ -704,7 +715,7 @@ export async function createVerificationObjects(signatureList, literalDataList, * @returns {module:message.Message} message Content of compressed message */ Message.prototype.unwrapCompressed = function() { - const compressed = this.packets.filterByTag(enums.packet.compressed); + const compressed = this.packets.filterByTag(enums.packet.compressedData); if (compressed.length) { return new Message(compressed[0].packets); } @@ -716,7 +727,7 @@ Message.prototype.unwrapCompressed = function() { * @param {String|Uint8Array} detachedSignature The detached ASCII-armored or Uint8Array PGP signature */ Message.prototype.appendSignature = async function(detachedSignature) { - await this.packets.read(util.isUint8Array(detachedSignature) ? detachedSignature : (await armor.decode(detachedSignature)).data); + await this.packets.read(util.isUint8Array(detachedSignature) ? detachedSignature : (await armor.decode(detachedSignature)).data, { SignaturePacket }); }; /** @@ -766,8 +777,18 @@ export async function read(input, fromStream = util.isStream(input)) { if (streamType === 'node') { input = stream.nodeToWeb(input); } - const packetlist = new packet.List(); - await packetlist.read(input, fromStream); + const packetlist = new PacketList(); + await packetlist.read(input, { + LiteralDataPacket, + CompressedDataPacket, + SymEncryptedAEADProtectedDataPacket, + SymEncryptedIntegrityProtectedDataPacket, + SymmetricallyEncryptedDataPacket, + PublicKeyEncryptedSessionKeyPacket, + SymEncryptedSessionKeyPacket, + OnePassSignaturePacket, + SignaturePacket + }, fromStream); const message = new Message(packetlist); message.fromStream = fromStream; return message; @@ -787,13 +808,13 @@ export function fromText(text, filename, date = new Date(), type = 'utf8') { if (streamType === 'node') { text = stream.nodeToWeb(text); } - const literalDataPacket = new packet.Literal(date); + const literalDataPacket = new LiteralDataPacket(date); // text will be converted to UTF8 literalDataPacket.setText(text, type); if (filename !== undefined) { literalDataPacket.setFilename(filename); } - const literalDataPacketlist = new packet.List(); + const literalDataPacketlist = new PacketList(); literalDataPacketlist.push(literalDataPacket); const message = new Message(literalDataPacketlist); message.fromStream = streamType; @@ -818,12 +839,12 @@ export function fromBinary(bytes, filename, date = new Date(), type = 'binary') bytes = stream.nodeToWeb(bytes); } - const literalDataPacket = new packet.Literal(date); + const literalDataPacket = new LiteralDataPacket(date); literalDataPacket.setBytes(bytes, type); if (filename !== undefined) { literalDataPacket.setFilename(filename); } - const literalDataPacketlist = new packet.List(); + const literalDataPacketlist = new PacketList(); literalDataPacketlist.push(literalDataPacket); const message = new Message(literalDataPacketlist); message.fromStream = streamType; diff --git a/src/openpgp.js b/src/openpgp.js index 50b1d0b1..9c255247 100644 --- a/src/openpgp.js +++ b/src/openpgp.js @@ -40,7 +40,11 @@ import stream from 'web-stream-tools'; import { createReadableStreamWrapper } from '@mattiasbuelens/web-streams-adapter'; -import * as messageLib from './message'; +import { + Message, + generateSessionKey as messageGenerateSessionKey, + encryptSessionKey as messageEncryptSessionKey +} from './message'; import { CleartextMessage } from './cleartext'; import { generate, reformat } from './key'; import config from './config/config'; @@ -407,7 +411,7 @@ export function generateSessionKey({ publicKeys, date = new Date(), toUserIds = return Promise.resolve().then(async function() { - return messageLib.generateSessionKey(publicKeys, date, toUserIds); + return messageGenerateSessionKey(publicKeys, date, toUserIds); }).catch(onError.bind(null, 'Error generating session key')); } @@ -433,7 +437,7 @@ export function encryptSessionKey({ data, algorithm, aeadAlgorithm, publicKeys, return Promise.resolve().then(async function() { - const message = await messageLib.encryptSessionKey(data, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard, date, toUserIds); + const message = await messageEncryptSessionKey(data, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard, date, toUserIds); return armor ? message.armor() : message.write(); }).catch(onError.bind(null, 'Error encrypting session key')); @@ -483,12 +487,12 @@ function checkBinary(data, name) { } } function checkMessage(message) { - if (!(message instanceof messageLib.Message)) { + if (!(message instanceof Message)) { throw new Error('Parameter [message] needs to be of type Message'); } } function checkCleartextOrMessage(message) { - if (!(message instanceof CleartextMessage) && !(message instanceof messageLib.Message)) { + if (!(message instanceof CleartextMessage) && !(message instanceof Message)) { throw new Error('Parameter [message] needs to be of type Message or CleartextMessage'); } } diff --git a/src/packet/all_packets.js b/src/packet/all_packets.js index 10f96679..26043264 100644 --- a/src/packet/all_packets.js +++ b/src/packet/all_packets.js @@ -4,75 +4,73 @@ * @module packet/all_packets */ -import * as packets from './all_packets.js'; // re-import module to parse packets from tag - export { - /** @see module:packet.Compressed */ - default as Compressed -} from './compressed.js'; + /** @see CompressedDataPacket */ + default as CompressedDataPacket +} from './compressed_data.js'; export { - /** @see module:packet.SymEncryptedIntegrityProtected */ - default as SymEncryptedIntegrityProtected -} from './sym_encrypted_integrity_protected.js'; + /** @see SymEncryptedIntegrityProtectedDataPacket */ + default as SymEncryptedIntegrityProtectedDataPacket +} from './sym_encrypted_integrity_protected_data.js'; export { - /** @see module:packet.SymEncryptedAEADProtected */ - default as SymEncryptedAEADProtected -} from './sym_encrypted_aead_protected.js'; + /** @see SymEncryptedAEADProtectedDataPacket */ + default as SymEncryptedAEADProtectedDataPacket +} from './sym_encrypted_aead_protected_data.js'; export { - /** @see module:packet.PublicKeyEncryptedSessionKey */ - default as PublicKeyEncryptedSessionKey + /** @see PublicKeyEncryptedSessionKeyPacket */ + default as PublicKeyEncryptedSessionKeyPacket } from './public_key_encrypted_session_key.js'; export { - /** @see module:packet.SymEncryptedSessionKey */ - default as SymEncryptedSessionKey + /** @see SymEncryptedSessionKeyPacket */ + default as SymEncryptedSessionKeyPacket } from './sym_encrypted_session_key.js'; export { - /** @see module:packet.Literal */ - default as Literal -} from './literal.js'; + /** @see LiteralDataPacket */ + default as LiteralDataPacket +} from './literal_data.js'; export { - /** @see module:packet.PublicKey */ - default as PublicKey + /** @see PublicKeyPacket */ + default as PublicKeyPacket } from './public_key.js'; export { - /** @see module:packet.SymmetricallyEncrypted */ - default as SymmetricallyEncrypted -} from './symmetrically_encrypted.js'; + /** @see SymmetricallyEncryptedDataPacket */ + default as SymmetricallyEncryptedDataPacket +} from './symmetrically_encrypted_data.js'; export { - /** @see module:packet.Marker */ - default as Marker + /** @see MarkerPacket */ + default as MarkerPacket } from './marker.js'; export { - /** @see module:packet.PublicSubkey */ - default as PublicSubkey + /** @see PublicSubkeyPacket */ + default as PublicSubkeyPacket } from './public_subkey.js'; export { - /** @see module:packet.UserAttribute */ - default as UserAttribute + /** @see UserAttributePacket */ + default as UserAttributePacket } from './user_attribute.js'; export { - /** @see module:packet.OnePassSignature */ - default as OnePassSignature + /** @see OnePassSignaturePacket */ + default as OnePassSignaturePacket } from './one_pass_signature.js'; export { - /** @see module:packet.SecretKey */ - default as SecretKey + /** @see SecretKeyPacket */ + default as SecretKeyPacket } from './secret_key.js'; export { - /** @see module:packet.Userid */ - default as Userid + /** @see UserIDPacket */ + default as UserIDPacket } from './userid.js'; export { - /** @see module:packet.SecretSubkey */ - default as SecretSubkey + /** @see SecretSubkeyPacket */ + default as SecretSubkeyPacket } from './secret_subkey.js'; export { - /** @see module:packet.Signature */ - default as Signature + /** @see SignaturePacket */ + default as SignaturePacket } from './signature.js'; export { - /** @see module:packet.Trust */ - default as Trust + /** @see TrustPacket */ + default as TrustPacket } from './trust.js'; /** @@ -82,8 +80,12 @@ export { * @param {String} tag property name from {@link module:enums.packet} * @returns {Object} new packet object with type based on tag */ -export function newPacketFromTag(tag) { - return new packets[packetClassFromTagName(tag)](); +export function newPacketFromTag(tag, allowedPackets) { + const className = packetClassFromTagName(tag); + if (!allowedPackets[className]) { + throw new Error('Packet not allowed in this context: ' + className); + } + return new allowedPackets[className](); } /** @@ -93,5 +95,5 @@ export function newPacketFromTag(tag) { * @private */ function packetClassFromTagName(tag) { - return tag.substr(0, 1).toUpperCase() + tag.substr(1); + return tag.substr(0, 1).toUpperCase() + tag.substr(1) + 'Packet'; } diff --git a/src/packet/compressed.js b/src/packet/compressed_data.js similarity index 69% rename from src/packet/compressed.js rename to src/packet/compressed_data.js index 417b5a47..3a837a92 100644 --- a/src/packet/compressed.js +++ b/src/packet/compressed_data.js @@ -18,18 +18,26 @@ /** * @requires web-stream-tools * @requires pako + * @requires seek-bzip * @requires config * @requires enums * @requires util - * @requires compression/bzip2 + * @requires packet */ -import pako from 'pako'; -import Bunzip from 'seek-bzip'; +import { Deflate } from 'pako/lib/deflate'; +import { Inflate } from 'pako/lib/inflate'; +import { Z_SYNC_FLUSH, Z_FINISH } from 'pako/lib/zlib/constants'; +import { decode as BunzipDecode } from 'seek-bzip'; import stream from 'web-stream-tools'; import config from '../config'; import enums from '../enums'; import util from '../util'; +import { + LiteralDataPacket, + OnePassSignaturePacket, + SignaturePacket +} from '../packet'; /** * Implementation of the Compressed Data Packet (Tag 8) @@ -41,15 +49,15 @@ import util from '../util'; * @memberof module:packet * @constructor */ -function Compressed() { +function CompressedDataPacket() { /** * Packet type * @type {module:enums.packet} */ - this.tag = enums.packet.compressed; + this.tag = enums.packet.compressedData; /** * List of packets - * @type {module:packet.List} + * @type {PacketList} */ this.packets = null; /** @@ -69,7 +77,7 @@ function Compressed() { * Parsing function for the packet. * @param {Uint8Array | ReadableStream} bytes Payload of a tag 8 packet */ -Compressed.prototype.read = async function (bytes, streaming) { +CompressedDataPacket.prototype.read = async function (bytes, streaming) { await stream.parse(bytes, async reader => { // One octet that gives the algorithm used to compress the packet. @@ -87,7 +95,7 @@ Compressed.prototype.read = async function (bytes, streaming) { * Return the compressed packet. * @returns {Uint8Array | ReadableStream} binary compressed packet */ -Compressed.prototype.write = function () { +CompressedDataPacket.prototype.write = function () { if (this.compressed === null) { this.compress(); } @@ -100,19 +108,23 @@ Compressed.prototype.write = function () { * Decompression method for decompressing the compressed data * read by read_packet */ -Compressed.prototype.decompress = async function (streaming) { +CompressedDataPacket.prototype.decompress = async function (streaming) { if (!decompress_fns[this.algorithm]) { throw new Error(this.algorithm + ' decompression not supported'); } - await this.packets.read(decompress_fns[this.algorithm](this.compressed), streaming); + await this.packets.read(decompress_fns[this.algorithm](this.compressed), { + LiteralDataPacket, + OnePassSignaturePacket, + SignaturePacket + }, streaming); }; /** * Compress the packet data (member decompressedData) */ -Compressed.prototype.compress = function () { +CompressedDataPacket.prototype.compress = function () { if (!compress_fns[this.algorithm]) { throw new Error(this.algorithm + ' compression not supported'); @@ -121,7 +133,7 @@ Compressed.prototype.compress = function () { this.compressed = compress_fns[this.algorithm](this.packets.write()); }; -export default Compressed; +export default CompressedDataPacket; ////////////////////////// // // @@ -147,12 +159,12 @@ function pako_zlib(constructor, options = {}) { const obj = new constructor(options); return stream.transform(data, value => { if (value.length) { - obj.push(value, pako.Z_SYNC_FLUSH); + obj.push(value, Z_SYNC_FLUSH); return obj.result; } }, () => { - if (constructor === pako.Deflate) { - obj.push([], pako.Z_FINISH); + if (constructor === Deflate) { + obj.push([], Z_FINISH); return obj.result; } }); @@ -165,30 +177,22 @@ function bzip2(func) { }; } -let compress_fns; -let decompress_fns; -if (nodeZlib) { // Use Node native zlib for DEFLATE compression/decompression - compress_fns = { - zip: node_zlib(nodeZlib.createDeflateRaw, { level: config.deflateLevel }), - zlib: node_zlib(nodeZlib.createDeflate, { level: config.deflateLevel }) - }; - - decompress_fns = { - uncompressed: uncompressed, - zip: node_zlib(nodeZlib.createInflateRaw), - zlib: node_zlib(nodeZlib.createInflate), - bzip2: bzip2(Bunzip.decode) - }; -} else { // Use JS fallbacks - compress_fns = { - zip: pako_zlib(pako.Deflate, { raw: true, level: config.deflateLevel }), - zlib: pako_zlib(pako.Deflate, { level: config.deflateLevel }) - }; +const compress_fns = nodeZlib ? { + zip: /*#__PURE__*/ node_zlib(nodeZlib.createDeflateRaw, { level: config.deflateLevel }), + zlib: /*#__PURE__*/ node_zlib(nodeZlib.createDeflate, { level: config.deflateLevel }) +} : { + zip: /*#__PURE__*/ pako_zlib(Deflate, { raw: true, level: config.deflateLevel }), + zlib: /*#__PURE__*/ pako_zlib(Deflate, { level: config.deflateLevel }) +}; - decompress_fns = { - uncompressed: uncompressed, - zip: pako_zlib(pako.Inflate, { raw: true }), - zlib: pako_zlib(pako.Inflate), - bzip2: bzip2(Bunzip.decode) - }; -} +const decompress_fns = nodeZlib ? { + uncompressed: uncompressed, + zip: /*#__PURE__*/ node_zlib(nodeZlib.createInflateRaw), + zlib: /*#__PURE__*/ node_zlib(nodeZlib.createInflate), + bzip2: /*#__PURE__*/ bzip2(BunzipDecode) +} : { + uncompressed: uncompressed, + zip: /*#__PURE__*/ pako_zlib(Inflate, { raw: true }), + zlib: /*#__PURE__*/ pako_zlib(Inflate), + bzip2: /*#__PURE__*/ bzip2(BunzipDecode) +}; diff --git a/src/packet/index.js b/src/packet/index.js index 44c8f270..499e7750 100644 --- a/src/packet/index.js +++ b/src/packet/index.js @@ -2,17 +2,9 @@ * @fileoverview OpenPGP packet types * @see module:packet/all_packets * @see module:packet/clone - * @see module:packet.List + * @see PacketList * @module packet */ -import * as packets from './all_packets'; -import List from './packetlist'; - -const mod = { - List -}; - -Object.assign(mod, packets); - -export default mod; +export * from './all_packets'; +export { default as PacketList } from './packetlist'; diff --git a/src/packet/literal.js b/src/packet/literal_data.js similarity index 87% rename from src/packet/literal.js rename to src/packet/literal_data.js index b3224a73..de364a0e 100644 --- a/src/packet/literal.js +++ b/src/packet/literal_data.js @@ -35,8 +35,8 @@ import util from '../util'; * @memberof module:packet * @constructor */ -function Literal(date = new Date()) { - this.tag = enums.packet.literal; +function LiteralDataPacket(date = new Date()) { + this.tag = enums.packet.literalData; this.format = 'utf8'; // default format for literal data packets this.date = util.normalizeDate(date); this.text = null; // textual data representation @@ -50,7 +50,7 @@ function Literal(date = new Date()) { * @param {String | ReadableStream} text Any native javascript string * @param {utf8|binary|text|mime} format (optional) The format of the string of bytes */ -Literal.prototype.setText = function(text, format = 'utf8') { +LiteralDataPacket.prototype.setText = function(text, format = 'utf8') { this.format = format; this.text = text; this.data = null; @@ -62,7 +62,7 @@ Literal.prototype.setText = function(text, format = 'utf8') { * @param {Boolean} clone (optional) Whether to return a clone so that getBytes/getText can be called again * @returns {String | ReadableStream} literal data as text */ -Literal.prototype.getText = function(clone = false) { +LiteralDataPacket.prototype.getText = function(clone = false) { if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read this.text = util.decodeUtf8(util.nativeEOL(this.getBytes(clone))); } @@ -74,7 +74,7 @@ Literal.prototype.getText = function(clone = false) { * @param {Uint8Array | ReadableStream} bytes The string of bytes * @param {utf8|binary|text|mime} format The format of the string of bytes */ -Literal.prototype.setBytes = function(bytes, format) { +LiteralDataPacket.prototype.setBytes = function(bytes, format) { this.format = format; this.data = bytes; this.text = null; @@ -86,7 +86,7 @@ Literal.prototype.setBytes = function(bytes, format) { * @param {Boolean} clone (optional) Whether to return a clone so that getBytes/getText can be called again * @returns {Uint8Array | ReadableStream} A sequence of bytes */ -Literal.prototype.getBytes = function(clone = false) { +LiteralDataPacket.prototype.getBytes = function(clone = false) { if (this.data === null) { // encode UTF8 and normalize EOL to \r\n this.data = util.canonicalizeEOL(util.encodeUtf8(this.text)); @@ -102,7 +102,7 @@ Literal.prototype.getBytes = function(clone = false) { * Sets the filename of the literal packet data * @param {String} filename Any native javascript string */ -Literal.prototype.setFilename = function(filename) { +LiteralDataPacket.prototype.setFilename = function(filename) { this.filename = filename; }; @@ -111,7 +111,7 @@ Literal.prototype.setFilename = function(filename) { * Get the filename of the literal packet data * @returns {String} filename */ -Literal.prototype.getFilename = function() { +LiteralDataPacket.prototype.getFilename = function() { return this.filename; }; @@ -120,9 +120,9 @@ Literal.prototype.getFilename = function() { * Parsing function for a literal data packet (tag 11). * * @param {Uint8Array | ReadableStream} input Payload of a tag 11 packet - * @returns {module:packet.Literal} object representation + * @returns {LiteralDataPacket} object representation */ -Literal.prototype.read = async function(bytes) { +LiteralDataPacket.prototype.read = async function(bytes) { await stream.parse(bytes, async reader => { // - A one-octet field that describes how the data is formatted. const format = enums.read(enums.literal, await reader.readByte()); @@ -143,7 +143,7 @@ Literal.prototype.read = async function(bytes) { * * @returns {Uint8Array} Uint8Array representation of the packet */ -Literal.prototype.writeHeader = function() { +LiteralDataPacket.prototype.writeHeader = function() { const filename = util.encodeUtf8(this.filename); const filename_length = new Uint8Array([filename.length]); @@ -158,11 +158,11 @@ Literal.prototype.writeHeader = function() { * * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet */ -Literal.prototype.write = function() { +LiteralDataPacket.prototype.write = function() { const header = this.writeHeader(); const data = this.getBytes(); return util.concat([header, data]); }; -export default Literal; +export default LiteralDataPacket; diff --git a/src/packet/marker.js b/src/packet/marker.js index 6fa03c63..baee17e5 100644 --- a/src/packet/marker.js +++ b/src/packet/marker.js @@ -34,7 +34,7 @@ import enums from '../enums'; * @memberof module:packet * @constructor */ -function Marker() { +function MarkerPacket() { this.tag = enums.packet.marker; } @@ -47,9 +47,9 @@ function Marker() { * @param {Integer} len * Length of the packet or the remaining length of * input at position - * @returns {module:packet.Marker} Object representation + * @returns {MarkerPacket} Object representation */ -Marker.prototype.read = function (bytes) { +MarkerPacket.prototype.read = function (bytes) { if (bytes[0] === 0x50 && // P bytes[1] === 0x47 && // G bytes[2] === 0x50) { // P @@ -59,4 +59,4 @@ Marker.prototype.read = function (bytes) { return false; }; -export default Marker; +export default MarkerPacket; diff --git a/src/packet/one_pass_signature.js b/src/packet/one_pass_signature.js index db15dfbe..45c7ad38 100644 --- a/src/packet/one_pass_signature.js +++ b/src/packet/one_pass_signature.js @@ -24,7 +24,7 @@ */ import stream from 'web-stream-tools'; -import Signature from './signature'; +import SignaturePacket from './signature'; import type_keyid from '../type/keyid'; import enums from '../enums'; import util from '../util'; @@ -41,7 +41,7 @@ import util from '../util'; * @memberof module:packet * @constructor */ -function OnePassSignature() { +function OnePassSignaturePacket() { /** * Packet type * @type {module:enums.packet} @@ -78,9 +78,9 @@ function OnePassSignature() { /** * parsing function for a one-pass signature packet (tag 4). * @param {Uint8Array} bytes payload of a tag 4 packet - * @returns {module:packet.OnePassSignature} object representation + * @returns {OnePassSignaturePacket} object representation */ -OnePassSignature.prototype.read = function (bytes) { +OnePassSignaturePacket.prototype.read = function (bytes) { let mypos = 0; // A one-octet version number. The current version is 3. this.version = bytes[mypos++]; @@ -112,7 +112,7 @@ OnePassSignature.prototype.read = function (bytes) { * creates a string representation of a one-pass signature packet * @returns {Uint8Array} a Uint8Array representation of a one-pass signature packet */ -OnePassSignature.prototype.write = function () { +OnePassSignaturePacket.prototype.write = function () { const start = new Uint8Array([3, enums.write(enums.signature, this.signatureType), enums.write(enums.hash, this.hashAlgorithm), enums.write(enums.publicKey, this.publicKeyAlgorithm)]); @@ -122,14 +122,14 @@ OnePassSignature.prototype.write = function () { return util.concatUint8Array([start, this.issuerKeyId.write(), end]); }; -OnePassSignature.prototype.hash = Signature.prototype.hash; -OnePassSignature.prototype.toHash = Signature.prototype.toHash; -OnePassSignature.prototype.toSign = Signature.prototype.toSign; -OnePassSignature.prototype.calculateTrailer = function(...args) { - return stream.fromAsync(async () => Signature.prototype.calculateTrailer.apply(await this.correspondingSig, args)); +OnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash; +OnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash; +OnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign; +OnePassSignaturePacket.prototype.calculateTrailer = function(...args) { + return stream.fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args)); }; -OnePassSignature.prototype.verify = async function() { +OnePassSignaturePacket.prototype.verify = async function() { const correspondingSig = await this.correspondingSig; if (!correspondingSig || correspondingSig.tag !== enums.packet.signature) { throw new Error('Corresponding signature packet missing'); @@ -146,4 +146,4 @@ OnePassSignature.prototype.verify = async function() { return correspondingSig.verify.apply(correspondingSig, arguments); }; -export default OnePassSignature; +export default OnePassSignaturePacket; diff --git a/src/packet/packet.js b/src/packet/packet.js index 49b61b2f..9ad2383d 100644 --- a/src/packet/packet.js +++ b/src/packet/packet.js @@ -105,11 +105,11 @@ export default { */ supportsStreaming: function(tag_type) { return [ - enums.packet.literal, - enums.packet.compressed, - enums.packet.symmetricallyEncrypted, - enums.packet.symEncryptedIntegrityProtected, - enums.packet.symEncryptedAEADProtected + enums.packet.literalData, + enums.packet.compressedData, + enums.packet.symmetricallyEncryptedData, + enums.packet.symEncryptedIntegrityProtectedData, + enums.packet.symEncryptedAEADProtectedData ].includes(tag_type); }, diff --git a/src/packet/packetlist.js b/src/packet/packetlist.js index 5006ac5f..f054cf50 100644 --- a/src/packet/packetlist.js +++ b/src/packet/packetlist.js @@ -23,7 +23,7 @@ import util from '../util'; * @constructor * @extends Array */ -function List() { +function PacketList() { /** * The number of packets contained within the list. * @readonly @@ -32,13 +32,13 @@ function List() { this.length = 0; } -List.prototype = []; +PacketList.prototype = []; /** * Reads a stream of binary data and interprents it as a list of packets. * @param {Uint8Array | ReadableStream} A Uint8Array of bytes. */ -List.prototype.read = async function (bytes, streaming) { +PacketList.prototype.read = async function (bytes, allowedPackets, streaming) { this.stream = stream.transformPair(bytes, async (readable, writable) => { const writer = stream.getWriter(writable); try { @@ -47,8 +47,8 @@ List.prototype.read = async function (bytes, streaming) { const done = await packetParser.read(readable, streaming, async parsed => { try { const tag = enums.read(enums.packet, parsed.tag); - const packet = packets.newPacketFromTag(tag); - packet.packets = new List(); + const packet = packets.newPacketFromTag(tag, allowedPackets); + packet.packets = new PacketList(); packet.fromStream = util.isStream(parsed.packet); await packet.read(parsed.packet, streaming); await writer.write(packet); @@ -94,7 +94,7 @@ List.prototype.read = async function (bytes, streaming) { * class instance. * @returns {Uint8Array} A Uint8Array containing valid openpgp packets. */ -List.prototype.write = function () { +PacketList.prototype.write = function () { const arr = []; for (let i = 0; i < this.length; i++) { @@ -137,12 +137,12 @@ List.prototype.write = function () { * writing to packetlist[i] directly will result in an error. * @param {Object} packet Packet to push */ -List.prototype.push = function (packet) { +PacketList.prototype.push = function (packet) { if (!packet) { return; } - packet.packets = packet.packets || new List(); + packet.packets = packet.packets || new PacketList(); this[this.length] = packet; this.length++; @@ -151,8 +151,8 @@ List.prototype.push = function (packet) { /** * Creates a new PacketList with all packets from the given types */ -List.prototype.filterByTag = function (...args) { - const filtered = new List(); +PacketList.prototype.filterByTag = function (...args) { + const filtered = new PacketList(); const handle = tag => packetType => tag === packetType; @@ -170,14 +170,14 @@ List.prototype.filterByTag = function (...args) { * @param {module:enums.packet} type The packet type * @returns {module:packet/packet|undefined} */ -List.prototype.findPacket = function (type) { +PacketList.prototype.findPacket = function (type) { return this.find(packet => packet.tag === type); }; /** * Returns array of found indices by tag */ -List.prototype.indexOfTag = function (...args) { +PacketList.prototype.indexOfTag = function (...args) { const tagIndex = []; const that = this; @@ -194,7 +194,7 @@ List.prototype.indexOfTag = function (...args) { /** * Concatenates packetlist or array of packets */ -List.prototype.concat = function (packetlist) { +PacketList.prototype.concat = function (packetlist) { if (packetlist) { for (let i = 0; i < packetlist.length; i++) { this.push(packetlist[i]); @@ -203,4 +203,4 @@ List.prototype.concat = function (packetlist) { return this; }; -export default List; +export default PacketList; diff --git a/src/packet/public_key.js b/src/packet/public_key.js index 3401baa7..a74c28cb 100644 --- a/src/packet/public_key.js +++ b/src/packet/public_key.js @@ -46,7 +46,7 @@ import util from '../util'; * @memberof module:packet * @constructor */ -function PublicKey(date = new Date()) { +function PublicKeyPacket(date = new Date()) { /** * Packet type * @type {module:enums.packet} @@ -95,7 +95,7 @@ function PublicKey(date = new Date()) { * @param {Uint8Array} bytes Input array to read the packet from * @returns {Object} This object with attributes set by the parser */ -PublicKey.prototype.read = function (bytes) { +PublicKeyPacket.prototype.read = function (bytes) { let pos = 0; // A one-octet version number (3, 4 or 5). this.version = bytes[pos++]; @@ -133,16 +133,16 @@ PublicKey.prototype.read = function (bytes) { /** * Alias of read() - * @see module:packet.PublicKey#read + * @see PublicKeyPacket#read */ -PublicKey.prototype.readPublicKey = PublicKey.prototype.read; +PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read; /** * Same as write_private_key, but has less information because of * public key. * @returns {Uint8Array} OpenPGP packet body contents, */ -PublicKey.prototype.write = function () { +PublicKeyPacket.prototype.write = function () { const arr = []; // Version arr.push(new Uint8Array([this.version])); @@ -164,14 +164,14 @@ PublicKey.prototype.write = function () { /** * Alias of write() - * @see module:packet.PublicKey#write + * @see PublicKeyPacket#write */ -PublicKey.prototype.writePublicKey = PublicKey.prototype.write; +PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write; /** * Write packet in order to be hashed; either for a signature or a fingerprint. */ -PublicKey.prototype.writeForHash = function (version) { +PublicKeyPacket.prototype.writeForHash = function (version) { const bytes = this.writePublicKey(); if (version === 5) { @@ -184,7 +184,7 @@ PublicKey.prototype.writeForHash = function (version) { * Check whether secret-key data is available in decrypted form. Returns null for public keys. * @returns {Boolean|null} */ -PublicKey.prototype.isDecrypted = function() { +PublicKeyPacket.prototype.isDecrypted = function() { return null; }; @@ -192,7 +192,7 @@ PublicKey.prototype.isDecrypted = function() { * Returns the creation time of the key * @returns {Date} */ -PublicKey.prototype.getCreationTime = function() { +PublicKeyPacket.prototype.getCreationTime = function() { return this.created; }; @@ -200,7 +200,7 @@ PublicKey.prototype.getCreationTime = function() { * Calculates the key id of the key * @returns {module:type/keyid} A 8 byte key id */ -PublicKey.prototype.getKeyId = function () { +PublicKeyPacket.prototype.getKeyId = function () { if (this.keyid) { return this.keyid; } @@ -217,7 +217,7 @@ PublicKey.prototype.getKeyId = function () { * Calculates the fingerprint of the key * @returns {Uint8Array} A Uint8Array containing the fingerprint */ -PublicKey.prototype.getFingerprintBytes = function () { +PublicKeyPacket.prototype.getFingerprintBytes = function () { if (this.fingerprint) { return this.fingerprint; } @@ -234,7 +234,7 @@ PublicKey.prototype.getFingerprintBytes = function () { * Calculates the fingerprint of the key * @returns {String} A string containing the fingerprint in lowercase hex */ -PublicKey.prototype.getFingerprint = function() { +PublicKeyPacket.prototype.getFingerprint = function() { return util.uint8ArrayToHex(this.getFingerprintBytes()); }; @@ -242,7 +242,7 @@ PublicKey.prototype.getFingerprint = function() { * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint * @returns {Boolean} Whether the two keys have the same version and public key data */ -PublicKey.prototype.hasSameFingerprintAs = function(other) { +PublicKeyPacket.prototype.hasSameFingerprintAs = function(other) { return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey()); }; @@ -250,7 +250,7 @@ PublicKey.prototype.hasSameFingerprintAs = function(other) { * Returns algorithm information * @returns {Object} An object of the form {algorithm: String, rsaBits:int, curve:String} */ -PublicKey.prototype.getAlgorithmInfo = function () { +PublicKeyPacket.prototype.getAlgorithmInfo = function () { const result = {}; result.algorithm = this.algorithm; if (this.params[0] instanceof type_mpi) { @@ -262,4 +262,4 @@ PublicKey.prototype.getAlgorithmInfo = function () { return result; }; -export default PublicKey; +export default PublicKeyPacket; diff --git a/src/packet/public_key_encrypted_session_key.js b/src/packet/public_key_encrypted_session_key.js index 34baa678..696bddc8 100644 --- a/src/packet/public_key_encrypted_session_key.js +++ b/src/packet/public_key_encrypted_session_key.js @@ -46,7 +46,7 @@ import util from '../util'; * @memberof module:packet * @constructor */ -function PublicKeyEncryptedSessionKey() { +function PublicKeyEncryptedSessionKeyPacket() { this.tag = enums.packet.publicKeyEncryptedSessionKey; this.version = 3; @@ -67,9 +67,9 @@ function PublicKeyEncryptedSessionKey() { * @param {Integer} position Position to start reading from the input string * @param {Integer} len Length of the packet or the remaining length of * input at position - * @returns {module:packet.PublicKeyEncryptedSessionKey} Object representation + * @returns {PublicKeyEncryptedSessionKeyPacket} Object representation */ -PublicKeyEncryptedSessionKey.prototype.read = function (bytes) { +PublicKeyEncryptedSessionKeyPacket.prototype.read = function (bytes) { this.version = bytes[0]; this.publicKeyId.read(bytes.subarray(1, bytes.length)); this.publicKeyAlgorithm = enums.read(enums.publicKey, bytes[9]); @@ -90,7 +90,7 @@ PublicKeyEncryptedSessionKey.prototype.read = function (bytes) { * * @returns {Uint8Array} The Uint8Array representation */ -PublicKeyEncryptedSessionKey.prototype.write = function () { +PublicKeyEncryptedSessionKeyPacket.prototype.write = function () { const arr = [new Uint8Array([this.version]), this.publicKeyId.write(), new Uint8Array([enums.write(enums.publicKey, this.publicKeyAlgorithm)])]; for (let i = 0; i < this.encrypted.length; i++) { @@ -102,11 +102,11 @@ PublicKeyEncryptedSessionKey.prototype.write = function () { /** * Encrypt session key packet - * @param {module:packet.PublicKey} key Public key + * @param {PublicKeyPacket} key Public key * @returns {Promise} * @async */ -PublicKeyEncryptedSessionKey.prototype.encrypt = async function (key) { +PublicKeyEncryptedSessionKeyPacket.prototype.encrypt = async function (key) { let data = String.fromCharCode(enums.write(enums.symmetric, this.sessionKeyAlgorithm)); data += util.uint8ArrayToStr(this.sessionKey); @@ -121,12 +121,12 @@ PublicKeyEncryptedSessionKey.prototype.encrypt = async function (key) { * Decrypts the session key (only for public key encrypted session key * packets (tag 1) * - * @param {module:packet.SecretKey} key + * @param {SecretKeyPacket} key * Private key with secret params unlocked * @returns {Promise} * @async */ -PublicKeyEncryptedSessionKey.prototype.decrypt = async function (key) { +PublicKeyEncryptedSessionKeyPacket.prototype.decrypt = async function (key) { const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm); const keyAlgo = enums.write(enums.publicKey, key.algorithm); // check that session key algo matches the secret key algo @@ -146,4 +146,4 @@ PublicKeyEncryptedSessionKey.prototype.decrypt = async function (key) { return true; }; -export default PublicKeyEncryptedSessionKey; +export default PublicKeyEncryptedSessionKeyPacket; diff --git a/src/packet/public_subkey.js b/src/packet/public_subkey.js index 4472d088..5903d410 100644 --- a/src/packet/public_subkey.js +++ b/src/packet/public_subkey.js @@ -20,7 +20,7 @@ * @requires enums */ -import PublicKey from './public_key'; +import PublicKeyPacket from './public_key'; import enums from '../enums'; /** @@ -31,14 +31,14 @@ import enums from '../enums'; * services. * @memberof module:packet * @constructor - * @extends module:packet.PublicKey + * @extends PublicKeyPacket */ -function PublicSubkey() { - PublicKey.call(this); +function PublicSubkeyPacket() { + PublicKeyPacket.call(this); this.tag = enums.packet.publicSubkey; } -PublicSubkey.prototype = new PublicKey(); -PublicSubkey.prototype.constructor = PublicSubkey; +PublicSubkeyPacket.prototype = new PublicKeyPacket(); +PublicSubkeyPacket.prototype.constructor = PublicSubkeyPacket; -export default PublicSubkey; +export default PublicSubkeyPacket; diff --git a/src/packet/secret_key.js b/src/packet/secret_key.js index d78dede2..6ee2f7bf 100644 --- a/src/packet/secret_key.js +++ b/src/packet/secret_key.js @@ -24,7 +24,7 @@ * @requires util */ -import PublicKey from './public_key'; +import PublicKeyPacket from './public_key'; import type_s2k from '../type/s2k'; import crypto from '../crypto'; import enums from '../enums'; @@ -36,10 +36,10 @@ import util from '../util'; * includes the secret-key material after all the public-key fields. * @memberof module:packet * @constructor - * @extends module:packet.PublicKey + * @extends PublicKeyPacket */ -function SecretKey(date = new Date()) { - PublicKey.call(this, date); +function SecretKeyPacket(date = new Date()) { + PublicKeyPacket.call(this, date); /** * Packet type * @type {module:enums.packet} @@ -75,8 +75,8 @@ function SecretKey(date = new Date()) { this.aead = null; } -SecretKey.prototype = new PublicKey(); -SecretKey.prototype.constructor = SecretKey; +SecretKeyPacket.prototype = new PublicKeyPacket(); +SecretKeyPacket.prototype.constructor = SecretKeyPacket; // Helper function @@ -116,7 +116,7 @@ function write_cleartext_params(params, algorithm) { * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} * @param {String} bytes Input string to read the packet from */ -SecretKey.prototype.read = function (bytes) { +SecretKeyPacket.prototype.read = function (bytes) { // - A Public-Key or Public-Subkey packet, as described above. let i = this.readPublicKey(bytes); @@ -197,7 +197,7 @@ SecretKey.prototype.read = function (bytes) { * Creates an OpenPGP key packet for the given key. * @returns {String} A string of bytes containing the secret key OpenPGP packet */ -SecretKey.prototype.write = function () { +SecretKeyPacket.prototype.write = function () { const arr = [this.writePublicKey()]; arr.push(new Uint8Array([this.s2k_usage])); @@ -254,7 +254,7 @@ SecretKey.prototype.write = function () { * Check whether secret-key data is available in decrypted form. Returns null for public keys. * @returns {Boolean|null} */ -SecretKey.prototype.isDecrypted = function() { +SecretKeyPacket.prototype.isDecrypted = function() { return this.isEncrypted === false; }; @@ -262,7 +262,7 @@ SecretKey.prototype.isDecrypted = function() { * Check whether this is a gnu-dummy key * @returns {Boolean} */ -SecretKey.prototype.isDummy = function() { +SecretKeyPacket.prototype.isDummy = function() { return !!(this.s2k && this.s2k.type === 'gnu-dummy'); }; @@ -298,7 +298,7 @@ SecretKey.prototype.makeDummy = function () { * @returns {Promise} * @async */ -SecretKey.prototype.encrypt = async function (passphrase) { +SecretKeyPacket.prototype.encrypt = async function (passphrase) { if (this.isDummy()) { return false; } @@ -347,13 +347,13 @@ async function produceEncryptionKey(s2k, passphrase, algorithm) { /** * Decrypts the private key params which are needed to use the key. - * {@link module:packet.SecretKey.isDecrypted} should be false, as + * {@link SecretKeyPacket.isDecrypted} should be false, as * otherwise calls to this function will throw an error. * @param {String} passphrase The passphrase for this private key as string * @returns {Promise} * @async */ -SecretKey.prototype.decrypt = async function (passphrase) { +SecretKeyPacket.prototype.decrypt = async function (passphrase) { if (this.isDummy()) { this.isEncrypted = false; return false; @@ -404,7 +404,7 @@ SecretKey.prototype.decrypt = async function (passphrase) { return true; }; -SecretKey.prototype.generate = async function (bits, curve) { +SecretKeyPacket.prototype.generate = async function (bits, curve) { const algo = enums.write(enums.publicKey, this.algorithm); this.params = await crypto.generateParams(algo, bits, curve); this.isEncrypted = false; @@ -415,7 +415,7 @@ SecretKey.prototype.generate = async function (bits, curve) { * @throws {Error} if validation was not successful * @async */ -SecretKey.prototype.validate = async function () { +SecretKeyPacket.prototype.validate = async function () { if (this.isDummy()) { return; } @@ -434,7 +434,7 @@ SecretKey.prototype.validate = async function () { /** * Clear private key parameters */ -SecretKey.prototype.clearPrivateParams = function () { +SecretKeyPacket.prototype.clearPrivateParams = function () { if (this.s2k && this.s2k.type === 'gnu-dummy') { this.isEncrypted = true; return; @@ -449,4 +449,4 @@ SecretKey.prototype.clearPrivateParams = function () { this.isEncrypted = true; }; -export default SecretKey; +export default SecretKeyPacket; diff --git a/src/packet/secret_subkey.js b/src/packet/secret_subkey.js index 824b77b3..2d2932dc 100644 --- a/src/packet/secret_subkey.js +++ b/src/packet/secret_subkey.js @@ -20,7 +20,7 @@ * @requires enums */ -import SecretKey from './secret_key'; +import SecretKeyPacket from './secret_key'; import enums from '../enums'; /** @@ -28,14 +28,14 @@ import enums from '../enums'; * Key packet and has exactly the same format. * @memberof module:packet * @constructor - * @extends module:packet.SecretKey + * @extends SecretKeyPacket */ -function SecretSubkey(date = new Date()) { - SecretKey.call(this, date); +function SecretSubkeyPacket(date = new Date()) { + SecretKeyPacket.call(this, date); this.tag = enums.packet.secretSubkey; } -SecretSubkey.prototype = new SecretKey(); -SecretSubkey.prototype.constructor = SecretSubkey; +SecretSubkeyPacket.prototype = new SecretKeyPacket(); +SecretSubkeyPacket.prototype.constructor = SecretSubkeyPacket; -export default SecretSubkey; +export default SecretSubkeyPacket; diff --git a/src/packet/signature.js b/src/packet/signature.js index f687360e..f05dae96 100644 --- a/src/packet/signature.js +++ b/src/packet/signature.js @@ -45,7 +45,7 @@ import config from '../config'; * @constructor * @param {Date} date the creation date of the signature */ -function Signature(date = new Date()) { +function SignaturePacket(date = new Date()) { this.tag = enums.packet.signature; this.version = 4; // This is set to 5 below if we sign with a V5 key. this.signatureType = null; @@ -99,9 +99,9 @@ function Signature(date = new Date()) { /** * parsing function for a signature packet (tag 2). * @param {String} bytes payload of a tag 2 packet - * @returns {module:packet.Signature} object representation + * @returns {SignaturePacket} object representation */ -Signature.prototype.read = function (bytes) { +SignaturePacket.prototype.read = function (bytes) { let i = 0; this.version = bytes[i++]; @@ -134,7 +134,7 @@ Signature.prototype.read = function (bytes) { this.signature = bytes.subarray(i, bytes.length); }; -Signature.prototype.write = function () { +SignaturePacket.prototype.write = function () { const arr = []; arr.push(this.signatureData); arr.push(this.write_unhashed_sub_packets()); @@ -145,14 +145,14 @@ Signature.prototype.write = function () { /** * Signs provided data. This needs to be done prior to serialization. - * @param {module:packet.SecretKey} key private key used to sign the message. + * @param {SecretKeyPacket} key private key used to sign the message. * @param {Object} data Contains packets to be signed. * @param {Boolean} detached (optional) whether to create a detached signature * @param {Boolean} streaming (optional) whether to process data as a stream * @returns {Promise} * @async */ -Signature.prototype.sign = async function (key, data, detached = false, streaming = false) { +SignaturePacket.prototype.sign = async function (key, data, detached = false, streaming = false) { const signatureType = enums.write(enums.signature, this.signatureType); const publicKeyAlgorithm = enums.write(enums.publicKey, this.publicKeyAlgorithm); const hashAlgorithm = enums.write(enums.hash, this.hashAlgorithm); @@ -197,7 +197,7 @@ Signature.prototype.sign = async function (key, data, detached = false, streamin * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets * @returns {Uint8Array} subpacket data */ -Signature.prototype.write_hashed_sub_packets = function () { +SignaturePacket.prototype.write_hashed_sub_packets = function () { const sub = enums.signatureSubpacket; const arr = []; let bytes; @@ -300,7 +300,7 @@ Signature.prototype.write_hashed_sub_packets = function () { * Creates Uint8Array of bytes of Issuer and Embedded Signature subpackets * @returns {Uint8Array} subpacket data */ -Signature.prototype.write_unhashed_sub_packets = function() { +SignaturePacket.prototype.write_unhashed_sub_packets = function() { const sub = enums.signatureSubpacket; const arr = []; let bytes; @@ -347,7 +347,7 @@ function write_sub_packet(type, data) { // V4 signature sub packets -Signature.prototype.read_sub_packet = function (bytes, trusted = true) { +SignaturePacket.prototype.read_sub_packet = function (bytes, trusted = true) { let mypos = 0; const read_array = (prop, bytes) => { @@ -515,7 +515,7 @@ Signature.prototype.read_sub_packet = function (bytes, trusted = true) { } case 32: // Embedded Signature - this.embeddedSignature = new Signature(); + this.embeddedSignature = new SignaturePacket(); this.embeddedSignature.read(bytes.subarray(mypos, bytes.length)); break; case 33: @@ -543,7 +543,7 @@ Signature.prototype.read_sub_packet = function (bytes, trusted = true) { } }; -Signature.prototype.read_sub_packets = function(bytes, trusted = true) { +SignaturePacket.prototype.read_sub_packets = function(bytes, trusted = true) { // Two-octet scalar octet count for following subpacket data. const subpacket_length = util.readNumber(bytes.subarray(0, 2)); @@ -563,7 +563,7 @@ Signature.prototype.read_sub_packets = function(bytes, trusted = true) { }; // Produces data to produce signature on -Signature.prototype.toSign = function (type, data) { +SignaturePacket.prototype.toSign = function (type, data) { const t = enums.signature; switch (type) { @@ -632,7 +632,7 @@ Signature.prototype.toSign = function (type, data) { }; -Signature.prototype.calculateTrailer = function (data, detached) { +SignaturePacket.prototype.calculateTrailer = function (data, detached) { let length = 0; return stream.transform(stream.clone(this.signatureData), value => { length += value.length; @@ -657,13 +657,13 @@ Signature.prototype.calculateTrailer = function (data, detached) { }; -Signature.prototype.toHash = function(signatureType, data, detached = false) { +SignaturePacket.prototype.toHash = function(signatureType, data, detached = false) { const bytes = this.toSign(signatureType, data); return util.concat([bytes, this.signatureData, this.calculateTrailer(data, detached)]); }; -Signature.prototype.hash = async function(signatureType, data, toHash, detached = false, streaming = true) { +SignaturePacket.prototype.hash = async function(signatureType, data, toHash, detached = false, streaming = true) { const hashAlgorithm = enums.write(enums.hash, this.hashAlgorithm); if (!toHash) toHash = this.toHash(signatureType, data, detached); if (!streaming && util.isStream(toHash)) { @@ -675,15 +675,15 @@ Signature.prototype.hash = async function(signatureType, data, toHash, detached /** * verifies the signature packet. Note: not all signature types are implemented - * @param {module:packet.PublicSubkey|module:packet.PublicKey| - * module:packet.SecretSubkey|module:packet.SecretKey} key the public key to verify the signature + * @param {PublicSubkeyPacket|PublicKeyPacket| + * SecretSubkeyPacket|SecretKeyPacket} key the public key to verify the signature * @param {module:enums.signature} signatureType expected signature type * @param {String|Object} data data which on the signature applies * @param {Boolean} detached (optional) whether to verify a detached signature * @returns {Promise} True if message is verified, else false. * @async */ -Signature.prototype.verify = async function (key, signatureType, data, detached = false, streaming = false) { +SignaturePacket.prototype.verify = async function (key, signatureType, data, detached = false, streaming = false) { const publicKeyAlgorithm = enums.write(enums.publicKey, this.publicKeyAlgorithm); const hashAlgorithm = enums.write(enums.hash, this.hashAlgorithm); @@ -757,7 +757,7 @@ Signature.prototype.verify = async function (key, signatureType, data, detached * @param {Date} date (optional) use the given date for verification instead of the current time * @returns {Boolean} true if expired */ -Signature.prototype.isExpired = function (date = new Date()) { +SignaturePacket.prototype.isExpired = function (date = new Date()) { const normDate = util.normalizeDate(date); if (normDate !== null) { const expirationTime = this.getExpirationTime(); @@ -770,8 +770,8 @@ Signature.prototype.isExpired = function (date = new Date()) { * Returns the expiration time of the signature or Infinity if signature does not expire * @returns {Date} expiration time */ -Signature.prototype.getExpirationTime = function () { +SignaturePacket.prototype.getExpirationTime = function () { return !this.signatureNeverExpires ? new Date(this.created.getTime() + this.signatureExpirationTime * 1000) : Infinity; }; -export default Signature; +export default SignaturePacket; diff --git a/src/packet/sym_encrypted_aead_protected.js b/src/packet/sym_encrypted_aead_protected_data.js similarity index 89% rename from src/packet/sym_encrypted_aead_protected.js rename to src/packet/sym_encrypted_aead_protected_data.js index c1c09f24..071f942e 100644 --- a/src/packet/sym_encrypted_aead_protected.js +++ b/src/packet/sym_encrypted_aead_protected_data.js @@ -21,6 +21,7 @@ * @requires crypto * @requires enums * @requires util + * @requires packet */ import stream from 'web-stream-tools'; @@ -28,6 +29,12 @@ import config from '../config'; import crypto from '../crypto'; import enums from '../enums'; import util from '../util'; +import { + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket +} from '../packet'; const VERSION = 1; // A one-octet version number of the data packet. @@ -40,8 +47,8 @@ const VERSION = 1; // A one-octet version number of the data packet. * @memberof module:packet * @constructor */ -function SymEncryptedAEADProtected() { - this.tag = enums.packet.symEncryptedAEADProtected; +function SymEncryptedAEADProtectedDataPacket() { + this.tag = enums.packet.symEncryptedAEADProtectedData; this.version = VERSION; this.cipherAlgo = null; this.aeadAlgorithm = 'eax'; @@ -52,13 +59,13 @@ function SymEncryptedAEADProtected() { this.packets = null; } -export default SymEncryptedAEADProtected; +export default SymEncryptedAEADProtectedDataPacket; /** * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification) * @param {Uint8Array | ReadableStream} bytes */ -SymEncryptedAEADProtected.prototype.read = async function (bytes) { +SymEncryptedAEADProtectedDataPacket.prototype.read = async function (bytes) { await stream.parse(bytes, async reader => { if (await reader.readByte() !== VERSION) { // The only currently defined value is 1. throw new Error('Invalid packet version.'); @@ -76,7 +83,7 @@ SymEncryptedAEADProtected.prototype.read = async function (bytes) { * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification) * @returns {Uint8Array | ReadableStream} The encrypted payload */ -SymEncryptedAEADProtected.prototype.write = function () { +SymEncryptedAEADProtectedDataPacket.prototype.write = function () { return util.concat([new Uint8Array([this.version, this.cipherAlgo, this.aeadAlgo, this.chunkSizeByte]), this.iv, this.encrypted]); }; @@ -88,8 +95,13 @@ SymEncryptedAEADProtected.prototype.write = function () { * @returns {Boolean} * @async */ -SymEncryptedAEADProtected.prototype.decrypt = async function (sessionKeyAlgorithm, key, streaming) { - await this.packets.read(await this.crypt('decrypt', key, stream.clone(this.encrypted), streaming), streaming); +SymEncryptedAEADProtectedDataPacket.prototype.decrypt = async function (sessionKeyAlgorithm, key, streaming) { + await this.packets.read(await this.crypt('decrypt', key, stream.clone(this.encrypted), streaming), { + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket + }, streaming); return true; }; @@ -100,7 +112,7 @@ SymEncryptedAEADProtected.prototype.decrypt = async function (sessionKeyAlgorith * @param {Boolean} streaming Whether the top-level function will return a stream * @async */ -SymEncryptedAEADProtected.prototype.encrypt = async function (sessionKeyAlgorithm, key, streaming) { +SymEncryptedAEADProtectedDataPacket.prototype.encrypt = async function (sessionKeyAlgorithm, key, streaming) { this.cipherAlgo = enums.write(enums.symmetric, sessionKeyAlgorithm); this.aeadAlgo = enums.write(enums.aead, this.aeadAlgorithm); const mode = crypto[enums.read(enums.aead, this.aeadAlgo)]; @@ -119,7 +131,7 @@ SymEncryptedAEADProtected.prototype.encrypt = async function (sessionKeyAlgorith * @returns {Uint8Array | ReadableStream} * @async */ -SymEncryptedAEADProtected.prototype.crypt = async function (fn, key, data, streaming) { +SymEncryptedAEADProtectedDataPacket.prototype.crypt = async function (fn, key, data, streaming) { const cipher = enums.read(enums.symmetric, this.cipherAlgo); const mode = crypto[enums.read(enums.aead, this.aeadAlgo)]; const modeInstance = await mode(cipher, key); diff --git a/src/packet/sym_encrypted_integrity_protected.js b/src/packet/sym_encrypted_integrity_protected_data.js similarity index 85% rename from src/packet/sym_encrypted_integrity_protected.js rename to src/packet/sym_encrypted_integrity_protected_data.js index 9967098d..95039339 100644 --- a/src/packet/sym_encrypted_integrity_protected.js +++ b/src/packet/sym_encrypted_integrity_protected_data.js @@ -22,6 +22,7 @@ * @requires crypto * @requires enums * @requires util + * @requires packet */ import stream from 'web-stream-tools'; @@ -29,6 +30,12 @@ import config from '../config'; import crypto from '../crypto'; import enums from '../enums'; import util from '../util'; +import { + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket +} from '../packet'; const VERSION = 1; // A one-octet version number of the data packet. @@ -44,8 +51,8 @@ const VERSION = 1; // A one-octet version number of the data packet. * @memberof module:packet * @constructor */ -function SymEncryptedIntegrityProtected() { - this.tag = enums.packet.symEncryptedIntegrityProtected; +function SymEncryptedIntegrityProtectedDataPacket() { + this.tag = enums.packet.symEncryptedIntegrityProtectedData; this.version = VERSION; /** The encrypted payload. */ this.encrypted = null; // string @@ -59,7 +66,7 @@ function SymEncryptedIntegrityProtected() { this.packets = null; } -SymEncryptedIntegrityProtected.prototype.read = async function (bytes) { +SymEncryptedIntegrityProtectedDataPacket.prototype.read = async function (bytes) { await stream.parse(bytes, async reader => { // - A one-octet version number. The only currently defined value is 1. @@ -74,7 +81,7 @@ SymEncryptedIntegrityProtected.prototype.read = async function (bytes) { }); }; -SymEncryptedIntegrityProtected.prototype.write = function () { +SymEncryptedIntegrityProtectedDataPacket.prototype.write = function () { return util.concat([new Uint8Array([VERSION]), this.encrypted]); }; @@ -86,7 +93,7 @@ SymEncryptedIntegrityProtected.prototype.write = function () { * @returns {Promise} * @async */ -SymEncryptedIntegrityProtected.prototype.encrypt = async function (sessionKeyAlgorithm, key, streaming) { +SymEncryptedIntegrityProtectedDataPacket.prototype.encrypt = async function (sessionKeyAlgorithm, key, streaming) { let bytes = this.packets.write(); if (!streaming) bytes = await stream.readToEnd(bytes); const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm); @@ -108,7 +115,7 @@ SymEncryptedIntegrityProtected.prototype.encrypt = async function (sessionKeyAlg * @returns {Promise} * @async */ -SymEncryptedIntegrityProtected.prototype.decrypt = async function (sessionKeyAlgorithm, key, streaming) { +SymEncryptedIntegrityProtectedDataPacket.prototype.decrypt = async function (sessionKeyAlgorithm, key, streaming) { let encrypted = stream.clone(this.encrypted); if (!streaming) encrypted = await stream.readToEnd(encrypted); const decrypted = await crypto.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(crypto.cipher[sessionKeyAlgorithm].blockSize)); @@ -132,8 +139,13 @@ SymEncryptedIntegrityProtected.prototype.decrypt = async function (sessionKeyAlg if (!util.isStream(encrypted) || !config.allowUnauthenticatedStream) { packetbytes = await stream.readToEnd(packetbytes); } - await this.packets.read(packetbytes, streaming); + await this.packets.read(packetbytes, { + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket + }, streaming); return true; }; -export default SymEncryptedIntegrityProtected; +export default SymEncryptedIntegrityProtectedDataPacket; diff --git a/src/packet/sym_encrypted_session_key.js b/src/packet/sym_encrypted_session_key.js index 734a6cd3..8f333f9c 100644 --- a/src/packet/sym_encrypted_session_key.js +++ b/src/packet/sym_encrypted_session_key.js @@ -47,7 +47,7 @@ import util from '../util'; * @memberof module:packet * @constructor */ -function SymEncryptedSessionKey() { +function SymEncryptedSessionKeyPacket() { this.tag = enums.packet.symEncryptedSessionKey; this.version = config.aeadProtect ? 5 : 4; this.sessionKey = null; @@ -67,9 +67,9 @@ function SymEncryptedSessionKey() { * @param {Integer} len * Length of the packet or the remaining length of * input at position - * @returns {module:packet.SymEncryptedSessionKey} Object representation + * @returns {SymEncryptedSessionKeyPacket} Object representation */ -SymEncryptedSessionKey.prototype.read = function(bytes) { +SymEncryptedSessionKeyPacket.prototype.read = function(bytes) { let offset = 0; // A one-octet version number. The only currently defined version is 4. @@ -105,7 +105,7 @@ SymEncryptedSessionKey.prototype.read = function(bytes) { } }; -SymEncryptedSessionKey.prototype.write = function() { +SymEncryptedSessionKeyPacket.prototype.write = function() { const algo = this.encrypted === null ? this.sessionKeyAlgorithm : this.sessionKeyEncryptionAlgorithm; @@ -131,7 +131,7 @@ SymEncryptedSessionKey.prototype.write = function() { * @returns {Promise} * @async */ -SymEncryptedSessionKey.prototype.decrypt = async function(passphrase) { +SymEncryptedSessionKeyPacket.prototype.decrypt = async function(passphrase) { const algo = this.sessionKeyEncryptionAlgorithm !== null ? this.sessionKeyEncryptionAlgorithm : this.sessionKeyAlgorithm; @@ -162,7 +162,7 @@ SymEncryptedSessionKey.prototype.decrypt = async function(passphrase) { * @returns {Promise} * @async */ -SymEncryptedSessionKey.prototype.encrypt = async function(passphrase) { +SymEncryptedSessionKeyPacket.prototype.encrypt = async function(passphrase) { const algo = this.sessionKeyEncryptionAlgorithm !== null ? this.sessionKeyEncryptionAlgorithm : this.sessionKeyAlgorithm; @@ -194,4 +194,4 @@ SymEncryptedSessionKey.prototype.encrypt = async function(passphrase) { return true; }; -export default SymEncryptedSessionKey; +export default SymEncryptedSessionKeyPacket; diff --git a/src/packet/symmetrically_encrypted.js b/src/packet/symmetrically_encrypted_data.js similarity index 82% rename from src/packet/symmetrically_encrypted.js rename to src/packet/symmetrically_encrypted_data.js index 901d682a..ba3fb883 100644 --- a/src/packet/symmetrically_encrypted.js +++ b/src/packet/symmetrically_encrypted_data.js @@ -21,6 +21,7 @@ * @requires crypto * @requires enums * @requires util + * @requires packet */ import stream from 'web-stream-tools'; @@ -28,6 +29,12 @@ import config from '../config'; import crypto from '../crypto'; import enums from '../enums'; import util from '../util'; +import { + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket +} from '../packet'; /** * Implementation of the Symmetrically Encrypted Data Packet (Tag 9) @@ -41,19 +48,19 @@ import util from '../util'; * @memberof module:packet * @constructor */ -function SymmetricallyEncrypted() { +function SymmetricallyEncryptedDataPacket() { /** * Packet type * @type {module:enums.packet} */ - this.tag = enums.packet.symmetricallyEncrypted; + this.tag = enums.packet.symmetricallyEncryptedData; /** * Encrypted secret-key data */ this.encrypted = null; /** * Decrypted packets contained within. - * @type {module:packet.List} + * @type {PacketList} */ this.packets = null; /** @@ -63,11 +70,11 @@ function SymmetricallyEncrypted() { this.ignoreMdcError = config.ignoreMdcError; } -SymmetricallyEncrypted.prototype.read = function (bytes) { +SymmetricallyEncryptedDataPacket.prototype.read = function (bytes) { this.encrypted = bytes; }; -SymmetricallyEncrypted.prototype.write = function () { +SymmetricallyEncryptedDataPacket.prototype.write = function () { return this.encrypted; }; @@ -79,7 +86,7 @@ SymmetricallyEncrypted.prototype.write = function () { * @returns {Promise} * @async */ -SymmetricallyEncrypted.prototype.decrypt = async function (sessionKeyAlgorithm, key) { +SymmetricallyEncryptedDataPacket.prototype.decrypt = async function (sessionKeyAlgorithm, key, streaming) { // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error if (!this.ignoreMdcError) { throw new Error('Decryption failed due to missing MDC.'); @@ -91,7 +98,12 @@ SymmetricallyEncrypted.prototype.decrypt = async function (sessionKeyAlgorithm, this.encrypted.subarray(2, crypto.cipher[sessionKeyAlgorithm].blockSize + 2) ); - await this.packets.read(decrypted); + await this.packets.read(decrypted, { + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket + }, streaming); return true; }; @@ -104,7 +116,7 @@ SymmetricallyEncrypted.prototype.decrypt = async function (sessionKeyAlgorithm, * @returns {Promise} * @async */ -SymmetricallyEncrypted.prototype.encrypt = async function (algo, key) { +SymmetricallyEncryptedDataPacket.prototype.encrypt = async function (algo, key) { const data = this.packets.write(); const prefix = await crypto.getPrefixRandom(algo); @@ -115,4 +127,4 @@ SymmetricallyEncrypted.prototype.encrypt = async function (algo, key) { return true; }; -export default SymmetricallyEncrypted; +export default SymmetricallyEncryptedDataPacket; diff --git a/src/packet/trust.js b/src/packet/trust.js index adc0148e..d40bf3c8 100644 --- a/src/packet/trust.js +++ b/src/packet/trust.js @@ -21,7 +21,7 @@ import enums from '../enums'; * @memberof module:packet * @constructor */ -function Trust() { +function TrustPacket() { this.tag = enums.packet.trust; } @@ -30,6 +30,6 @@ function Trust() { * Currently not implemented as we ignore trust packets * @param {String} byptes payload of a tag 12 packet */ -Trust.prototype.read = function () {}; // TODO +TrustPacket.prototype.read = function () {}; // TODO -export default Trust; +export default TrustPacket; diff --git a/src/packet/user_attribute.js b/src/packet/user_attribute.js index 071facf2..841848ab 100644 --- a/src/packet/user_attribute.js +++ b/src/packet/user_attribute.js @@ -44,7 +44,7 @@ import util from '../util'; * @memberof module:packet * @constructor */ -function UserAttribute() { +function UserAttributePacket() { this.tag = enums.packet.userAttribute; this.attributes = []; } @@ -53,7 +53,7 @@ function UserAttribute() { * parsing function for a user attribute packet (tag 17). * @param {Uint8Array} input payload of a tag 17 packet */ -UserAttribute.prototype.read = function(bytes) { +UserAttributePacket.prototype.read = function(bytes) { let i = 0; while (i < bytes.length) { const len = packet.readSimpleLength(bytes.subarray(i, bytes.length)); @@ -68,7 +68,7 @@ UserAttribute.prototype.read = function(bytes) { * Creates a binary representation of the user attribute packet * @returns {Uint8Array} string representation */ -UserAttribute.prototype.write = function() { +UserAttributePacket.prototype.write = function() { const arr = []; for (let i = 0; i < this.attributes.length; i++) { arr.push(packet.writeSimpleLength(this.attributes[i].length)); @@ -79,11 +79,11 @@ UserAttribute.prototype.write = function() { /** * Compare for equality - * @param {module:packet.UserAttribute} usrAttr + * @param {UserAttributePacket} usrAttr * @returns {Boolean} true if equal */ -UserAttribute.prototype.equals = function(usrAttr) { - if (!usrAttr || !(usrAttr instanceof UserAttribute)) { +UserAttributePacket.prototype.equals = function(usrAttr) { + if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) { return false; } return this.attributes.every(function(attr, index) { @@ -91,4 +91,4 @@ UserAttribute.prototype.equals = function(usrAttr) { }); }; -export default UserAttribute; +export default UserAttributePacket; diff --git a/src/packet/userid.js b/src/packet/userid.js index 9ef68f53..daadcc0a 100644 --- a/src/packet/userid.js +++ b/src/packet/userid.js @@ -34,8 +34,8 @@ import util from '../util'; * @memberof module:packet * @constructor */ -function Userid() { - this.tag = enums.packet.userid; +function UserIDPacket() { + this.tag = enums.packet.userID; /** A string containing the user id. Usually in the form * John Doe * @type {String} @@ -51,14 +51,14 @@ function Userid() { * Parsing function for a user id packet (tag 13). * @param {Uint8Array} input payload of a tag 13 packet */ -Userid.prototype.read = function (bytes) { +UserIDPacket.prototype.read = function (bytes) { this.parse(util.decodeUtf8(bytes)); }; /** * Parse userid string, e.g. 'John Doe ' */ -Userid.prototype.parse = function (userid) { +UserIDPacket.prototype.parse = function (userid) { try { Object.assign(this, util.parseUserId(userid)); } catch (e) {} @@ -69,14 +69,14 @@ Userid.prototype.parse = function (userid) { * Creates a binary representation of the user id packet * @returns {Uint8Array} binary representation */ -Userid.prototype.write = function () { +UserIDPacket.prototype.write = function () { return util.encodeUtf8(this.userid); }; /** * Set userid string from object, e.g. { name:'Phil Zimmermann', email:'phil@openpgp.org' } */ -Userid.prototype.format = function (userid) { +UserIDPacket.prototype.format = function (userid) { if (util.isString(userid)) { userid = util.parseUserId(userid); } @@ -84,4 +84,4 @@ Userid.prototype.format = function (userid) { this.userid = util.formatUserId(userid); }; -export default Userid; +export default UserIDPacket; diff --git a/src/signature.js b/src/signature.js index 704e1a7b..e1488eaa 100644 --- a/src/signature.js +++ b/src/signature.js @@ -23,19 +23,19 @@ */ import armor from './encoding/armor'; -import packet from './packet'; +import { PacketList, SignaturePacket } from './packet'; import enums from './enums'; /** * @class * @classdesc Class that represents an OpenPGP signature. - * @param {module:packet.List} packetlist The signature packets + * @param {PacketList} packetlist The signature packets */ export function Signature(packetlist) { if (!(this instanceof Signature)) { return new Signature(packetlist); } - this.packets = packetlist || new packet.List(); + this.packets = packetlist || new PacketList(); } @@ -75,7 +75,7 @@ export async function readArmored(armoredText) { * @static */ export async function read(input) { - const packetlist = new packet.List(); - await packetlist.read(input); + const packetlist = new PacketList(); + await packetlist.read(input, { SignaturePacket }); return new Signature(packetlist); } diff --git a/test/general/key.js b/test/general/key.js index da744ab0..5ff8808a 100644 --- a/test/general/key.js +++ b/test/general/key.js @@ -2609,8 +2609,8 @@ module.exports = () => describe('Key', function() { 43 ee 3b 24 06 `.replace(/\s+/g, '')); - let packetlist = new openpgp.packet.List(); - await packetlist.read(packetBytes); + let packetlist = new openpgp.PacketList(); + await packetlist.read(packetBytes, { PublicKeyPacket: openpgp.PublicKeyPacket }); let key = packetlist[0]; expect(key).to.exist; }); @@ -2638,9 +2638,9 @@ module.exports = () => describe('Key', function() { const pubKey = await openpgp.key.readArmored(pub_sig_test); expect(pubKey).to.exist; - const packetlist = new openpgp.packet.List(); + const packetlist = new openpgp.PacketList(); - await packetlist.read((await openpgp.armor.decode(pub_sig_test)).data); + await packetlist.read((await openpgp.armor.decode(pub_sig_test)).data, openpgp); const subkeys = pubKey.getSubkeys(); expect(subkeys).to.exist; @@ -2886,7 +2886,7 @@ module.exports = () => describe('Key', function() { expect(source.revocationSignatures).to.exist; dest.revocationSignatures = []; return dest.update(source).then(() => { - expect(dest.revocationSignatures[0]).to.exist.and.be.an.instanceof(openpgp.packet.Signature); + expect(dest.revocationSignatures[0]).to.exist.and.be.an.instanceof(openpgp.SignaturePacket); }); }); @@ -3064,8 +3064,8 @@ module.exports = () => describe('Key', function() { const revocationCertificate = await revKey.getRevocationCertificate(); const input = await openpgp.armor.decode(revocation_certificate_arm4); - const packetlist = new openpgp.packet.List(); - await packetlist.read(input.data); + const packetlist = new openpgp.PacketList(); + await packetlist.read(input.data, { SignaturePacket: openpgp.SignaturePacket }); const armored = openpgp.armor.encode(openpgp.enums.armor.publicKey, packetlist.write()); expect(revocationCertificate.replace(/^Comment: .*$\r\n/mg, '')).to.equal(armored.replace(/^Comment: .*$\r\n/mg, '')); @@ -3158,7 +3158,7 @@ module.exports = () => describe('Key', function() { expect(primUser.user.userId.name).to.equal('Signature Test'); expect(primUser.user.userId.email).to.equal('signature@test.com'); expect(primUser.user.userId.comment).to.equal(''); - expect(primUser.selfCertification).to.be.an.instanceof(openpgp.packet.Signature); + expect(primUser.selfCertification).to.be.an.instanceof(openpgp.SignaturePacket); }); it('getPrimaryUser() should throw if no UserIDs are bound', async function() { diff --git a/test/general/openpgp.js b/test/general/openpgp.js index 82026b32..0a622254 100644 --- a/test/general/openpgp.js +++ b/test/general/openpgp.js @@ -452,8 +452,8 @@ function withCompression(tests) { let decompressSpy; beforeEach(function () { - compressSpy = spy(openpgp.packet.Compressed.prototype, 'compress'); - decompressSpy = spy(openpgp.packet.Compressed.prototype, 'decompress'); + compressSpy = spy(openpgp.CompressedDataPacket.prototype, 'compress'); + decompressSpy = spy(openpgp.CompressedDataPacket.prototype, 'decompress'); }); afterEach(function () { @@ -1080,7 +1080,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { return openpgp.encrypt(encOpt).then(async function (encrypted) { expect(encrypted).to.match(/^-----BEGIN PGP MESSAGE/); decOpt.message = await openpgp.message.readArmored(encrypted); - expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.symEncryptedAEADProtected)).to.equal(false); + expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.symEncryptedAEADProtectedData)).to.equal(false); return openpgp.decrypt(decOpt); }).then(function (decrypted) { expect(decrypted.data).to.equal(plaintext); @@ -1103,7 +1103,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { return openpgp.encrypt(encOpt).then(async function (encrypted) { expect(encrypted).to.match(/^-----BEGIN PGP MESSAGE/); decOpt.message = await openpgp.message.readArmored(encrypted); - expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.symEncryptedAEADProtected)).to.equal(false); + expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.symEncryptedAEADProtectedData)).to.equal(false); return openpgp.decrypt(decOpt); }).then(function (decrypted) { expect(decrypted.data).to.equal(plaintext); @@ -1122,7 +1122,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }; return openpgp.encrypt(encOpt).then(async function (encrypted) { decOpt.message = await openpgp.message.readArmored(encrypted); - expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.symEncryptedAEADProtected)).to.equal(openpgp.config.aeadProtect); + expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.symEncryptedAEADProtectedData)).to.equal(openpgp.config.aeadProtect); return openpgp.decrypt(decOpt); }).then(async function (decrypted) { expect(decrypted.data).to.equal(plaintext); @@ -1145,7 +1145,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }; return openpgp.encrypt(encOpt).then(async function (encrypted) { decOpt.message = await openpgp.message.readArmored(encrypted); - expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.symEncryptedAEADProtected)).to.equal(false); + expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.symEncryptedAEADProtectedData)).to.equal(false); return openpgp.decrypt(decOpt); }).then(async function (decrypted) { expect(decrypted.data).to.equal(plaintext); @@ -1176,7 +1176,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }; return openpgp.encrypt(encOpt).then(async function (encrypted) { decOpt.message = await openpgp.message.readArmored(encrypted); - expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.symEncryptedAEADProtected)).to.equal(openpgp.config.aeadProtect); + expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.symEncryptedAEADProtectedData)).to.equal(openpgp.config.aeadProtect); return openpgp.decrypt(decOpt); }).then(async function (decrypted) { expect(decrypted.data).to.equal(plaintext); @@ -1205,7 +1205,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { detached: true }); const message = await openpgp.message.readArmored(encrypted); - expect(!!message.packets.findPacket(openpgp.enums.packet.symEncryptedAEADProtected)).to.equal(openpgp.config.aeadProtect); + expect(!!message.packets.findPacket(openpgp.enums.packet.symEncryptedAEADProtectedData)).to.equal(openpgp.config.aeadProtect); const decrypted = await openpgp.decrypt({ message, signature: await openpgp.signature.readArmored(signed), @@ -2020,9 +2020,9 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { return openpgp.sign(signOpt).then(async function (signed) { const message = await openpgp.message.read(signed); message.packets.concat(await openpgp.stream.readToEnd(message.packets.stream, _ => _)); - const packets = new openpgp.packet.List(); + const packets = new openpgp.PacketList(); packets.push(message.packets.findPacket(openpgp.enums.packet.signature)); - packets.push(message.packets.findPacket(openpgp.enums.packet.literal)); + packets.push(message.packets.findPacket(openpgp.enums.packet.literalData)); verifyOpt.message = new openpgp.message.Message(packets); return openpgp.verify(verifyOpt); }).then(async function (verified) { @@ -2052,9 +2052,9 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(openpgp.util.isStream(signed)).to.equal(useNativeStream ? 'web' : 'ponyfill'); const message = await openpgp.message.read(signed); message.packets.concat(await openpgp.stream.readToEnd(message.packets.stream, _ => _)); - const packets = new openpgp.packet.List(); + const packets = new openpgp.PacketList(); packets.push(message.packets.findPacket(openpgp.enums.packet.signature)); - packets.push(message.packets.findPacket(openpgp.enums.packet.literal)); + packets.push(message.packets.findPacket(openpgp.enums.packet.literalData)); verifyOpt.message = new openpgp.message.Message(packets); return openpgp.verify(verifyOpt); }).then(async function (verified) { @@ -2080,7 +2080,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { const message = await openpgp.message.read(encrypted); return message.decrypt([privateKey_2038_2045]); }).then(async function (packets) { - const literals = packets.packets.filterByTag(openpgp.enums.packet.literal); + const literals = packets.packets.filterByTag(openpgp.enums.packet.literalData); expect(literals.length).to.equal(1); expect(+literals[0].date).to.equal(+future); expect(await openpgp.stream.readToEnd(packets.getText())).to.equal(plaintext); @@ -2101,7 +2101,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { const message = await openpgp.message.read(encrypted); return message.decrypt([privateKey_2000_2008]); }).then(async function (packets) { - const literals = packets.packets.filterByTag(openpgp.enums.packet.literal); + const literals = packets.packets.filterByTag(openpgp.enums.packet.literalData); expect(literals.length).to.equal(1); expect(+literals[0].date).to.equal(+past); expect(await openpgp.stream.readToEnd(packets.getLiteralData())).to.deep.equal(data); @@ -2122,7 +2122,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { const message = await openpgp.message.read(encrypted); return message.decrypt([privateKey_2000_2008]); }).then(async function (message) { - const literals = message.packets.filterByTag(openpgp.enums.packet.literal); + const literals = message.packets.filterByTag(openpgp.enums.packet.literalData); expect(literals.length).to.equal(1); expect(+literals[0].date).to.equal(+past); const signatures = await message.verify([publicKey_2000_2008], past); @@ -2150,7 +2150,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { const message = await openpgp.message.read(encrypted); return message.decrypt([privateKey_2038_2045]); }).then(async function (message) { - const literals = message.packets.filterByTag(openpgp.enums.packet.literal); + const literals = message.packets.filterByTag(openpgp.enums.packet.literalData); expect(literals.length).to.equal(1); expect(literals[0].format).to.equal('binary'); expect(+literals[0].date).to.equal(+future); @@ -2179,7 +2179,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { const message = await openpgp.message.read(encrypted); return message.decrypt([privateKey_2038_2045]); }).then(async function (message) { - const literals = message.packets.filterByTag(openpgp.enums.packet.literal); + const literals = message.packets.filterByTag(openpgp.enums.packet.literalData); expect(literals.length).to.equal(1); expect(literals[0].format).to.equal('mime'); expect(+literals[0].date).to.equal(+future); diff --git a/test/general/packet.js b/test/general/packet.js index ee7a8c13..929fb4c3 100644 --- a/test/general/packet.js +++ b/test/general/packet.js @@ -62,13 +62,13 @@ module.exports = () => describe("Packet", function() { '-----END PGP PRIVATE KEY BLOCK-----'; it('Symmetrically encrypted packet', async function() { - const message = new openpgp.packet.List(); + const message = new openpgp.PacketList(); const testText = input.createSomeMessage(); - const literal = new openpgp.packet.Literal(); + const literal = new openpgp.LiteralDataPacket(); literal.setText(testText); - const enc = new openpgp.packet.SymmetricallyEncrypted(); + const enc = new openpgp.SymmetricallyEncryptedDataPacket(); message.push(enc); enc.packets.push(literal); @@ -78,7 +78,7 @@ module.exports = () => describe("Packet", function() { await enc.encrypt(algo, key); const msg2 = new openpgp.message.Message(); - await msg2.packets.read(message.write()); + await msg2.packets.read(message.write(), { SymmetricallyEncryptedDataPacket: openpgp.SymmetricallyEncryptedDataPacket }); msg2.packets[0].ignoreMdcError = true; const dec = await msg2.decrypt(null, null, [{ algorithm: algo, data: key }]); @@ -86,13 +86,13 @@ module.exports = () => describe("Packet", function() { }); it('Symmetrically encrypted packet - MDC error for modern cipher', async function() { - const message = new openpgp.packet.List(); + const message = new openpgp.PacketList(); const testText = input.createSomeMessage(); - const literal = new openpgp.packet.Literal(); + const literal = new openpgp.LiteralDataPacket(); literal.setText(testText); - const enc = new openpgp.packet.SymmetricallyEncrypted(); + const enc = new openpgp.SymmetricallyEncryptedDataPacket(); message.push(enc); await enc.packets.push(literal); @@ -101,8 +101,8 @@ module.exports = () => describe("Packet", function() { await enc.encrypt(algo, key); - const msg2 = new openpgp.packet.List(); - await msg2.read(message.write()); + const msg2 = new openpgp.PacketList(); + await msg2.read(message.write(), { SymmetricallyEncryptedDataPacket: openpgp.SymmetricallyEncryptedDataPacket }); await expect(msg2[0].decrypt(algo, key)).to.eventually.be.rejectedWith('Decryption failed due to missing MDC.'); }); @@ -111,17 +111,17 @@ module.exports = () => describe("Packet", function() { const algo = 'aes256'; const testText = input.createSomeMessage(); - const literal = new openpgp.packet.Literal(); - const enc = new openpgp.packet.SymEncryptedIntegrityProtected(); - const msg = new openpgp.packet.List(); + const literal = new openpgp.LiteralDataPacket(); + const enc = new openpgp.SymEncryptedIntegrityProtectedDataPacket(); + const msg = new openpgp.PacketList(); msg.push(enc); literal.setText(testText); enc.packets.push(literal); await enc.encrypt(algo, key); - const msg2 = new openpgp.packet.List(); - await msg2.read(msg.write()); + const msg2 = new openpgp.PacketList(); + await msg2.read(msg.write(), openpgp); await msg2[0].decrypt(algo, key); @@ -132,18 +132,18 @@ module.exports = () => describe("Packet", function() { const key = new Uint8Array([1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2]); const algo = 'aes256'; const testText = input.createSomeMessage(); - const literal = new openpgp.packet.Literal(); - const enc = new openpgp.packet.SymEncryptedAEADProtected(); - const msg = new openpgp.packet.List(); + const literal = new openpgp.LiteralDataPacket(); + const enc = new openpgp.SymEncryptedAEADProtectedDataPacket(); + const msg = new openpgp.PacketList(); msg.push(enc); literal.setText(testText); enc.packets.push(literal); - const msg2 = new openpgp.packet.List(); + const msg2 = new openpgp.PacketList(); return enc.encrypt(algo, key).then(async function() { - await msg2.read(msg.write()); + await msg2.read(msg.write(), openpgp); return msg2[0].decrypt(algo, key); }).then(async function() { expect(await openpgp.stream.readToEnd(msg2[0].packets[0].data)).to.deep.equal(literal.data); @@ -158,19 +158,19 @@ module.exports = () => describe("Packet", function() { const key = new Uint8Array([1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2]); const algo = 'aes256'; - const literal = new openpgp.packet.Literal(); - const enc = new openpgp.packet.SymEncryptedAEADProtected(); - const msg = new openpgp.packet.List(); + const literal = new openpgp.LiteralDataPacket(); + const enc = new openpgp.SymEncryptedAEADProtectedDataPacket(); + const msg = new openpgp.PacketList(); msg.push(enc); literal.setText(testText); enc.packets.push(literal); - const msg2 = new openpgp.packet.List(); + const msg2 = new openpgp.PacketList(); try { await enc.encrypt(algo, key); - await msg2.read(msg.write()); + await msg2.read(msg.write(), openpgp); await msg2[0].decrypt(algo, key); expect(await openpgp.stream.readToEnd(msg2[0].packets[0].data)).to.deep.equal(literal.data); } finally { @@ -213,20 +213,20 @@ module.exports = () => describe("Packet", function() { const key = new Uint8Array([1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2]); const algo = 'aes256'; - const literal = new openpgp.packet.Literal(); - const enc = new openpgp.packet.SymEncryptedAEADProtected(); - const msg = new openpgp.packet.List(); + const literal = new openpgp.LiteralDataPacket(); + const enc = new openpgp.SymEncryptedAEADProtectedDataPacket(); + const msg = new openpgp.PacketList(); enc.aeadAlgorithm = 'experimentalGcm'; msg.push(enc); literal.setText(testText); enc.packets.push(literal); - const msg2 = new openpgp.packet.List(); + const msg2 = new openpgp.PacketList(); try { await enc.encrypt(algo, key); - await msg2.read(msg.write()); + await msg2.read(msg.write(), openpgp); await msg2[0].decrypt(algo, key); expect(await openpgp.stream.readToEnd(msg2[0].packets[0].data)).to.deep.equal(literal.data); expect(encryptStub.callCount > 1).to.be.true; @@ -259,16 +259,16 @@ module.exports = () => describe("Packet", function() { const key = openpgp.util.hexToUint8Array('86 f1 ef b8 69 52 32 9f 24 ac d3 bf d0 e5 34 6d'.replace(/\s+/g, '')); const algo = 'aes128'; - const literal = new openpgp.packet.Literal(0); - const enc = new openpgp.packet.SymEncryptedAEADProtected(); - const msg = new openpgp.packet.List(); + const literal = new openpgp.LiteralDataPacket(0); + const enc = new openpgp.SymEncryptedAEADProtectedDataPacket(); + const msg = new openpgp.PacketList(); msg.push(enc); literal.setBytes(openpgp.util.strToUint8Array('Hello, world!\n'), openpgp.enums.literal.binary); literal.filename = ''; enc.packets.push(literal); - const msg2 = new openpgp.packet.List(); + const msg2 = new openpgp.PacketList(); let randomBytesStub = stub(openpgp.crypto.random, 'getRandomBytes'); randomBytesStub.returns(resolves(iv)); @@ -277,7 +277,7 @@ module.exports = () => describe("Packet", function() { await enc.encrypt(algo, key); const data = msg.write(); expect(await openpgp.stream.readToEnd(openpgp.stream.clone(data))).to.deep.equal(packetBytes); - await msg2.read(data); + await msg2.read(data, openpgp); await msg2[0].decrypt(algo, key); expect(await openpgp.stream.readToEnd(msg2[0].packets[0].data)).to.deep.equal(literal.data); } finally { @@ -299,8 +299,8 @@ module.exports = () => describe("Packet", function() { const msgbytes = (await openpgp.armor.decode(msg)).data; - const parsed = new openpgp.packet.List(); - await parsed.read(msgbytes); + const parsed = new openpgp.PacketList(); + await parsed.read(msgbytes, openpgp); return parsed[0].decrypt('test').then(() => { const key = parsed[0].sessionKey; @@ -325,9 +325,9 @@ module.exports = () => describe("Packet", function() { return new openpgp.MPI(k); }); - const enc = new openpgp.packet.PublicKeyEncryptedSessionKey(); - const msg = new openpgp.packet.List(); - const msg2 = new openpgp.packet.List(); + const enc = new openpgp.PublicKeyEncryptedSessionKeyPacket(); + const msg = new openpgp.PacketList(); + const msg2 = new openpgp.PacketList(); enc.sessionKey = new Uint8Array([1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2]); enc.publicKeyAlgorithm = 'rsaEncryptSign'; @@ -337,7 +337,7 @@ module.exports = () => describe("Packet", function() { msg.push(enc); - await msg2.read(msg.write()); + await msg2.read(msg.write(), openpgp); return msg2[0].decrypt({ algorithm: 'rsaEncryptSign', params: mpi, getFingerprintBytes() {} }).then(() => { @@ -371,11 +371,11 @@ module.exports = () => describe("Packet", function() { '=lKiS\n' + '-----END PGP PRIVATE KEY BLOCK-----'; - let key = new openpgp.packet.List(); - await key.read((await openpgp.armor.decode(armored_key)).data); + let key = new openpgp.PacketList(); + await key.read((await openpgp.armor.decode(armored_key)).data, openpgp); key = key[0]; - const enc = new openpgp.packet.PublicKeyEncryptedSessionKey(); + const enc = new openpgp.PublicKeyEncryptedSessionKeyPacket(); const secret = new Uint8Array([1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2]); enc.sessionKey = secret; @@ -438,12 +438,12 @@ module.exports = () => describe("Packet", function() { '=iSaK\n' + '-----END PGP MESSAGE-----'; - let key = new openpgp.packet.List(); - await key.read((await openpgp.armor.decode(armored_key)).data); + let key = new openpgp.PacketList(); + await key.read((await openpgp.armor.decode(armored_key)).data, openpgp); key = key[3]; - const msg = new openpgp.packet.List(); - await msg.read((await openpgp.armor.decode(armored_msg)).data); + const msg = new openpgp.PacketList(); + await msg.read((await openpgp.armor.decode(armored_msg)).data, openpgp); return msg[0].decrypt(key).then(async () => { await msg[1].decrypt(msg[0].sessionKeyAlgorithm, msg[0].sessionKey); @@ -459,10 +459,10 @@ module.exports = () => describe("Packet", function() { const algo = 'aes256'; const testText = input.createSomeMessage(); - const literal = new openpgp.packet.Literal(); - const key_enc = new openpgp.packet.SymEncryptedSessionKey(); - const enc = new openpgp.packet.SymEncryptedIntegrityProtected(); - const msg = new openpgp.packet.List(); + const literal = new openpgp.LiteralDataPacket(); + const key_enc = new openpgp.SymEncryptedSessionKeyPacket(); + const enc = new openpgp.SymEncryptedIntegrityProtectedDataPacket(); + const msg = new openpgp.PacketList(); msg.push(key_enc); msg.push(enc); @@ -476,8 +476,8 @@ module.exports = () => describe("Packet", function() { enc.packets.push(literal); await enc.encrypt(algo, key); - const msg2 = new openpgp.packet.List(); - await msg2.read(msg.write()); + const msg2 = new openpgp.PacketList(); + await msg2.read(msg.write(), openpgp); await msg2[0].decrypt(passphrase); const key2 = msg2[0].sessionKey; @@ -495,10 +495,10 @@ module.exports = () => describe("Packet", function() { const algo = 'aes256'; const testText = input.createSomeMessage(); - const literal = new openpgp.packet.Literal(); - const key_enc = new openpgp.packet.SymEncryptedSessionKey(); - const enc = new openpgp.packet.SymEncryptedAEADProtected(); - const msg = new openpgp.packet.List(); + const literal = new openpgp.LiteralDataPacket(); + const key_enc = new openpgp.SymEncryptedSessionKeyPacket(); + const enc = new openpgp.SymEncryptedAEADProtectedDataPacket(); + const msg = new openpgp.PacketList(); msg.push(key_enc); msg.push(enc); @@ -512,8 +512,8 @@ module.exports = () => describe("Packet", function() { enc.packets.push(literal); await enc.encrypt(algo, key); - const msg2 = new openpgp.packet.List(); - await msg2.read(msg.write()); + const msg2 = new openpgp.PacketList(); + await msg2.read(msg.write(), openpgp); await msg2[0].decrypt(passphrase); const key2 = msg2[0].sessionKey; @@ -563,10 +563,10 @@ module.exports = () => describe("Packet", function() { const passphrase = 'password'; const algo = 'aes128'; - const literal = new openpgp.packet.Literal(0); - const key_enc = new openpgp.packet.SymEncryptedSessionKey(); - const enc = new openpgp.packet.SymEncryptedAEADProtected(); - const msg = new openpgp.packet.List(); + const literal = new openpgp.LiteralDataPacket(0); + const key_enc = new openpgp.SymEncryptedSessionKeyPacket(); + const enc = new openpgp.SymEncryptedAEADProtectedDataPacket(); + const msg = new openpgp.PacketList(); msg.push(key_enc); msg.push(enc); @@ -584,8 +584,8 @@ module.exports = () => describe("Packet", function() { const data = msg.write(); expect(await openpgp.stream.readToEnd(openpgp.stream.clone(data))).to.deep.equal(packetBytes); - const msg2 = new openpgp.packet.List(); - await msg2.read(data); + const msg2 = new openpgp.PacketList(); + await msg2.read(data, openpgp); await msg2[0].decrypt(passphrase); const key2 = msg2[0].sessionKey; @@ -638,10 +638,10 @@ module.exports = () => describe("Packet", function() { const passphrase = 'password'; const algo = 'aes128'; - const literal = new openpgp.packet.Literal(0); - const key_enc = new openpgp.packet.SymEncryptedSessionKey(); - const enc = new openpgp.packet.SymEncryptedAEADProtected(); - const msg = new openpgp.packet.List(); + const literal = new openpgp.LiteralDataPacket(0); + const key_enc = new openpgp.SymEncryptedSessionKeyPacket(); + const enc = new openpgp.SymEncryptedAEADProtectedDataPacket(); + const msg = new openpgp.PacketList(); enc.aeadAlgorithm = key_enc.aeadAlgorithm = 'ocb'; msg.push(key_enc); @@ -660,8 +660,8 @@ module.exports = () => describe("Packet", function() { const data = msg.write(); expect(await openpgp.stream.readToEnd(openpgp.stream.clone(data))).to.deep.equal(packetBytes); - const msg2 = new openpgp.packet.List(); - await msg2.read(data); + const msg2 = new openpgp.PacketList(); + await msg2.read(data, openpgp); await msg2[0].decrypt(passphrase); const key2 = msg2[0].sessionKey; @@ -689,13 +689,13 @@ module.exports = () => describe("Packet", function() { '=pR+C\n' + '-----END PGP MESSAGE-----'; - let key = new openpgp.packet.List(); - await key.read((await openpgp.armor.decode(armored_key)).data); + let key = new openpgp.PacketList(); + await key.read((await openpgp.armor.decode(armored_key)).data, openpgp); key = key[3]; await key.decrypt('test'); - const msg = new openpgp.packet.List(); - await msg.read((await openpgp.armor.decode(armored_msg)).data); + const msg = new openpgp.PacketList(); + await msg.read((await openpgp.armor.decode(armored_msg)).data, openpgp); return msg[0].decrypt(key).then(async () => { await msg[1].decrypt(msg[0].sessionKeyAlgorithm, msg[0].sessionKey); @@ -707,8 +707,8 @@ module.exports = () => describe("Packet", function() { }); it('Secret key reading with signature verification.', async function() { - const key = new openpgp.packet.List(); - await key.read((await openpgp.armor.decode(armored_key)).data); + const key = new openpgp.PacketList(); + await key.read((await openpgp.armor.decode(armored_key)).data, openpgp); return Promise.all([ expect(key[2].verify(key[0], openpgp.enums.signature.certGeneric, @@ -742,12 +742,12 @@ module.exports = () => describe("Packet", function() { '=htrB\n' + '-----END PGP MESSAGE-----'; - const key = new openpgp.packet.List(); - await key.read((await openpgp.armor.decode(armored_key)).data); + const key = new openpgp.PacketList(); + await key.read((await openpgp.armor.decode(armored_key)).data, openpgp); await key[3].decrypt('test'); - const msg = new openpgp.packet.List(); - await msg.read((await openpgp.armor.decode(armored_msg)).data); + const msg = new openpgp.PacketList(); + await msg.read((await openpgp.armor.decode(armored_msg)).data, openpgp); return msg[0].decrypt(key[3]).then(async () => { await msg[1].decrypt(msg[0].sessionKeyAlgorithm, msg[0].sessionKey); @@ -842,8 +842,8 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ }); it('Writing and encryption of a secret key packet.', function() { - const key = new openpgp.packet.List(); - key.push(new openpgp.packet.SecretKey()); + const key = new openpgp.PacketList(); + key.push(new openpgp.SecretKeyPacket()); const rsa = openpgp.crypto.publicKey.rsa; const keySize = openpgp.util.getWebCryptoAll() ? 2048 : 512; // webkit webcrypto accepts minimum 2048 bit keys @@ -861,8 +861,8 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ const raw = key.write(); - const key2 = new openpgp.packet.List(); - await key2.read(raw); + const key2 = new openpgp.PacketList(); + await key2.read(raw, openpgp); await key2[0].decrypt('hello'); expect(key[0].params.toString()).to.equal(key2[0].params.toString()); @@ -873,8 +873,8 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ let aeadProtectVal = openpgp.config.aeadProtect; openpgp.config.aeadProtect = true; - const key = new openpgp.packet.List(); - key.push(new openpgp.packet.SecretKey()); + const key = new openpgp.PacketList(); + key.push(new openpgp.SecretKeyPacket()); const rsa = openpgp.crypto.publicKey.rsa; const keySize = openpgp.util.getWebCryptoAll() ? 2048 : 512; // webkit webcrypto accepts minimum 2048 bit keys @@ -893,8 +893,8 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ const raw = key.write(); - const key2 = new openpgp.packet.List(); - await key2.read(raw); + const key2 = new openpgp.PacketList(); + await key2.read(raw, openpgp); await key2[0].decrypt('hello'); expect(key[0].params.toString()).to.equal(key2[0].params.toString()); @@ -904,7 +904,7 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ }); it('Writing and verification of a signature packet.', function() { - const key = new openpgp.packet.SecretKey(); + const key = new openpgp.SecretKeyPacket(); const rsa = openpgp.crypto.publicKey.rsa; const keySize = openpgp.util.getWebCryptoAll() ? 2048 : 512; // webkit webcrypto accepts minimum 2048 bit keys @@ -919,9 +919,9 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ key.params = mpi; key.algorithm = "rsaSign"; - const signed = new openpgp.packet.List(); - const literal = new openpgp.packet.Literal(); - const signature = new openpgp.packet.Signature(); + const signed = new openpgp.PacketList(); + const literal = new openpgp.LiteralDataPacket(); + const signature = new openpgp.SignaturePacket(); literal.setText(testText); @@ -936,8 +936,8 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ const raw = signed.write(); - const signed2 = new openpgp.packet.List(); - await signed2.read(raw); + const signed2 = new openpgp.PacketList(); + await signed2.read(raw, openpgp); signed2.concat(await openpgp.stream.readToEnd(signed2.stream, arr => arr)); await Promise.all([ diff --git a/test/security/message_signature_bypass.js b/test/security/message_signature_bypass.js index f28fac8f..abb65eb9 100644 --- a/test/security/message_signature_bypass.js +++ b/test/security/message_signature_bypass.js @@ -1,6 +1,6 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); -const { key, cleartext, util, packet: { Signature } } = openpgp; +const { key, cleartext, util, SignaturePacket } = openpgp; const chai = require('chai'); chai.use(require('chai-as-promised')); @@ -89,7 +89,7 @@ async function fakeSignature() { 'You owe me', 'I owe you')); // read the standalone signature packet - const tmp = new Signature(); + const tmp = new SignaturePacket(); await tmp.read(STANDALONE_PKT); // replace the "text" signature with the diff --git a/test/security/preferred_algo_mismatch.js b/test/security/preferred_algo_mismatch.js index 00a385d9..5dd1094a 100644 --- a/test/security/preferred_algo_mismatch.js +++ b/test/security/preferred_algo_mismatch.js @@ -1,6 +1,6 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); -const { key, cleartext, enums, packet: { List, Signature } } = openpgp; +const { key, cleartext, enums, PacketList, SignaturePacket } = openpgp; const chai = require('chai'); chai.use(require('chai-as-promised')); diff --git a/test/security/subkey_trust.js b/test/security/subkey_trust.js index 3f15d169..175a3468 100644 --- a/test/security/subkey_trust.js +++ b/test/security/subkey_trust.js @@ -1,6 +1,6 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); -const { key, cleartext, enums, packet: { List, Signature } } = openpgp; +const { key, cleartext, enums, PacketList, SignaturePacket } = openpgp; const chai = require('chai'); chai.use(require('chai-as-promised')); @@ -48,13 +48,13 @@ async function testSubkeyTrust() { key: attackerPrivKey.toPublic().keyPacket, bind: pktPubVictim[3] // victim subkey }; - const fakeBindingSignature = new Signature(); + const fakeBindingSignature = new SignaturePacket(); fakeBindingSignature.signatureType = enums.signature.subkeyBinding; fakeBindingSignature.publicKeyAlgorithm = attackerPrivKey.keyPacket.algorithm; fakeBindingSignature.hashAlgorithm = enums.hash.sha256; fakeBindingSignature.keyFlags = [enums.keyFlags.signData]; await fakeBindingSignature.sign(attackerPrivKey.keyPacket, dataToSign); - const newList = new List(); + const newList = new PacketList(); newList.concat([ pktPrivAttacker[0], // attacker private key pktPrivAttacker[1], // attacker user diff --git a/test/security/unsigned_subpackets.js b/test/security/unsigned_subpackets.js index bf9701d2..5c305d27 100644 --- a/test/security/unsigned_subpackets.js +++ b/test/security/unsigned_subpackets.js @@ -1,6 +1,6 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); -const { key, message, enums, packet: { List, Signature } } = openpgp; +const { key, message, enums, PacketList, SignaturePacket } = openpgp; const chai = require('chai'); chai.use(require('chai-as-promised')); @@ -70,7 +70,7 @@ async function makeKeyValid() { // deconstruct invalid key const [pubkey, puser, pusersig] = invalidkey.toPacketlist().map(i => i); // create a fake signature - const fake = new Signature(); + const fake = new SignaturePacket(); Object.assign(fake, pusersig); // extend expiration times fake.keyExpirationTime = 0x7FFFFFFF; @@ -80,7 +80,7 @@ async function makeKeyValid() { // create modified subpacket data pusersig.read_sub_packets(fake.write_hashed_sub_packets(), false); // reconstruct the modified key - const newlist = new List(); + const newlist = new PacketList(); newlist.concat([pubkey, puser, pusersig]); let modifiedkey = new key.Key(newlist); // re-read the message to eliminate any