From ceb64710a6d1d1b2fca7af5f290bb23cd8b6c2bb Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Thu, 18 Mar 2021 20:34:11 +0100 Subject: [PATCH 01/18] Uniform config name casing --- README.md | 8 +-- openpgp.d.ts | 6 +- src/config/config.js | 28 ++++---- src/enums.js | 2 +- src/key/factory.js | 8 +-- src/key/helper.js | 8 +-- src/key/key.js | 14 ++-- src/message.js | 2 +- src/openpgp.js | 4 +- src/packet/aead_encrypted_data.js | 2 +- src/packet/secret_key.js | 2 +- src/packet/signature.js | 10 +-- src/packet/sym_encrypted_session_key.js | 4 +- src/packet/userid.js | 2 +- src/type/s2k.js | 2 +- test/general/config.js | 22 +++---- test/general/key.js | 88 ++++++++++++------------- test/general/openpgp.js | 48 +++++++------- test/general/packet.js | 74 ++++++++++----------- test/general/signature.js | 50 +++++++------- test/general/streaming.js | 68 +++++++++---------- test/unittests.js | 2 +- 22 files changed, 227 insertions(+), 227 deletions(-) diff --git a/README.md b/README.md index 9509385ad..178f029fa 100644 --- a/README.md +++ b/README.md @@ -74,14 +74,14 @@ library to convert back and forth between them. * If the user's browser supports [native WebCrypto](https://caniuse.com/#feat=cryptography) via the `window.crypto.subtle` API, this will be used. Under Node.js the native [crypto module](https://nodejs.org/api/crypto.html#crypto_crypto) is used. -* The library implements the [IETF proposal](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10) for authenticated encryption using native AES-EAX, OCB, or GCM. This makes symmetric encryption up to 30x faster on supported platforms. Since the specification has not been finalized and other OpenPGP implementations haven't adopted it yet, the feature is currently behind a flag. **Note: activating this setting can break compatibility with other OpenPGP implementations, and also with future versions of OpenPGP.js. Don't use it with messages you want to store on disk or in a database.** You can enable it by setting `openpgp.config.aeadProtect = true`. +* The library implements the [IETF proposal](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10) for authenticated encryption using native AES-EAX, OCB, or GCM. This makes symmetric encryption up to 30x faster on supported platforms. Since the specification has not been finalized and other OpenPGP implementations haven't adopted it yet, the feature is currently behind a flag. **Note: activating this setting can break compatibility with other OpenPGP implementations, and also with future versions of OpenPGP.js. Don't use it with messages you want to store on disk or in a database.** You can enable it by setting `openpgp.config.AEADProtect = true`. You can change the AEAD mode by setting one of the following options: ``` - openpgp.config.preferredAeadAlgorithm = openpgp.enums.aead.eax // Default, native - openpgp.config.preferredAeadAlgorithm = openpgp.enums.aead.ocb // Non-native - openpgp.config.preferredAeadAlgorithm = openpgp.enums.aead.experimentalGcm // **Non-standard**, fastest + openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.eax // Default, native + openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.ocb // Non-native + openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.experimentalGcm // **Non-standard**, fastest ``` * For environments that don't provide native crypto, the library falls back to [asm.js](https://caniuse.com/#feat=asmjs) implementations of AES, SHA-1, and SHA-256. diff --git a/openpgp.d.ts b/openpgp.d.ts index 42ed65318..83e7ec4f9 100644 --- a/openpgp.d.ts +++ b/openpgp.d.ts @@ -316,11 +316,11 @@ interface Config { showVersion: boolean; showComment: boolean; deflateLevel: number; - aeadProtect: boolean; + AEADProtect: boolean; allowUnauthenticatedMessages: boolean; allowUnauthenticatedStream: boolean; checksumRequired: boolean; - minRsaBits: number; + minRSABits: number; passwordCollisionCheck: boolean; revocationsExpire: boolean; tolerant: boolean; @@ -479,7 +479,7 @@ export class SignaturePacket extends BasePacket { public embeddedSignature: null | SignaturePacket; public issuerKeyVersion: null | number; public issuerFingerprint: null | Uint8Array; - public preferredAeadAlgorithms: enums.aead[] | null; + public preferredAEADAlgorithms: enums.aead[] | null; public verified: null | boolean; public revoked: null | boolean; public sign(key: AnySecretKeyPacket, data: Uint8Array, detached?: boolean, streaming?: boolean): Promise; diff --git a/src/config/config.js b/src/config/config.js index d960faace..305ac082f 100644 --- a/src/config/config.js +++ b/src/config/config.js @@ -49,24 +49,24 @@ export default { * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07} * @memberof module:config - * @property {Boolean} aeadProtect + * @property {Boolean} AEADProtect */ - aeadProtect: false, + AEADProtect: false, /** * Default Authenticated Encryption with Additional Data (AEAD) encryption mode - * Only has an effect when aeadProtect is set to true. + * Only has an effect when AEADProtect is set to true. * @memberof module:config - * @property {Integer} preferredAeadAlgorithm Default AEAD mode {@link module:enums.aead} + * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead} */ - preferredAeadAlgorithm: enums.aead.eax, + preferredAEADAlgorithm: enums.aead.eax, /** * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode - * Only has an effect when aeadProtect is set to true. + * Only has an effect when AEADProtect is set to true. * Must be an integer value from 0 to 56. * @memberof module:config - * @property {Integer} aeadChunkSizeByte + * @property {Integer} AEADChunkSizeByte */ - aeadChunkSizeByte: 12, + AEADChunkSizeByte: 12, /** * Use V5 keys. * Note: not all OpenPGP implementations are compatible with this option. @@ -79,9 +79,9 @@ export default { * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}: * Iteration Count Byte for S2K (String to Key) * @memberof module:config - * @property {Integer} s2kIterationCountByte + * @property {Integer} S2KIterationCountByte */ - s2kIterationCountByte: 224, + S2KIterationCountByte: 224, /** * Allow decryption of messages without integrity protection. * This is an **insecure** setting: @@ -105,9 +105,9 @@ export default { checksumRequired: false, /** * @memberof module:config - * @property {Number} minRsaBits Minimum RSA key size allowed for key generation and message signing, verification and encryption + * @property {Number} minRSABits Minimum RSA key size allowed for key generation and message signing, verification and encryption */ - minRsaBits: 2048, + minRSABits: 2048, /** * Work-around for rare GPG decryption bug when encrypting with multiple passwords. * **Slower and slightly less secure** @@ -164,9 +164,9 @@ export default { /** * Max userid string length (used for parsing) * @memberof module:config - * @property {Integer} maxUseridLength + * @property {Integer} maxUserIDLength */ - maxUseridLength: 1024 * 5, + maxUserIDLength: 1024 * 5, /** * Contains notatations that are considered "known". Known notations do not trigger * validation error when the notation is marked as critical. diff --git a/src/enums.js b/src/enums.js index 88fe6ba1f..3b4280a43 100644 --- a/src/enums.js +++ b/src/enums.js @@ -376,7 +376,7 @@ export default { signatureTarget: 31, embeddedSignature: 32, issuerFingerprint: 33, - preferredAeadAlgorithms: 34 + preferredAEADAlgorithms: 34 }, /** Key flags diff --git a/src/key/factory.js b/src/key/factory.js index 2345e6ef4..37c1c3ab6 100644 --- a/src/key/factory.js +++ b/src/key/factory.js @@ -153,11 +153,11 @@ async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, conf enums.symmetric.aes128, enums.symmetric.aes192 ], config.preferredSymmetricAlgorithm); - if (config.aeadProtect) { - signaturePacket.preferredAeadAlgorithms = createPreferredAlgos([ + if (config.AEADProtect) { + signaturePacket.preferredAEADAlgorithms = createPreferredAlgos([ enums.aead.eax, enums.aead.ocb - ], config.preferredAeadAlgorithm); + ], config.preferredAEADAlgorithm); } signaturePacket.preferredHashAlgorithms = createPreferredAlgos([ // prefer fast asm.js implementations (SHA-256) @@ -175,7 +175,7 @@ async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, conf // integrity protection always enabled signaturePacket.features = [0]; signaturePacket.features[0] |= enums.features.modificationDetection; - if (config.aeadProtect) { + if (config.AEADProtect) { signaturePacket.features[0] |= enums.features.aead; } if (config.v5Keys) { diff --git a/src/key/helper.js b/src/key/helper.js index 14d71cb70..d4fd1ea1d 100644 --- a/src/key/helper.js +++ b/src/key/helper.js @@ -176,12 +176,12 @@ export async function getPreferredAlgo(type, keys = [], date = new Date(), userI }[type]; const preferredSenderAlgo = { 'symmetric': config.preferredSymmetricAlgorithm, - 'aead': config.preferredAeadAlgorithm, + 'aead': config.preferredAEADAlgorithm, 'compression': config.preferredCompressionAlgorithm }[type]; const prefPropertyName = { 'symmetric': 'preferredSymmetricAlgorithms', - 'aead': 'preferredAeadAlgorithms', + 'aead': 'preferredAEADAlgorithms', 'compression': 'preferredCompressionAlgorithms' }[type]; @@ -415,7 +415,7 @@ export function checkKeyStrength(keyPacket, config) { throw new Error(`${keyPacket.algorithm} keys are considered too weak.`); } const rsaAlgos = new Set([enums.publicKey.rsaEncryptSign, enums.publicKey.rsaSign, enums.publicKey.rsaEncrypt]); - if (rsaAlgos.has(keyAlgo) && util.uint8ArrayBitLength(keyPacket.publicParams.n) < config.minRsaBits) { - throw new Error(`RSA keys shorter than ${config.minRsaBits} bits are considered too weak.`); + if (rsaAlgos.has(keyAlgo) && util.uint8ArrayBitLength(keyPacket.publicParams.n) < config.minRSABits) { + throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`); } } diff --git a/src/key/key.js b/src/key/key.js index b60d64839..19776b8fc 100644 --- a/src/key/key.js +++ b/src/key/key.js @@ -505,7 +505,7 @@ class Key { * It is enough to validate any signing keys * since its binding signatures are also checked */ - const signingKey = await this.getSigningKey(null, null, undefined, { ...config, rejectPublicKeyAlgorithms: new Set(), minRsaBits: 0 }); + const signingKey = await this.getSigningKey(null, null, undefined, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }); // This could again be a dummy key if (signingKey && !signingKey.keyPacket.isDummy()) { signingKeyPacket = signingKey.keyPacket; @@ -600,16 +600,16 @@ class Key { let expiry = keyExpiry < sigExpiry ? keyExpiry : sigExpiry; if (capabilities === 'encrypt' || capabilities === 'encrypt_sign') { const encryptKey = - await this.getEncryptionKey(keyId, expiry, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRsaBits: 0 }).catch(() => {}) || - await this.getEncryptionKey(keyId, null, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRsaBits: 0 }).catch(() => {}); + await this.getEncryptionKey(keyId, expiry, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}) || + await this.getEncryptionKey(keyId, null, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}); if (!encryptKey) return null; const encryptExpiry = await encryptKey.getExpirationTime(this.keyPacket, undefined, config); if (encryptExpiry < expiry) expiry = encryptExpiry; } if (capabilities === 'sign' || capabilities === 'encrypt_sign') { const signKey = - await this.getSigningKey(keyId, expiry, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRsaBits: 0 }).catch(() => {}) || - await this.getSigningKey(keyId, null, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRsaBits: 0 }).catch(() => {}); + await this.getSigningKey(keyId, expiry, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}) || + await this.getSigningKey(keyId, null, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}); if (!signKey) return null; const signExpiry = await signKey.getExpirationTime(this.keyPacket, undefined, config); if (signExpiry < expiry) expiry = signExpiry; @@ -920,8 +920,8 @@ class Key { if (options.passphrase) { throw new Error("Subkey could not be encrypted here, please encrypt whole key"); } - if (options.rsaBits < config.minRsaBits) { - throw new Error(`rsaBits should be at least ${config.minRsaBits}, got: ${options.rsaBits}`); + if (options.rsaBits < config.minRSABits) { + throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${options.rsaBits}`); } const secretKeyPacket = this.primaryKey; if (secretKeyPacket.isDummy()) { diff --git a/src/message.js b/src/message.js index 0f6431cec..82274fbd6 100644 --- a/src/message.js +++ b/src/message.js @@ -283,7 +283,7 @@ export class Message { */ static async generateSessionKey(keys = [], date = new Date(), userIds = [], config = defaultConfig) { const algorithm = enums.read(enums.symmetric, await getPreferredAlgo('symmetric', keys, date, userIds, config)); - const aeadAlgorithm = config.aeadProtect && await isAeadSupported(keys, date, userIds, config) ? + const aeadAlgorithm = config.AEADProtect && await isAeadSupported(keys, date, userIds, config) ? enums.read(enums.aead, await getPreferredAlgo('aead', keys, date, userIds, config)) : undefined; diff --git a/src/openpgp.js b/src/openpgp.js index 9378dd480..41dac45fc 100644 --- a/src/openpgp.js +++ b/src/openpgp.js @@ -61,8 +61,8 @@ export function generateKey({ userIds = [], passphrase = "", type = "ecc", rsaBi config = { ...defaultConfig, ...config }; userIds = toArray(userIds); const options = { userIds, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys }; - if (type === "rsa" && rsaBits < config.minRsaBits) { - throw new Error(`rsaBits should be at least ${config.minRsaBits}, got: ${rsaBits}`); + if (type === "rsa" && rsaBits < config.minRSABits) { + throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${rsaBits}`); } return generate(options, config).then(async key => { diff --git a/src/packet/aead_encrypted_data.js b/src/packet/aead_encrypted_data.js index 94ffc776c..cac47c3e4 100644 --- a/src/packet/aead_encrypted_data.js +++ b/src/packet/aead_encrypted_data.js @@ -106,7 +106,7 @@ class AEADEncryptedDataPacket { this.aeadAlgo = enums.write(enums.aead, this.aeadAlgorithm); const mode = crypto[enums.read(enums.aead, this.aeadAlgo)]; this.iv = await crypto.random.getRandomBytes(mode.ivLength); // generate new random IV - this.chunkSizeByte = config.aeadChunkSizeByte; + this.chunkSizeByte = config.AEADChunkSizeByte; const data = this.packets.write(); this.encrypted = await this.crypt('encrypt', key, data, streaming); } diff --git a/src/packet/secret_key.js b/src/packet/secret_key.js index bef72d17a..af3d93fa8 100644 --- a/src/packet/secret_key.js +++ b/src/packet/secret_key.js @@ -296,7 +296,7 @@ class SecretKeyPacket extends PublicKeyPacket { const blockLen = crypto.cipher[this.symmetric].blockSize; this.iv = await crypto.random.getRandomBytes(blockLen); - if (config.aeadProtect) { + if (config.AEADProtect) { this.s2k_usage = 253; this.aead = 'eax'; const mode = crypto[this.aead]; diff --git a/src/packet/signature.js b/src/packet/signature.js index 1e3485227..d6a8cf450 100644 --- a/src/packet/signature.js +++ b/src/packet/signature.js @@ -80,7 +80,7 @@ class SignaturePacket { this.embeddedSignature = null; this.issuerKeyVersion = null; this.issuerFingerprint = null; - this.preferredAeadAlgorithms = null; + this.preferredAEADAlgorithms = null; this.verified = null; this.revoked = null; @@ -285,9 +285,9 @@ class SignaturePacket { bytes = util.concat(bytes); arr.push(write_sub_packet(sub.signatureTarget, bytes)); } - if (this.preferredAeadAlgorithms !== null) { - bytes = util.strToUint8Array(util.uint8ArrayToStr(this.preferredAeadAlgorithms)); - arr.push(write_sub_packet(sub.preferredAeadAlgorithms, bytes)); + if (this.preferredAEADAlgorithms !== null) { + bytes = util.strToUint8Array(util.uint8ArrayToStr(this.preferredAEADAlgorithms)); + arr.push(write_sub_packet(sub.preferredAEADAlgorithms, bytes)); } const result = util.concat(arr); @@ -509,7 +509,7 @@ class SignaturePacket { break; case 34: // Preferred AEAD Algorithms - read_array.call(this, 'preferredAeadAlgorithms', bytes.subarray(mypos, bytes.length)); + read_array.call(this, 'preferredAEADAlgorithms', bytes.subarray(mypos, bytes.length)); break; default: { const err = new Error("Unknown signature subpacket type " + type + " @:" + mypos); diff --git a/src/packet/sym_encrypted_session_key.js b/src/packet/sym_encrypted_session_key.js index 4fc8a1d02..e07e8d9c9 100644 --- a/src/packet/sym_encrypted_session_key.js +++ b/src/packet/sym_encrypted_session_key.js @@ -40,11 +40,11 @@ class SymEncryptedSessionKeyPacket { */ constructor(config = defaultConfig) { this.tag = enums.packet.symEncryptedSessionKey; - this.version = config.aeadProtect ? 5 : 4; + this.version = config.AEADProtect ? 5 : 4; this.sessionKey = null; this.sessionKeyEncryptionAlgorithm = null; this.sessionKeyAlgorithm = 'aes256'; - this.aeadAlgorithm = enums.read(enums.aead, config.preferredAeadAlgorithm); + this.aeadAlgorithm = enums.read(enums.aead, config.preferredAEADAlgorithm); this.encrypted = null; this.s2k = null; this.iv = null; diff --git a/src/packet/userid.js b/src/packet/userid.js index 3c0d8fb25..69072d9f7 100644 --- a/src/packet/userid.js +++ b/src/packet/userid.js @@ -73,7 +73,7 @@ class UserIDPacket { */ read(bytes, config = defaultConfig) { const userid = util.decodeUtf8(bytes); - if (userid.length > config.maxUseridLength) { + if (userid.length > config.maxUserIDLength) { throw new Error('User ID string is too long'); } try { diff --git a/src/type/s2k.js b/src/type/s2k.js index 6873fe6fe..67ccaac10 100644 --- a/src/type/s2k.js +++ b/src/type/s2k.js @@ -43,7 +43,7 @@ class S2K { /** @type {module:enums.s2k} */ this.type = 'iterated'; /** @type {Integer} */ - this.c = config.s2kIterationCountByte; + this.c = config.S2KIterationCountByte; /** Eight bytes of salt in a binary string. * @type {String} */ diff --git a/test/general/config.js b/test/general/config.js index aa9b79e99..ad6d14800 100644 --- a/test/general/config.js +++ b/test/general/config.js @@ -122,8 +122,8 @@ module.exports = () => describe('Custom configuration', function() { }); it('openpgp.encryptKey', async function() { - const s2kIterationCountByteVal = openpgp.config.s2kIterationCountByte; - openpgp.config.s2kIterationCountByte = 224; + const S2KIterationCountByteVal = openpgp.config.S2KIterationCountByte; + openpgp.config.S2KIterationCountByte = 224; try { const passphrase = '12345678'; @@ -131,20 +131,20 @@ module.exports = () => describe('Custom configuration', function() { const { key: privateKey } = await openpgp.generateKey({ userIds }); const encKey = await openpgp.encryptKey({ privateKey, userIds, passphrase }); - expect(encKey.keyPacket.s2k.c).to.equal(openpgp.config.s2kIterationCountByte); + expect(encKey.keyPacket.s2k.c).to.equal(openpgp.config.S2KIterationCountByte); - const config = { s2kIterationCountByte: 123 }; + const config = { S2KIterationCountByte: 123 }; const encKey2 = await openpgp.encryptKey({ privateKey, userIds, passphrase, config }); - expect(encKey2.keyPacket.s2k.c).to.equal(config.s2kIterationCountByte); + expect(encKey2.keyPacket.s2k.c).to.equal(config.S2KIterationCountByte); } finally { - openpgp.config.s2kIterationCountByte = s2kIterationCountByteVal; + openpgp.config.S2KIterationCountByte = S2KIterationCountByteVal; } }); it('openpgp.encrypt', async function() { - const aeadProtectVal = openpgp.config.aeadProtect; + const AEADProtectVal = openpgp.config.AEADProtect; const preferredCompressionAlgorithmVal = openpgp.config.preferredCompressionAlgorithm; - openpgp.config.aeadProtect = false; + openpgp.config.AEADProtect = false; openpgp.config.preferredCompressionAlgorithm = openpgp.enums.compression.uncompressed; try { @@ -160,7 +160,7 @@ module.exports = () => describe('Custom configuration', function() { expect(literal.tag).to.equal(openpgp.enums.packet.literalData); const config = { - aeadProtect: true, + AEADProtect: true, preferredCompressionAlgorithm: openpgp.enums.compression.zip, deflateLevel: 1 }; @@ -179,7 +179,7 @@ module.exports = () => describe('Custom configuration', function() { message, publicKeys: [key], config: { rejectPublicKeyAlgorithms: new Set([openpgp.enums.publicKey.ecdh]) } })).to.be.eventually.rejectedWith(/ecdh keys are considered too weak/); } finally { - openpgp.config.aeadProtect = aeadProtectVal; + openpgp.config.AEADProtect = AEADProtectVal; openpgp.config.preferredCompressionAlgorithm = preferredCompressionAlgorithmVal; } }); @@ -203,7 +203,7 @@ module.exports = () => describe('Custom configuration', function() { message: await openpgp.readMessage({ armoredMessage }), privateKeys: [key], publicKeys: [key], - config: { minRsaBits: 4096 } + config: { minRSABits: 4096 } }); expect(data2).to.equal(plaintext); expect(signatures2[0].valid).to.be.false; diff --git a/test/general/key.js b/test/general/key.js index bbfbfae9d..25134d44d 100644 --- a/test/general/key.js +++ b/test/general/key.js @@ -2085,9 +2085,9 @@ function versionSpecificTests() { expect(key.subKeys[0].bindingSignatures[0].keyFlags[0] & keyFlags.encryptStorage).to.equal(keyFlags.encryptStorage); const sym = openpgp.enums.symmetric; expect(key.users[0].selfCertifications[0].preferredSymmetricAlgorithms).to.eql([sym.aes256, sym.aes128, sym.aes192]); - if (openpgp.config.aeadProtect) { + if (openpgp.config.AEADProtect) { const aead = openpgp.enums.aead; - expect(key.users[0].selfCertifications[0].preferredAeadAlgorithms).to.eql([aead.eax, aead.ocb]); + expect(key.users[0].selfCertifications[0].preferredAEADAlgorithms).to.eql([aead.eax, aead.ocb]); } const hash = openpgp.enums.hash; expect(key.users[0].selfCertifications[0].preferredHashAlgorithms).to.eql([hash.sha256, hash.sha512]); @@ -2097,7 +2097,7 @@ function versionSpecificTests() { let expectedFeatures; if (openpgp.config.v5Keys) { expectedFeatures = [7]; // v5 + aead + mdc - } else if (openpgp.config.aeadProtect) { + } else if (openpgp.config.AEADProtect) { expectedFeatures = [3]; // aead + mdc } else { expectedFeatures = [1]; // mdc @@ -2115,11 +2115,11 @@ function versionSpecificTests() { const preferredSymmetricAlgorithmVal = openpgp.config.preferredSymmetricAlgorithm; const preferredHashAlgorithmVal = openpgp.config.preferredHashAlgorithm; const preferredCompressionAlgorithmVal = openpgp.config.preferredCompressionAlgorithm; - const preferredAeadAlgorithmVal = openpgp.config.preferredAeadAlgorithm; + const preferredAEADAlgorithmVal = openpgp.config.preferredAEADAlgorithm; openpgp.config.preferredSymmetricAlgorithm = openpgp.enums.symmetric.aes192; openpgp.config.preferredHashAlgorithm = openpgp.enums.hash.sha224; openpgp.config.preferredCompressionAlgorithm = openpgp.enums.compression.zip; - openpgp.config.preferredAeadAlgorithm = openpgp.enums.aead.experimentalGcm; + openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.experimentalGcm; const testPref = function(key) { // key flags @@ -2130,9 +2130,9 @@ function versionSpecificTests() { expect(key.subKeys[0].bindingSignatures[0].keyFlags[0] & keyFlags.encryptStorage).to.equal(keyFlags.encryptStorage); const sym = openpgp.enums.symmetric; expect(key.users[0].selfCertifications[0].preferredSymmetricAlgorithms).to.eql([sym.aes192, sym.aes256, sym.aes128]); - if (openpgp.config.aeadProtect) { + if (openpgp.config.AEADProtect) { const aead = openpgp.enums.aead; - expect(key.users[0].selfCertifications[0].preferredAeadAlgorithms).to.eql([aead.experimentalGcm, aead.eax, aead.ocb]); + expect(key.users[0].selfCertifications[0].preferredAEADAlgorithms).to.eql([aead.experimentalGcm, aead.eax, aead.ocb]); } const hash = openpgp.enums.hash; expect(key.users[0].selfCertifications[0].preferredHashAlgorithms).to.eql([hash.sha224, hash.sha256, hash.sha512]); @@ -2142,7 +2142,7 @@ function versionSpecificTests() { let expectedFeatures; if (openpgp.config.v5Keys) { expectedFeatures = [7]; // v5 + aead + mdc - } else if (openpgp.config.aeadProtect) { + } else if (openpgp.config.AEADProtect) { expectedFeatures = [3]; // aead + mdc } else { expectedFeatures = [1]; // mdc @@ -2158,7 +2158,7 @@ function versionSpecificTests() { openpgp.config.preferredSymmetricAlgorithm = preferredSymmetricAlgorithmVal; openpgp.config.preferredHashAlgorithm = preferredHashAlgorithmVal; openpgp.config.preferredCompressionAlgorithm = preferredCompressionAlgorithmVal; - openpgp.config.preferredAeadAlgorithm = preferredAeadAlgorithmVal; + openpgp.config.preferredAEADAlgorithm = preferredAEADAlgorithmVal; } }); @@ -2304,8 +2304,8 @@ function versionSpecificTests() { it('Generate RSA key - two subkeys with default values', async function() { const rsaBits = 512; - const minRsaBits = openpgp.config.minRsaBits; - openpgp.config.minRsaBits = rsaBits; + const minRSABits = openpgp.config.minRSABits; + openpgp.config.minRSABits = rsaBits; const userId = { name: 'test', email: 'a@b.com' }; const opt = { type: 'rsa', rsaBits, userIds: [userId], passphrase: '123', subkeys:[{},{}] }; @@ -2318,7 +2318,7 @@ function versionSpecificTests() { expect(key.subKeys[0].getAlgorithmInfo().algorithm).to.equal('rsaEncryptSign'); expect(key.subKeys[1].getAlgorithmInfo().algorithm).to.equal('rsaEncryptSign'); } finally { - openpgp.config.minRsaBits = minRsaBits; + openpgp.config.minRSABits = minRSABits; } }); @@ -2359,8 +2359,8 @@ function versionSpecificTests() { it('Generate key - override main RSA key options for subkey', async function() { const rsaBits = 512; - const minRsaBits = openpgp.config.minRsaBits; - openpgp.config.minRsaBits = rsaBits; + const minRSABits = openpgp.config.minRSABits; + openpgp.config.minRSABits = rsaBits; const userId = { name: 'test', email: 'a@b.com' }; const opt = { type: 'rsa', rsaBits, userIds: [userId], passphrase: '123', subkeys:[{ type: 'ecc', curve: 'curve25519' }] }; @@ -2373,7 +2373,7 @@ function versionSpecificTests() { expect(key.getAlgorithmInfo().bits).to.equal(opt.rsaBits); expect(key.subKeys[0].getAlgorithmInfo().algorithm).to.equal('ecdh'); } finally { - openpgp.config.minRsaBits = minRsaBits; + openpgp.config.minRSABits = minRSABits; } }); @@ -2422,8 +2422,8 @@ function versionSpecificTests() { const privateKey = await openpgp.readKey({ armoredKey: priv_key_rsa }); await privateKey.decrypt('hello world'); - const { minRsaBits } = openpgp.config; - openpgp.config.minRsaBits = 1024; + const { minRSABits } = openpgp.config; + openpgp.config.minRSABits = 1024; try { publicKey = await publicKey.signPrimaryUser([privateKey]); const signatures = await publicKey.verifyPrimaryUser([privateKey]); @@ -2435,7 +2435,7 @@ function versionSpecificTests() { expect(signatures[1].keyid.toHex()).to.equal(privateSigningKey.getKeyId().toHex()); expect(signatures[1].valid).to.be.true; } finally { - openpgp.config.minRsaBits = minRsaBits; + openpgp.config.minRSABits = minRSABits; } }); @@ -2445,8 +2445,8 @@ function versionSpecificTests() { const wrongKey = await openpgp.readKey({ armoredKey: wrong_key }); await privateKey.decrypt('hello world'); - const { minRsaBits } = openpgp.config; - openpgp.config.minRsaBits = 1024; + const { minRSABits } = openpgp.config; + openpgp.config.minRSABits = 1024; try { publicKey = await publicKey.signPrimaryUser([privateKey]); const signatures = await publicKey.verifyPrimaryUser([wrongKey]); @@ -2458,7 +2458,7 @@ function versionSpecificTests() { expect(signatures[1].keyid.toHex()).to.equal(privateSigningKey.getKeyId().toHex()); expect(signatures[1].valid).to.be.null; } finally { - openpgp.config.minRsaBits = minRsaBits; + openpgp.config.minRSABits = minRSABits; } }); @@ -2467,8 +2467,8 @@ function versionSpecificTests() { const privateKey = await openpgp.readKey({ armoredKey: priv_key_rsa }); await privateKey.decrypt('hello world'); - const { minRsaBits } = openpgp.config; - openpgp.config.minRsaBits = 1024; + const { minRSABits } = openpgp.config; + openpgp.config.minRSABits = 1024; try { publicKey = await publicKey.signAllUsers([privateKey]); const signatures = await publicKey.verifyAllUsers([privateKey]); @@ -2488,7 +2488,7 @@ function versionSpecificTests() { expect(signatures[3].keyid.toHex()).to.equal(privateSigningKey.getKeyId().toHex()); expect(signatures[3].valid).to.be.true; } finally { - openpgp.config.minRsaBits = minRsaBits; + openpgp.config.minRSABits = minRSABits; } }); @@ -2498,8 +2498,8 @@ function versionSpecificTests() { const wrongKey = await openpgp.readKey({ armoredKey: wrong_key }); await privateKey.decrypt('hello world'); - const { minRsaBits } = openpgp.config; - openpgp.config.minRsaBits = 1024; + const { minRSABits } = openpgp.config; + openpgp.config.minRSABits = 1024; try { publicKey = await publicKey.signAllUsers([privateKey]); const signatures = await publicKey.verifyAllUsers([wrongKey]); @@ -2519,7 +2519,7 @@ function versionSpecificTests() { expect(signatures[3].keyid.toHex()).to.equal(privateSigningKey.getKeyId().toHex()); expect(signatures[3].valid).to.be.null; } finally { - openpgp.config.minRsaBits = minRsaBits; + openpgp.config.minRSABits = minRSABits; } }); @@ -2691,7 +2691,7 @@ function versionSpecificTests() { module.exports = () => describe('Key', function() { let v5KeysVal; - let aeadProtectVal; + let AEADProtectVal; tryTests('V4', versionSpecificTests, { if: !openpgp.config.ci, @@ -2708,13 +2708,13 @@ module.exports = () => describe('Key', function() { if: !openpgp.config.ci, beforeEach: function() { v5KeysVal = openpgp.config.v5Keys; - aeadProtectVal = openpgp.config.aeadProtect; + AEADProtectVal = openpgp.config.AEADProtect; openpgp.config.v5Keys = true; - openpgp.config.aeadProtect = true; + openpgp.config.AEADProtect = true; }, afterEach: function() { openpgp.config.v5Keys = v5KeysVal; - openpgp.config.aeadProtect = aeadProtectVal; + openpgp.config.AEADProtect = AEADProtectVal; } }); @@ -3011,7 +3011,7 @@ module.exports = () => describe('Key', function() { expect(key.primaryKey.isDummy()).to.be.false; key.primaryKey.makeDummy(); expect(key.primaryKey.isDummy()).to.be.true; - await expect(openpgp.sign({ message: openpgp.Message.fromText('test'), privateKeys: [key], config: { minRsaBits: 1024 } })).to.be.fulfilled; + await expect(openpgp.sign({ message: openpgp.Message.fromText('test'), privateKeys: [key], config: { minRSABits: 1024 } })).to.be.fulfilled; }); it('makeDummy() - should work for encrypted keys', async function() { @@ -3313,9 +3313,9 @@ module.exports = () => describe('Key', function() { const [key1] = await openpgp.readKeys({ armoredKeys: twoKeys }); const primaryUser = await key1.getPrimaryUser(); primaryUser.selfCertification.features = [7]; // Monkey-patch AEAD feature flag - primaryUser.selfCertification.preferredAeadAlgorithms = [2,1]; + primaryUser.selfCertification.preferredAEADAlgorithms = [2,1]; const prefAlgo = await key.getPreferredAlgo('aead', [key1], undefined, undefined, { - ...openpgp.config, preferredAeadAlgorithm: openpgp.enums.aead.ocb + ...openpgp.config, preferredAEADAlgorithm: openpgp.enums.aead.ocb }); expect(prefAlgo).to.equal(openpgp.enums.aead.ocb); const supported = await key.isAeadSupported([key1]); @@ -3328,7 +3328,7 @@ module.exports = () => describe('Key', function() { const key2 = keys[1]; const primaryUser = await key1.getPrimaryUser(); primaryUser.selfCertification.features = [7]; // Monkey-patch AEAD feature flag - primaryUser.selfCertification.preferredAeadAlgorithms = [2,1]; + primaryUser.selfCertification.preferredAEADAlgorithms = [2,1]; const primaryUser2 = await key2.getPrimaryUser(); primaryUser2.selfCertification.features = [7]; // Monkey-patch AEAD feature flag const prefAlgo = await key.getPreferredAlgo('aead', [key1, key2]); @@ -3343,7 +3343,7 @@ module.exports = () => describe('Key', function() { const key2 = keys[1]; const primaryUser = await key1.getPrimaryUser(); primaryUser.selfCertification.features = [7]; // Monkey-patch AEAD feature flag - primaryUser.selfCertification.preferredAeadAlgorithms = [2,1]; + primaryUser.selfCertification.preferredAEADAlgorithms = [2,1]; const prefAlgo = await key.getPreferredAlgo('aead', [key1, key2]); expect(prefAlgo).to.equal(openpgp.enums.aead.eax); const supported = await key.isAeadSupported([key1, key2]); @@ -3416,7 +3416,7 @@ VYGdb3eNlV8CfoEC publicKey.users[1].selfCertifications[0].preferredSymmetricAlgorithms = [openpgp.enums.symmetric.aes128]; const sessionKey = await openpgp.generateSessionKey({ publicKeys: publicKey, toUserIds: { name: 'Test User', email: 'b@c.com' } }); expect(sessionKey.algorithm).to.equal('aes128'); - const config = { minRsaBits: 1024 }; + const config = { minRSABits: 1024 }; await openpgp.encrypt({ message: openpgp.Message.fromText('hello'), publicKeys: publicKey, privateKeys: privateKey, toUserIds: { name: 'Test User', email: 'b@c.com' }, armor: false, config }); @@ -3446,7 +3446,7 @@ VYGdb3eNlV8CfoEC privateKey.users[0].userId = openpgp.UserIDPacket.fromObject({ name: 'Test User', email: 'b@c.com' }); // Set second user to prefer aes128. We will select this user. privateKey.users[1].selfCertifications[0].preferredHashAlgorithms = [openpgp.enums.hash.sha512]; - const config = { minRsaBits: 1024 }; + const config = { minRSABits: 1024 }; const signed = await openpgp.sign({ message: openpgp.Message.fromText('hello'), privateKeys: privateKey, fromUserIds: { name: 'Test McTestington', email: 'test@example.com' }, armor: false, config }); @@ -3464,7 +3464,7 @@ VYGdb3eNlV8CfoEC it('Find a valid subkey binding signature among many invalid ones', async function() { const key = await openpgp.readKey({ armoredKey: valid_binding_sig_among_many_expired_sigs_pub }); - expect(await key.getEncryptionKey(undefined, undefined, undefined, { ...openpgp.config, minRsaBits: 1024 })).to.not.be.null; + expect(await key.getEncryptionKey(undefined, undefined, undefined, { ...openpgp.config, minRSABits: 1024 })).to.not.be.null; }); it('Selects the most recent subkey binding signature', async function() { @@ -3548,13 +3548,13 @@ VYGdb3eNlV8CfoEC describe('addSubkey functionality testing', function() { const rsaBits = 1024; const rsaOpt = { type: 'rsa' }; - let minRsaBits; + let minRSABits; beforeEach(function() { - minRsaBits = openpgp.config.minRsaBits; - openpgp.config.minRsaBits = rsaBits; + minRSABits = openpgp.config.minRSABits; + openpgp.config.minRSABits = rsaBits; }); afterEach(function() { - openpgp.config.minRsaBits = minRsaBits; + openpgp.config.minRSABits = minRSABits; }); it('create and add a new rsa subkey to stored rsa key', async function() { @@ -3600,7 +3600,7 @@ VYGdb3eNlV8CfoEC const total = key.subKeys.length; const newKey = await key.addSubkey(); expect(newKey.subKeys[total].getAlgorithmInfo().algorithm).to.equal('rsaEncryptSign'); - expect(newKey.subKeys[total].getAlgorithmInfo().bits).to.equal(Math.max(key.getAlgorithmInfo().bits, openpgp.config.minRsaBits)); + expect(newKey.subKeys[total].getAlgorithmInfo().bits).to.equal(Math.max(key.getAlgorithmInfo().bits, openpgp.config.minRSABits)); }); it('should throw when trying to encrypt a subkey separately from key', async function() { diff --git a/test/general/openpgp.js b/test/general/openpgp.js index b36fabe24..f261dbcb3 100644 --- a/test/general/openpgp.js +++ b/test/general/openpgp.js @@ -823,11 +823,11 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { let publicKeyNoAEAD; let privateKeyMismatchingParams; - let aeadProtectVal; - let preferredAeadAlgorithmVal; - let aeadChunkSizeByteVal; + let AEADProtectVal; + let preferredAEADAlgorithmVal; + let AEADChunkSizeByteVal; let v5KeysVal; - let minRsaBitsVal; + let minRSABitsVal; beforeEach(async function() { publicKey = await openpgp.readKey({ armoredKey: pub_key }); @@ -841,21 +841,21 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { publicKey_1337 = privateKey_1337.toPublic(); privateKeyMismatchingParams = await openpgp.readKey({ armoredKey: mismatchingKeyParams }); - aeadProtectVal = openpgp.config.aeadProtect; - preferredAeadAlgorithmVal = openpgp.config.preferredAeadAlgorithm; - aeadChunkSizeByteVal = openpgp.config.aeadChunkSizeByte; + AEADProtectVal = openpgp.config.AEADProtect; + preferredAEADAlgorithmVal = openpgp.config.preferredAEADAlgorithm; + AEADChunkSizeByteVal = openpgp.config.AEADChunkSizeByte; v5KeysVal = openpgp.config.v5Keys; - minRsaBitsVal = openpgp.config.minRsaBits; + minRSABitsVal = openpgp.config.minRSABits; - openpgp.config.minRsaBits = 512; + openpgp.config.minRSABits = 512; }); afterEach(function() { - openpgp.config.aeadProtect = aeadProtectVal; - openpgp.config.preferredAeadAlgorithm = preferredAeadAlgorithmVal; - openpgp.config.aeadChunkSizeByte = aeadChunkSizeByteVal; + openpgp.config.AEADProtect = AEADProtectVal; + openpgp.config.preferredAEADAlgorithm = preferredAEADAlgorithmVal; + openpgp.config.AEADChunkSizeByte = AEADChunkSizeByteVal; openpgp.config.v5Keys = v5KeysVal; - openpgp.config.minRsaBits = minRsaBitsVal; + openpgp.config.minRSABits = minRSABitsVal; }); it('Configuration', async function() { @@ -1033,15 +1033,15 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { tryTests('CFB mode (asm.js)', tests, { if: true, beforeEach: function() { - openpgp.config.aeadProtect = false; + openpgp.config.AEADProtect = false; } }); tryTests('GCM mode (V5 keys)', tests, { if: true, beforeEach: function() { - openpgp.config.aeadProtect = true; - openpgp.config.preferredAeadAlgorithm = openpgp.enums.aead.experimentalGcm; + openpgp.config.AEADProtect = true; + openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.experimentalGcm; openpgp.config.v5Keys = true; // Monkey-patch AEAD feature flag @@ -1054,8 +1054,8 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { tryTests('EAX mode (small chunk size)', tests, { if: true, beforeEach: function() { - openpgp.config.aeadProtect = true; - openpgp.config.aeadChunkSizeByte = 0; + openpgp.config.AEADProtect = true; + openpgp.config.AEADChunkSizeByte = 0; // Monkey-patch AEAD feature flag publicKey.users[0].selfCertifications[0].features = [7]; @@ -1067,8 +1067,8 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { tryTests('OCB mode', tests, { if: !openpgp.config.ci, beforeEach: function() { - openpgp.config.aeadProtect = true; - openpgp.config.preferredAeadAlgorithm = openpgp.enums.aead.ocb; + openpgp.config.AEADProtect = true; + openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.ocb; // Monkey-patch AEAD feature flag publicKey.users[0].selfCertifications[0].features = [7]; @@ -1410,7 +1410,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }; return openpgp.encrypt(encOpt).then(async function (encrypted) { decOpt.message = await openpgp.readMessage({ armoredMessage: encrypted }); - expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(openpgp.config.aeadProtect); + expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(openpgp.config.AEADProtect); return openpgp.decrypt(decOpt); }).then(async function (decrypted) { expect(decrypted.data).to.equal(plaintext); @@ -1464,7 +1464,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }; return openpgp.encrypt(encOpt).then(async function (encrypted) { decOpt.message = await openpgp.readMessage({ armoredMessage: encrypted }); - expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(openpgp.config.aeadProtect); + expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(openpgp.config.AEADProtect); return openpgp.decrypt(decOpt); }).then(async function (decrypted) { expect(decrypted.data).to.equal(plaintext); @@ -1493,7 +1493,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { detached: true }); const message = await openpgp.readMessage({ armoredMessage: encrypted }); - expect(!!message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(openpgp.config.aeadProtect); + expect(!!message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(openpgp.config.AEADProtect); const decrypted = await openpgp.decrypt({ message, signature: await openpgp.readSignature({ armoredSignature: signed }), @@ -1813,7 +1813,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(e.message).to.match(/Ascii armor integrity check on message failed/); expect(stepReached).to.equal( j === 0 ? 0 : - (openpgp.config.aeadChunkSizeByte === 0 && (j === 2 || util.detectNode() || util.getHardwareConcurrency() < 8)) || (!openpgp.config.aeadProtect && openpgp.config.allowUnauthenticatedStream) ? 2 : + (openpgp.config.AEADChunkSizeByte === 0 && (j === 2 || util.detectNode() || util.getHardwareConcurrency() < 8)) || (!openpgp.config.AEADProtect && openpgp.config.allowUnauthenticatedStream) ? 2 : 1 ); return; diff --git a/test/general/packet.js b/test/general/packet.js index 167ce769a..41dbe808c 100644 --- a/test/general/packet.js +++ b/test/general/packet.js @@ -66,9 +66,9 @@ module.exports = () => describe("Packet", function() { '-----END PGP PRIVATE KEY BLOCK-----'; it('Symmetrically encrypted packet without integrity protection - allow decryption', async function() { - const aeadProtectVal = openpgp.config.aeadProtect; + const AEADProtectVal = openpgp.config.AEADProtect; const allowUnauthenticatedMessagesVal = openpgp.config.allowUnauthenticatedMessages; - openpgp.config.aeadProtect = false; + openpgp.config.AEADProtect = false; openpgp.config.allowUnauthenticatedMessages = true; const message = new openpgp.PacketList(); @@ -93,14 +93,14 @@ module.exports = () => describe("Packet", function() { expect(await stringify(msg2[0].packets[0].data)).to.equal(stringify(literal.data)); } finally { - openpgp.config.aeadProtect = aeadProtectVal; + openpgp.config.AEADProtect = AEADProtectVal; openpgp.config.allowUnauthenticatedMessages = allowUnauthenticatedMessagesVal; } }); it('Symmetrically encrypted packet without integrity protection - disallow decryption by default', async function() { - const aeadProtectVal = openpgp.config.aeadProtect; - openpgp.config.aeadProtect = false; + const AEADProtectVal = openpgp.config.AEADProtect; + openpgp.config.AEADProtect = false; try { const message = new openpgp.PacketList(); @@ -122,7 +122,7 @@ module.exports = () => describe("Packet", function() { await msg2.read(message.write(), { SymmetricallyEncryptedDataPacket: openpgp.SymmetricallyEncryptedDataPacket }); await expect(msg2[0].decrypt(algo, key, undefined, openpgp.config)).to.eventually.be.rejectedWith('Message is not authenticated.'); } finally { - openpgp.config.aeadProtect = aeadProtectVal; + openpgp.config.AEADProtect = AEADProtectVal; } }); @@ -149,8 +149,8 @@ module.exports = () => describe("Packet", function() { }); it('Sym. encrypted AEAD protected packet', function() { - const aeadProtectVal = openpgp.config.aeadProtect; - openpgp.config.aeadProtect = false; + const AEADProtectVal = openpgp.config.AEADProtect; + openpgp.config.AEADProtect = false; try { 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]); @@ -173,7 +173,7 @@ module.exports = () => describe("Packet", function() { expect(await openpgp.stream.readToEnd(msg2[0].packets[0].data)).to.deep.equal(literal.data); }); } finally { - openpgp.config.aeadProtect = aeadProtectVal; + openpgp.config.AEADProtect = AEADProtectVal; } }); @@ -220,7 +220,7 @@ module.exports = () => describe("Packet", function() { const msg2 = new openpgp.PacketList(); try { - await enc.encrypt(algo, key, undefined, { ...openpgp.config, aeadChunkSizeByte: 0 }); + await enc.encrypt(algo, key, undefined, { ...openpgp.config, AEADChunkSizeByte: 0 }); 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); @@ -265,7 +265,7 @@ module.exports = () => describe("Packet", function() { randomBytesStub.returns(iv); try { - await enc.encrypt(algo, key, undefined, { ...openpgp.config, aeadChunkSizeByte: 14 }); + await enc.encrypt(algo, key, undefined, { ...openpgp.config, AEADChunkSizeByte: 14 }); const data = msg.write(); expect(await openpgp.stream.readToEnd(openpgp.stream.clone(data))).to.deep.equal(packetBytes); await msg2.read(data, openpgp); @@ -436,8 +436,8 @@ module.exports = () => describe("Packet", function() { }); it('Sym. encrypted session key reading/writing (CFB)', async function() { - const aeadProtectVal = openpgp.config.aeadProtect; - openpgp.config.aeadProtect = false; + const AEADProtectVal = openpgp.config.AEADProtect; + openpgp.config.AEADProtect = false; try { const passphrase = 'hello'; @@ -470,13 +470,13 @@ module.exports = () => describe("Packet", function() { expect(await stringify(msg2[1].packets[0].data)).to.equal(stringify(literal.data)); } finally { - openpgp.config.aeadProtect = aeadProtectVal; + openpgp.config.AEADProtect = AEADProtectVal; } }); it('Sym. encrypted session key reading/writing (AEAD)', async function() { - const aeadProtectVal = openpgp.config.aeadProtect; - openpgp.config.aeadProtect = true; + const AEADProtectVal = openpgp.config.AEADProtect; + openpgp.config.AEADProtect = true; try { const passphrase = 'hello'; @@ -509,7 +509,7 @@ module.exports = () => describe("Packet", function() { expect(await stringify(msg2[1].packets[0].data)).to.equal(stringify(literal.data)); } finally { - openpgp.config.aeadProtect = aeadProtectVal; + openpgp.config.AEADProtect = AEADProtectVal; } }); @@ -519,12 +519,12 @@ module.exports = () => describe("Packet", function() { const nodeCrypto = util.getNodeCrypto(); if (!nodeCrypto) return; - const aeadProtectVal = openpgp.config.aeadProtect; - const aeadChunkSizeByteVal = openpgp.config.aeadChunkSizeByte; - const s2kIterationCountByteVal = openpgp.config.s2kIterationCountByte; - openpgp.config.aeadProtect = true; - openpgp.config.aeadChunkSizeByte = 14; - openpgp.config.s2kIterationCountByte = 0x90; + const AEADProtectVal = openpgp.config.AEADProtect; + const AEADChunkSizeByteVal = openpgp.config.AEADChunkSizeByte; + const S2KIterationCountByteVal = openpgp.config.S2KIterationCountByte; + openpgp.config.AEADProtect = true; + openpgp.config.AEADChunkSizeByte = 14; + openpgp.config.S2KIterationCountByte = 0x90; const salt = util.hexToUint8Array(`cd5a9f70fbe0bc65`); const sessionKey = util.hexToUint8Array(`86 f1 ef b8 69 52 32 9f 24 ac d3 bf d0 e5 34 6d`.replace(/\s+/g, '')); @@ -584,9 +584,9 @@ module.exports = () => describe("Packet", function() { expect(await stringify(msg2[1].packets[0].data)).to.equal(stringify(literal.data)); } finally { - openpgp.config.aeadProtect = aeadProtectVal; - openpgp.config.aeadChunkSizeByte = aeadChunkSizeByteVal; - openpgp.config.s2kIterationCountByte = s2kIterationCountByteVal; + openpgp.config.AEADProtect = AEADProtectVal; + openpgp.config.AEADChunkSizeByte = AEADChunkSizeByteVal; + openpgp.config.S2KIterationCountByte = S2KIterationCountByteVal; randomBytesStub.restore(); } }); @@ -597,12 +597,12 @@ module.exports = () => describe("Packet", function() { const nodeCrypto = util.getNodeCrypto(); if (!nodeCrypto) return; - const aeadProtectVal = openpgp.config.aeadProtect; - const aeadChunkSizeByteVal = openpgp.config.aeadChunkSizeByte; - const s2kIterationCountByteVal = openpgp.config.s2kIterationCountByte; - openpgp.config.aeadProtect = true; - openpgp.config.aeadChunkSizeByte = 14; - openpgp.config.s2kIterationCountByte = 0x90; + const AEADProtectVal = openpgp.config.AEADProtect; + const AEADChunkSizeByteVal = openpgp.config.AEADChunkSizeByte; + const S2KIterationCountByteVal = openpgp.config.S2KIterationCountByte; + openpgp.config.AEADProtect = true; + openpgp.config.AEADChunkSizeByte = 14; + openpgp.config.S2KIterationCountByte = 0x90; const salt = util.hexToUint8Array(`9f0b7da3e5ea6477`); const sessionKey = util.hexToUint8Array(`d1 f0 1b a3 0e 13 0a a7 d2 58 2c 16 e0 50 ae 44`.replace(/\s+/g, '')); @@ -663,9 +663,9 @@ module.exports = () => describe("Packet", function() { expect(await stringify(msg2[1].packets[0].data)).to.equal(stringify(literal.data)); } finally { - openpgp.config.aeadProtect = aeadProtectVal; - openpgp.config.aeadChunkSizeByte = aeadChunkSizeByteVal; - openpgp.config.s2kIterationCountByte = s2kIterationCountByteVal; + openpgp.config.AEADProtect = AEADProtectVal; + openpgp.config.AEADChunkSizeByte = AEADChunkSizeByteVal; + openpgp.config.S2KIterationCountByte = S2KIterationCountByteVal; randomBytesStub.restore(); } }); @@ -843,7 +843,7 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ secretKeyPacket.publicParams = publicParams; secretKeyPacket.algorithm = "rsaSign"; secretKeyPacket.isEncrypted = false; - await secretKeyPacket.encrypt('hello', { ...openpgp.config, aeadProtect: true }); + await secretKeyPacket.encrypt('hello', { ...openpgp.config, AEADProtect: true }); expect(secretKeyPacket.s2k_usage).to.equal(253); const raw = new openpgp.PacketList(); @@ -865,7 +865,7 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ secretKeyPacket.publicParams = publicParams; secretKeyPacket.algorithm = "rsaSign"; secretKeyPacket.isEncrypted = false; - await secretKeyPacket.encrypt('hello', { ...openpgp.config, aeadProtect: false }); + await secretKeyPacket.encrypt('hello', { ...openpgp.config, AEADProtect: false }); expect(secretKeyPacket.s2k_usage).to.equal(254); const raw = new openpgp.PacketList(); diff --git a/test/general/signature.js b/test/general/signature.js index 7fbf34495..c96c3cdfa 100644 --- a/test/general/signature.js +++ b/test/general/signature.js @@ -918,10 +918,10 @@ hUhMKMuiM3pRwdIyDOItkUWQmjEEw7/XmhgInkXsCw== }); it('Verify V4 signature. Hash: SHA1. PK: RSA. Signature Type: 0x00 (binary document)', async function() { - const { rejectMessageHashAlgorithms, minRsaBits } = openpgp.config; + const { rejectMessageHashAlgorithms, minRSABits } = openpgp.config; Object.assign(openpgp.config, { rejectMessageHashAlgorithms: new Set([openpgp.enums.hash.md5, openpgp.enums.hash.ripemd]), - minRsaBits: 1024 + minRSABits: 1024 }); try { const signedArmor = @@ -945,7 +945,7 @@ hUhMKMuiM3pRwdIyDOItkUWQmjEEw7/XmhgInkXsCw== expect(await verified[0].verified).to.be.true; expect((await verified[0].signature).packets.length).to.equal(1); } finally { - Object.assign(openpgp.config, { rejectMessageHashAlgorithms, minRsaBits }); + Object.assign(openpgp.config, { rejectMessageHashAlgorithms, minRSABits }); } }); @@ -973,7 +973,7 @@ hUhMKMuiM3pRwdIyDOItkUWQmjEEw7/XmhgInkXsCw== await Promise.all(esMsg.getEncryptionKeyIds().map(keyId => privKey.decrypt('hello world', keyId))); - return openpgp.decrypt({ privateKeys: privKey, publicKeys:[pubKey], message:esMsg, config: { minRsaBits: 1024 } }).then(function(decrypted) { + return openpgp.decrypt({ privateKeys: privKey, publicKeys:[pubKey], message:esMsg, config: { minRSABits: 1024 } }).then(function(decrypted) { expect(decrypted.data).to.exist; expect(decrypted.data).to.equal(plaintext); expect(decrypted.signatures).to.have.length(1); @@ -1009,7 +1009,7 @@ hUhMKMuiM3pRwdIyDOItkUWQmjEEw7/XmhgInkXsCw== expect(pubKey2.getKeys(keyids[1])).to.not.be.empty; expect(pubKey3.getKeys(keyids[0])).to.not.be.empty; - const { data, signatures } = await openpgp.verify({ message: sMsg, publicKeys: [pubKey2, pubKey3], config: { minRsaBits: 1024 } }); + const { data, signatures } = await openpgp.verify({ message: sMsg, publicKeys: [pubKey2, pubKey3], config: { minRSABits: 1024 } }); expect(data).to.equal(plaintext); expect(signatures).to.exist; expect(signatures).to.have.length(2); @@ -1022,7 +1022,7 @@ hUhMKMuiM3pRwdIyDOItkUWQmjEEw7/XmhgInkXsCw== it('Verify fails with signed message with critical notations', async function() { const message = await openpgp.readMessage({ armoredMessage: signature_with_critical_notation }); const key = await openpgp.readKey({ armoredKey: pub_key_arm2 }); - const { signatures: [sig] } = await openpgp.verify({ message, publicKeys: key, config: { minRsaBits: 1024 } }); + const { signatures: [sig] } = await openpgp.verify({ message, publicKeys: key, config: { minRSABits: 1024 } }); expect(sig.valid).to.be.false; expect(sig.error).to.match(/Unknown critical notation: test@example.com/); }); @@ -1031,7 +1031,7 @@ hUhMKMuiM3pRwdIyDOItkUWQmjEEw7/XmhgInkXsCw== const message = await openpgp.readMessage({ armoredMessage: signature_with_critical_notation }); const key = await openpgp.readKey({ armoredKey: pub_key_arm2 }); - const config = { knownNotations: ['test@example.com'], minRsaBits: 1024 }; + const config = { knownNotations: ['test@example.com'], minRSABits: 1024 }; const { signatures: [sig] } = await openpgp.verify({ message, publicKeys: key, config }); expect(sig.valid).to.be.true; }); @@ -1070,7 +1070,7 @@ hUhMKMuiM3pRwdIyDOItkUWQmjEEw7/XmhgInkXsCw== expect(pubKey2.getKeys(keyids[0])).to.not.be.empty; expect(pubKey3.getKeys(keyids[1])).to.not.be.empty; - return openpgp.verify({ publicKeys:[pubKey2, pubKey3], message, config: { minRsaBits: 1024 } }).then(function(cleartextSig) { + return openpgp.verify({ publicKeys:[pubKey2, pubKey3], message, config: { minRSABits: 1024 } }).then(function(cleartextSig) { expect(cleartextSig).to.exist; expect(cleartextSig.data).to.equal(plaintext); expect(cleartextSig.signatures).to.have.length(2); @@ -1146,7 +1146,7 @@ zmuVOdNuWQqxT9Sqa84= const cleartextSig = await openpgp.verify({ publicKeys:[pubKey], message, - config: { minRsaBits: 1024, rejectMessageHashAlgorithms: new Set() } + config: { minRSABits: 1024, rejectMessageHashAlgorithms: new Set() } }); expect(cleartextSig).to.exist; expect(cleartextSig.data).to.equal(plaintext.replace(/[ \t]+$/mg, '')); @@ -1177,7 +1177,7 @@ yYDnCgA= const keyids = message.getSigningKeyIds(); expect(pubKey.getKeys(keyids[0])).to.not.be.empty; - return openpgp.verify({ publicKeys: [pubKey], message, config: { minRsaBits: 1024 } }).then(({ data, signatures }) => { + return openpgp.verify({ publicKeys: [pubKey], message, config: { minRSABits: 1024 } }).then(({ data, signatures }) => { expect(data).to.equal(plaintext); expect(signatures).to.have.length(1); expect(signatures[0].valid).to.equal(!openpgp.config.rejectMessageHashAlgorithms.has(openpgp.enums.hash.sha1)); @@ -1214,7 +1214,7 @@ yYDnCgA= const keyids = message.getSigningKeyIds(); expect(pubKey.getKeys(keyids[0])).to.not.be.empty; - return openpgp.verify({ publicKeys: [pubKey], message, config: { minRsaBits: 1024 } }).then(async function(cleartextSig) { + return openpgp.verify({ publicKeys: [pubKey], message, config: { minRSABits: 1024 } }).then(async function(cleartextSig) { expect(cleartextSig).to.exist; expect(await openpgp.stream.readToEnd(cleartextSig.data)).to.equal(plaintext); expect(cleartextSig.signatures).to.have.length(1); @@ -1246,7 +1246,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA const keyids = message.getSigningKeyIds(); expect(pubKey.getKeys(keyids[0])).to.not.be.empty; - return openpgp.verify({ publicKeys: [pubKey], message, config: { minRsaBits: 1024 } }).then(async ({ data, signatures }) => { + return openpgp.verify({ publicKeys: [pubKey], message, config: { minRSABits: 1024 } }).then(async ({ data, signatures }) => { expect(data).to.equal(plaintext); expect(signatures).to.have.length(0); }); @@ -1279,7 +1279,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA const keyids = message.getSigningKeyIds(); expect(pubKey.getKeys(keyids[0])).to.not.be.empty; - return openpgp.verify({ publicKeys: [pubKey], message, config: { minRsaBits: 1024 } }).then(async ({ data, signatures }) => { + return openpgp.verify({ publicKeys: [pubKey], message, config: { minRSABits: 1024 } }).then(async ({ data, signatures }) => { expect(await openpgp.stream.readToEnd(data)).to.equal(plaintext); expect(signatures).to.have.length(1); await expect(signatures[0].verified).to.be.rejectedWith('Corresponding signature packet missing'); @@ -1308,7 +1308,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA const privKey = await openpgp.readKey({ armoredKey: priv_key_arm2 }); await privKey.decrypt('hello world'); - const config = { minRsaBits: 1024 }; + const config = { minRSABits: 1024 }; return openpgp.sign({ privateKeys:[privKey], message: openpgp.CleartextMessage.fromText(plaintext), config }).then(async function(signed) { const message = await openpgp.readCleartextMessage({ cleartextMessage: signed }); @@ -1328,7 +1328,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA const privKey = await openpgp.readKey({ armoredKey: priv_key_arm2 }); await privKey.decrypt('hello world'); - const config = { minRsaBits: 1024 }; + const config = { minRSABits: 1024 }; return openpgp.sign({ privateKeys:[privKey], message: openpgp.CleartextMessage.fromText(plaintext), config }).then(async function(signed) { const message = await openpgp.readCleartextMessage({ cleartextMessage: signed }); @@ -1348,7 +1348,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA const privKey = await openpgp.readKey({ armoredKey: priv_key_arm2 }); await privKey.decrypt('hello world'); - const config = { minRsaBits: 1024 }; + const config = { minRSABits: 1024 }; return openpgp.sign({ privateKeys:[privKey], message: openpgp.CleartextMessage.fromText(plaintext), config }).then(async function(signed) { const message = await openpgp.readCleartextMessage({ cleartextMessage: signed }); @@ -1368,7 +1368,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA const privKey = await openpgp.readKey({ armoredKey: priv_key_arm2 }); await privKey.decrypt('hello world'); - const config = { minRsaBits: 1024 }; + const config = { minRSABits: 1024 }; return openpgp.sign({ privateKeys:[privKey], message: openpgp.Message.fromBinary(plaintext), config }).then(async function(signed) { const message = await openpgp.readMessage({ armoredMessage: signed }); @@ -1388,7 +1388,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA const privKey = await openpgp.readKey({ armoredKey: priv_key_arm2 }); await privKey.decrypt('hello world'); - const config = { minRsaBits: 1024 }; + const config = { minRSABits: 1024 }; return openpgp.sign({ privateKeys:[privKey], message: openpgp.Message.fromBinary(plaintext), armor:false, config }).then(async function(signed) { const message = await openpgp.readMessage({ binaryMessage: signed }); @@ -1408,7 +1408,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA const privKey = await openpgp.readKey({ armoredKey: priv_key_arm2 }); await privKey.decrypt('hello world'); - const config = { minRsaBits: 1024 }; + const config = { minRSABits: 1024 }; return openpgp.sign({ privateKeys:[privKey], message: openpgp.Message.fromText(plaintext), detached: true, config }).then(async function(armoredSignature) { const signature = await openpgp.readSignature({ armoredSignature }); return openpgp.verify({ publicKeys:[pubKey], message: openpgp.Message.fromBinary(util.encodeUtf8(plaintext)), signature, config }); @@ -1427,7 +1427,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA const privKey = await openpgp.readKey({ armoredKey: priv_key_arm2 }); await privKey.decrypt('hello world'); - const config = { minRsaBits: 1024 }; + const config = { minRSABits: 1024 }; return openpgp.sign({ privateKeys:[privKey], message:openpgp.Message.fromBinary(binaryPlaintext), detached: true, config }).then(async function(armoredSignature) { const signature = await openpgp.readSignature({ armoredSignature }); return openpgp.verify({ publicKeys:[pubKey], message: openpgp.Message.fromText(plaintext), signature, config }); @@ -1445,7 +1445,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA const privKey = await openpgp.readKey({ armoredKey: priv_key_arm2 }); await privKey.decrypt('hello world'); - const config = { minRsaBits: 1024 }; + const config = { minRSABits: 1024 }; return openpgp.sign({ privateKeys:[privKey], message: openpgp.Message.fromText(plaintext), detached: true, config }).then(async function(armoredSignature) { const signature = await openpgp.readSignature({ armoredSignature }); return openpgp.encrypt({ message: openpgp.Message.fromBinary(util.encodeUtf8(plaintext)), publicKeys: [pubKey], signature, config }); @@ -1567,7 +1567,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA const message = openpgp.Message.fromText(content); await message.appendSignature(detachedSig); - const { data, signatures } = await openpgp.verify({ publicKeys:[publicKey], message, config: { minRsaBits: 1024 } }); + const { data, signatures } = await openpgp.verify({ publicKeys:[publicKey], message, config: { minRSABits: 1024 } }); expect(data).to.equal(content); expect(signatures).to.have.length(1); expect(signatures[0].valid).to.be.true; @@ -1583,9 +1583,9 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA const opt = { rsaBits: 2048, userIds: { name:'test', email:'a@b.com' }, passphrase: null }; const { key: generatedKey } = await openpgp.generateKey(opt); - const armoredSignature = await openpgp.sign({ privateKeys:[generatedKey, privKey2], message, detached: true, config: { minRsaBits: 1024 } }); + const armoredSignature = await openpgp.sign({ privateKeys:[generatedKey, privKey2], message, detached: true, config: { minRSABits: 1024 } }); const signature = await openpgp.readSignature({ armoredSignature }); - const { data, signatures } = await openpgp.verify({ publicKeys:[generatedKey.toPublic(), pubKey2], message, signature, config: { minRsaBits: 1024 } }); + const { data, signatures } = await openpgp.verify({ publicKeys:[generatedKey.toPublic(), pubKey2], message, signature, config: { minRSABits: 1024 } }); expect(data).to.equal('hello'); expect(await signatures[0].verified).to.be.true; expect(await signatures[1].verified).to.be.true; @@ -1732,7 +1732,7 @@ oaBUyhCKt8tz6Q== message: await openpgp.readMessage({ armoredMessage: encrypted }), publicKeys: key, privateKeys: key, - config: { minRsaBits: 1024 } + config: { minRSABits: 1024 } }); expect(decrypted.signatures[0].valid).to.be.true; }); diff --git a/test/general/streaming.js b/test/general/streaming.js index 74bc29ab4..305e3b4d5 100644 --- a/test/general/streaming.js +++ b/test/general/streaming.js @@ -238,7 +238,7 @@ function tests() { const signed = await openpgp.sign({ message: openpgp.Message.fromBinary(data), privateKeys: privKey, - config: { minRsaBits: 1024 } + config: { minRSABits: 1024 } }); const reader = openpgp.stream.getReader(signed); expect(await reader.readBytes(1024)).to.match(/^-----BEGIN PGP MESSAGE-----\n/); @@ -249,8 +249,8 @@ function tests() { }); it('Encrypt and decrypt larger message roundtrip', async function() { - const aeadProtectValue = openpgp.config.aeadProtect; - openpgp.config.aeadProtect = false; + const AEADProtectValue = openpgp.config.AEADProtect; + openpgp.config.AEADProtect = false; const encrypted = await openpgp.encrypt({ message: openpgp.Message.fromBinary(data), passwords: ['test'], @@ -270,13 +270,13 @@ function tests() { expect(await reader.peekBytes(1024)).to.deep.equal(plaintext[0]); if (i <= 10) throw new Error('Data arrived early.'); expect(await reader.readToEnd()).to.deep.equal(util.concatUint8Array(plaintext)); - openpgp.config.aeadProtect = aeadProtectValue; + openpgp.config.AEADProtect = AEADProtectValue; }); it('Encrypt and decrypt larger message roundtrip (allowUnauthenticatedStream=true)', async function() { - const aeadProtectValue = openpgp.config.aeadProtect; + const AEADProtectValue = openpgp.config.AEADProtect; const allowUnauthenticatedStreamValue = openpgp.config.allowUnauthenticatedStream; - openpgp.config.aeadProtect = false; + openpgp.config.AEADProtect = false; openpgp.config.allowUnauthenticatedStream = true; try { const encrypted = await openpgp.encrypt({ @@ -300,7 +300,7 @@ function tests() { expect(await reader.readToEnd()).to.deep.equal(util.concatUint8Array(plaintext)); expect(decrypted.signatures).to.exist.and.have.length(0); } finally { - openpgp.config.aeadProtect = aeadProtectValue; + openpgp.config.AEADProtect = AEADProtectValue; openpgp.config.allowUnauthenticatedStream = allowUnauthenticatedStreamValue; } }); @@ -314,7 +314,7 @@ function tests() { publicKeys: pubKey, privateKeys: privKey, armor: false, - config: { minRsaBits: 1024 } + config: { minRSABits: 1024 } }); expect(openpgp.stream.isStream(encrypted)).to.equal(expectedType); @@ -400,8 +400,8 @@ function tests() { }); it('Detect MDC modifications (allowUnauthenticatedStream=true)', async function() { - const aeadProtectValue = openpgp.config.aeadProtect; - openpgp.config.aeadProtect = false; + const AEADProtectValue = openpgp.config.AEADProtect; + openpgp.config.AEADProtect = false; const allowUnauthenticatedStreamValue = openpgp.config.allowUnauthenticatedStream; openpgp.config.allowUnauthenticatedStream = true; try { @@ -433,7 +433,7 @@ function tests() { await expect(reader.readToEnd()).to.be.rejectedWith('Modification detected.'); expect(decrypted.signatures).to.exist.and.have.length(0); } finally { - openpgp.config.aeadProtect = aeadProtectValue; + openpgp.config.AEADProtect = AEADProtectValue; openpgp.config.allowUnauthenticatedStream = allowUnauthenticatedStreamValue; } }); @@ -446,7 +446,7 @@ function tests() { message: openpgp.Message.fromBinary(data), publicKeys: pubKey, privateKeys: privKey, - config: { minRsaBits: 1024 } + config: { minRSABits: 1024 } }); expect(openpgp.stream.isStream(encrypted)).to.equal(expectedType); @@ -484,7 +484,7 @@ function tests() { message: openpgp.Message.fromBinary(data), publicKeys: pubKey, privateKeys: privKey, - config: { minRsaBits: 1024 } + config: { minRSABits: 1024 } }); expect(openpgp.stream.isStream(encrypted)).to.equal(expectedType); @@ -518,7 +518,7 @@ function tests() { const signed = await openpgp.sign({ message: openpgp.Message.fromBinary(data), privateKeys: privKey, - config: { minRsaBits: 1024 } + config: { minRSABits: 1024 } }); expect(openpgp.stream.isStream(signed)).to.equal(expectedType); @@ -535,7 +535,7 @@ function tests() { message, streaming: expectedType, format: 'binary', - config: { minRsaBits: 1024 } + config: { minRSABits: 1024 } }); expect(openpgp.stream.isStream(verified.data)).to.equal(expectedType); const reader = openpgp.stream.getReader(verified.data); @@ -574,7 +574,7 @@ function tests() { const signed = await openpgp.sign({ message: openpgp.Message.fromBinary(data), privateKeys: privKey, - config: { minRsaBits: 1024 } + config: { minRSABits: 1024 } }); expect(openpgp.stream.isStream(signed)).to.equal(expectedType); @@ -583,7 +583,7 @@ function tests() { publicKeys: pubKey, message, format: 'binary', - config: { minRsaBits: 1024 } + config: { minRSABits: 1024 } }); expect(openpgp.stream.isStream(verified.data)).to.equal(expectedType); const reader = openpgp.stream.getReader(verified.data); @@ -614,7 +614,7 @@ function tests() { const signed = await openpgp.sign({ message: openpgp.Message.fromBinary(data), privateKeys: privKey, - config: { minRsaBits: 1024 } + config: { minRSABits: 1024 } }); expect(openpgp.stream.isStream(signed)).to.equal(expectedType); @@ -629,7 +629,7 @@ function tests() { const signed = await openpgp.sign({ message: openpgp.Message.fromBinary(data), privateKeys: privKey, - config: { minRsaBits: 1024 } + config: { minRSABits: 1024 } }); expect(openpgp.stream.isStream(signed)).to.equal(expectedType); const message = await openpgp.readMessage({ armoredMessage: signed }); @@ -660,7 +660,7 @@ function tests() { privateKeys: privKey, detached: true, streaming: expectedType, - config: { minRsaBits: 1024 } + config: { minRSABits: 1024 } }); expect(openpgp.stream.isStream(signed)).to.equal(expectedType); const armoredSignature = await openpgp.stream.readToEnd(signed); @@ -669,7 +669,7 @@ function tests() { signature, publicKeys: pubKey, message: openpgp.Message.fromText('hello world'), - config: { minRsaBits: 1024 } + config: { minRSABits: 1024 } }); expect(verified.data).to.equal('hello world'); expect(verified.signatures).to.exist.and.have.length(1); @@ -691,7 +691,7 @@ function tests() { detached: true, streaming: false, armor: false, - config: { minRsaBits: 1024 } + config: { minRSABits: 1024 } }); expect(openpgp.stream.isStream(signed)).to.be.false; const signature = await openpgp.readMessage({ binaryMessage: signed }); @@ -699,7 +699,7 @@ function tests() { signature, publicKeys: pubKey, message: openpgp.Message.fromText('hello world'), - config: { minRsaBits: 1024 } + config: { minRSABits: 1024 } }); expect(verified.data).to.equal('hello world'); expect(verified.signatures).to.exist.and.have.length(1); @@ -773,7 +773,7 @@ function tests() { message: openpgp.Message.fromBinary(data), privateKeys: privKey, detached: true, - config: { minRsaBits: 1024 } + config: { minRSABits: 1024 } }); expect(openpgp.stream.isStream(signed)).to.equal(expectedType); const reader = openpgp.stream.getReader(signed); @@ -788,7 +788,7 @@ function tests() { message: openpgp.Message.fromBinary(data), privateKeys: privKey, detached: true, - config: { minRsaBits: 1024 } + config: { minRSABits: 1024 } }); expect(openpgp.stream.isStream(signed)).to.equal(expectedType); const reader = openpgp.stream.getReader(signed); @@ -800,17 +800,17 @@ function tests() { }); describe('AEAD', function() { - let aeadProtectValue; - let aeadChunkSizeByteValue; + let AEADProtectValue; + let AEADChunkSizeByteValue; beforeEach(function() { - aeadProtectValue = openpgp.config.aeadProtect; - aeadChunkSizeByteValue = openpgp.config.aeadChunkSizeByte; - openpgp.config.aeadProtect = true; - openpgp.config.aeadChunkSizeByte = 4; + AEADProtectValue = openpgp.config.AEADProtect; + AEADChunkSizeByteValue = openpgp.config.AEADChunkSizeByte; + openpgp.config.AEADProtect = true; + openpgp.config.AEADChunkSizeByte = 4; }); afterEach(function() { - openpgp.config.aeadProtect = aeadProtectValue; - openpgp.config.aeadChunkSizeByte = aeadChunkSizeByteValue; + openpgp.config.AEADProtect = AEADProtectValue; + openpgp.config.AEADChunkSizeByte = AEADChunkSizeByteValue; }); @@ -836,7 +836,7 @@ function tests() { }); it('Encrypt and decrypt larger text message roundtrip (AEAD)', async function() { - openpgp.config.aeadChunkSizeByte = 0; + openpgp.config.AEADChunkSizeByte = 0; const plaintext = []; let i = 0; diff --git a/test/unittests.js b/test/unittests.js index 756612684..65ad0a6d7 100644 --- a/test/unittests.js +++ b/test/unittests.js @@ -29,7 +29,7 @@ describe('Unit Tests', function () { if (typeof window !== 'undefined') { - openpgp.config.s2kIterationCountByte = 0; + openpgp.config.S2KIterationCountByte = 0; window.location.search.substr(1).split('&').forEach(param => { const [key, value] = param.split('='); From f08ae48646789db3e6b38fcd7b6a036fb75ca8a2 Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Thu, 18 Mar 2021 20:40:29 +0100 Subject: [PATCH 02/18] uniform keyID casing --- README.md | 6 +- openpgp.d.ts | 48 +++---- src/cleartext.js | 20 +-- src/key/helper.js | 12 +- src/key/key.js | 120 ++++++++--------- src/key/subkey.js | 6 +- src/key/user.js | 12 +- src/message.js | 96 ++++++------- src/openpgp.js | 30 ++--- src/packet/one_pass_signature.js | 12 +- src/packet/public_key.js | 24 ++-- .../public_key_encrypted_session_key.js | 8 +- src/packet/signature.js | 16 +-- src/type/keyid.js | 28 ++-- test/general/brainpool.js | 4 +- test/general/ecc_secp256k1.js | 4 +- test/general/key.js | 74 +++++----- test/general/openpgp.js | 126 +++++++++--------- test/general/packet.js | 4 +- test/general/signature.js | 38 +++--- test/general/x25519.js | 4 +- test/security/subkey_trust.js | 2 +- 22 files changed, 347 insertions(+), 347 deletions(-) diff --git a/README.md b/README.md index 178f029fa..f62600914 100644 --- a/README.md +++ b/README.md @@ -473,7 +473,7 @@ Using the private key: }); const { valid } = verified.signatures[0]; if (valid) { - console.log('signed by key id ' + verified.signatures[0].keyid.toHex()); + console.log('signed by key id ' + verified.signatures[0].keyID.toHex()); } else { throw new Error('signature could not be verified'); } @@ -515,7 +515,7 @@ Using the private key: }); const { valid } = verified.signatures[0]; if (valid) { - console.log('signed by key id ' + verified.signatures[0].keyid.toHex()); + console.log('signed by key id ' + verified.signatures[0].keyID.toHex()); } else { throw new Error('signature could not be verified'); } @@ -563,7 +563,7 @@ Using the private key: const { valid } = verified.signatures[0]; if (valid) { - console.log('signed by key id ' + verified.signatures[0].keyid.toHex()); + console.log('signed by key id ' + verified.signatures[0].keyID.toHex()); } else { throw new Error('signature could not be verified'); } diff --git a/openpgp.d.ts b/openpgp.d.ts index 83e7ec4f9..7aeeba3bb 100644 --- a/openpgp.d.ts +++ b/openpgp.d.ts @@ -28,10 +28,10 @@ export class Key { private keyPacket: PublicKeyPacket | SecretKeyPacket; public write(): Uint8Array; public armor(config?: Config): string; - public decrypt(passphrase: string | string[], keyId?: Keyid, config?: Config): Promise; // throws on error - public encrypt(passphrase: string | string[], keyId?: Keyid, config?: Config): Promise; // throws on error - public getExpirationTime(capability?: 'encrypt' | 'encrypt_sign' | 'sign', keyId?: Keyid, userId?: UserID, config?: Config): Promise; // Returns null if `capabilities` is passed and the key does not have the specified capabilities or is revoked or invalid. - public getKeyIds(): Keyid[]; + public decrypt(passphrase: string | string[], keyID?: KeyID, config?: Config): Promise; // throws on error + public encrypt(passphrase: string | string[], keyID?: KeyID, config?: Config): Promise; // throws on error + public getExpirationTime(capability?: 'encrypt' | 'encrypt_sign' | 'sign', keyID?: KeyID, userId?: UserID, config?: Config): Promise; // Returns null if `capabilities` is passed and the key does not have the specified capabilities or is revoked or invalid. + public getKeyIDs(): KeyID[]; public getPrimaryUser(date?: Date, userId?: UserID, config?: Config): Promise; // throws on error public getUserIds(): string[]; public isPrivate(): boolean; @@ -41,20 +41,20 @@ export class Key { public signPrimaryUser(privateKeys: Key[], date?: Date, userId?: UserID, config?: Config): Promise public signAllUsers(privateKeys: Key[], config?: Config): Promise public verifyPrimaryKey(date?: Date, userId?: UserID, config?: Config): Promise; // throws on error - public verifyPrimaryUser(publicKeys: Key[], date?: Date, userIds?: UserID, config?: Config): Promise<{ keyid: Keyid, valid: boolean | null }[]>; - public verifyAllUsers(publicKeys: Key[], config?: Config): Promise<{ userid: string, keyid: Keyid, valid: boolean | null }[]>; + public verifyPrimaryUser(publicKeys: Key[], date?: Date, userIds?: UserID, config?: Config): Promise<{ keyID: KeyID, valid: boolean | null }[]>; + public verifyAllUsers(publicKeys: Key[], config?: Config): Promise<{ userid: string, keyID: KeyID, valid: boolean | null }[]>; public isRevoked(signature: SignaturePacket, key?: AnyKeyPacket, date?: Date, config?: Config): Promise; public revoke(reason: { flag?: enums.reasonForRevocation; string?: string; }, date?: Date, config?: Config): Promise; public getRevocationCertificate(date?: Date, config?: Config): Promise | string | undefined>; - public getEncryptionKey(keyid?: Keyid, date?: Date | null, userId?: UserID, config?: Config): Promise; - public getSigningKey(keyid?: Keyid, date?: Date | null, userId?: UserID, config?: Config): Promise; - public getKeys(keyId?: Keyid): (Key | SubKey)[]; - public getSubkeys(keyId?: Keyid): SubKey[]; + public getEncryptionKey(keyID?: KeyID, date?: Date | null, userId?: UserID, config?: Config): Promise; + public getSigningKey(keyID?: KeyID, date?: Date | null, userId?: UserID, config?: Config): Promise; + public getKeys(keyID?: KeyID): (Key | SubKey)[]; + public getSubkeys(keyID?: KeyID): SubKey[]; public isDecrypted(): boolean; public getFingerprint(): string; public getCreationTime(): Date; public getAlgorithmInfo(): AlgorithmInfo; - public getKeyId(): Keyid; + public getKeyID(): KeyID; public addSubkey(options: SubKeyOptions): Promise; } @@ -68,7 +68,7 @@ export class SubKey { public getFingerprint(): string; public getCreationTime(): Date; public getAlgorithmInfo(): AlgorithmInfo; - public getKeyId(): Keyid; + public getKeyID(): KeyID; } export interface User { @@ -103,7 +103,7 @@ export class Signature { } interface VerificationResult { - keyid: Keyid; + keyID: KeyID; verified: Promise; signature: Promise; } @@ -121,7 +121,7 @@ export class CleartextMessage { /** Returns the key IDs of the keys that signed the cleartext message */ - getSigningKeyIds(): Keyid[]; + getSigningKeyIDs(): KeyID[]; /** Get cleartext */ @@ -131,7 +131,7 @@ export class CleartextMessage { * * @param privateKeys private keys with decrypted secret key data for signing */ - sign(privateKeys: Key[], signature?: Signature, signingKeyIds?: Keyid[], date?: Date, userIds?: UserID[], config?: Config): void; + sign(privateKeys: Key[], signature?: Signature, signingKeyIDs?: KeyID[], date?: Date, userIds?: UserID[], config?: Config): void; /** Verify signatures of cleartext signed message * @param keys array of keys to verify signatures @@ -262,11 +262,11 @@ export class Message> { /** Encrypt the message @param keys array of keys, used to encrypt the message */ - public encrypt(keys?: Key[], passwords?: string[], sessionKeys?: SessionKey[], wildcard?: boolean, encryptionKeyIds?: Keyid[], date?: Date, userIds?: UserID[], streaming?: boolean, config?: Config): Promise>>; + public encrypt(keys?: Key[], passwords?: string[], sessionKeys?: SessionKey[], wildcard?: boolean, encryptionKeyIDs?: KeyID[], date?: Date, userIds?: UserID[], streaming?: boolean, config?: Config): Promise>>; /** Returns the key IDs of the keys to which the session key is encrypted */ - public getEncryptionKeyIds(): Keyid[]; + public getEncryptionKeyIDs(): KeyID[]; /** Get literal data that is the body of the message */ @@ -274,7 +274,7 @@ export class Message> { /** Returns the key IDs of the keys that signed the message */ - public getSigningKeyIds(): Keyid[]; + public getSigningKeyIDs(): KeyID[]; /** Get literal data as text */ @@ -285,7 +285,7 @@ export class Message> { /** Sign the message (the literal data packet of the message) @param privateKey private keys with decrypted secret key data for signing */ - public sign(privateKey: Key[], signature?: Signature, signingKeyIds?: Keyid[], date?: Date, userIds?: UserID[], streaming?: boolean, config?: Config): Promise>; + public sign(privateKey: Key[], signature?: Signature, signingKeyIDs?: KeyID[], date?: Date, userIds?: UserID[], streaming?: boolean, config?: Config): Promise>; /** Unwrap compressed message */ @@ -357,7 +357,7 @@ declare abstract class BasePublicKeyPacket extends BasePacket { public getFingerprintBytes(): Uint8Array | null; public hasSameFingerprintAs(other: BasePublicKeyPacket): boolean; public getCreationTime(): Date; - public getKeyId(): Keyid; + public getKeyID(): KeyID; public isDecrypted(): boolean; public publicParams: object; } @@ -460,7 +460,7 @@ export class SignaturePacket extends BasePacket { public revocationKeyClass: null | number; public revocationKeyAlgorithm: null | enums.publicKey; public revocationKeyFingerprint: null | Uint8Array; - public issuerKeyId: Keyid; + public issuerKeyID: KeyID; public notation: null | { [name: string]: string }; public preferredHashAlgorithms: enums.hash[] | null; public preferredCompressionAlgorithms: enums.compression[] | null; @@ -659,11 +659,11 @@ interface SubKeyOptions { config?: PartialConfig; } -declare class Keyid { +declare class KeyID { bytes: string; - equals(keyid: Keyid, matchWildcard?: boolean): boolean; + equals(keyID: KeyID, matchWildcard?: boolean): boolean; toHex(): string; - static fromId(hex: string): Keyid; + static fromId(hex: string): KeyID; } interface DecryptMessageResult { diff --git a/src/cleartext.js b/src/cleartext.js index 8b9dd794b..b04220863 100644 --- a/src/cleartext.js +++ b/src/cleartext.js @@ -43,32 +43,32 @@ export class CleartextMessage { /** * Returns the key IDs of the keys that signed the cleartext message - * @returns {Array} Array of keyid objects. + * @returns {Array} Array of keyID objects. */ - getSigningKeyIds() { - const keyIds = []; + getSigningKeyIDs() { + const keyIDs = []; const signatureList = this.signature.packets; signatureList.forEach(function(packet) { - keyIds.push(packet.issuerKeyId); + keyIDs.push(packet.issuerKeyID); }); - return keyIds; + return keyIDs; } /** * Sign the cleartext message * @param {Array} privateKeys - private keys with decrypted secret key data for signing * @param {Signature} [signature] - Any existing detached signature - * @param {Array} [signingKeyIds] - Array of key IDs to use for signing. Each signingKeyIds[i] corresponds to privateKeys[i] + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] * @param {Date} [date] - The creation time of the signature that should be created * @param {Array} [userIds] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {CleartextMessage} New cleartext message with signed content. * @async */ - async sign(privateKeys, signature = null, signingKeyIds = [], date = new Date(), userIds = [], config = defaultConfig) { + async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIds = [], config = defaultConfig) { const literalDataPacket = new LiteralDataPacket(); literalDataPacket.setText(this.text); - const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIds, date, userIds, true, undefined, config)); + const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIds, true, undefined, config)); return new CleartextMessage(this.text, newSignature); } @@ -77,9 +77,9 @@ export class CleartextMessage { * @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 * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Array<{keyid: module:type/keyid~Keyid, + * @returns {Array<{keyID: module:type/keyid~KeyID, * signature: Promise, - * verified: Promise}>} List of signer's keyid and validity of signature. + * verified: Promise}>} List of signer's keyID and validity of signature. * @async */ verify(keys, date = new Date(), config = defaultConfig) { diff --git a/src/key/helper.js b/src/key/helper.js index d4fd1ea1d..2e11400cc 100644 --- a/src/key/helper.js +++ b/src/key/helper.js @@ -72,7 +72,7 @@ export async function getLatestValidSignature(signatures, primaryKey, signatureT } if (!signature) { throw util.wrapError( - `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${primaryKey.getKeyId().toHex()}` + `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${primaryKey.getKeyID().toHex()}` .replace('certGeneric ', 'self-') .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()) , exception); @@ -269,7 +269,7 @@ export async function mergeSignatures(source, dest, attr, checkFn) { export async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) { key = key || primaryKey; const normDate = util.normalizeDate(date); - const revocationKeyIds = []; + const revocationKeyIDs = []; await Promise.all(revocations.map(async function(revocationSignature) { try { if ( @@ -281,23 +281,23 @@ export async function isDataRevoked(primaryKey, signatureType, dataToVerify, rev // third-party revocation signatures here. (It could also be revoking a // third-party key certification, which should only affect // `verifyAllCertifications`.) - (!signature || revocationSignature.issuerKeyId.equals(signature.issuerKeyId)) && + (!signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID)) && !(config.revocationsExpire && revocationSignature.isExpired(normDate)) ) { revocationSignature.verified || await revocationSignature.verify(key, signatureType, dataToVerify, undefined, undefined, config); // TODO get an identifier of the revoked object instead - revocationKeyIds.push(revocationSignature.issuerKeyId); + revocationKeyIDs.push(revocationSignature.issuerKeyID); } } catch (e) {} })); // TODO further verify that this is the signature that should be revoked if (signature) { - signature.revoked = revocationKeyIds.some(keyId => keyId.equals(signature.issuerKeyId)) ? true : + signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true : signature.revoked || false; return signature.revoked; } - return revocationKeyIds.length > 0; + return revocationKeyIDs.length > 0; } export function getExpirationTime(keyPacket, signature) { diff --git a/src/key/key.js b/src/key/key.js index 19776b8fc..10fff8435 100644 --- a/src/key/key.js +++ b/src/key/key.js @@ -32,7 +32,7 @@ import * as helper from './helper'; /** * Class that represents an OpenPGP key. Must contain a primary key. * Can contain additional subkeys, signatures, user ids, user attributes. - * @borrows PublicKeyPacket#getKeyId as Key#getKeyId + * @borrows PublicKeyPacket#getKeyID as Key#getKeyID * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo @@ -68,7 +68,7 @@ class Key { */ packetlist2structure(packetlist) { let user; - let primaryKeyId; + let primaryKeyID; let subKey; for (let i = 0; i < packetlist.length; i++) { switch (packetlist[i].tag) { @@ -78,7 +78,7 @@ class Key { throw new Error('Key block contains multiple keys'); } this.keyPacket = packetlist[i]; - primaryKeyId = this.getKeyId(); + primaryKeyID = this.getKeyID(); break; case enums.packet.userID: case enums.packet.userAttribute: @@ -101,7 +101,7 @@ class Key { util.printDebug('Dropping certification signatures without preceding user packet'); continue; } - if (packetlist[i].issuerKeyId.equals(primaryKeyId)) { + if (packetlist[i].issuerKeyID.equals(primaryKeyID)) { user.selfCertifications.push(packetlist[i]); } else { user.otherCertifications.push(packetlist[i]); @@ -164,15 +164,15 @@ class Key { } /** - * Returns an array containing all public or private subkeys matching keyId; - * If keyId is not present, returns all subkeys. - * @param {type/keyid} keyId + * Returns an array containing all public or private subkeys matching keyID; + * If keyID is not present, returns all subkeys. + * @param {type/keyid} keyID * @returns {Array} */ - getSubkeys(keyId = null) { + getSubkeys(keyID = null) { const subKeys = []; this.subKeys.forEach(subKey => { - if (!keyId || subKey.getKeyId().equals(keyId, true)) { + if (!keyID || subKey.getKeyID().equals(keyID, true)) { subKeys.push(subKey); } }); @@ -180,25 +180,25 @@ class Key { } /** - * Returns an array containing all public or private keys matching keyId. - * If keyId is not present, returns all keys starting with the primary key. - * @param {type/keyid} keyId + * Returns an array containing all public or private keys matching keyID. + * If keyID is not present, returns all keys starting with the primary key. + * @param {type/keyid} keyID * @returns {Array} */ - getKeys(keyId = null) { + getKeys(keyID = null) { const keys = []; - if (!keyId || this.getKeyId().equals(keyId, true)) { + if (!keyID || this.getKeyID().equals(keyID, true)) { keys.push(this); } - return keys.concat(this.getSubkeys(keyId)); + return keys.concat(this.getSubkeys(keyID)); } /** * Returns key IDs of all keys - * @returns {Array} + * @returns {Array} */ - getKeyIds() { - return this.getKeys().map(key => key.getKeyId()); + getKeyIDs() { + return this.getKeys().map(key => key.getKeyID()); } /** @@ -278,21 +278,21 @@ class Key { } /** - * Returns last created key or key by given keyId that is available for signing and verification - * @param {module:type/keyid~Keyid} keyId, optional + * Returns last created key or key by given keyID that is available for signing and verification + * @param {module:type/keyid~KeyID} keyID, optional * @param {Date} [date] - Use the given date for verification instead of the current time * @param {Object} userId, optional user ID * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Key|SubKey|null} Key or null if no signing key has been found. * @async */ - async getSigningKey(keyId = null, date = new Date(), userId = {}, config = defaultConfig) { + async getSigningKey(keyID = null, date = new Date(), userId = {}, config = defaultConfig) { await this.verifyPrimaryKey(date, userId, config); const primaryKey = this.keyPacket; const subKeys = this.subKeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); let exception; for (const subKey of subKeys) { - if (!keyId || subKey.getKeyId().equals(keyId)) { + if (!keyID || subKey.getKeyID().equals(keyID)) { try { await subKey.verify(primaryKey, date, config); const dataToVerify = { key: primaryKey, bind: subKey.keyPacket }; @@ -319,7 +319,7 @@ class Key { try { const primaryUser = await this.getPrimaryUser(date, userId, config); - if ((!keyId || primaryKey.getKeyId().equals(keyId)) && + if ((!keyID || primaryKey.getKeyID().equals(keyID)) && helper.isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification, config)) { helper.checkKeyStrength(primaryKey, config); return this; @@ -327,26 +327,26 @@ class Key { } catch (e) { exception = e; } - throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyId().toHex(), exception); + throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception); } /** - * Returns last created key or key by given keyId that is available for encryption or decryption - * @param {module:type/keyid~Keyid} keyId, optional + * Returns last created key or key by given keyID that is available for encryption or decryption + * @param {module:type/keyid~KeyID} keyID, optional * @param {Date} date, optional * @param {String} userId, optional * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Key|SubKey|null} Key or null if no encryption key has been found. * @async */ - async getEncryptionKey(keyId, date = new Date(), userId = {}, config = defaultConfig) { + async getEncryptionKey(keyID, date = new Date(), userId = {}, config = defaultConfig) { await this.verifyPrimaryKey(date, userId, config); const primaryKey = this.keyPacket; // V4: by convention subkeys are preferred for encryption service const subKeys = this.subKeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); let exception; for (const subKey of subKeys) { - if (!keyId || subKey.getKeyId().equals(keyId)) { + if (!keyID || subKey.getKeyID().equals(keyID)) { try { await subKey.verify(primaryKey, date, config); const dataToVerify = { key: primaryKey, bind: subKey.keyPacket }; @@ -364,7 +364,7 @@ class Key { try { // if no valid subkey for encryption, evaluate primary key const primaryUser = await this.getPrimaryUser(date, userId, config); - if ((!keyId || primaryKey.getKeyId().equals(keyId)) && + if ((!keyID || primaryKey.getKeyID().equals(keyID)) && helper.isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) { helper.checkKeyStrength(primaryKey, config); return this; @@ -372,24 +372,24 @@ class Key { } catch (e) { exception = e; } - throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyId().toHex(), exception); + throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception); } /** - * Returns all keys that are available for decryption, matching the keyId when given + * Returns all keys that are available for decryption, matching the keyID when given * This is useful to retrieve keys for session key decryption - * @param {module:type/keyid~Keyid} keyId, optional + * @param {module:type/keyid~KeyID} keyID, optional * @param {Date} date, optional * @param {String} userId, optional * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Array} Array of decryption keys. * @async */ - async getDecryptionKeys(keyId, date = new Date(), userId = {}, config = defaultConfig) { + async getDecryptionKeys(keyID, date = new Date(), userId = {}, config = defaultConfig) { const primaryKey = this.keyPacket; const keys = []; for (let i = 0; i < this.subKeys.length; i++) { - if (!keyId || this.subKeys[i].getKeyId().equals(keyId, true)) { + if (!keyID || this.subKeys[i].getKeyID().equals(keyID, true)) { try { const dataToVerify = { key: primaryKey, bind: this.subKeys[i].keyPacket }; const bindingSignature = await helper.getLatestValidSignature(this.subKeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config); @@ -402,7 +402,7 @@ class Key { // evaluate primary key const primaryUser = await this.getPrimaryUser(date, userId, config); - if ((!keyId || primaryKey.getKeyId().equals(keyId, true)) && + if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && helper.isValidDecryptionKeyPacket(primaryUser.selfCertification, config)) { keys.push(this); } @@ -411,19 +411,19 @@ class Key { } /** - * Encrypts all secret key and subkey packets matching keyId + * 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} keyId + * @param {module:type/keyid~KeyID} keyID * @param {Object} [config] - Full configuration, defaults to openpgp.config * @throws {Error} if encryption failed for any key or subkey * @async */ - async encrypt(passphrases, keyId = null, config = defaultConfig) { + async encrypt(passphrases, keyID = null, config = defaultConfig) { if (!this.isPrivate()) { throw new Error("Nothing to encrypt in a public key"); } - const keys = this.getKeys(keyId); + const keys = this.getKeys(keyID); passphrases = util.isArray(passphrases) ? passphrases : new Array(keys.length).fill(passphrases); if (passphrases.length !== keys.length) { throw new Error("Invalid number of passphrases for key"); @@ -437,27 +437,27 @@ class Key { } /** - * Decrypts all secret key and subkey packets matching keyId + * Decrypts all secret key and subkey packets matching keyID * @param {String|Array} passphrases - * @param {module:type/keyid~Keyid} keyId + * @param {module:type/keyid~KeyID} keyID * @param {Object} [config] - Full configuration, defaults to openpgp.config * @throws {Error} if any matching key or subkey packets did not decrypt successfully * @async */ - async decrypt(passphrases, keyId = null, config = defaultConfig) { + async decrypt(passphrases, keyID = null, config = defaultConfig) { if (!this.isPrivate()) { throw new Error("Nothing to decrypt in a public key"); } passphrases = util.isArray(passphrases) ? passphrases : [passphrases]; - await Promise.all(this.getKeys(keyId).map(async function(key) { + await Promise.all(this.getKeys(keyID).map(async function(key) { let decrypted = false; let error = null; await Promise.all(passphrases.map(async function(passphrase) { try { await key.keyPacket.decrypt(passphrase); // If we are decrypting a single key packet, we also validate it directly - if (keyId) await key.keyPacket.validate(); + if (keyID) await key.keyPacket.validate(); decrypted = true; } catch (e) { error = e; @@ -468,7 +468,7 @@ class Key { } })); - if (!keyId) { + if (!keyID) { // The full key should be decrypted and we can validate it all await this.validate(config); } @@ -586,13 +586,13 @@ class Key { * Returns null if `capabilities` is passed and the key does not have the specified capabilities or is revoked or invalid. * Returns Infinity if the key doesn't expire. * @param {encrypt|sign|encrypt_sign} capabilities, optional - * @param {module:type/keyid~Keyid} keyId, optional + * @param {module:type/keyid~KeyID} keyID, optional * @param {Object} userId, optional user ID * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Date | Infinity | null} * @async */ - async getExpirationTime(capabilities, keyId, userId, config = defaultConfig) { + async getExpirationTime(capabilities, keyID, userId, config = defaultConfig) { const primaryUser = await this.getPrimaryUser(null, userId, config); const selfCert = primaryUser.selfCertification; const keyExpiry = helper.getExpirationTime(this.keyPacket, selfCert); @@ -600,16 +600,16 @@ class Key { let expiry = keyExpiry < sigExpiry ? keyExpiry : sigExpiry; if (capabilities === 'encrypt' || capabilities === 'encrypt_sign') { const encryptKey = - await this.getEncryptionKey(keyId, expiry, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}) || - await this.getEncryptionKey(keyId, null, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}); + await this.getEncryptionKey(keyID, expiry, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}) || + await this.getEncryptionKey(keyID, null, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}); if (!encryptKey) return null; const encryptExpiry = await encryptKey.getExpirationTime(this.keyPacket, undefined, config); if (encryptExpiry < expiry) expiry = encryptExpiry; } if (capabilities === 'sign' || capabilities === 'encrypt_sign') { const signKey = - await this.getSigningKey(keyId, expiry, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}) || - await this.getSigningKey(keyId, null, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}); + await this.getSigningKey(keyID, expiry, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}) || + await this.getSigningKey(keyID, null, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}); if (!signKey) return null; const signExpiry = await signKey.getExpirationTime(this.keyPacket, undefined, config); if (signExpiry < expiry) expiry = signExpiry; @@ -802,7 +802,7 @@ class Key { if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) { throw new Error('Could not find revocation signature packet'); } - if (!revocationSignature.issuerKeyId.equals(this.getKeyId())) { + if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) { throw new Error('Revocation signature does not match key'); } if (revocationSignature.isExpired()) { @@ -859,15 +859,15 @@ class Key { * @param {Date} [date] - Use the given date for verification instead of the current time * @param {Object} [userId] - User ID to get instead of the primary user, if it exists * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} List of signer's keyid and validity of signature + * @returns {Promise>} List of signer's keyID and validity of signature * @async */ async verifyPrimaryUser(keys, date, userId, config = defaultConfig) { const primaryKey = this.keyPacket; const { user } = await this.getPrimaryUser(date, userId, config); const results = keys ? await user.verifyAllCertifications(primaryKey, keys, undefined, config) : - [{ keyid: primaryKey.keyid, valid: await user.verify(primaryKey, undefined, config).catch(() => false) }]; + [{ keyID: primaryKey.keyID, valid: await user.verify(primaryKey, undefined, config).catch(() => false) }]; return results; } @@ -878,8 +878,8 @@ class Key { * @param {Array} keys - array of keys to verify certificate signatures * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Promise>} list of userid, signer's keyid and validity of signature + * keyID: module:type/keyid~KeyID, + * valid: Boolean}>>} list of userid, signer's keyID and validity of signature * @async */ async verifyAllUsers(keys, config = defaultConfig) { @@ -887,11 +887,11 @@ class Key { const primaryKey = this.keyPacket; await Promise.all(this.users.map(async function(user) { const signatures = keys ? await user.verifyAllCertifications(primaryKey, keys, undefined, config) : - [{ keyid: primaryKey.keyid, valid: await user.verify(primaryKey, undefined, config).catch(() => false) }]; + [{ keyID: primaryKey.keyID, valid: await user.verify(primaryKey, undefined, config).catch(() => false) }]; signatures.forEach(signature => { results.push({ userid: user.userId.userid, - keyid: signature.keyid, + keyID: signature.keyID, valid: signature.valid }); }); @@ -944,7 +944,7 @@ class Key { } } -['getKeyId', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => { +['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => { Key.prototype[name] = SubKey.prototype[name]; }); diff --git a/src/key/subkey.js b/src/key/subkey.js index 720073f7e..655889af4 100644 --- a/src/key/subkey.js +++ b/src/key/subkey.js @@ -10,7 +10,7 @@ import defaultConfig from '../config'; /** * Class that represents a subkey packet and the relevant signatures. - * @borrows PublicSubkeyPacket#getKeyId as SubKey#getKeyId + * @borrows PublicSubkeyPacket#getKeyID as SubKey#getKeyID * @borrows PublicSubkeyPacket#getFingerprint as SubKey#getFingerprint * @borrows PublicSubkeyPacket#hasSameFingerprintAs as SubKey#hasSameFingerprintAs * @borrows PublicSubkeyPacket#getAlgorithmInfo as SubKey#getAlgorithmInfo @@ -134,7 +134,7 @@ class SubKey { const dataToVerify = { key: primaryKey, bind: that.keyPacket }; await helper.mergeSignatures(subKey, this, 'bindingSignatures', async function(srcBindSig) { for (let i = 0; i < that.bindingSignatures.length; i++) { - if (that.bindingSignatures[i].issuerKeyId.equals(srcBindSig.issuerKeyId)) { + if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) { if (srcBindSig.created > that.bindingSignatures[i].created) { that.bindingSignatures[i] = srcBindSig; } @@ -190,7 +190,7 @@ class SubKey { } } -['getKeyId', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => { +['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => { SubKey.prototype[name] = function() { return this.keyPacket[name](); diff --git a/src/key/user.js b/src/key/user.js index b422557e7..7d21d0a9d 100644 --- a/src/key/user.js +++ b/src/key/user.js @@ -107,17 +107,17 @@ class User { */ async verifyCertificate(primaryKey, certificate, keys, date = new Date(), config) { const that = this; - const keyid = certificate.issuerKeyId; + const keyID = certificate.issuerKeyID; const dataToVerify = { userId: this.userId, userAttribute: this.userAttribute, key: primaryKey }; const results = await Promise.all(keys.map(async function(key) { - if (!key.getKeyIds().some(id => id.equals(keyid))) { + if (!key.getKeyIDs().some(id => id.equals(keyID))) { return null; } - const signingKey = await key.getSigningKey(keyid, date, undefined, config); + const signingKey = await key.getSigningKey(keyID, date, undefined, config); if (certificate.revoked || await that.isRevoked(primaryKey, certificate, signingKey.keyPacket, date, config)) { throw new Error('User certificate is revoked'); } @@ -141,8 +141,8 @@ class User { * @param {Array} keys - Array of keys to verify certificate signatures * @param {Date} date - Use the given date instead of the current time * @param {Object} config - Full configuration - * @returns {Promise>} List of signer's keyid and validity of signature + * @returns {Promise>} List of signer's keyID and validity of signature * @async */ async verifyAllCertifications(primaryKey, keys, date = new Date(), config) { @@ -150,7 +150,7 @@ class User { const certifications = this.selfCertifications.concat(this.otherCertifications); return Promise.all(certifications.map(async function(certification) { return { - keyid: certification.issuerKeyId, + keyID: certification.issuerKeyID, valid: await that.verifyCertificate(primaryKey, certification, keys, date, config).catch(() => false) }; })); diff --git a/src/message.js b/src/message.js index 82274fbd6..5aac2138f 100644 --- a/src/message.js +++ b/src/message.js @@ -17,7 +17,7 @@ import stream from '@openpgp/web-stream-tools'; import { armor, unarmor } from './encoding/armor'; -import type_keyid from './type/keyid'; +import KeyID from './type/keyid'; import defaultConfig from './config'; import crypto from './crypto'; import enums from './enums'; @@ -52,37 +52,37 @@ export class Message { /** * Returns the key IDs of the keys to which the session key is encrypted - * @returns {Array} Array of keyid objects. + * @returns {Array} Array of keyID objects. */ - getEncryptionKeyIds() { - const keyIds = []; + getEncryptionKeyIDs() { + const keyIDs = []; const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); pkESKeyPacketlist.forEach(function(packet) { - keyIds.push(packet.publicKeyId); + keyIDs.push(packet.publicKeyID); }); - return keyIds; + return keyIDs; } /** * Returns the key IDs of the keys that signed the message - * @returns {Array} Array of keyid objects. + * @returns {Array} Array of keyID objects. */ - getSigningKeyIds() { - const keyIds = []; + getSigningKeyIDs() { + const keyIDs = []; const msg = this.unwrapCompressed(); // search for one pass signatures const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature); onePassSigList.forEach(function(packet) { - keyIds.push(packet.issuerKeyId); + keyIDs.push(packet.issuerKeyID); }); // if nothing found look for signature packets - if (!keyIds.length) { + if (!keyIDs.length) { const signatureList = msg.packets.filterByTag(enums.packet.signature); signatureList.forEach(function(packet) { - keyIds.push(packet.issuerKeyId); + keyIDs.push(packet.issuerKeyID); }); } - return keyIds; + return keyIDs; } /** @@ -193,7 +193,7 @@ export class Message { } catch (e) {} // do not check key expiration to allow decryption of old messages - const privateKeyPackets = (await privateKey.getDecryptionKeys(keyPacket.publicKeyId, null, undefined, config)).map(key => key.keyPacket); + const privateKeyPackets = (await privateKey.getDecryptionKeys(keyPacket.publicKeyID, null, undefined, config)).map(key => key.keyPacket); await Promise.all(privateKeyPackets.map(async function(privateKeyPacket) { if (!privateKeyPacket || privateKeyPacket.isDummy()) { return; @@ -297,7 +297,7 @@ export class Message { * @param {Array} [passwords] - Password(s) for message encryption * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs - * @param {Array} [encryptionKeyIds] - Array of key IDs to use for encryption. Each encryptionKeyIds[i] corresponds to publicKeys[i] + * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to publicKeys[i] * @param {Date} [date] - Override the creation date of the literal package * @param {Array} [userIds] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] * @param {Boolean} [streaming] - Whether to process data as a stream @@ -305,7 +305,7 @@ export class Message { * @returns {Message} New message with encrypted content. * @async */ - async encrypt(keys, passwords, sessionKey, wildcard = false, encryptionKeyIds = [], date = new Date(), userIds = [], streaming, config = defaultConfig) { + async encrypt(keys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIds = [], streaming, config = defaultConfig) { if (sessionKey) { if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) { throw new Error('Invalid session key for encryption.'); @@ -320,7 +320,7 @@ export class Message { const { data: sessionKeyData, algorithm, aeadAlgorithm } = sessionKey; - const msg = await Message.encryptSessionKey(sessionKeyData, algorithm, aeadAlgorithm, keys, passwords, wildcard, encryptionKeyIds, date, userIds, config); + const msg = await Message.encryptSessionKey(sessionKeyData, algorithm, aeadAlgorithm, keys, passwords, wildcard, encryptionKeyIDs, date, userIds, config); let symEncryptedPacket; if (aeadAlgorithm) { @@ -346,21 +346,21 @@ export class Message { * @param {Array} [publicKeys] - Public key(s) for message encryption * @param {Array} [passwords] - For message encryption * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs - * @param {Array} [encryptionKeyIds] - Array of key IDs to use for encryption. Each encryptionKeyIds[i] corresponds to publicKeys[i] + * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to publicKeys[i] * @param {Date} [date] - Override the date * @param {Array} [userIds] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Message} New message with encrypted content. * @async */ - static async encryptSessionKey(sessionKey, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard = false, encryptionKeyIds = [], date = new Date(), userIds = [], config = defaultConfig) { + static async encryptSessionKey(sessionKey, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIds = [], config = defaultConfig) { const packetlist = new PacketList(); if (publicKeys) { const results = await Promise.all(publicKeys.map(async function(publicKey, i) { - const encryptionKey = await publicKey.getEncryptionKey(encryptionKeyIds[i], date, userIds, config); + const encryptionKey = await publicKey.getEncryptionKey(encryptionKeyIDs[i], date, userIds, config); const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket(); - pkESKeyPacket.publicKeyId = wildcard ? type_keyid.wildcard() : encryptionKey.getKeyId(); + pkESKeyPacket.publicKeyID = wildcard ? KeyID.wildcard() : encryptionKey.getKeyID(); pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm; pkESKeyPacket.sessionKey = sessionKey; pkESKeyPacket.sessionKeyAlgorithm = algorithm; @@ -413,7 +413,7 @@ export class Message { * Sign the message (the literal data packet of the message) * @param {Array} privateKeys - private keys with decrypted secret key data for signing * @param {Signature} [signature] - Any existing detached signature to add to the message - * @param {Array} [signingKeyIds] - Array of key IDs to use for signing. Each signingKeyIds[i] corresponds to privateKeys[i] + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] * @param {Date} [date] - Override the creation time of the signature * @param {Array} [userIds] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] * @param {Boolean} [streaming] - Whether to process data as a stream @@ -421,7 +421,7 @@ export class Message { * @returns {Message} New message with signed content. * @async */ - async sign(privateKeys = [], signature = null, signingKeyIds = [], date = new Date(), userIds = [], streaming = false, config = defaultConfig) { + async sign(privateKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIds = [], streaming = false, config = defaultConfig) { const packetlist = new PacketList(); const literalDataPacket = this.packets.findPacket(enums.packet.literalData); @@ -443,7 +443,7 @@ export class Message { onePassSig.signatureType = signaturePacket.signatureType; onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm; onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm; - onePassSig.issuerKeyId = signaturePacket.issuerKeyId; + onePassSig.issuerKeyID = signaturePacket.issuerKeyID; if (!privateKeys.length && i === 0) { onePassSig.flags = 1; } @@ -455,13 +455,13 @@ export class Message { if (privateKey.isPublic()) { throw new Error('Need private key for signing'); } - const signingKeyId = signingKeyIds[privateKeys.length - 1 - i]; - const signingKey = await privateKey.getSigningKey(signingKeyId, date, userIds, config); + const signingKeyID = signingKeyIDs[privateKeys.length - 1 - i]; + const signingKey = await privateKey.getSigningKey(signingKeyID, date, userIds, config); const onePassSig = new OnePassSignaturePacket(); onePassSig.signatureType = signatureType; onePassSig.hashAlgorithm = await getPreferredHashAlgo(privateKey, signingKey.keyPacket, date, userIds, config); onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm; - onePassSig.issuerKeyId = signingKey.getKeyId(); + onePassSig.issuerKeyID = signingKey.getKeyID(); if (i === privateKeys.length - 1) { onePassSig.flags = 1; } @@ -471,7 +471,7 @@ export class Message { }); packetlist.push(literalDataPacket); - packetlist.concat(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIds, date, userIds, false, streaming, config)); + packetlist.concat(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIds, false, streaming, config)); return new Message(packetlist); } @@ -501,7 +501,7 @@ export class Message { * Create a detached signature for the message (the literal data packet of the message) * @param {Array} privateKeys - private keys with decrypted secret key data for signing * @param {Signature} [signature] - Any existing detached signature - * @param {Array} [signingKeyIds] - Array of key IDs to use for signing. Each signingKeyIds[i] corresponds to privateKeys[i] + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] * @param {Date} [date] - Override the creation time of the signature * @param {Array} [userIds] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] * @param {Boolean} [streaming] - Whether to process data as a stream @@ -509,12 +509,12 @@ export class Message { * @returns {Signature} New detached signature of message content. * @async */ - async signDetached(privateKeys = [], signature = null, signingKeyIds = [], date = new Date(), userIds = [], streaming = false, config = defaultConfig) { + async signDetached(privateKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIds = [], streaming = false, config = defaultConfig) { const literalDataPacket = this.packets.findPacket(enums.packet.literalData); if (!literalDataPacket) { throw new Error('No literal data packet to sign.'); } - return new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIds, date, userIds, true, streaming, config)); + return new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIds, true, streaming, config)); } /** @@ -523,9 +523,9 @@ export class Message { * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time * @param {Boolean} [streaming] - Whether to process data as a stream * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Array<{keyid: module:type/keyid~Keyid, + * @returns {Array<{keyID: module:type/keyid~KeyID, * signature: Promise, - * verified: Promise}>} List of signer's keyid and validity of signatures. + * verified: Promise}>} List of signer's keyID and validity of signatures. * @async */ async verify(keys, date = new Date(), streaming, config = defaultConfig) { @@ -578,9 +578,9 @@ export class Message { * @param {Signature} signature * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Array<{keyid: module:type/keyid~Keyid, + * @returns {Array<{keyID: module:type/keyid~KeyID, * signature: Promise, - * verified: Promise}>} List of signer's keyid and validity of signature. + * verified: Promise}>} List of signer's keyID and validity of signature. * @async */ verifyDetached(signature, keys, date = new Date(), streaming, config = defaultConfig) { @@ -693,7 +693,7 @@ export class Message { * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign * @param {Array} privateKeys - private keys with decrypted secret key data for signing * @param {Signature} [signature] - Any existing detached signature to append - * @param {Array} [signingKeyIds] - Array of key IDs to use for signing. Each signingKeyIds[i] corresponds to privateKeys[i] + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] * @param {Date} [date] - Override the creationtime of the signature * @param {Array} [userIds] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] * @param {Boolean} [detached] - Whether to create detached signature packets @@ -703,7 +703,7 @@ export class Message { * @async * @private */ -export async function createSignaturePackets(literalDataPacket, privateKeys, signature = null, signingKeyIds = [], date = new Date(), userIds = [], detached = false, streaming = false, config = defaultConfig) { +export async function createSignaturePackets(literalDataPacket, privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIds = [], detached = false, streaming = false, config = defaultConfig) { const packetlist = new PacketList(); // If data packet was created from Uint8Array, use binary, otherwise use text @@ -715,7 +715,7 @@ export async function createSignaturePackets(literalDataPacket, privateKeys, sig if (privateKey.isPublic()) { throw new Error('Need private key for signing'); } - const signingKey = await privateKey.getSigningKey(signingKeyIds[i], date, userId, config); + const signingKey = await privateKey.getSigningKey(signingKeyIDs[i], date, userId, config); return createSignaturePacket(literalDataPacket, privateKey, signingKey.keyPacket, { signatureType }, date, userId, detached, streaming, config); })).then(signatureList => { signatureList.forEach(signaturePacket => packetlist.push(signaturePacket)); @@ -729,7 +729,7 @@ export async function createSignaturePackets(literalDataPacket, privateKeys, sig } /** - * Create object containing signer's keyid and validity of signature + * Create object containing signer's keyID and validity of signature * @param {SignaturePacket} signature - Signature packets * @param {Array} literalDataList - Array of literal data packets * @param {Array} keys - Array of keys to verify signatures @@ -737,9 +737,9 @@ export async function createSignaturePackets(literalDataPacket, privateKeys, sig * i.e. check signature creation time < date < expiration time * @param {Boolean} [detached] - Whether to verify detached signature packets * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {{keyid: module:type/keyid~Keyid, + * @returns {{keyID: module:type/keyid~KeyID, * signature: Promise, - * verified: Promise}} signer's keyid and validity of signature + * verified: Promise}} signer's keyID and validity of signature * @async * @private */ @@ -749,24 +749,24 @@ async function createVerificationObject(signature, literalDataList, keys, date = let keyError; for (const key of keys) { - const issuerKeys = key.getKeys(signature.issuerKeyId); + const issuerKeys = key.getKeys(signature.issuerKeyID); if (issuerKeys.length > 0) { primaryKey = key; break; } } if (!primaryKey) { - keyError = new Error(`Could not find signing key with key ID ${signature.issuerKeyId.toHex()}`); + keyError = new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`); } else { try { - signingKey = await primaryKey.getSigningKey(signature.issuerKeyId, null, undefined, config); + signingKey = await primaryKey.getSigningKey(signature.issuerKeyID, null, undefined, config); } catch (e) { keyError = e; } } const signaturePacket = signature.correspondingSig || signature; const verifiedSig = { - keyid: signature.issuerKeyId, + keyID: signature.issuerKeyID, verified: (async () => { if (keyError) { throw keyError; @@ -803,7 +803,7 @@ async function createVerificationObject(signature, literalDataList, keys, date = } /** - * Create list of objects containing signer's keyid and validity of signature + * 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} keys - Array of keys to verify signatures @@ -811,9 +811,9 @@ async function createVerificationObject(signature, literalDataList, keys, date = * i.e. check signature creation time < date < expiration time * @param {Boolean} [detached] - Whether to verify detached signature packets * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Array<{keyid: module:type/keyid~Keyid, + * @returns {Array<{keyID: module:type/keyid~KeyID, * signature: Promise, - * verified: Promise}>} list of signer's keyid and validity of signatures + * verified: Promise}>} list of signer's keyID and validity of signatures * @async * @private */ diff --git a/src/openpgp.js b/src/openpgp.js index 41dac45fc..125bbcea2 100644 --- a/src/openpgp.js +++ b/src/openpgp.js @@ -240,8 +240,8 @@ export async function encryptKey({ privateKey, passphrase, config }) { * @param {'web'|'ponyfill'|'node'|false} [options.streaming=type of stream `message` was created from, if any] - Whether to return data as a stream * @param {Signature} [options.signature] - A detached signature to add to the encrypted message * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs - * @param {Array} [options.signingKeyIds=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIds[i]` corresponds to `privateKeys[i]` - * @param {Array} [options.encryptionKeyIds=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIds[i]` corresponds to `publicKeys[i]` + * @param {Array} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `privateKeys[i]` + * @param {Array} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `publicKeys[i]` * @param {Date} [options.date=current date] - Override the creation date of the message signature * @param {Array} [options.fromUserIds=primary user IDs] - Array of user IDs to sign with, one per key in `privateKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` * @param {Array} [options.toUserIds=primary user IDs] - Array of user IDs to encrypt for, one per key in `publicKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]` @@ -250,7 +250,7 @@ export async function encryptKey({ privateKey, passphrase, config }) { * @async * @static */ -export function encrypt({ message, publicKeys, privateKeys, passwords, sessionKey, armor = true, streaming = message && message.fromStream, detached = false, signature = null, wildcard = false, signingKeyIds = [], encryptionKeyIds = [], date = new Date(), fromUserIds = [], toUserIds = [], config }) { +export function encrypt({ message, publicKeys, privateKeys, passwords, sessionKey, armor = true, streaming = message && message.fromStream, detached = false, signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), fromUserIds = [], toUserIds = [], config }) { config = { ...defaultConfig, ...config }; checkMessage(message); publicKeys = toArray(publicKeys); privateKeys = toArray(privateKeys); passwords = toArray(passwords); fromUserIds = toArray(fromUserIds); toUserIds = toArray(toUserIds); if (detached) { @@ -262,13 +262,13 @@ export function encrypt({ message, publicKeys, privateKeys, passwords, sessionKe privateKeys = []; } if (privateKeys.length || signature) { // sign the message only if private keys or signature is specified - message = await message.sign(privateKeys, signature, signingKeyIds, date, fromUserIds, message.fromStream, config); + message = await message.sign(privateKeys, signature, signingKeyIDs, date, fromUserIds, message.fromStream, config); } message = message.compress( await getPreferredAlgo('compression', publicKeys, date, toUserIds, config), config ); - message = await message.encrypt(publicKeys, passwords, sessionKey, wildcard, encryptionKeyIds, date, toUserIds, streaming, config); + message = await message.encrypt(publicKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, toUserIds, streaming, config); const data = armor ? message.armor(config) : message.write(); return convertStream(data, streaming, armor ? 'utf8' : 'binary'); }).catch(onError.bind(null, 'Error encrypting message')); @@ -296,7 +296,7 @@ export function encrypt({ message, publicKeys, privateKeys, passwords, sessionKe * filename: String, * signatures: [ * { - * keyid: module:type/keyid~Keyid, + * keyID: module:type/keyid~KeyID, * verified: Promise, * valid: Boolean (if streaming was false) * }, ... @@ -341,7 +341,7 @@ export function decrypt({ message, privateKeys, passwords, sessionKeys, publicKe * @param {Boolean} [options.armor=true] - Whether the return values should be ascii armored (true, the default) or binary (false) * @param {'web'|'ponyfill'|'node'|false} [options.streaming=type of stream `message` was created from, if any] - Whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature - * @param {Array} [options.signingKeyIds=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIds[i] corresponds to privateKeys[i] + * @param {Array} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] * @param {Date} [options.date=current date] - Override the creation date of the signature * @param {Array} [options.fromUserIds=primary user IDs] - Array of user IDs to sign with, one per key in `privateKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} @@ -349,7 +349,7 @@ export function decrypt({ message, privateKeys, passwords, sessionKeys, publicKe * @async * @static */ -export function sign({ message, privateKeys, armor = true, streaming = message && message.fromStream, detached = false, signingKeyIds = [], date = new Date(), fromUserIds = [], config }) { +export function sign({ message, privateKeys, armor = true, streaming = message && message.fromStream, detached = false, signingKeyIDs = [], date = new Date(), fromUserIds = [], config }) { config = { ...defaultConfig, ...config }; checkCleartextOrMessage(message); if (message instanceof CleartextMessage && !armor) throw new Error("Can't sign non-armored cleartext message"); @@ -359,11 +359,11 @@ export function sign({ message, privateKeys, armor = true, streaming = message & return Promise.resolve().then(async function() { let signature; if (message instanceof CleartextMessage) { - signature = await message.sign(privateKeys, undefined, signingKeyIds, date, fromUserIds, config); + signature = await message.sign(privateKeys, undefined, signingKeyIDs, date, fromUserIds, config); } else if (detached) { - signature = await message.signDetached(privateKeys, undefined, signingKeyIds, date, fromUserIds, message.fromStream, config); + signature = await message.signDetached(privateKeys, undefined, signingKeyIDs, date, fromUserIds, message.fromStream, config); } else { - signature = await message.sign(privateKeys, undefined, signingKeyIds, date, fromUserIds, message.fromStream, config); + signature = await message.sign(privateKeys, undefined, signingKeyIDs, date, fromUserIds, message.fromStream, config); } signature = armor ? signature.armor(config) : signature.write(); if (detached) { @@ -395,7 +395,7 @@ export function sign({ message, privateKeys, armor = true, streaming = message & * data: Uint8Array|ReadableStream|NodeStream, (if `message` was a Message) * signatures: [ * { - * keyid: module:type/keyid~Keyid, + * keyID: module:type/keyid~KeyID, * verified: Promise, * valid: Boolean (if `streaming` was false) * }, ... @@ -466,7 +466,7 @@ export function generateSessionKey({ publicKeys, date = new Date(), toUserIds = * @param {String|Array} [options.passwords] - Passwords for the message * @param {Boolean} [options.armor=true] - Whether the return values should be ascii armored (true, the default) or binary (false) * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs - * @param {Array} [options.encryptionKeyIds=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIds[i] corresponds to publicKeys[i] + * @param {Array} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to publicKeys[i] * @param {Date} [options.date=current date] - Override the date * @param {Array} [options.toUserIds=primary user IDs] - Array of user IDs to encrypt for, one per key in `publicKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]` * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} @@ -474,13 +474,13 @@ export function generateSessionKey({ publicKeys, date = new Date(), toUserIds = * @async * @static */ -export function encryptSessionKey({ data, algorithm, aeadAlgorithm, publicKeys, passwords, armor = true, wildcard = false, encryptionKeyIds = [], date = new Date(), toUserIds = [], config }) { +export function encryptSessionKey({ data, algorithm, aeadAlgorithm, publicKeys, passwords, armor = true, wildcard = false, encryptionKeyIDs = [], date = new Date(), toUserIds = [], config }) { config = { ...defaultConfig, ...config }; checkBinary(data); checkString(algorithm, 'algorithm'); publicKeys = toArray(publicKeys); passwords = toArray(passwords); toUserIds = toArray(toUserIds); return Promise.resolve().then(async function() { - const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard, encryptionKeyIds, date, toUserIds, config); + const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard, encryptionKeyIDs, date, toUserIds, config); return armor ? message.armor(config) : message.write(); }).catch(onError.bind(null, 'Error encrypting session key')); diff --git a/src/packet/one_pass_signature.js b/src/packet/one_pass_signature.js index 624c713c4..ac4c980e7 100644 --- a/src/packet/one_pass_signature.js +++ b/src/packet/one_pass_signature.js @@ -17,7 +17,7 @@ import stream from '@openpgp/web-stream-tools'; import SignaturePacket from './signature'; -import type_keyid from '../type/keyid'; +import KeyID from '../type/keyid'; import enums from '../enums'; import util from '../util'; @@ -57,7 +57,7 @@ class OnePassSignaturePacket { */ this.publicKeyAlgorithm = null; /** An eight-octet number holding the Key ID of the signing key. */ - this.issuerKeyId = null; + this.issuerKeyID = null; /** * A one-octet number holding a flag showing whether the signature is nested. * A zero value indicates that the next packet is another One-Pass Signature packet @@ -87,8 +87,8 @@ class OnePassSignaturePacket { this.publicKeyAlgorithm = bytes[mypos++]; // An eight-octet number holding the Key ID of the signing key. - this.issuerKeyId = new type_keyid(); - this.issuerKeyId.read(bytes.subarray(mypos, mypos + 8)); + this.issuerKeyID = new KeyID(); + this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8)); mypos += 8; // A one-octet number holding a flag showing whether the signature @@ -110,7 +110,7 @@ class OnePassSignaturePacket { const end = new Uint8Array([this.flags]); - return util.concatUint8Array([start, this.issuerKeyId.write(), end]); + return util.concatUint8Array([start, this.issuerKeyID.write(), end]); } calculateTrailer(...args) { @@ -126,7 +126,7 @@ class OnePassSignaturePacket { correspondingSig.signatureType !== this.signatureType || correspondingSig.hashAlgorithm !== this.hashAlgorithm || correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm || - !correspondingSig.issuerKeyId.equals(this.issuerKeyId) + !correspondingSig.issuerKeyID.equals(this.issuerKeyID) ) { throw new Error('Corresponding signature packet does not match one-pass signature packet'); } diff --git a/src/packet/public_key.js b/src/packet/public_key.js index be1bdb4e7..32d674827 100644 --- a/src/packet/public_key.js +++ b/src/packet/public_key.js @@ -19,7 +19,7 @@ import { Sha1 } from '@openpgp/asmcrypto.js/dist_es8/hash/sha1/sha1'; import { Sha256 } from '@openpgp/asmcrypto.js/dist_es8/hash/sha256/sha256'; -import type_keyid from '../type/keyid'; +import KeyID from '../type/keyid'; import defaultConfig from '../config'; import crypto from '../crypto'; import enums from '../enums'; @@ -78,10 +78,10 @@ class PublicKeyPacket { */ this.fingerprint = null; /** - * Keyid - * @type {module:type/keyid~Keyid} + * KeyID + * @type {module:type/keyid~KeyID} */ - this.keyid = null; + this.keyID = null; } /** @@ -176,19 +176,19 @@ class PublicKeyPacket { /** * Calculates the key id of the key - * @returns {module:type/keyid~Keyid} A 8 byte key id. + * @returns {module:type/keyid~KeyID} A 8 byte key id. */ - getKeyId() { - if (this.keyid) { - return this.keyid; + getKeyID() { + if (this.keyID) { + return this.keyID; } - this.keyid = new type_keyid(); + this.keyID = new KeyID(); if (this.version === 5) { - this.keyid.read(util.hexToUint8Array(this.getFingerprint()).subarray(0, 8)); + this.keyID.read(util.hexToUint8Array(this.getFingerprint()).subarray(0, 8)); } else if (this.version === 4) { - this.keyid.read(util.hexToUint8Array(this.getFingerprint()).subarray(12, 20)); + this.keyID.read(util.hexToUint8Array(this.getFingerprint()).subarray(12, 20)); } - return this.keyid; + return this.keyID; } /** diff --git a/src/packet/public_key_encrypted_session_key.js b/src/packet/public_key_encrypted_session_key.js index 92e5cffcf..ce758b1bd 100644 --- a/src/packet/public_key_encrypted_session_key.js +++ b/src/packet/public_key_encrypted_session_key.js @@ -15,7 +15,7 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -import type_keyid from '../type/keyid'; +import KeyID from '../type/keyid'; import crypto from '../crypto'; import enums from '../enums'; import util from '../util'; @@ -41,7 +41,7 @@ class PublicKeyEncryptedSessionKeyPacket { this.tag = enums.packet.publicKeyEncryptedSessionKey; this.version = 3; - this.publicKeyId = new type_keyid(); + this.publicKeyID = new KeyID(); this.publicKeyAlgorithm = null; this.sessionKey = null; @@ -58,7 +58,7 @@ class PublicKeyEncryptedSessionKeyPacket { */ read(bytes) { this.version = bytes[0]; - this.publicKeyId.read(bytes.subarray(1, bytes.length)); + this.publicKeyID.read(bytes.subarray(1, bytes.length)); this.publicKeyAlgorithm = enums.read(enums.publicKey, bytes[9]); const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm); @@ -75,7 +75,7 @@ class PublicKeyEncryptedSessionKeyPacket { const arr = [ new Uint8Array([this.version]), - this.publicKeyId.write(), + this.publicKeyID.write(), new Uint8Array([enums.write(enums.publicKey, this.publicKeyAlgorithm)]), crypto.serializeParams(algo, this.encrypted) ]; diff --git a/src/packet/signature.js b/src/packet/signature.js index d6a8cf450..69ce4c08c 100644 --- a/src/packet/signature.js +++ b/src/packet/signature.js @@ -17,7 +17,7 @@ import stream from '@openpgp/web-stream-tools'; import { readSimpleLength, writeSimpleLength } from './packet'; -import type_keyid from '../type/keyid.js'; +import KeyID from '../type/keyid.js'; import crypto from '../crypto'; import enums from '../enums'; import util from '../util'; @@ -60,7 +60,7 @@ class SignaturePacket { this.revocationKeyClass = null; this.revocationKeyAlgorithm = null; this.revocationKeyFingerprint = null; - this.issuerKeyId = new type_keyid(); + this.issuerKeyID = new KeyID(); this.rawNotations = []; this.notations = {}; this.preferredHashAlgorithms = null; @@ -166,7 +166,7 @@ class SignaturePacket { this.issuerKeyVersion = key.version; this.issuerFingerprint = key.getFingerprintBytes(); - this.issuerKeyId = key.getKeyId(); + this.issuerKeyID = key.getKeyID(); // Add hashed subpackets arr.push(this.write_hashed_sub_packets()); @@ -304,10 +304,10 @@ class SignaturePacket { const sub = enums.signatureSubpacket; const arr = []; let bytes; - if (!this.issuerKeyId.isNull() && this.issuerKeyVersion !== 5) { + if (!this.issuerKeyID.isNull() && this.issuerKeyVersion !== 5) { // If the version of [the] key is greater than 4, this subpacket // MUST NOT be included in the signature. - arr.push(write_sub_packet(sub.issuer, this.issuerKeyId.write())); + arr.push(write_sub_packet(sub.issuer, this.issuerKeyID.write())); } if (this.embeddedSignature !== null) { arr.push(write_sub_packet(sub.embeddedSignature, this.embeddedSignature.write())); @@ -416,7 +416,7 @@ class SignaturePacket { case 16: // Issuer - this.issuerKeyId.read(bytes.subarray(mypos, bytes.length)); + this.issuerKeyID.read(bytes.subarray(mypos, bytes.length)); break; case 20: { @@ -502,9 +502,9 @@ class SignaturePacket { this.issuerKeyVersion = bytes[mypos++]; this.issuerFingerprint = bytes.subarray(mypos, bytes.length); if (this.issuerKeyVersion === 5) { - this.issuerKeyId.read(this.issuerFingerprint); + this.issuerKeyID.read(this.issuerFingerprint); } else { - this.issuerKeyId.read(this.issuerFingerprint.subarray(-8)); + this.issuerKeyID.read(this.issuerFingerprint.subarray(-8)); } break; case 34: diff --git a/src/type/keyid.js b/src/type/keyid.js index 47cee5937..d7b24f318 100644 --- a/src/type/keyid.js +++ b/src/type/keyid.js @@ -31,7 +31,7 @@ import util from '../util.js'; * section "Enhanced Key Formats" below describes how Key IDs are * formed. */ -class Keyid { +class KeyID { constructor() { this.bytes = ''; } @@ -62,11 +62,11 @@ class Keyid { /** * Checks equality of Key ID's - * @param {Keyid} keyid - * @param {Boolean} matchWildcard - Indicates whether to check if either keyid is a wildcard + * @param {KeyID} keyID + * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard */ - equals(keyid, matchWildcard = false) { - return (matchWildcard && (keyid.isWildcard() || this.isWildcard())) || this.bytes === keyid.bytes; + equals(keyID, matchWildcard = false) { + return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes; } /** @@ -85,21 +85,21 @@ class Keyid { return /^0+$/.test(this.toHex()); } - static mapToHex(keyId) { - return keyId.toHex(); + static mapToHex(keyID) { + return keyID.toHex(); } static fromId(hex) { - const keyid = new Keyid(); - keyid.read(util.hexToUint8Array(hex)); - return keyid; + const keyID = new KeyID(); + keyID.read(util.hexToUint8Array(hex)); + return keyID; } static wildcard() { - const keyid = new Keyid(); - keyid.read(new Uint8Array(8)); - return keyid; + const keyID = new KeyID(); + keyID.read(new Uint8Array(8)); + return keyID; } } -export default Keyid; +export default KeyID; diff --git a/test/general/brainpool.js b/test/general/brainpool.js index 5cce0ea86..07c2b5331 100644 --- a/test/general/brainpool.js +++ b/test/general/brainpool.js @@ -174,7 +174,7 @@ EJ4QcD/oQ6x1M/8X/iKQCtxZP8RnlrbH7ExkNON5s5g= return data[name].pub_key; } const pub = await openpgp.readKey({ armoredKey: data[name].pub }); - expect(pub.getKeyId().toHex()).to.equal(data[name].id); + expect(pub.getKeyID().toHex()).to.equal(data[name].id); data[name].pub_key = pub; return pub; } @@ -184,7 +184,7 @@ EJ4QcD/oQ6x1M/8X/iKQCtxZP8RnlrbH7ExkNON5s5g= } const pk = await openpgp.readKey({ armoredKey: data[name].priv }); expect(pk).to.exist; - expect(pk.getKeyId().toHex()).to.equal(data[name].id); + expect(pk.getKeyID().toHex()).to.equal(data[name].id); await pk.decrypt(data[name].pass); data[name].priv_key = pk; return pk; diff --git a/test/general/ecc_secp256k1.js b/test/general/ecc_secp256k1.js index bc8692d44..217265b71 100644 --- a/test/general/ecc_secp256k1.js +++ b/test/general/ecc_secp256k1.js @@ -142,7 +142,7 @@ module.exports = () => describe('Elliptic Curve Cryptography for secp256k1 curve } const pub = await openpgp.readKey({ armoredKey: data[name].pub }); expect(pub).to.exist; - expect(pub.getKeyId().toHex()).to.equal(data[name].id); + expect(pub.getKeyID().toHex()).to.equal(data[name].id); data[name].pub_key = pub; return pub; } @@ -152,7 +152,7 @@ module.exports = () => describe('Elliptic Curve Cryptography for secp256k1 curve } const pk = await openpgp.readKey({ armoredKey: data[name].priv }); expect(pk).to.exist; - expect(pk.getKeyId().toHex()).to.equal(data[name].id); + expect(pk.getKeyID().toHex()).to.equal(data[name].id); await pk.decrypt(data[name].pass); data[name].priv_key = pk; return pk; diff --git a/test/general/key.js b/test/general/key.js index 25134d44d..2ccd666a6 100644 --- a/test/general/key.js +++ b/test/general/key.js @@ -2430,9 +2430,9 @@ function versionSpecificTests() { const publicSigningKey = await publicKey.getSigningKey(); const privateSigningKey = await privateKey.getSigningKey(); expect(signatures.length).to.equal(2); - expect(signatures[0].keyid.toHex()).to.equal(publicSigningKey.getKeyId().toHex()); + expect(signatures[0].keyID.toHex()).to.equal(publicSigningKey.getKeyID().toHex()); expect(signatures[0].valid).to.be.null; - expect(signatures[1].keyid.toHex()).to.equal(privateSigningKey.getKeyId().toHex()); + expect(signatures[1].keyID.toHex()).to.equal(privateSigningKey.getKeyID().toHex()); expect(signatures[1].valid).to.be.true; } finally { openpgp.config.minRSABits = minRSABits; @@ -2453,9 +2453,9 @@ function versionSpecificTests() { const publicSigningKey = await publicKey.getSigningKey(); const privateSigningKey = await privateKey.getSigningKey(); expect(signatures.length).to.equal(2); - expect(signatures[0].keyid.toHex()).to.equal(publicSigningKey.getKeyId().toHex()); + expect(signatures[0].keyID.toHex()).to.equal(publicSigningKey.getKeyID().toHex()); expect(signatures[0].valid).to.be.null; - expect(signatures[1].keyid.toHex()).to.equal(privateSigningKey.getKeyId().toHex()); + expect(signatures[1].keyID.toHex()).to.equal(privateSigningKey.getKeyID().toHex()); expect(signatures[1].valid).to.be.null; } finally { openpgp.config.minRSABits = minRSABits; @@ -2476,16 +2476,16 @@ function versionSpecificTests() { const privateSigningKey = await privateKey.getSigningKey(); expect(signatures.length).to.equal(4); expect(signatures[0].userid).to.equal(publicKey.users[0].userId.userid); - expect(signatures[0].keyid.toHex()).to.equal(publicSigningKey.getKeyId().toHex()); + expect(signatures[0].keyID.toHex()).to.equal(publicSigningKey.getKeyID().toHex()); expect(signatures[0].valid).to.be.null; expect(signatures[1].userid).to.equal(publicKey.users[0].userId.userid); - expect(signatures[1].keyid.toHex()).to.equal(privateSigningKey.getKeyId().toHex()); + expect(signatures[1].keyID.toHex()).to.equal(privateSigningKey.getKeyID().toHex()); expect(signatures[1].valid).to.be.true; expect(signatures[2].userid).to.equal(publicKey.users[1].userId.userid); - expect(signatures[2].keyid.toHex()).to.equal(publicSigningKey.getKeyId().toHex()); + expect(signatures[2].keyID.toHex()).to.equal(publicSigningKey.getKeyID().toHex()); expect(signatures[2].valid).to.be.null; expect(signatures[3].userid).to.equal(publicKey.users[1].userId.userid); - expect(signatures[3].keyid.toHex()).to.equal(privateSigningKey.getKeyId().toHex()); + expect(signatures[3].keyID.toHex()).to.equal(privateSigningKey.getKeyID().toHex()); expect(signatures[3].valid).to.be.true; } finally { openpgp.config.minRSABits = minRSABits; @@ -2507,16 +2507,16 @@ function versionSpecificTests() { const privateSigningKey = await privateKey.getSigningKey(); expect(signatures.length).to.equal(4); expect(signatures[0].userid).to.equal(publicKey.users[0].userId.userid); - expect(signatures[0].keyid.toHex()).to.equal(publicSigningKey.getKeyId().toHex()); + expect(signatures[0].keyID.toHex()).to.equal(publicSigningKey.getKeyID().toHex()); expect(signatures[0].valid).to.be.null; expect(signatures[1].userid).to.equal(publicKey.users[0].userId.userid); - expect(signatures[1].keyid.toHex()).to.equal(privateSigningKey.getKeyId().toHex()); + expect(signatures[1].keyID.toHex()).to.equal(privateSigningKey.getKeyID().toHex()); expect(signatures[1].valid).to.be.null; expect(signatures[2].userid).to.equal(publicKey.users[1].userId.userid); - expect(signatures[2].keyid.toHex()).to.equal(publicSigningKey.getKeyId().toHex()); + expect(signatures[2].keyID.toHex()).to.equal(publicSigningKey.getKeyID().toHex()); expect(signatures[2].valid).to.be.null; expect(signatures[3].userid).to.equal(publicKey.users[1].userId.userid); - expect(signatures[3].keyid.toHex()).to.equal(privateSigningKey.getKeyId().toHex()); + expect(signatures[3].keyID.toHex()).to.equal(privateSigningKey.getKeyID().toHex()); expect(signatures[3].valid).to.be.null; } finally { openpgp.config.minRSABits = minRSABits; @@ -2592,7 +2592,7 @@ function versionSpecificTests() { ).then(async function(verified) { expect(verified.signatures[0].valid).to.be.true; const newSigningKey = await newKey.getSigningKey(); - expect(verified.signatures[0].keyid.toHex()).to.equal(newSigningKey.getKeyId().toHex()); + expect(verified.signatures[0].keyID.toHex()).to.equal(newSigningKey.getKeyID().toHex()); expect(verified.signatures[0].signature.packets.length).to.equal(1); }); }); @@ -2722,15 +2722,15 @@ module.exports = () => describe('Key', function() { const pubKeys = await openpgp.readKeys({ armoredKeys: rsa_ecc_pub }); expect(pubKeys).to.exist; expect(pubKeys).to.have.length(1); - expect(pubKeys[0].getKeyId().toHex()).to.equal('b8e4105cc9dedc77'); + expect(pubKeys[0].getKeyID().toHex()).to.equal('b8e4105cc9dedc77'); }); it('Parsing armored text with two keys', async function() { const pubKeys = await openpgp.readKeys({ armoredKeys: twoKeys }); expect(pubKeys).to.exist; expect(pubKeys).to.have.length(2); - expect(pubKeys[0].getKeyId().toHex()).to.equal('4a63613a4d6e4094'); - expect(pubKeys[1].getKeyId().toHex()).to.equal('dbf223e870534df4'); + expect(pubKeys[0].getKeyID().toHex()).to.equal('4a63613a4d6e4094'); + expect(pubKeys[1].getKeyID().toHex()).to.equal('dbf223e870534df4'); }); it('Parsing armored key with an authorized revocation key in a User ID self-signature', async function() { @@ -2767,15 +2767,15 @@ module.exports = () => describe('Key', function() { const pubKeyV4 = pubKeysV4[0]; expect(pubKeyV4).to.exist; - expect(pubKeyV4.getKeyId().toHex()).to.equal('4a63613a4d6e4094'); + expect(pubKeyV4.getKeyID().toHex()).to.equal('4a63613a4d6e4094'); expect(pubKeyV4.getFingerprint()).to.equal('f470e50dcb1ad5f1e64e08644a63613a4d6e4094'); }); it('Create new key ID with fromId()', async function() { const [pubKeyV4] = await openpgp.readKeys({ armoredKeys: twoKeys }); - const keyId = pubKeyV4.getKeyId(); - const newKeyId = keyId.constructor.fromId(keyId.toHex()); - expect(newKeyId.toHex()).to.equal(keyId.toHex()); + const keyID = pubKeyV4.getKeyID(); + const newKeyID = keyID.constructor.fromId(keyID.toHex()); + expect(newKeyID.toHex()).to.equal(keyID.toHex()); }); it('Testing key method getSubkeys', async function() { @@ -2789,8 +2789,8 @@ module.exports = () => describe('Key', function() { const subkeys = pubKey.getSubkeys(); expect(subkeys).to.exist; expect(subkeys).to.have.length(2); - expect(subkeys[0].getKeyId().equals(packetlist[8].getKeyId())).to.be.true; - expect(subkeys[1].getKeyId().equals(packetlist[11].getKeyId())).to.be.true; + expect(subkeys[0].getKeyID().equals(packetlist[8].getKeyID())).to.be.true; + expect(subkeys[1].getKeyID().equals(packetlist[11].getKeyID())).to.be.true; }); it('Verify status of revoked primary key', async function() { @@ -2817,16 +2817,16 @@ module.exports = () => describe('Key', function() { const pubKey = await openpgp.readKey({ armoredKey: key_with_revoked_third_party_cert }); const [selfCertification] = await pubKey.verifyPrimaryUser(); const publicSigningKey = await pubKey.getSigningKey(); - expect(selfCertification.keyid.toHex()).to.equal(publicSigningKey.getKeyId().toHex()); + expect(selfCertification.keyID.toHex()).to.equal(publicSigningKey.getKeyID().toHex()); expect(selfCertification.valid).to.be.true; const certifyingKey = await openpgp.readKey({ armoredKey: certifying_key }); const certifyingSigningKey = await certifyingKey.getSigningKey(); const signatures = await pubKey.verifyPrimaryUser([certifyingKey]); expect(signatures.length).to.equal(2); - expect(signatures[0].keyid.toHex()).to.equal(publicSigningKey.getKeyId().toHex()); + expect(signatures[0].keyID.toHex()).to.equal(publicSigningKey.getKeyID().toHex()); expect(signatures[0].valid).to.be.null; - expect(signatures[1].keyid.toHex()).to.equal(certifyingSigningKey.getKeyId().toHex()); + expect(signatures[1].keyID.toHex()).to.equal(certifyingSigningKey.getKeyID().toHex()); expect(signatures[1].valid).to.be.false; const { user } = await pubKey.getPrimaryUser(); @@ -2926,10 +2926,10 @@ module.exports = () => describe('Key', function() { await expect(key.decrypt('userpass')).to.be.rejectedWith('Key is invalid'); }); - it("decrypt(keyId) - throw if key parameters don't correspond", async function() { + it("decrypt(keyID) - throw if key parameters don't correspond", async function() { const key = await openpgp.readKey({ armoredKey: mismatchingKeyParams }); - const subKeyId = key.subKeys[0].getKeyId(); - await expect(key.decrypt('userpass', subKeyId)).to.be.rejectedWith('Key is invalid'); + const subKeyID = key.subKeys[0].getKeyID(); + await expect(key.decrypt('userpass', subKeyID)).to.be.rejectedWith('Key is invalid'); }); it("validate() - don't throw if key parameters correspond", async function() { @@ -2961,7 +2961,7 @@ module.exports = () => describe('Key', function() { const passphrase = '12345678'; const { key } = await openpgp.generateKey({ userIds: {}, curve: 'ed25519', passphrase }); expect(key.isDecrypted()).to.be.false; - await key.decrypt(passphrase, key.subKeys[0].getKeyId()); + await key.decrypt(passphrase, key.subKeys[0].getKeyID()); expect(key.isDecrypted()).to.be.true; }); @@ -3119,8 +3119,8 @@ module.exports = () => describe('Key', function() { return dest.update(source).then(() => { expect(dest.subKeys[1]).to.exist; expect( - dest.subKeys[1].getKeyId().toHex() - ).to.equal(source.subKeys[1].getKeyId().toHex()); + dest.subKeys[1].getKeyID().toHex() + ).to.equal(source.subKeys[1].getKeyID().toHex()); }); }); @@ -3508,7 +3508,7 @@ VYGdb3eNlV8CfoEC return openpgp.encrypt({ publicKeys: [key], message: openpgp.Message.fromText('random data'), date: new Date(1386842743000) }).then(() => { throw new Error('encryptSessionKey should not encrypt with revoked public key'); }).catch(function(error) { - expect(error.message).to.equal('Error encrypting message: Could not find valid encryption key packet in key ' + key.getKeyId().toHex() + ': Subkey is revoked'); + expect(error.message).to.equal('Error encrypting message: Could not find valid encryption key packet in key ' + key.getKeyID().toHex() + ': Subkey is revoked'); }); }); @@ -3640,7 +3640,7 @@ VYGdb3eNlV8CfoEC await newPrivateKey.decrypt('12345678'); const subKey = newPrivateKey.subKeys[total]; expect(subKey.isDecrypted()).to.be.true; - expect(subKey1.getKeyId().toHex()).to.be.equal(subKey.getKeyId().toHex()); + expect(subKey1.getKeyID().toHex()).to.be.equal(subKey.getKeyID().toHex()); expect(subKey).to.exist; expect(newPrivateKey.subKeys.length).to.be.equal(total + 1); const subkeyOid = subKey.keyPacket.publicParams.oid; @@ -3734,7 +3734,7 @@ VYGdb3eNlV8CfoEC const { signatures } = await openpgp.verify({ message, publicKeys: [newPrivateKey.toPublic()] }); expect(signatures).to.exist; expect(signatures.length).to.be.equal(1); - expect(signatures[0].keyid.toHex()).to.be.equal(subKey.getKeyId().toHex()); + expect(signatures[0].keyID.toHex()).to.be.equal(subKey.getKeyID().toHex()); expect(await signatures[0].verified).to.be.true; }); @@ -3757,7 +3757,7 @@ VYGdb3eNlV8CfoEC const pkSessionKeys = message.packets.filterByTag(openpgp.enums.packet.publicKeyEncryptedSessionKey); expect(pkSessionKeys).to.exist; expect(pkSessionKeys.length).to.be.equal(1); - expect(pkSessionKeys[0].publicKeyId.toHex()).to.be.equals(subKey.keyPacket.getKeyId().toHex()); + expect(pkSessionKeys[0].publicKeyID.toHex()).to.be.equals(subKey.keyPacket.getKeyID().toHex()); const decrypted = await openpgp.decrypt({ message, privateKeys: newPrivateKey }); expect(decrypted).to.exist; expect(decrypted.data).to.be.equal(vData); @@ -3780,7 +3780,7 @@ VYGdb3eNlV8CfoEC const { signatures } = await openpgp.verify({ message, publicKeys: [newPrivateKey.toPublic()] }); expect(signatures).to.exist; expect(signatures.length).to.be.equal(1); - expect(signatures[0].keyid.toHex()).to.be.equal(subKey.getKeyId().toHex()); + expect(signatures[0].keyID.toHex()).to.be.equal(subKey.getKeyID().toHex()); expect(await signatures[0].verified).to.be.true; }); @@ -3801,7 +3801,7 @@ VYGdb3eNlV8CfoEC const pkSessionKeys = message.packets.filterByTag(openpgp.enums.packet.publicKeyEncryptedSessionKey); expect(pkSessionKeys).to.exist; expect(pkSessionKeys.length).to.be.equal(1); - expect(pkSessionKeys[0].publicKeyId.toHex()).to.be.equals(subKey.keyPacket.getKeyId().toHex()); + expect(pkSessionKeys[0].publicKeyID.toHex()).to.be.equals(subKey.keyPacket.getKeyID().toHex()); const decrypted = await openpgp.decrypt({ message, privateKeys: newPrivateKey }); expect(decrypted).to.exist; expect(decrypted.data).to.be.equal(vData); diff --git a/test/general/openpgp.js b/test/general/openpgp.js index f261dbcb3..fe28d075e 100644 --- a/test/general/openpgp.js +++ b/test/general/openpgp.js @@ -5,7 +5,7 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp const crypto = require('../../src/crypto'); const random = require('../../src/crypto/random'); const util = require('../../src/util'); -const keyIdType = require('../../src/type/keyid'); +const keyIDType = require('../../src/type/keyid'); const spy = require('sinon/lib/sinon/spy'); const input = require('./testInputs.js'); @@ -899,14 +899,14 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { privateKey: privateKey, passphrase: passphrase }).then(function(unlocked){ - expect(unlocked.getKeyId().toHex()).to.equal(privateKey.getKeyId().toHex()); - expect(unlocked.subKeys[0].getKeyId().toHex()).to.equal(privateKey.subKeys[0].getKeyId().toHex()); + expect(unlocked.getKeyID().toHex()).to.equal(privateKey.getKeyID().toHex()); + expect(unlocked.subKeys[0].getKeyID().toHex()).to.equal(privateKey.subKeys[0].getKeyID().toHex()); expect(unlocked.isDecrypted()).to.be.true; expect(unlocked.keyPacket.privateParams).to.not.be.null; // original key should be unchanged expect(privateKey.isDecrypted()).to.be.false; expect(privateKey.keyPacket.privateParams).to.be.null; - originalKey.subKeys[0].getKeyId(); // fill in keyid + originalKey.subKeys[0].getKeyID(); // fill in keyID expect(privateKey).to.deep.equal(originalKey); }); }); @@ -953,14 +953,14 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { privateKey: key, passphrase: passphrase }).then(function(locked){ - expect(locked.getKeyId().toHex()).to.equal(key.getKeyId().toHex()); - expect(locked.subKeys[0].getKeyId().toHex()).to.equal(key.subKeys[0].getKeyId().toHex()); + expect(locked.getKeyID().toHex()).to.equal(key.getKeyID().toHex()); + expect(locked.subKeys[0].getKeyID().toHex()).to.equal(key.subKeys[0].getKeyID().toHex()); expect(locked.isDecrypted()).to.be.false; expect(locked.keyPacket.privateParams).to.be.null; // original key should be unchanged expect(key.isDecrypted()).to.be.true; expect(key.keyPacket.privateParams).to.not.be.null; - originalKey.subKeys[0].getKeyId(); // fill in keyid + originalKey.subKeys[0].getKeyID(); // fill in keyID expect(key).to.deep.equal(originalKey); }); }); @@ -1416,7 +1416,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(decrypted.data).to.equal(plaintext); expect(decrypted.signatures[0].valid).to.be.true; const signingKey = await privateKey.getSigningKey(); - expect(decrypted.signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(decrypted.signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(decrypted.signatures[0].signature.packets.length).to.equal(1); }); }); @@ -1439,7 +1439,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(decrypted.data).to.equal(plaintext); expect(decrypted.signatures[0].valid).to.be.true; const signingKey = await privateKey.getSigningKey(); - expect(decrypted.signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(decrypted.signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(decrypted.signatures[0].signature.packets.length).to.equal(1); }); }); @@ -1470,7 +1470,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(decrypted.data).to.equal(plaintext); expect(decrypted.signatures[0].valid).to.be.true; const signingKey = await newPrivateKey.getSigningKey(); - expect(decrypted.signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(decrypted.signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(decrypted.signatures[0].signature.packets.length).to.equal(1); }); }); @@ -1503,7 +1503,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(decrypted.data).to.equal(plaintext); expect(decrypted.signatures[0].valid).to.be.true; const signingKey = await newPrivateKey.getSigningKey(); - expect(decrypted.signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(decrypted.signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(decrypted.signatures[0].signature.packets.length).to.equal(1); }); @@ -1524,7 +1524,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(decrypted.data).to.equal(''); expect(decrypted.signatures[0].valid).to.be.true; const signingKey = await privateKey.getSigningKey(); - expect(decrypted.signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(decrypted.signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(decrypted.signatures[0].signature.packets.length).to.equal(1); }); }); @@ -1548,7 +1548,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(decrypted.data).to.equal(plaintext); expect(decrypted.signatures[0].valid).to.be.true; const signingKey = await privateKey.getSigningKey(); - expect(decrypted.signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(decrypted.signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(decrypted.signatures[0].signature.packets.length).to.equal(1); }); @@ -1592,11 +1592,11 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(decrypted.data).to.equal(plaintext); expect(decrypted.signatures[0].valid).to.be.true; signingKey = await privateKey.getSigningKey(); - expect(decrypted.signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(decrypted.signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(decrypted.signatures[0].signature.packets.length).to.equal(1); expect(decrypted.signatures[1].valid).to.be.true; signingKey = await privKeyDE.getSigningKey(); - expect(decrypted.signatures[1].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(decrypted.signatures[1].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(decrypted.signatures[1].signature.packets.length).to.equal(1); }); } finally { @@ -1632,7 +1632,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(signatures[0].valid).to.be.false; expect(signatures[0].error).to.match(/Could not find signing key/); const signingKey = await privateKey.getSigningKey(); - expect(signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(signatures[0].signature.packets.length).to.equal(1); }); }); @@ -1655,7 +1655,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(signatures[0].valid).to.be.false; expect(signatures[0].error).to.match(/Could not find signing key/); const signingKey = await privateKey.getSigningKey(); - expect(signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(signatures[0].signature.packets.length).to.equal(1); }); }); @@ -1678,7 +1678,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(signatures[0].valid).to.be.false; expect(signatures[0].error).to.match(/Could not find signing key/); const signingKey = await privateKey.getSigningKey(); - expect(signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(signatures[0].signature.packets.length).to.equal(1); }); }); @@ -1700,7 +1700,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(signatures[0].valid).to.be.false; expect(signatures[0].error).to.match(/Could not find signing key/); const signingKey = await privateKey.getSigningKey(); - expect(signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(signatures[0].signature.packets.length).to.equal(1); }); }); @@ -1725,7 +1725,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(signatures[0].valid).to.be.false; expect(signatures[0].error).to.match(/Could not find signing key/); const signingKey = await privateKey.getSigningKey(); - expect(signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(signatures[0].signature.packets.length).to.equal(1); }); @@ -1758,11 +1758,11 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(decrypted.data).to.equal(plaintext); expect(decrypted.signatures[0].valid).to.be.true; signingKey = await privateKey.getSigningKey(); - expect(decrypted.signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(decrypted.signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(decrypted.signatures[0].signature.packets.length).to.equal(1); expect(decrypted.signatures[1].valid).to.be.true; signingKey = await privKeyDE.getSigningKey(); - expect(decrypted.signatures[1].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(decrypted.signatures[1].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(decrypted.signatures[1].signature.packets.length).to.equal(1); }); } finally { @@ -1860,7 +1860,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(decrypted.data).to.equal(plaintext); expect(decrypted.signatures[0].valid).to.be.true; const signingKey = await privKeyDE.getSigningKey(); - expect(decrypted.signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(decrypted.signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(decrypted.signatures[0].signature.packets.length).to.equal(1); }); } finally { @@ -2104,7 +2104,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(verified.data).to.equal(plaintext.replace(/[ \t]+$/mg, '')); expect(verified.signatures[0].valid).to.be.true; const signingKey = await privateKey.getSigningKey(); - expect(verified.signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(verified.signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(verified.signatures[0].signature.packets.length).to.equal(1); }); }); @@ -2134,11 +2134,11 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(verified.data).to.equal(plaintext.replace(/[ \t]+$/mg, '')); expect(verified.signatures[0].valid).to.be.true; signingKey = await privateKey.getSigningKey(); - expect(verified.signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(verified.signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(verified.signatures[0].signature.packets.length).to.equal(1); expect(verified.signatures[1].valid).to.be.true; signingKey = await privKeyDE.getSigningKey(); - expect(verified.signatures[1].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(verified.signatures[1].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(verified.signatures[1].signature.packets.length).to.equal(1); }); } finally { @@ -2164,7 +2164,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(verified.data).to.equal(plaintext); expect(verified.signatures[0].valid).to.be.true; const signingKey = await privateKey.getSigningKey(); - expect(verified.signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(verified.signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(verified.signatures[0].signature.packets.length).to.equal(1); }); }); @@ -2186,7 +2186,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(signatures[0].valid).to.be.false; expect(signatures[0].error).to.match(/Could not find signing key/); const signingKey = await privateKey.getSigningKey(); - expect(signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(signatures[0].signature.packets.length).to.equal(1); }); }); @@ -2210,7 +2210,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(signatures[0].valid).to.be.false; expect(signatures[0].error).to.match(/Could not find signing key/); const signingKey = await privateKey.getSigningKey(); - expect(signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(signatures[0].signature.packets.length).to.equal(1); }); }); @@ -2232,7 +2232,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(verified.data).to.equal(plaintext); expect(verified.signatures[0].valid).to.be.true; const signingKey = await privateKey.getSigningKey(); - expect(verified.signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(verified.signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(verified.signatures[0].signature.packets.length).to.equal(1); }); }); @@ -2259,7 +2259,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(+verified.signatures[0].signature.packets[0].created).to.be.gte(+start); expect(verified.signatures[0].valid).to.be.true; const signingKey = await privateKey.getSigningKey(); - expect(verified.signatures[0].keyid.toHex()).to.equal(signingKey.getKeyId().toHex()); + expect(verified.signatures[0].keyID.toHex()).to.equal(signingKey.getKeyID().toHex()); expect(verified.signatures[0].signature.packets.length).to.equal(1); }); }); @@ -2285,7 +2285,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(+verified.signatures[0].signature.packets[0].created).to.equal(+past); expect(verified.data).to.equal(plaintext); expect(verified.signatures[0].valid).to.be.true; - expect(await privateKey_1337.getSigningKey(verified.signatures[0].keyid, past)) + expect(await privateKey_1337.getSigningKey(verified.signatures[0].keyID, past)) .to.be.not.null; expect(verified.signatures[0].signature.packets.length).to.equal(1); // now check with expiration checking disabled @@ -2295,7 +2295,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(+verified.signatures[0].signature.packets[0].created).to.equal(+past); expect(verified.data).to.equal(plaintext); expect(verified.signatures[0].valid).to.be.true; - expect(await privateKey_1337.getSigningKey(verified.signatures[0].keyid, null)) + expect(await privateKey_1337.getSigningKey(verified.signatures[0].keyID, null)) .to.be.not.null; expect(verified.signatures[0].signature.packets.length).to.equal(1); }); @@ -2325,7 +2325,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(+verified.signatures[0].signature.packets[0].created).to.equal(+future); expect([].slice.call(verified.data)).to.deep.equal([].slice.call(data)); expect(verified.signatures[0].valid).to.be.true; - expect(await privateKey_2038_2045.getSigningKey(verified.signatures[0].keyid, future)) + expect(await privateKey_2038_2045.getSigningKey(verified.signatures[0].keyID, future)) .to.be.not.null; expect(verified.signatures[0].signature.packets.length).to.equal(1); }); @@ -2353,7 +2353,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }).then(async function (verified) { expect([].slice.call(verified.data)).to.deep.equal([].slice.call(data)); expect(verified.signatures[0].valid).to.be.true; - expect(await privateKey.getSigningKey(verified.signatures[0].keyid)) + expect(await privateKey.getSigningKey(verified.signatures[0].keyID)) .to.be.not.null; expect(verified.signatures[0].signature.packets.length).to.equal(1); }); @@ -2386,7 +2386,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(openpgp.stream.isStream(verified.data)).to.equal(useNativeStream ? 'web' : 'ponyfill'); expect([].slice.call(await openpgp.stream.readToEnd(verified.data))).to.deep.equal([].slice.call(data)); expect(await verified.signatures[0].verified).to.be.true; - expect(await privateKey.getSigningKey(verified.signatures[0].keyid)) + expect(await privateKey.getSigningKey(verified.signatures[0].keyID)) .to.be.not.null; expect((await verified.signatures[0].signature).packets.length).to.equal(1); }); @@ -2454,7 +2454,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(await openpgp.stream.readToEnd(message.getText())).to.equal(plaintext); expect(+(await signatures[0].signature).packets[0].created).to.equal(+past); expect(await signatures[0].verified).to.be.true; - expect(await privateKey_2000_2008.getSigningKey(signatures[0].keyid, past)) + expect(await privateKey_2000_2008.getSigningKey(signatures[0].keyID, past)) .to.be.not.null; expect((await signatures[0].signature).packets.length).to.equal(1); }); @@ -2483,7 +2483,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(await openpgp.stream.readToEnd(message.getLiteralData())).to.deep.equal(data); expect(+(await signatures[0].signature).packets[0].created).to.equal(+future); expect(await signatures[0].verified).to.be.true; - expect(await privateKey_2038_2045.getSigningKey(signatures[0].keyid, future)) + expect(await privateKey_2038_2045.getSigningKey(signatures[0].keyID, future)) .to.be.not.null; expect((await signatures[0].signature).packets.length).to.equal(1); }); @@ -2512,7 +2512,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(await openpgp.stream.readToEnd(message.getLiteralData())).to.deep.equal(data); expect(+(await signatures[0].signature).packets[0].created).to.equal(+future); expect(await signatures[0].verified).to.be.true; - expect(await privateKey_2038_2045.getSigningKey(signatures[0].keyid, future)) + expect(await privateKey_2038_2045.getSigningKey(signatures[0].keyID, future)) .to.be.not.null; expect((await signatures[0].signature).packets.length).to.equal(1); }); @@ -2837,15 +2837,15 @@ bsZgJWVlAa5eil6J9ePX2xbo1vVAkLQdzE9+1jL+l7PRIZuVBQ== }); describe('Specific encryption/signing key testing', async function () { - const encryptionKeyIds = [ - keyIdType.fromId("87EAE0977B2185EA"), - keyIdType.fromId("F94F9B34AF93FA14"), - keyIdType.fromId("08F7D4C7C59545C0") + const encryptionKeyIDs = [ + keyIDType.fromId("87EAE0977B2185EA"), + keyIDType.fromId("F94F9B34AF93FA14"), + keyIDType.fromId("08F7D4C7C59545C0") ]; - const signingKeyIds = [ - keyIdType.fromId("663277AF60400638"), - keyIdType.fromId("BBE14491E6EE6366"), - keyIdType.fromId("3E0F20F1A71D6DFD") + const signingKeyIDs = [ + keyIDType.fromId("663277AF60400638"), + keyIDType.fromId("BBE14491E6EE6366"), + keyIDType.fromId("3E0F20F1A71D6DFD") ]; const getPrimaryKey = async () => openpgp.readKey({ armoredKey: multipleEncryptionAndSigningSubkeys @@ -2855,17 +2855,17 @@ bsZgJWVlAa5eil6J9ePX2xbo1vVAkLQdzE9+1jL+l7PRIZuVBQ== const primaryKey = await getPrimaryKey(); let m; let p; - for (let i = 0; i < encryptionKeyIds.length; i++) { + for (let i = 0; i < encryptionKeyIDs.length; i++) { m = await openpgp.readMessage({ armoredMessage: await openpgp.encrypt({ message: openpgp.Message.fromText("Hello World\n"), publicKeys: primaryKey, - encryptionKeyIds: [encryptionKeyIds[i]] + encryptionKeyIDs: [encryptionKeyIDs[i]] }) }); p = m.packets.filterByTag(openpgp.enums.packet.publicKeyEncryptedSessionKey); expect(p.length).equals(1); - expect(p[0].publicKeyId.equals(encryptionKeyIds[i])).to.be.true; + expect(p[0].publicKeyID.equals(encryptionKeyIDs[i])).to.be.true; } }); @@ -2873,18 +2873,18 @@ bsZgJWVlAa5eil6J9ePX2xbo1vVAkLQdzE9+1jL+l7PRIZuVBQ== const primaryKey = await getPrimaryKey(); let s; let p; - for (let i = 0; i < signingKeyIds.length; i++) { + for (let i = 0; i < signingKeyIDs.length; i++) { s = await openpgp.readSignature({ armoredSignature: await openpgp.sign({ message: openpgp.Message.fromText("Hello World\n"), privateKeys: primaryKey, - signingKeyIds: [signingKeyIds[i]], + signingKeyIDs: [signingKeyIDs[i]], detached: true }) }); p = s.packets.filterByTag(openpgp.enums.packet.signature); expect(p.length).equals(1); - expect(p[0].issuerKeyId.equals(signingKeyIds[i])).to.be.true; + expect(p[0].issuerKeyID.equals(signingKeyIDs[i])).to.be.true; } }); @@ -2892,26 +2892,26 @@ bsZgJWVlAa5eil6J9ePX2xbo1vVAkLQdzE9+1jL+l7PRIZuVBQ== const primaryKey = await getPrimaryKey(); const plaintextMessage = openpgp.Message.fromText("Hello World\n"); - const checkEncryptedPackets = (encryptionKeyIds, pKESKList) => { - pKESKList.forEach(({ publicKeyId }, i) => { - expect(publicKeyId.equals(encryptionKeyIds[i])).to.be.true; + const checkEncryptedPackets = (encryptionKeyIDs, pKESKList) => { + pKESKList.forEach(({ publicKeyID }, i) => { + expect(publicKeyID.equals(encryptionKeyIDs[i])).to.be.true; }); }; - const checkSignatures = (signingKeyIds, signatures) => { - signatures.forEach(({ keyid }, i) => { - expect(keyid.equals(signingKeyIds[i])).to.be.true; + const checkSignatures = (signingKeyIDs, signatures) => { + signatures.forEach(({ keyID }, i) => { + expect(keyID.equals(signingKeyIDs[i])).to.be.true; }); }; - const kIds = [encryptionKeyIds[1], encryptionKeyIds[0], encryptionKeyIds[2]]; - const sIds = [signingKeyIds[2], signingKeyIds[1], signingKeyIds[0]]; + const kIds = [encryptionKeyIDs[1], encryptionKeyIDs[0], encryptionKeyIDs[2]]; + const sIds = [signingKeyIDs[2], signingKeyIDs[1], signingKeyIDs[0]]; const message = await openpgp.readMessage({ armoredMessage: await openpgp.encrypt({ message: plaintextMessage, privateKeys: [primaryKey, primaryKey, primaryKey], publicKeys: [primaryKey, primaryKey, primaryKey], - encryptionKeyIds: kIds, - signingKeyIds: sIds + encryptionKeyIDs: kIds, + signingKeyIDs: sIds }) }); const pKESKList = message.packets.filterByTag(openpgp.enums.packet.publicKeyEncryptedSessionKey); diff --git a/test/general/packet.js b/test/general/packet.js index 41dbe808c..f09e38ad4 100644 --- a/test/general/packet.js +++ b/test/general/packet.js @@ -315,7 +315,7 @@ module.exports = () => describe("Packet", function() { 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'; enc.sessionKeyAlgorithm = 'aes256'; - enc.publicKeyId.bytes = '12345678'; + enc.publicKeyID.bytes = '12345678'; return enc.encrypt({ publicParams, getFingerprintBytes() {} }).then(async () => { msg.push(enc); @@ -362,7 +362,7 @@ module.exports = () => describe("Packet", function() { enc.sessionKey = secret; enc.publicKeyAlgorithm = 'rsaEncryptSign'; enc.sessionKeyAlgorithm = 'aes256'; - enc.publicKeyId.bytes = '12345678'; + enc.publicKeyID.bytes = '12345678'; return enc.encrypt(key).then(() => { return enc.decrypt(key).then(() => { diff --git a/test/general/signature.js b/test/general/signature.js index c96c3cdfa..298e1f2be 100644 --- a/test/general/signature.js +++ b/test/general/signature.js @@ -971,7 +971,7 @@ hUhMKMuiM3pRwdIyDOItkUWQmjEEw7/XmhgInkXsCw== const pubKey = await openpgp.readKey({ armoredKey: pub_key_arm2 }); const privKey = await openpgp.readKey({ armoredKey: priv_key_arm2 }); - await Promise.all(esMsg.getEncryptionKeyIds().map(keyId => privKey.decrypt('hello world', keyId))); + await Promise.all(esMsg.getEncryptionKeyIDs().map(keyID => privKey.decrypt('hello world', keyID))); return openpgp.decrypt({ privateKeys: privKey, publicKeys:[pubKey], message:esMsg, config: { minRSABits: 1024 } }).then(function(decrypted) { expect(decrypted.data).to.exist; @@ -1005,9 +1005,9 @@ hUhMKMuiM3pRwdIyDOItkUWQmjEEw7/XmhgInkXsCw== const pubKey2 = await openpgp.readKey({ armoredKey: pub_key_arm2 }); const pubKey3 = await openpgp.readKey({ armoredKey: pub_key_arm3 }); - const keyids = sMsg.getSigningKeyIds(); - expect(pubKey2.getKeys(keyids[1])).to.not.be.empty; - expect(pubKey3.getKeys(keyids[0])).to.not.be.empty; + const keyIDs = sMsg.getSigningKeyIDs(); + expect(pubKey2.getKeys(keyIDs[1])).to.not.be.empty; + expect(pubKey3.getKeys(keyIDs[0])).to.not.be.empty; const { data, signatures } = await openpgp.verify({ message: sMsg, publicKeys: [pubKey2, pubKey3], config: { minRSABits: 1024 } }); expect(data).to.equal(plaintext); @@ -1065,10 +1065,10 @@ hUhMKMuiM3pRwdIyDOItkUWQmjEEw7/XmhgInkXsCw== const pubKey2 = await openpgp.readKey({ armoredKey: pub_key_arm2 }); const pubKey3 = await openpgp.readKey({ armoredKey: pub_key_arm3 }); - const keyids = message.getSigningKeyIds(); + const keyIDs = message.getSigningKeyIDs(); - expect(pubKey2.getKeys(keyids[0])).to.not.be.empty; - expect(pubKey3.getKeys(keyids[1])).to.not.be.empty; + expect(pubKey2.getKeys(keyIDs[0])).to.not.be.empty; + expect(pubKey3.getKeys(keyIDs[1])).to.not.be.empty; return openpgp.verify({ publicKeys:[pubKey2, pubKey3], message, config: { minRSABits: 1024 } }).then(function(cleartextSig) { expect(cleartextSig).to.exist; @@ -1139,9 +1139,9 @@ zmuVOdNuWQqxT9Sqa84= const message = await openpgp.readCleartextMessage({ cleartextMessage }); const pubKey = await openpgp.readKey({ armoredKey: pub_key_arm2 }); - const keyids = message.getSigningKeyIds(); + const keyIDs = message.getSigningKeyIDs(); - expect(pubKey.getKeys(keyids[0])).to.not.be.empty; + expect(pubKey.getKeys(keyIDs[0])).to.not.be.empty; const cleartextSig = await openpgp.verify({ publicKeys:[pubKey], @@ -1174,8 +1174,8 @@ yYDnCgA= const message = await openpgp.readMessage({ armoredMessage }); const pubKey = await openpgp.readKey({ armoredKey: pub_key_arm2 }); - const keyids = message.getSigningKeyIds(); - expect(pubKey.getKeys(keyids[0])).to.not.be.empty; + const keyIDs = message.getSigningKeyIDs(); + expect(pubKey.getKeys(keyIDs[0])).to.not.be.empty; return openpgp.verify({ publicKeys: [pubKey], message, config: { minRSABits: 1024 } }).then(({ data, signatures }) => { expect(data).to.equal(plaintext); @@ -1211,8 +1211,8 @@ yYDnCgA= }); const pubKey = await openpgp.readKey({ armoredKey: pub_key_arm2 }); - const keyids = message.getSigningKeyIds(); - expect(pubKey.getKeys(keyids[0])).to.not.be.empty; + const keyIDs = message.getSigningKeyIDs(); + expect(pubKey.getKeys(keyIDs[0])).to.not.be.empty; return openpgp.verify({ publicKeys: [pubKey], message, config: { minRSABits: 1024 } }).then(async function(cleartextSig) { expect(cleartextSig).to.exist; @@ -1243,8 +1243,8 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA const message = await openpgp.readMessage({ armoredMessage }); const pubKey = await openpgp.readKey({ armoredKey: pub_key_arm2 }); - const keyids = message.getSigningKeyIds(); - expect(pubKey.getKeys(keyids[0])).to.not.be.empty; + const keyIDs = message.getSigningKeyIDs(); + expect(pubKey.getKeys(keyIDs[0])).to.not.be.empty; return openpgp.verify({ publicKeys: [pubKey], message, config: { minRSABits: 1024 } }).then(async ({ data, signatures }) => { expect(data).to.equal(plaintext); @@ -1276,8 +1276,8 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA }); const pubKey = await openpgp.readKey({ armoredKey: pub_key_arm2 }); - const keyids = message.getSigningKeyIds(); - expect(pubKey.getKeys(keyids[0])).to.not.be.empty; + const keyIDs = message.getSigningKeyIDs(); + expect(pubKey.getKeys(keyIDs[0])).to.not.be.empty; return openpgp.verify({ publicKeys: [pubKey], message, config: { minRSABits: 1024 } }).then(async ({ data, signatures }) => { expect(await openpgp.stream.readToEnd(data)).to.equal(plaintext); @@ -1632,9 +1632,9 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA const signerKey = await openpgp.readKey({ armoredKey: priv_key_arm1 }); return signedKey.verifyPrimaryUser([signerKey], undefined, undefined, { ...openpgp.config, rejectPublicKeyAlgorithms: new Set() }).then(signatures => { expect(signatures[0].valid).to.be.null; - expect(signatures[0].keyid.toHex()).to.equal(signedKey.getKeyId().toHex()); + expect(signatures[0].keyID.toHex()).to.equal(signedKey.getKeyID().toHex()); expect(signatures[1].valid).to.be.true; - expect(signatures[1].keyid.toHex()).to.equal(signerKey.getKeyId().toHex()); + expect(signatures[1].keyID.toHex()).to.equal(signerKey.getKeyID().toHex()); }); }); diff --git a/test/general/x25519.js b/test/general/x25519.js index d10cc5c62..19a08742e 100644 --- a/test/general/x25519.js +++ b/test/general/x25519.js @@ -128,7 +128,7 @@ module.exports = () => (openpgp.config.ci ? describe.skip : describe)('X25519 Cr } const pub = await openpgp.readKey({ armoredKey: data[name].pub }); expect(pub).to.exist; - expect(pub.getKeyId().toHex()).to.equal(data[name].id); + expect(pub.getKeyID().toHex()).to.equal(data[name].id); data[name].pub_key = pub; return pub; } @@ -139,7 +139,7 @@ module.exports = () => (openpgp.config.ci ? describe.skip : describe)('X25519 Cr } const pk = await openpgp.readKey({ armoredKey: data[name].priv }); expect(pk).to.exist; - expect(pk.getKeyId().toHex()).to.equal(data[name].id); + expect(pk.getKeyID().toHex()).to.equal(data[name].id); await pk.decrypt(data[name].pass); data[name].priv_key = pk; return pk; diff --git a/test/security/subkey_trust.js b/test/security/subkey_trust.js index 3293e2838..8b9634f5d 100644 --- a/test/security/subkey_trust.js +++ b/test/security/subkey_trust.js @@ -71,7 +71,7 @@ async function testSubkeyTrust() { publicKeys: fakeKey, streaming: false }); - expect(verifyAttackerIsBatman.signatures[0].keyid.equals(victimPubKey.subKeys[0].getKeyId())).to.be.true; + expect(verifyAttackerIsBatman.signatures[0].keyID.equals(victimPubKey.subKeys[0].getKeyID())).to.be.true; expect(verifyAttackerIsBatman.signatures[0].valid).to.be.false; expect(verifyAttackerIsBatman.signatures[0].error).to.match(/Could not find valid signing key packet/); } From 3e36049a5ba561d0ee779655cc0ee0c7f1609d55 Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Thu, 18 Mar 2021 20:46:49 +0100 Subject: [PATCH 03/18] Uniform userID casing --- README.md | 6 +- openpgp.d.ts | 48 +++--- src/cleartext.js | 6 +- src/config/config.js | 2 +- src/enums.js | 6 +- src/key/factory.js | 16 +- src/key/helper.js | 24 +-- src/key/key.js | 88 +++++------ src/key/user.js | 16 +- src/message.js | 52 +++--- src/openpgp.js | 58 +++---- src/packet/signature.js | 16 +- src/packet/userid.js | 28 ++-- test/crypto/validate.js | 12 +- test/general/brainpool.js | 4 +- test/general/config.js | 44 +++--- test/general/ecc_nist.js | 10 +- test/general/ecc_secp256k1.js | 14 +- test/general/key.js | 278 ++++++++++++++++----------------- test/general/openpgp.js | 42 ++--- test/general/packet.js | 8 +- test/general/signature.js | 8 +- test/general/x25519.js | 10 +- test/security/subkey_trust.js | 4 +- test/typescript/definitions.ts | 2 +- 25 files changed, 401 insertions(+), 401 deletions(-) diff --git a/README.md b/README.md index f62600914..759cb058b 100644 --- a/README.md +++ b/README.md @@ -139,7 +139,7 @@ To test whether the lazy loading works, try to generate a key with a non-standar ```js import { generateKey } from 'openpgp/lightweight'; -await generateKey({ curve: 'brainpoolP512r1', userIds: [{ name: 'Test', email: 'test@test.com' }] }); +await generateKey({ curve: 'brainpoolP512r1', userIDs: [{ name: 'Test', email: 'test@test.com' }] }); ``` For more examples of how to generate a key, see [Generate new key pair](#generate-new-key-pair). It is recommended to use `curve25519` instead of `brainpoolP512r1` by default. @@ -395,7 +395,7 @@ and a subkey for encryption using Curve25519. const { privateKeyArmored, publicKeyArmored, revocationCertificate } = await openpgp.generateKey({ type: 'ecc', // Type of the key, defaults to ECC curve: 'curve25519', // ECC curve name, defaults to curve25519 - userIds: [{ name: 'Jon Smith', email: 'jon@example.com' }], // you can pass multiple user IDs + userIDs: [{ name: 'Jon Smith', email: 'jon@example.com' }], // you can pass multiple user IDs passphrase: 'super long and hard to guess secret' // protects the private key }); @@ -412,7 +412,7 @@ RSA keys (increased compatibility): const key = await openpgp.generateKey({ type: 'rsa', // Type of the key rsaBits: 4096, // RSA key size (defaults to 4096 bits) - userIds: [{ name: 'Jon Smith', email: 'jon@example.com' }], // you can pass multiple user IDs + userIDs: [{ name: 'Jon Smith', email: 'jon@example.com' }], // you can pass multiple user IDs passphrase: 'super long and hard to guess secret' // protects the private key }); })(); diff --git a/openpgp.d.ts b/openpgp.d.ts index 7aeeba3bb..510e3b3f9 100644 --- a/openpgp.d.ts +++ b/openpgp.d.ts @@ -14,10 +14,10 @@ export function readKey(options: { binaryKey: Uint8Array, config?: PartialConfig export function readKeys(options: { armoredKeys: string, config?: PartialConfig }): Promise; export function readKeys(options: { binaryKeys: Uint8Array, config?: PartialConfig }): Promise; export function generateKey(options: KeyOptions): Promise; -export function generateSessionKey(options: { publicKeys: Key[], date?: Date, toUserIds?: UserID[], config?: PartialConfig }): Promise; +export function generateSessionKey(options: { publicKeys: Key[], date?: Date, toUserIDs?: UserID[], config?: PartialConfig }): Promise; export function decryptKey(options: { privateKey: Key; passphrase?: string | string[]; config?: PartialConfig }): Promise; export function encryptKey(options: { privateKey: Key; passphrase?: string | string[]; config?: PartialConfig }): Promise; -export function reformatKey(options: { privateKey: Key; userIds?: UserID|UserID[]; passphrase?: string; keyExpirationTime?: number; config?: PartialConfig }): Promise; +export function reformatKey(options: { privateKey: Key; userIDs?: UserID|UserID[]; passphrase?: string; keyExpirationTime?: number; config?: PartialConfig }): Promise; export class Key { constructor(packetlist: PacketList); @@ -30,24 +30,24 @@ export class Key { public armor(config?: Config): string; public decrypt(passphrase: string | string[], keyID?: KeyID, config?: Config): Promise; // throws on error public encrypt(passphrase: string | string[], keyID?: KeyID, config?: Config): Promise; // throws on error - public getExpirationTime(capability?: 'encrypt' | 'encrypt_sign' | 'sign', keyID?: KeyID, userId?: UserID, config?: Config): Promise; // Returns null if `capabilities` is passed and the key does not have the specified capabilities or is revoked or invalid. + public getExpirationTime(capability?: 'encrypt' | 'encrypt_sign' | 'sign', keyID?: KeyID, userID?: UserID, config?: Config): Promise; // Returns null if `capabilities` is passed and the key does not have the specified capabilities or is revoked or invalid. public getKeyIDs(): KeyID[]; - public getPrimaryUser(date?: Date, userId?: UserID, config?: Config): Promise; // throws on error - public getUserIds(): string[]; + public getPrimaryUser(date?: Date, userID?: UserID, config?: Config): Promise; // throws on error + public getUserIDs(): string[]; public isPrivate(): boolean; public isPublic(): boolean; public toPublic(): Key; public update(key: Key, config?: Config): void; - public signPrimaryUser(privateKeys: Key[], date?: Date, userId?: UserID, config?: Config): Promise + public signPrimaryUser(privateKeys: Key[], date?: Date, userID?: UserID, config?: Config): Promise public signAllUsers(privateKeys: Key[], config?: Config): Promise - public verifyPrimaryKey(date?: Date, userId?: UserID, config?: Config): Promise; // throws on error - public verifyPrimaryUser(publicKeys: Key[], date?: Date, userIds?: UserID, config?: Config): Promise<{ keyID: KeyID, valid: boolean | null }[]>; - public verifyAllUsers(publicKeys: Key[], config?: Config): Promise<{ userid: string, keyID: KeyID, valid: boolean | null }[]>; + public verifyPrimaryKey(date?: Date, userID?: UserID, config?: Config): Promise; // throws on error + public verifyPrimaryUser(publicKeys: Key[], date?: Date, userIDs?: UserID, config?: Config): Promise<{ keyID: KeyID, valid: boolean | null }[]>; + public verifyAllUsers(publicKeys: Key[], config?: Config): Promise<{ userID: string, keyID: KeyID, valid: boolean | null }[]>; public isRevoked(signature: SignaturePacket, key?: AnyKeyPacket, date?: Date, config?: Config): Promise; public revoke(reason: { flag?: enums.reasonForRevocation; string?: string; }, date?: Date, config?: Config): Promise; public getRevocationCertificate(date?: Date, config?: Config): Promise | string | undefined>; - public getEncryptionKey(keyID?: KeyID, date?: Date | null, userId?: UserID, config?: Config): Promise; - public getSigningKey(keyID?: KeyID, date?: Date | null, userId?: UserID, config?: Config): Promise; + public getEncryptionKey(keyID?: KeyID, date?: Date | null, userID?: UserID, config?: Config): Promise; + public getSigningKey(keyID?: KeyID, date?: Date | null, userID?: UserID, config?: Config): Promise; public getKeys(keyID?: KeyID): (Key | SubKey)[]; public getSubkeys(keyID?: KeyID): SubKey[]; public isDecrypted(): boolean; @@ -72,7 +72,7 @@ export class SubKey { } export interface User { - userId: UserIDPacket | null; + userID: UserIDPacket | null; userAttribute: UserAttributePacket | null; selfCertifications: SignaturePacket[]; otherCertifications: SignaturePacket[]; @@ -131,7 +131,7 @@ export class CleartextMessage { * * @param privateKeys private keys with decrypted secret key data for signing */ - sign(privateKeys: Key[], signature?: Signature, signingKeyIDs?: KeyID[], date?: Date, userIds?: UserID[], config?: Config): void; + sign(privateKeys: Key[], signature?: Signature, signingKeyIDs?: KeyID[], date?: Date, userIDs?: UserID[], config?: Config): void; /** Verify signatures of cleartext signed message * @param keys array of keys to verify signatures @@ -262,7 +262,7 @@ export class Message> { /** Encrypt the message @param keys array of keys, used to encrypt the message */ - public encrypt(keys?: Key[], passwords?: string[], sessionKeys?: SessionKey[], wildcard?: boolean, encryptionKeyIDs?: KeyID[], date?: Date, userIds?: UserID[], streaming?: boolean, config?: Config): Promise>>; + public encrypt(keys?: Key[], passwords?: string[], sessionKeys?: SessionKey[], wildcard?: boolean, encryptionKeyIDs?: KeyID[], date?: Date, userIDs?: UserID[], streaming?: boolean, config?: Config): Promise>>; /** Returns the key IDs of the keys to which the session key is encrypted */ @@ -285,7 +285,7 @@ export class Message> { /** Sign the message (the literal data packet of the message) @param privateKey private keys with decrypted secret key data for signing */ - public sign(privateKey: Key[], signature?: Signature, signingKeyIDs?: KeyID[], date?: Date, userIds?: UserID[], streaming?: boolean, config?: Config): Promise>; + public sign(privateKey: Key[], signature?: Signature, signingKeyIDs?: KeyID[], date?: Date, userIDs?: UserID[], streaming?: boolean, config?: Config): Promise>; /** Unwrap compressed message */ @@ -433,8 +433,8 @@ export class UserIDPacket extends BasePacket { public readonly name: string; public readonly comment: string; public readonly email: string; - public readonly userid: string; - static fromObject(userId: UserID): UserIDPacket; + public readonly userID: string; + static fromObject(userID: UserID): UserIDPacket; } export class SignaturePacket extends BasePacket { @@ -469,7 +469,7 @@ export class SignaturePacket extends BasePacket { public isPrimaryUserID: null | boolean; public policyURI: null | string; public keyFlags: Uint8Array | null; - public signersUserId: null | string; + public signersUserID: null | string; public reasonForRevocationFlag: null | enums.reasonForRevocation; public reasonForRevocationString: null | string; public features: Uint8Array | null; @@ -572,9 +572,9 @@ interface EncryptOptions { /** (optional) use a key ID of 0 instead of the public key IDs */ wildcard?: boolean; /** (optional) user ID to sign with, e.g. { name:'Steve Sender', email:'steve@openpgp.org' } */ - fromUserId?: UserID; + fromUserID?: UserID; /** (optional) user ID to encrypt for, e.g. { name:'Robert Receiver', email:'robert@openpgp.org' } */ - toUserId?: UserID; + toUserID?: UserID; config?: PartialConfig; } @@ -608,7 +608,7 @@ interface SignOptions { dataType?: DataPacketType; detached?: boolean; date?: Date; - fromUserId?: UserID; + fromUserID?: UserID; config?: PartialConfig; } @@ -638,7 +638,7 @@ interface KeyPair { export type EllipticCurveName = 'ed25519' | 'curve25519' | 'p256' | 'p384' | 'p521' | 'secp256k1' | 'brainpoolP256r1' | 'brainpoolP384r1' | 'brainpoolP512r1'; interface KeyOptions { - userIds: UserID|UserID[]; + userIDs: UserID|UserID[]; passphrase?: string; type?: 'ecc' | 'rsa'; curve?: EllipticCurveName; @@ -717,7 +717,7 @@ export namespace enums { keySuperseded = 1, // Key is superseded (key revocations) keyCompromised = 2, // Key material has been compromised (key revocations) keyRetired = 3, // Key is retired and no longer used (key revocations) - useridInvalid = 32, // User ID information is no longer valid (cert revocations) + userIDInvalid = 32, // User ID information is no longer valid (cert revocations) } export type compressionNames = 'uncompressed' | 'zip' | 'zlib' | 'bzip2'; @@ -740,7 +740,7 @@ export namespace enums { } export type packetNames = 'publicKeyEncryptedSessionKey' | 'signature' | 'symEncryptedSessionKey' | 'onePassSignature' | 'secretKey' | 'publicKey' - | 'secretSubkey' | 'compressed' | 'symmetricallyEncrypted' | 'marker' | 'literal' | 'trust' | 'userid' | 'publicSubkey' | 'userAttribute' + | 'secretSubkey' | 'compressed' | 'symmetricallyEncrypted' | 'marker' | 'literal' | 'trust' | 'userID' | 'publicSubkey' | 'userAttribute' | 'symEncryptedIntegrityProtected' | 'modificationDetectionCode' | 'AEADEncryptedDataPacket'; enum packet { publicKeyEncryptedSessionKey = 1, diff --git a/src/cleartext.js b/src/cleartext.js index b04220863..93002add5 100644 --- a/src/cleartext.js +++ b/src/cleartext.js @@ -60,15 +60,15 @@ export class CleartextMessage { * @param {Signature} [signature] - Any existing detached signature * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] * @param {Date} [date] - The creation time of the signature that should be created - * @param {Array} [userIds] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {CleartextMessage} New cleartext message with signed content. * @async */ - async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIds = [], config = defaultConfig) { + async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) { const literalDataPacket = new LiteralDataPacket(); literalDataPacket.setText(this.text); - const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIds, true, undefined, config)); + const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, true, undefined, config)); return new CleartextMessage(this.text, newSignature); } diff --git a/src/config/config.js b/src/config/config.js index 305ac082f..56be4c200 100644 --- a/src/config/config.js +++ b/src/config/config.js @@ -162,7 +162,7 @@ export default { commentString: "https://openpgpjs.org", /** - * Max userid string length (used for parsing) + * Max userID string length (used for parsing) * @memberof module:config * @property {Integer} maxUserIDLength */ diff --git a/src/enums.js b/src/enums.js index 3b4280a43..592d61895 100644 --- a/src/enums.js +++ b/src/enums.js @@ -367,10 +367,10 @@ export default { preferredCompressionAlgorithms: 22, keyServerPreferences: 23, preferredKeyServer: 24, - primaryUserId: 25, + primaryUserID: 25, policyUri: 26, keyFlags: 27, - signersUserId: 28, + signersUserID: 28, reasonForRevocation: 29, features: 30, signatureTarget: 31, @@ -430,7 +430,7 @@ export default { /** Key is retired and no longer used (key revocations) */ keyRetired: 3, /** User ID information is no longer valid (cert revocations) */ - userIdInvalid: 32 + userIDInvalid: 32 }, /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25} diff --git a/src/key/factory.js b/src/key/factory.js index 37c1c3ab6..0b3c29d86 100644 --- a/src/key/factory.js +++ b/src/key/factory.js @@ -29,7 +29,7 @@ import { unarmor } from '../encoding/armor'; * @param {ecc|rsa} options.type The primary key algorithm type: ECC or RSA * @param {String} options.curve Elliptic curve for ECC keys * @param {Integer} options.rsaBits Number of bits for RSA keys - * @param {Array} options.userIds User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } + * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } * @param {String} options.passphrase Passphrase used to encrypt the resulting private key * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires * @param {Date} options.date Creation date of the key and the key signatures @@ -53,7 +53,7 @@ export async function generate(options, config) { /** * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys. * @param {Key} options.privateKey The private key to reformat - * @param {Array} options.userIds User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } + * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } * @param {String} options.passphrase Passphrase used to encrypt the resulting private key * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires * @param {Date} options.date Override the creation date of the key and the key signatures @@ -133,14 +133,14 @@ async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, conf packetlist.push(secretKeyPacket); - await Promise.all(options.userIds.map(async function(userId, index) { + await Promise.all(options.userIDs.map(async function(userID, index) { function createPreferredAlgos(algos, preferredAlgo) { return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)]; } - const userIdPacket = UserIDPacket.fromObject(userId); + const userIDPacket = UserIDPacket.fromObject(userID); const dataToSign = {}; - dataToSign.userId = userIdPacket; + dataToSign.userID = userIDPacket; dataToSign.key = secretKeyPacket; const signaturePacket = new SignaturePacket(options.date); signaturePacket.signatureType = enums.signature.certGeneric; @@ -187,10 +187,10 @@ async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, conf } await signaturePacket.sign(secretKeyPacket, dataToSign); - return { userIdPacket, signaturePacket }; + return { userIDPacket, signaturePacket }; })).then(list => { - list.forEach(({ userIdPacket, signaturePacket }) => { - packetlist.push(userIdPacket); + list.forEach(({ userIDPacket, signaturePacket }) => { + packetlist.push(userIDPacket); packetlist.push(signaturePacket); }); }); diff --git a/src/key/helper.js b/src/key/helper.js index 2e11400cc..ec98021eb 100644 --- a/src/key/helper.js +++ b/src/key/helper.js @@ -126,16 +126,16 @@ export async function createBindingSignature(subkey, primaryKey, options, config * @param {Key} [key] - The key to get preferences from * @param {SecretKeyPacket|SecretSubkeyPacket} keyPacket - key packet used for signing * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userId] - User ID + * @param {Object} [userID] - User ID * @param {Object} config - full configuration * @returns {String} * @async */ -export async function getPreferredHashAlgo(key, keyPacket, date = new Date(), userId = {}, config) { +export async function getPreferredHashAlgo(key, keyPacket, date = new Date(), userID = {}, config) { let hash_algo = config.preferredHashAlgorithm; let pref_algo = hash_algo; if (key) { - const primaryUser = await key.getPrimaryUser(date, userId, config); + const primaryUser = await key.getPrimaryUser(date, userID, config); if (primaryUser.selfCertification.preferredHashAlgorithms) { [pref_algo] = primaryUser.selfCertification.preferredHashAlgorithms; hash_algo = crypto.hash.getHashByteLength(hash_algo) <= crypto.hash.getHashByteLength(pref_algo) ? @@ -163,12 +163,12 @@ export async function getPreferredHashAlgo(key, keyPacket, date = new Date(), us * @param {symmetric|aead|compression} type - Type of preference to return * @param {Array} [keys] - Set of keys * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Array} [userIds] - User IDs + * @param {Array} [userIDs] - User IDs * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {module:enums.symmetric|aead|compression} Preferred algorithm * @async */ -export async function getPreferredAlgo(type, keys = [], date = new Date(), userIds = [], config = defaultConfig) { +export async function getPreferredAlgo(type, keys = [], date = new Date(), userIDs = [], config = defaultConfig) { const defaultAlgo = { // these are all must-implement in rfc4880bis 'symmetric': enums.symmetric.aes128, 'aead': enums.aead.eax, @@ -189,7 +189,7 @@ export async function getPreferredAlgo(type, keys = [], date = new Date(), userI // otherwise we use the default algo // if no keys are available, preferredSenderAlgo is returned const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) { - const primaryUser = await key.getPrimaryUser(date, userIds[i], config); + const primaryUser = await key.getPrimaryUser(date, userIDs[i], config); const recipientPrefs = primaryUser.selfCertification[prefPropertyName]; return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0; })); @@ -203,14 +203,14 @@ export async function getPreferredAlgo(type, keys = [], date = new Date(), userI * SecretSubkeyPacket} signingKeyPacket secret key packet for signing * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing * @param {Date} [date] - Override the creationtime of the signature - * @param {Object} [userId] - User ID + * @param {Object} [userID] - User ID * @param {Object} [detached] - Whether to create a detached signature packet * @param {Boolean} [streaming] - Whether to process data as a stream * @param {Object} config - full configuration * @returns {SignaturePacket} Signature packet. * @async */ -export async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userId, detached = false, streaming = false, config) { +export async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userID, detached = false, streaming = false, config) { if (signingKeyPacket.isDummy()) { throw new Error('Cannot sign with a gnu-dummy key.'); } @@ -220,7 +220,7 @@ export async function createSignaturePacket(dataToSign, privateKey, signingKeyPa const signaturePacket = new SignaturePacket(date); Object.assign(signaturePacket, signatureProperties); signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; - signaturePacket.hashAlgorithm = await getPreferredHashAlgo(privateKey, signingKeyPacket, date, userId, config); + signaturePacket.hashAlgorithm = await getPreferredHashAlgo(privateKey, signingKeyPacket, date, userID, config); await signaturePacket.sign(signingKeyPacket, dataToSign, detached, streaming); return signaturePacket; } @@ -313,16 +313,16 @@ export function getExpirationTime(keyPacket, signature) { * Returns whether aead is supported by all keys in the set * @param {Array} keys - Set of keys * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Array} [userIds] - User IDs + * @param {Array} [userIDs] - User IDs * @param {Object} config - full configuration * @returns {Boolean} * @async */ -export async function isAeadSupported(keys, date = new Date(), userIds = [], config = defaultConfig) { +export async function isAeadSupported(keys, date = new Date(), userIDs = [], config = defaultConfig) { let supported = true; // TODO replace when Promise.some or Promise.any are implemented await Promise.all(keys.map(async function(key, i) { - const primaryUser = await key.getPrimaryUser(date, userIds[i], config); + const primaryUser = await key.getPrimaryUser(date, userIDs[i], config); if (!primaryUser.selfCertification.features || !(primaryUser.selfCertification.features[0] & enums.features.aead)) { supported = false; diff --git a/src/key/key.js b/src/key/key.js index 10fff8435..159df8ae8 100644 --- a/src/key/key.js +++ b/src/key/key.js @@ -202,13 +202,13 @@ class Key { } /** - * Returns userids - * @returns {Array} Array of userids. + * Returns userIDs + * @returns {Array} Array of userIDs. */ - getUserIds() { + getUserIDs() { return this.users.map(user => { - return user.userId ? user.userId.userid : null; - }).filter(userid => userid !== null); + return user.userID ? user.userID.userID : null; + }).filter(userID => userID !== null); } /** @@ -281,13 +281,13 @@ class Key { * Returns last created key or key by given keyID that is available for signing and verification * @param {module:type/keyid~KeyID} keyID, optional * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} userId, optional user ID + * @param {Object} userID, optional user ID * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Key|SubKey|null} Key or null if no signing key has been found. * @async */ - async getSigningKey(keyID = null, date = new Date(), userId = {}, config = defaultConfig) { - await this.verifyPrimaryKey(date, userId, config); + async getSigningKey(keyID = null, date = new Date(), userID = {}, config = defaultConfig) { + await this.verifyPrimaryKey(date, userID, config); const primaryKey = this.keyPacket; const subKeys = this.subKeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); let exception; @@ -318,7 +318,7 @@ class Key { } try { - const primaryUser = await this.getPrimaryUser(date, userId, config); + const primaryUser = await this.getPrimaryUser(date, userID, config); if ((!keyID || primaryKey.getKeyID().equals(keyID)) && helper.isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification, config)) { helper.checkKeyStrength(primaryKey, config); @@ -334,13 +334,13 @@ class Key { * Returns last created key or key by given keyID that is available for encryption or decryption * @param {module:type/keyid~KeyID} keyID, optional * @param {Date} date, optional - * @param {String} userId, optional + * @param {String} userID, optional * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Key|SubKey|null} Key or null if no encryption key has been found. * @async */ - async getEncryptionKey(keyID, date = new Date(), userId = {}, config = defaultConfig) { - await this.verifyPrimaryKey(date, userId, config); + async getEncryptionKey(keyID, date = new Date(), userID = {}, config = defaultConfig) { + await this.verifyPrimaryKey(date, userID, config); const primaryKey = this.keyPacket; // V4: by convention subkeys are preferred for encryption service const subKeys = this.subKeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); @@ -363,7 +363,7 @@ class Key { try { // if no valid subkey for encryption, evaluate primary key - const primaryUser = await this.getPrimaryUser(date, userId, config); + const primaryUser = await this.getPrimaryUser(date, userID, config); if ((!keyID || primaryKey.getKeyID().equals(keyID)) && helper.isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) { helper.checkKeyStrength(primaryKey, config); @@ -380,12 +380,12 @@ class Key { * This is useful to retrieve keys for session key decryption * @param {module:type/keyid~KeyID} keyID, optional * @param {Date} date, optional - * @param {String} userId, optional + * @param {String} userID, optional * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Array} Array of decryption keys. * @async */ - async getDecryptionKeys(keyID, date = new Date(), userId = {}, config = defaultConfig) { + async getDecryptionKeys(keyID, date = new Date(), userID = {}, config = defaultConfig) { const primaryKey = this.keyPacket; const keys = []; for (let i = 0; i < this.subKeys.length; i++) { @@ -401,7 +401,7 @@ class Key { } // evaluate primary key - const primaryUser = await this.getPrimaryUser(date, userId, config); + const primaryUser = await this.getPrimaryUser(date, userID, config); if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && helper.isValidDecryptionKeyPacket(primaryUser.selfCertification, config)) { keys.push(this); @@ -561,19 +561,19 @@ class Key { * Verify primary key. Checks for revocation signatures, expiration time * and valid self signature. Throws if the primary key is invalid. * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userId] - User ID + * @param {Object} [userID] - User ID * @param {Object} [config] - Full configuration, defaults to openpgp.config * @throws {Error} If key verification failed * @async */ - async verifyPrimaryKey(date = new Date(), userId = {}, config = defaultConfig) { + async verifyPrimaryKey(date = new Date(), userID = {}, config = defaultConfig) { const primaryKey = this.keyPacket; // check for key revocation signatures if (await this.isRevoked(null, null, date, config)) { throw new Error('Primary key is revoked'); } // check for valid, unrevoked, unexpired self signature - const { selfCertification } = await this.getPrimaryUser(date, userId, config); + const { selfCertification } = await this.getPrimaryUser(date, userID, config); // check for expiration time if (helper.isDataExpired(primaryKey, selfCertification, date)) { throw new Error('Primary key is expired'); @@ -587,29 +587,29 @@ class Key { * Returns Infinity if the key doesn't expire. * @param {encrypt|sign|encrypt_sign} capabilities, optional * @param {module:type/keyid~KeyID} keyID, optional - * @param {Object} userId, optional user ID + * @param {Object} userID, optional user ID * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Date | Infinity | null} * @async */ - async getExpirationTime(capabilities, keyID, userId, config = defaultConfig) { - const primaryUser = await this.getPrimaryUser(null, userId, config); + async getExpirationTime(capabilities, keyID, userID, config = defaultConfig) { + const primaryUser = await this.getPrimaryUser(null, userID, config); const selfCert = primaryUser.selfCertification; const keyExpiry = helper.getExpirationTime(this.keyPacket, selfCert); const sigExpiry = selfCert.getExpirationTime(); let expiry = keyExpiry < sigExpiry ? keyExpiry : sigExpiry; if (capabilities === 'encrypt' || capabilities === 'encrypt_sign') { const encryptKey = - await this.getEncryptionKey(keyID, expiry, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}) || - await this.getEncryptionKey(keyID, null, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}); + await this.getEncryptionKey(keyID, expiry, userID, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}) || + await this.getEncryptionKey(keyID, null, userID, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}); if (!encryptKey) return null; const encryptExpiry = await encryptKey.getExpirationTime(this.keyPacket, undefined, config); if (encryptExpiry < expiry) expiry = encryptExpiry; } if (capabilities === 'sign' || capabilities === 'encrypt_sign') { const signKey = - await this.getSigningKey(keyID, expiry, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}) || - await this.getSigningKey(keyID, null, userId, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}); + await this.getSigningKey(keyID, expiry, userID, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}) || + await this.getSigningKey(keyID, null, userID, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }).catch(() => {}); if (!signKey) return null; const signExpiry = await signKey.getExpirationTime(this.keyPacket, undefined, config); if (signExpiry < expiry) expiry = signExpiry; @@ -622,30 +622,30 @@ class Key { * - if multiple primary users exist, returns the one with the latest self signature * - otherwise, returns the user with the latest self signature * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userId] - User ID to get instead of the primary user, if it exists + * @param {Object} [userID] - User ID to get instead of the primary user, if it exists * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Promise<{user: User, * selfCertification: SignaturePacket}>} The primary user and the self signature * @async */ - async getPrimaryUser(date = new Date(), userId = {}, config = defaultConfig) { + async getPrimaryUser(date = new Date(), userID = {}, config = defaultConfig) { const primaryKey = this.keyPacket; const users = []; let exception; for (let i = 0; i < this.users.length; i++) { try { const user = this.users[i]; - if (!user.userId) { + if (!user.userID) { continue; } if ( - (userId.name !== undefined && user.userId.name !== userId.name) || - (userId.email !== undefined && user.userId.email !== userId.email) || - (userId.comment !== undefined && user.userId.comment !== userId.comment) + (userID.name !== undefined && user.userID.name !== userID.name) || + (userID.email !== undefined && user.userID.email !== userID.email) || + (userID.comment !== undefined && user.userID.comment !== userID.comment) ) { throw new Error('Could not find user that matches that user ID'); } - const dataToVerify = { userId: user.userId, key: primaryKey }; + const dataToVerify = { userID: user.userID, key: primaryKey }; const selfCertification = await helper.getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config); users.push({ index: i, user, selfCertification }); } catch (e) { @@ -711,8 +711,8 @@ class Key { await Promise.all(key.users.map(async srcUser => { let found = false; await Promise.all(this.users.map(async dstUser => { - if ((srcUser.userId && dstUser.userId && - (srcUser.userId.userid === dstUser.userId.userid)) || + if ((srcUser.userID && dstUser.userID && + (srcUser.userID.userID === dstUser.userID.userID)) || (srcUser.userAttribute && (srcUser.userAttribute.equals(dstUser.userAttribute)))) { await dstUser.update(srcUser, this.keyPacket, config); found = true; @@ -822,13 +822,13 @@ class Key { * Signs primary user of key * @param {Array} privateKeys - decrypted private keys for signing * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userId] - User ID to get instead of the primary user, if it exists + * @param {Object} [userID] - User ID to get instead of the primary user, if it exists * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Key} New public key with new certificate signature. * @async */ - async signPrimaryUser(privateKeys, date, userId, config = defaultConfig) { - const { index, user } = await this.getPrimaryUser(date, userId, config); + async signPrimaryUser(privateKeys, date, userID, config = defaultConfig) { + const { index, user } = await this.getPrimaryUser(date, userID, config); const userSign = await user.sign(this.keyPacket, privateKeys, config); const key = await this.clone(); key.users[index] = userSign; @@ -857,15 +857,15 @@ class Key { * - otherwise, verifies all certificates signed with given keys. * @param {Array} keys - array of keys to verify certificate signatures * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userId] - User ID to get instead of the primary user, if it exists + * @param {Object} [userID] - User ID to get instead of the primary user, if it exists * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Promise>} List of signer's keyID and validity of signature * @async */ - async verifyPrimaryUser(keys, date, userId, config = defaultConfig) { + async verifyPrimaryUser(keys, date, userID, config = defaultConfig) { const primaryKey = this.keyPacket; - const { user } = await this.getPrimaryUser(date, userId, config); + const { user } = await this.getPrimaryUser(date, userID, config); const results = keys ? await user.verifyAllCertifications(primaryKey, keys, undefined, config) : [{ keyID: primaryKey.keyID, valid: await user.verify(primaryKey, undefined, config).catch(() => false) }]; return results; @@ -877,9 +877,9 @@ class Key { * - otherwise, verifies all certificates signed with given keys. * @param {Array} keys - array of keys to verify certificate signatures * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} list of userid, signer's keyID and validity of signature + * valid: Boolean}>>} list of userID, signer's keyID and validity of signature * @async */ async verifyAllUsers(keys, config = defaultConfig) { @@ -890,7 +890,7 @@ class Key { [{ keyID: primaryKey.keyID, valid: await user.verify(primaryKey, undefined, config).catch(() => false) }]; signatures.forEach(signature => { results.push({ - userid: user.userId.userid, + userID: user.userID.userID, keyID: signature.keyID, valid: signature.valid }); diff --git a/src/key/user.js b/src/key/user.js index 7d21d0a9d..91aa25bb3 100644 --- a/src/key/user.js +++ b/src/key/user.js @@ -16,7 +16,7 @@ class User { 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 = []; @@ -29,7 +29,7 @@ class User { */ toPacketlist() { const packetlist = new PacketList(); - packetlist.push(this.userId || this.userAttribute); + packetlist.push(this.userID || this.userAttribute); packetlist.concat(this.revocationSignatures); packetlist.concat(this.selfCertifications); packetlist.concat(this.otherCertifications); @@ -47,11 +47,11 @@ class User { */ async sign(primaryKey, privateKeys, config) { const dataToSign = { - userId: this.userId, + userID: this.userID, userAttribute: this.userAttribute, key: primaryKey }; - const user = new User(dataToSign.userId || dataToSign.userAttribute); + const user = new User(dataToSign.userID || dataToSign.userAttribute); user.otherCertifications = await Promise.all(privateKeys.map(async function(privateKey) { if (privateKey.isPublic()) { throw new Error('Need private key for signing'); @@ -88,7 +88,7 @@ class User { return isDataRevoked( primaryKey, enums.signature.certRevocation, { key: primaryKey, - userId: this.userId, + userID: this.userID, userAttribute: this.userAttribute }, this.revocationSignatures, certificate, key, date, config ); @@ -109,7 +109,7 @@ class User { const that = this; const keyID = certificate.issuerKeyID; const dataToVerify = { - userId: this.userId, + userID: this.userID, userAttribute: this.userAttribute, key: primaryKey }; @@ -173,7 +173,7 @@ class User { } const that = this; const dataToVerify = { - userId: this.userId, + userID: this.userID, userAttribute: this.userAttribute, key: primaryKey }; @@ -212,7 +212,7 @@ class User { */ async update(user, primaryKey, config) { const dataToVerify = { - userId: this.userId, + userID: this.userID, userAttribute: this.userAttribute, key: primaryKey }; diff --git a/src/message.js b/src/message.js index 5aac2138f..f853e355f 100644 --- a/src/message.js +++ b/src/message.js @@ -186,7 +186,7 @@ export class Message { enums.symmetric.cast5 // Golang OpenPGP fallback ]; try { - const primaryUser = await privateKey.getPrimaryUser(undefined, undefined, config); // TODO: Pass userId from somewhere. + const primaryUser = await privateKey.getPrimaryUser(undefined, undefined, config); // TODO: Pass userID from somewhere. if (primaryUser.selfCertification.preferredSymmetricAlgorithms) { algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms); } @@ -276,15 +276,15 @@ export class Message { * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any. * @param {Array} [keys] - Public key(s) to select algorithm preferences for * @param {Date} [date] - Date to select algorithm preferences at - * @param {Array} [userIds] - User IDs to select algorithm preferences for + * @param {Array} [userIDs] - User IDs to select algorithm preferences for * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {{ data: Uint8Array, algorithm: String }} Object with session key data and algorithm. * @async */ - static async generateSessionKey(keys = [], date = new Date(), userIds = [], config = defaultConfig) { - const algorithm = enums.read(enums.symmetric, await getPreferredAlgo('symmetric', keys, date, userIds, config)); - const aeadAlgorithm = config.AEADProtect && await isAeadSupported(keys, date, userIds, config) ? - enums.read(enums.aead, await getPreferredAlgo('aead', keys, date, userIds, config)) : + static async generateSessionKey(keys = [], date = new Date(), userIDs = [], config = defaultConfig) { + const algorithm = enums.read(enums.symmetric, await getPreferredAlgo('symmetric', keys, date, userIDs, config)); + const aeadAlgorithm = config.AEADProtect && await isAeadSupported(keys, date, userIDs, config) ? + enums.read(enums.aead, await getPreferredAlgo('aead', keys, date, userIDs, config)) : undefined; const sessionKeyData = await crypto.generateSessionKey(algorithm); @@ -299,19 +299,19 @@ export class Message { * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to publicKeys[i] * @param {Date} [date] - Override the creation date of the literal package - * @param {Array} [userIds] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] + * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] * @param {Boolean} [streaming] - Whether to process data as a stream * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Message} New message with encrypted content. * @async */ - async encrypt(keys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIds = [], streaming, config = defaultConfig) { + async encrypt(keys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], streaming, config = defaultConfig) { if (sessionKey) { if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) { throw new Error('Invalid session key for encryption.'); } } else if (keys && keys.length) { - sessionKey = await Message.generateSessionKey(keys, date, userIds, config); + sessionKey = await Message.generateSessionKey(keys, date, userIDs, config); } else if (passwords && passwords.length) { sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config); } else { @@ -320,7 +320,7 @@ export class Message { const { data: sessionKeyData, algorithm, aeadAlgorithm } = sessionKey; - const msg = await Message.encryptSessionKey(sessionKeyData, algorithm, aeadAlgorithm, keys, passwords, wildcard, encryptionKeyIDs, date, userIds, config); + const msg = await Message.encryptSessionKey(sessionKeyData, algorithm, aeadAlgorithm, keys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config); let symEncryptedPacket; if (aeadAlgorithm) { @@ -348,17 +348,17 @@ export class Message { * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to publicKeys[i] * @param {Date} [date] - Override the date - * @param {Array} [userIds] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] + * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Message} New message with encrypted content. * @async */ - static async encryptSessionKey(sessionKey, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIds = [], config = defaultConfig) { + static async encryptSessionKey(sessionKey, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) { const packetlist = new PacketList(); if (publicKeys) { const results = await Promise.all(publicKeys.map(async function(publicKey, i) { - const encryptionKey = await publicKey.getEncryptionKey(encryptionKeyIDs[i], date, userIds, config); + const encryptionKey = await publicKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config); const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket(); pkESKeyPacket.publicKeyID = wildcard ? KeyID.wildcard() : encryptionKey.getKeyID(); pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm; @@ -415,13 +415,13 @@ export class Message { * @param {Signature} [signature] - Any existing detached signature to add to the message * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] * @param {Date} [date] - Override the creation time of the signature - * @param {Array} [userIds] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] * @param {Boolean} [streaming] - Whether to process data as a stream * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Message} New message with signed content. * @async */ - async sign(privateKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIds = [], streaming = false, config = defaultConfig) { + async sign(privateKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], streaming = false, config = defaultConfig) { const packetlist = new PacketList(); const literalDataPacket = this.packets.findPacket(enums.packet.literalData); @@ -456,10 +456,10 @@ export class Message { throw new Error('Need private key for signing'); } const signingKeyID = signingKeyIDs[privateKeys.length - 1 - i]; - const signingKey = await privateKey.getSigningKey(signingKeyID, date, userIds, config); + const signingKey = await privateKey.getSigningKey(signingKeyID, date, userIDs, config); const onePassSig = new OnePassSignaturePacket(); onePassSig.signatureType = signatureType; - onePassSig.hashAlgorithm = await getPreferredHashAlgo(privateKey, signingKey.keyPacket, date, userIds, config); + onePassSig.hashAlgorithm = await getPreferredHashAlgo(privateKey, signingKey.keyPacket, date, userIDs, config); onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm; onePassSig.issuerKeyID = signingKey.getKeyID(); if (i === privateKeys.length - 1) { @@ -471,7 +471,7 @@ export class Message { }); packetlist.push(literalDataPacket); - packetlist.concat(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIds, false, streaming, config)); + packetlist.concat(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, false, streaming, config)); return new Message(packetlist); } @@ -503,18 +503,18 @@ export class Message { * @param {Signature} [signature] - Any existing detached signature * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] * @param {Date} [date] - Override the creation time of the signature - * @param {Array} [userIds] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] * @param {Boolean} [streaming] - Whether to process data as a stream * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Signature} New detached signature of message content. * @async */ - async signDetached(privateKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIds = [], streaming = false, config = defaultConfig) { + async signDetached(privateKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], streaming = false, config = defaultConfig) { const literalDataPacket = this.packets.findPacket(enums.packet.literalData); if (!literalDataPacket) { throw new Error('No literal data packet to sign.'); } - return new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIds, true, streaming, config)); + return new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, true, streaming, config)); } /** @@ -695,7 +695,7 @@ export class Message { * @param {Signature} [signature] - Any existing detached signature to append * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] * @param {Date} [date] - Override the creationtime of the signature - * @param {Array} [userIds] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] * @param {Boolean} [detached] - Whether to create detached signature packets * @param {Boolean} [streaming] - Whether to process data as a stream * @param {Object} [config] - Full configuration, defaults to openpgp.config @@ -703,7 +703,7 @@ export class Message { * @async * @private */ -export async function createSignaturePackets(literalDataPacket, privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIds = [], detached = false, streaming = false, config = defaultConfig) { +export async function createSignaturePackets(literalDataPacket, privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], detached = false, streaming = false, config = defaultConfig) { const packetlist = new PacketList(); // If data packet was created from Uint8Array, use binary, otherwise use text @@ -711,12 +711,12 @@ export async function createSignaturePackets(literalDataPacket, privateKeys, sig enums.signature.binary : enums.signature.text; await Promise.all(privateKeys.map(async (privateKey, i) => { - const userId = userIds[i]; + const userID = userIDs[i]; if (privateKey.isPublic()) { throw new Error('Need private key for signing'); } - const signingKey = await privateKey.getSigningKey(signingKeyIDs[i], date, userId, config); - return createSignaturePacket(literalDataPacket, privateKey, signingKey.keyPacket, { signatureType }, date, userId, detached, streaming, config); + const signingKey = await privateKey.getSigningKey(signingKeyIDs[i], date, userID, config); + return createSignaturePacket(literalDataPacket, privateKey, signingKey.keyPacket, { signatureType }, date, userID, detached, streaming, config); })).then(signatureList => { signatureList.forEach(signaturePacket => packetlist.push(signaturePacket)); }); diff --git a/src/openpgp.js b/src/openpgp.js index 125bbcea2..2e943265d 100644 --- a/src/openpgp.js +++ b/src/openpgp.js @@ -41,7 +41,7 @@ if (globalThis.ReadableStream) { * Generates a new OpenPGP key pair. Supports RSA and ECC keys. By default, primary and subkeys will be of same type. * @param {Object} options * @param {'ecc'|'rsa'} [options.type='ecc'] - The primary key algorithm type: ECC (default) or RSA - * @param {Object|Array} options.userIds - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` + * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys * @param {String} [options.curve='curve25519'] - Elliptic curve for ECC keys: @@ -57,10 +57,10 @@ if (globalThis.ReadableStream) { * @async * @static */ -export function generateKey({ userIds = [], passphrase = "", type = "ecc", rsaBits = 4096, curve = "curve25519", keyExpirationTime = 0, date = new Date(), subkeys = [{}], config }) { +export function generateKey({ userIDs = [], passphrase = "", type = "ecc", rsaBits = 4096, curve = "curve25519", keyExpirationTime = 0, date = new Date(), subkeys = [{}], config }) { config = { ...defaultConfig, ...config }; - userIds = toArray(userIds); - const options = { userIds, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys }; + userIDs = toArray(userIDs); + const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys }; if (type === "rsa" && rsaBits < config.minRSABits) { throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${rsaBits}`); } @@ -84,7 +84,7 @@ export function generateKey({ userIds = [], passphrase = "", type = "ecc", rsaBi * Reformats signature packets for a key and rewraps key object. * @param {Object} options * @param {Key} options.privateKey - Private key to reformat - * @param {Object|Array} options.userIds - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` + * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} @@ -93,10 +93,10 @@ export function generateKey({ userIds = [], passphrase = "", type = "ecc", rsaBi * @async * @static */ -export function reformatKey({ privateKey, userIds = [], passphrase = "", keyExpirationTime = 0, date, config }) { +export function reformatKey({ privateKey, userIDs = [], passphrase = "", keyExpirationTime = 0, date, config }) { config = { ...defaultConfig, ...config }; - userIds = toArray(userIds); - const options = { privateKey, userIds, passphrase, keyExpirationTime, date }; + userIDs = toArray(userIDs); + const options = { privateKey, userIDs, passphrase, keyExpirationTime, date }; return reformat(options, config).then(async key => { const revocationCertificate = await key.getRevocationCertificate(date, config); @@ -243,16 +243,16 @@ export async function encryptKey({ privateKey, passphrase, config }) { * @param {Array} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `privateKeys[i]` * @param {Array} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `publicKeys[i]` * @param {Date} [options.date=current date] - Override the creation date of the message signature - * @param {Array} [options.fromUserIds=primary user IDs] - Array of user IDs to sign with, one per key in `privateKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` - * @param {Array} [options.toUserIds=primary user IDs] - Array of user IDs to encrypt for, one per key in `publicKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]` + * @param {Array} [options.fromUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `privateKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` + * @param {Array} [options.toUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `publicKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]` * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} * @returns {String|ReadableStream|NodeStream|Uint8Array|ReadableStream|NodeStream} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false). * @async * @static */ -export function encrypt({ message, publicKeys, privateKeys, passwords, sessionKey, armor = true, streaming = message && message.fromStream, detached = false, signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), fromUserIds = [], toUserIds = [], config }) { +export function encrypt({ message, publicKeys, privateKeys, passwords, sessionKey, armor = true, streaming = message && message.fromStream, detached = false, signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), fromUserIDs = [], toUserIDs = [], config }) { config = { ...defaultConfig, ...config }; - checkMessage(message); publicKeys = toArray(publicKeys); privateKeys = toArray(privateKeys); passwords = toArray(passwords); fromUserIds = toArray(fromUserIds); toUserIds = toArray(toUserIds); + checkMessage(message); publicKeys = toArray(publicKeys); privateKeys = toArray(privateKeys); passwords = toArray(passwords); fromUserIDs = toArray(fromUserIDs); toUserIDs = toArray(toUserIDs); if (detached) { throw new Error("detached option has been removed from openpgp.encrypt. Separately call openpgp.sign instead. Don't forget to remove privateKeys option as well."); } @@ -262,13 +262,13 @@ export function encrypt({ message, publicKeys, privateKeys, passwords, sessionKe privateKeys = []; } if (privateKeys.length || signature) { // sign the message only if private keys or signature is specified - message = await message.sign(privateKeys, signature, signingKeyIDs, date, fromUserIds, message.fromStream, config); + message = await message.sign(privateKeys, signature, signingKeyIDs, date, fromUserIDs, message.fromStream, config); } message = message.compress( - await getPreferredAlgo('compression', publicKeys, date, toUserIds, config), + await getPreferredAlgo('compression', publicKeys, date, toUserIDs, config), config ); - message = await message.encrypt(publicKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, toUserIds, streaming, config); + message = await message.encrypt(publicKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, toUserIDs, streaming, config); const data = armor ? message.armor(config) : message.write(); return convertStream(data, streaming, armor ? 'utf8' : 'binary'); }).catch(onError.bind(null, 'Error encrypting message')); @@ -343,27 +343,27 @@ export function decrypt({ message, privateKeys, passwords, sessionKeys, publicKe * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature * @param {Array} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] * @param {Date} [options.date=current date] - Override the creation date of the signature - * @param {Array} [options.fromUserIds=primary user IDs] - Array of user IDs to sign with, one per key in `privateKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` + * @param {Array} [options.fromUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `privateKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} * @returns {String|ReadableStream|NodeStream|Uint8Array|ReadableStream|NodeStream} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false). * @async * @static */ -export function sign({ message, privateKeys, armor = true, streaming = message && message.fromStream, detached = false, signingKeyIDs = [], date = new Date(), fromUserIds = [], config }) { +export function sign({ message, privateKeys, armor = true, streaming = message && message.fromStream, detached = false, signingKeyIDs = [], date = new Date(), fromUserIDs = [], config }) { config = { ...defaultConfig, ...config }; checkCleartextOrMessage(message); if (message instanceof CleartextMessage && !armor) throw new Error("Can't sign non-armored cleartext message"); if (message instanceof CleartextMessage && detached) throw new Error("Can't detach-sign a cleartext message"); - privateKeys = toArray(privateKeys); fromUserIds = toArray(fromUserIds); + privateKeys = toArray(privateKeys); fromUserIDs = toArray(fromUserIDs); return Promise.resolve().then(async function() { let signature; if (message instanceof CleartextMessage) { - signature = await message.sign(privateKeys, undefined, signingKeyIDs, date, fromUserIds, config); + signature = await message.sign(privateKeys, undefined, signingKeyIDs, date, fromUserIDs, config); } else if (detached) { - signature = await message.signDetached(privateKeys, undefined, signingKeyIDs, date, fromUserIds, message.fromStream, config); + signature = await message.signDetached(privateKeys, undefined, signingKeyIDs, date, fromUserIDs, message.fromStream, config); } else { - signature = await message.sign(privateKeys, undefined, signingKeyIDs, date, fromUserIds, message.fromStream, config); + signature = await message.sign(privateKeys, undefined, signingKeyIDs, date, fromUserIDs, message.fromStream, config); } signature = armor ? signature.armor(config) : signature.write(); if (detached) { @@ -438,19 +438,19 @@ export function verify({ message, publicKeys, format = 'utf8', streaming = messa * @param {Object} options * @param {Key|Array} options.publicKeys - Array of public keys or single key used to select algorithm preferences for * @param {Date} [options.date=current date] - Date to select algorithm preferences at - * @param {Array} [options.toUserIds=primary user IDs] - User IDs to select algorithm preferences for + * @param {Array} [options.toUserIDs=primary user IDs] - User IDs to select algorithm preferences for * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} * @returns {{ data: Uint8Array, algorithm: String }} Object with session key data and algorithm. * @async * @static */ -export function generateSessionKey({ publicKeys, date = new Date(), toUserIds = [], config }) { +export function generateSessionKey({ publicKeys, date = new Date(), toUserIDs = [], config }) { config = { ...defaultConfig, ...config }; - publicKeys = toArray(publicKeys); toUserIds = toArray(toUserIds); + publicKeys = toArray(publicKeys); toUserIDs = toArray(toUserIDs); return Promise.resolve().then(async function() { - return Message.generateSessionKey(publicKeys, date, toUserIds, config); + return Message.generateSessionKey(publicKeys, date, toUserIDs, config); }).catch(onError.bind(null, 'Error generating session key')); } @@ -468,19 +468,19 @@ export function generateSessionKey({ publicKeys, date = new Date(), toUserIds = * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs * @param {Array} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to publicKeys[i] * @param {Date} [options.date=current date] - Override the date - * @param {Array} [options.toUserIds=primary user IDs] - Array of user IDs to encrypt for, one per key in `publicKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]` + * @param {Array} [options.toUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `publicKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]` * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} * @returns {String|Uint8Array} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false). * @async * @static */ -export function encryptSessionKey({ data, algorithm, aeadAlgorithm, publicKeys, passwords, armor = true, wildcard = false, encryptionKeyIDs = [], date = new Date(), toUserIds = [], config }) { +export function encryptSessionKey({ data, algorithm, aeadAlgorithm, publicKeys, passwords, armor = true, wildcard = false, encryptionKeyIDs = [], date = new Date(), toUserIDs = [], config }) { config = { ...defaultConfig, ...config }; - checkBinary(data); checkString(algorithm, 'algorithm'); publicKeys = toArray(publicKeys); passwords = toArray(passwords); toUserIds = toArray(toUserIds); + checkBinary(data); checkString(algorithm, 'algorithm'); publicKeys = toArray(publicKeys); passwords = toArray(passwords); toUserIDs = toArray(toUserIDs); return Promise.resolve().then(async function() { - const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard, encryptionKeyIDs, date, toUserIds, config); + const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard, encryptionKeyIDs, date, toUserIDs, config); return armor ? message.armor(config) : message.write(); }).catch(onError.bind(null, 'Error encrypting session key')); diff --git a/src/packet/signature.js b/src/packet/signature.js index 69ce4c08c..6b3b54879 100644 --- a/src/packet/signature.js +++ b/src/packet/signature.js @@ -70,7 +70,7 @@ class SignaturePacket { this.isPrimaryUserID = null; this.policyURI = null; this.keyFlags = null; - this.signersUserId = null; + this.signersUserID = null; this.reasonForRevocationFlag = null; this.reasonForRevocationString = null; this.features = null; @@ -259,7 +259,7 @@ class SignaturePacket { arr.push(write_sub_packet(sub.preferredKeyServer, util.strToUint8Array(this.preferredKeyServer))); } if (this.isPrimaryUserID !== null) { - arr.push(write_sub_packet(sub.primaryUserId, new Uint8Array([this.isPrimaryUserID ? 1 : 0]))); + arr.push(write_sub_packet(sub.primaryUserID, new Uint8Array([this.isPrimaryUserID ? 1 : 0]))); } if (this.policyURI !== null) { arr.push(write_sub_packet(sub.policyUri, util.strToUint8Array(this.policyURI))); @@ -268,8 +268,8 @@ class SignaturePacket { bytes = util.strToUint8Array(util.uint8ArrayToStr(this.keyFlags)); arr.push(write_sub_packet(sub.keyFlags, bytes)); } - if (this.signersUserId !== null) { - arr.push(write_sub_packet(sub.signersUserId, util.strToUint8Array(this.signersUserId))); + if (this.signersUserID !== null) { + arr.push(write_sub_packet(sub.signersUserID, util.strToUint8Array(this.signersUserID))); } if (this.reasonForRevocationFlag !== null) { bytes = util.strToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString); @@ -470,7 +470,7 @@ class SignaturePacket { break; case 28: // Signer's User ID - this.signersUserId = util.uint8ArrayToStr(bytes.subarray(mypos, bytes.length)); + this.signersUserID = util.uint8ArrayToStr(bytes.subarray(mypos, bytes.length)); break; case 29: // Reason for Revocation @@ -568,14 +568,14 @@ class SignaturePacket { let packet; let tag; - if (data.userId) { + if (data.userID) { tag = 0xB4; - packet = data.userId; + packet = data.userID; } else if (data.userAttribute) { tag = 0xD1; packet = data.userAttribute; } else { - throw new Error('Either a userId or userAttribute packet needs to be ' + + throw new Error('Either a userID or userAttribute packet needs to be ' + 'supplied for certification.'); } diff --git a/src/packet/userid.js b/src/packet/userid.js index 69072d9f7..ec6e50910 100644 --- a/src/packet/userid.js +++ b/src/packet/userid.js @@ -37,7 +37,7 @@ class UserIDPacket { * John Doe * @type {String} */ - this.userid = ''; + this.userID = ''; this.name = ''; this.email = ''; @@ -46,24 +46,24 @@ class UserIDPacket { /** * Create UserIDPacket instance from object - * @param {Object} userId - Object specifying userId name, email and comment + * @param {Object} userID - Object specifying userID name, email and comment * @returns {UserIDPacket} * @static */ - static fromObject(userId) { - if (util.isString(userId) || - (userId.name && !util.isString(userId.name)) || - (userId.email && !util.isEmailAddress(userId.email)) || - (userId.comment && !util.isString(userId.comment))) { + static fromObject(userID) { + if (util.isString(userID) || + (userID.name && !util.isString(userID.name)) || + (userID.email && !util.isEmailAddress(userID.email)) || + (userID.comment && !util.isString(userID.comment))) { throw new Error('Invalid user ID format'); } const packet = new UserIDPacket(); - Object.assign(packet, userId); + Object.assign(packet, userID); const components = []; if (packet.name) components.push(packet.name); if (packet.comment) components.push(`(${packet.comment})`); if (packet.email) components.push(`<${packet.email}>`); - packet.userid = components.join(' '); + packet.userID = components.join(' '); return packet; } @@ -72,17 +72,17 @@ class UserIDPacket { * @param {Uint8Array} input - Payload of a tag 13 packet */ read(bytes, config = defaultConfig) { - const userid = util.decodeUtf8(bytes); - if (userid.length > config.maxUserIDLength) { + const userID = util.decodeUtf8(bytes); + if (userID.length > config.maxUserIDLength) { throw new Error('User ID string is too long'); } try { - const { name, address: email, comments } = emailAddresses.parseOneAddress({ input: userid, atInDisplayName: true }); + const { name, address: email, comments } = emailAddresses.parseOneAddress({ input: userID, atInDisplayName: true }); this.comment = comments.replace(/^\(|\)$/g, ''); this.name = name; this.email = email; } catch (e) {} - this.userid = userid; + this.userID = userID; } /** @@ -90,7 +90,7 @@ class UserIDPacket { * @returns {Uint8Array} Binary representation. */ write() { - return util.encodeUtf8(this.userid); + return util.encodeUtf8(this.userID); } } diff --git a/test/crypto/validate.js b/test/crypto/validate.js index 9173bbc8c..a700b35d9 100644 --- a/test/crypto/validate.js +++ b/test/crypto/validate.js @@ -85,7 +85,7 @@ module.exports = () => { describe('EdDSA parameter validation', function() { let eddsaKey; before(async () => { - eddsaKey = (await openpgp.generateKey({ curve: 'ed25519', userIds: [{ name: 'Test', email: 'test@test.com' }] })).key; + eddsaKey = (await openpgp.generateKey({ curve: 'ed25519', userIDs: [{ name: 'Test', email: 'test@test.com' }] })).key; }); it('EdDSA params should be valid', async function() { @@ -109,9 +109,9 @@ module.exports = () => { let ecdhKey; let ecdsaKey; before(async () => { - eddsaKey = (await openpgp.generateKey({ curve: 'ed25519', userIds: [{ name: 'Test', email: 'test@test.com' }] })).key; + eddsaKey = (await openpgp.generateKey({ curve: 'ed25519', userIDs: [{ name: 'Test', email: 'test@test.com' }] })).key; ecdhKey = eddsaKey.subKeys[0]; - ecdsaKey = (await openpgp.generateKey({ curve: 'p256', userIds: [{ name: 'Test', email: 'test@test.com' }] })).key; + ecdsaKey = (await openpgp.generateKey({ curve: 'p256', userIDs: [{ name: 'Test', email: 'test@test.com' }] })).key; }); it('EdDSA params are not valid for ECDH', async function() { @@ -194,10 +194,10 @@ module.exports = () => { let ecdhKey; before(async () => { if (curve !== 'curve25519') { - ecdsaKey = (await openpgp.generateKey({ curve, userIds: [{ name: 'Test', email: 'test@test.com' }] })).key; + ecdsaKey = (await openpgp.generateKey({ curve, userIDs: [{ name: 'Test', email: 'test@test.com' }] })).key; ecdhKey = ecdsaKey.subKeys[0]; } else { - const eddsaKey = (await openpgp.generateKey({ curve: 'ed25519', userIds: [{ name: 'Test', email: 'test@test.com' }] })).key; + const eddsaKey = (await openpgp.generateKey({ curve: 'ed25519', userIDs: [{ name: 'Test', email: 'test@test.com' }] })).key; ecdhKey = eddsaKey.subKeys[0]; } }); @@ -244,7 +244,7 @@ module.exports = () => { describe('RSA parameter validation', function() { let rsaKey; before(async () => { - rsaKey = (await openpgp.generateKey({ type: 'rsa', rsaBits: 2048, userIds: [{ name: 'Test', email: 'test@test.com' }] })).key; + rsaKey = (await openpgp.generateKey({ type: 'rsa', rsaBits: 2048, userIDs: [{ name: 'Test', email: 'test@test.com' }] })).key; }); it('generated RSA params are valid', async function() { diff --git a/test/general/brainpool.js b/test/general/brainpool.js index 07c2b5331..567e1f6fc 100644 --- a/test/general/brainpool.js +++ b/test/general/brainpool.js @@ -283,10 +283,10 @@ function omnibus() { const testData = input.createSomeMessage(); const testData2 = input.createSomeMessage(); - const firstKey = await openpgp.generateKey({ userIds: { name: "Hi", email: "hi@hel.lo" }, curve: "brainpoolP256r1" }); + const firstKey = await openpgp.generateKey({ userIDs: { name: "Hi", email: "hi@hel.lo" }, curve: "brainpoolP256r1" }); const hi = firstKey.key; const pubHi = hi.toPublic(); - const secondKey = await openpgp.generateKey({ userIds: { name: "Bye", email: "bye@good.bye" }, curve: "brainpoolP256r1" }); + const secondKey = await openpgp.generateKey({ userIDs: { name: "Bye", email: "bye@good.bye" }, curve: "brainpoolP256r1" }); const bye = secondKey.key; const pubBye = bye.toPublic(); diff --git a/test/general/config.js b/test/general/config.js index ad6d14800..1e2c0243c 100644 --- a/test/general/config.js +++ b/test/general/config.js @@ -13,7 +13,7 @@ module.exports = () => describe('Custom configuration', function() { try { const opt = { - userIds: { name: 'Test User', email: 'text@example.com' } + userIDs: { name: 'Test User', email: 'text@example.com' } }; const { key, privateKeyArmored } = await openpgp.generateKey(opt); expect(key.keyPacket.version).to.equal(4); @@ -26,7 +26,7 @@ module.exports = () => describe('Custom configuration', function() { preferredHashAlgorithm: openpgp.enums.hash.sha512 }; const opt2 = { - userIds: { name: 'Test User', email: 'text@example.com' }, + userIDs: { name: 'Test User', email: 'text@example.com' }, config }; const { key: key2, privateKeyArmored: privateKeyArmored2 } = await openpgp.generateKey(opt2); @@ -49,10 +49,10 @@ module.exports = () => describe('Custom configuration', function() { openpgp.config.showComment = false; try { - const userIds = { name: 'Test User', email: 'text2@example.com' }; - const { key: origKey } = await openpgp.generateKey({ userIds }); + const userIDs = { name: 'Test User', email: 'text2@example.com' }; + const { key: origKey } = await openpgp.generateKey({ userIDs }); - const opt = { privateKey: origKey, userIds }; + const opt = { privateKey: origKey, userIDs }; const { key: refKey, privateKeyArmored: refKeyArmored } = await openpgp.reformatKey(opt); const prefs = refKey.users[0].selfCertifications[0]; expect(prefs.preferredCompressionAlgorithms[0]).to.equal(openpgp.config.preferredCompressionAlgorithm); @@ -65,7 +65,7 @@ module.exports = () => describe('Custom configuration', function() { preferredHashAlgorithm: openpgp.enums.hash.sha512, rejectPublicKeyAlgorithms: new Set([openpgp.enums.publicKey.eddsa]) // should not matter in this context }; - const opt2 = { privateKey: origKey, userIds, config }; + const opt2 = { privateKey: origKey, userIDs, config }; const { key: refKey2, privateKeyArmored: refKeyArmored2 } = await openpgp.reformatKey(opt2); const prefs2 = refKey2.users[0].selfCertifications[0]; expect(prefs2.preferredCompressionAlgorithms[0]).to.equal(config.preferredCompressionAlgorithm); @@ -84,8 +84,8 @@ module.exports = () => describe('Custom configuration', function() { openpgp.config.showComment = false; try { - const userIds = { name: 'Test User', email: 'text2@example.com' }; - const { key, revocationCertificate } = await openpgp.generateKey({ userIds }); + const userIDs = { name: 'Test User', email: 'text2@example.com' }; + const { key, revocationCertificate } = await openpgp.generateKey({ userIDs }); const opt = { key }; const { privateKeyArmored: revKeyArmored } = await openpgp.revokeKey(opt); @@ -107,10 +107,10 @@ module.exports = () => describe('Custom configuration', function() { }); it('openpgp.decryptKey', async function() { - const userIds = { name: 'Test User', email: 'text2@example.com' }; + const userIDs = { name: 'Test User', email: 'text2@example.com' }; const passphrase = '12345678'; - const { key } = await openpgp.generateKey({ userIds, passphrase }); + const { key } = await openpgp.generateKey({ userIDs, passphrase }); key.keyPacket.makeDummy(); const opt = { @@ -127,14 +127,14 @@ module.exports = () => describe('Custom configuration', function() { try { const passphrase = '12345678'; - const userIds = { name: 'Test User', email: 'text2@example.com' }; - const { key: privateKey } = await openpgp.generateKey({ userIds }); + const userIDs = { name: 'Test User', email: 'text2@example.com' }; + const { key: privateKey } = await openpgp.generateKey({ userIDs }); - const encKey = await openpgp.encryptKey({ privateKey, userIds, passphrase }); + const encKey = await openpgp.encryptKey({ privateKey, userIDs, passphrase }); expect(encKey.keyPacket.s2k.c).to.equal(openpgp.config.S2KIterationCountByte); const config = { S2KIterationCountByte: 123 }; - const encKey2 = await openpgp.encryptKey({ privateKey, userIds, passphrase, config }); + const encKey2 = await openpgp.encryptKey({ privateKey, userIDs, passphrase, config }); expect(encKey2.keyPacket.s2k.c).to.equal(config.S2KIterationCountByte); } finally { openpgp.config.S2KIterationCountByte = S2KIterationCountByteVal; @@ -173,8 +173,8 @@ module.exports = () => describe('Custom configuration', function() { expect(compressed.tag).to.equal(openpgp.enums.packet.compressedData); expect(compressed.algorithm).to.equal("zip"); - const userIds = { name: 'Test User', email: 'text2@example.com' }; - const { key } = await openpgp.generateKey({ userIds }); + const userIDs = { name: 'Test User', email: 'text2@example.com' }; + const { key } = await openpgp.generateKey({ userIDs }); await expect(openpgp.encrypt({ message, publicKeys: [key], config: { rejectPublicKeyAlgorithms: new Set([openpgp.enums.publicKey.ecdh]) } })).to.be.eventually.rejectedWith(/ecdh keys are considered too weak/); @@ -187,8 +187,8 @@ module.exports = () => describe('Custom configuration', function() { it('openpgp.decrypt', async function() { const plaintext = 'test'; const message = openpgp.Message.fromText(plaintext); - const userIds = { name: 'Test User', email: 'text2@example.com' }; - const { key } = await openpgp.generateKey({ userIds, type: 'rsa', rsaBits: 2048 }); + const userIDs = { name: 'Test User', email: 'text2@example.com' }; + const { key } = await openpgp.generateKey({ userIDs, type: 'rsa', rsaBits: 2048 }); const armoredMessage = await openpgp.encrypt({ message, publicKeys:[key], privateKeys: [key] }); const { data, signatures } = await openpgp.decrypt({ @@ -221,8 +221,8 @@ module.exports = () => describe('Custom configuration', function() { }); it('openpgp.sign', async function() { - const userIds = { name: 'Test User', email: 'text2@example.com' }; - const { privateKeyArmored } = await openpgp.generateKey({ userIds }); + const userIDs = { name: 'Test User', email: 'text2@example.com' }; + const { privateKeyArmored } = await openpgp.generateKey({ userIDs }); const key = await openpgp.readKey({ armoredKey: privateKeyArmored }); const message = openpgp.Message.fromText("test"); @@ -249,8 +249,8 @@ module.exports = () => describe('Custom configuration', function() { }); it('openpgp.verify', async function() { - const userIds = { name: 'Test User', email: 'text2@example.com' }; - const { privateKeyArmored } = await openpgp.generateKey({ userIds }); + const userIDs = { name: 'Test User', email: 'text2@example.com' }; + const { privateKeyArmored } = await openpgp.generateKey({ userIDs }); const key = await openpgp.readKey({ armoredKey: privateKeyArmored }); const config = { rejectMessageHashAlgorithms: new Set([openpgp.enums.hash.sha256, openpgp.enums.hash.sha512]) }; diff --git a/test/general/ecc_nist.js b/test/general/ecc_nist.js index 7ed0610ab..20629d047 100644 --- a/test/general/ecc_nist.js +++ b/test/general/ecc_nist.js @@ -13,10 +13,10 @@ module.exports = () => describe('Elliptic Curve Cryptography for NIST P-256,P-38 const testData = input.createSomeMessage(); const testData2 = input.createSomeMessage(); - const firstKey = await openpgp.generateKey({ userIds: { name: "Hi", email: "hi@hel.lo" }, curve: "p256" }); + const firstKey = await openpgp.generateKey({ userIDs: { name: "Hi", email: "hi@hel.lo" }, curve: "p256" }); const hi = firstKey.key; const pubHi = hi.toPublic(); - const secondKey = await openpgp.generateKey({ userIds: { name: "Bye", email: "bye@good.bye" }, curve: "p256" }); + const secondKey = await openpgp.generateKey({ userIDs: { name: "Bye", email: "bye@good.bye" }, curve: "p256" }); const bye = secondKey.key; const pubBye = bye.toPublic(); @@ -54,7 +54,7 @@ module.exports = () => describe('Elliptic Curve Cryptography for NIST P-256,P-38 it('Sign message', async function () { const testData = input.createSomeMessage(); - const options = { userIds: { name: "Hi", email: "hi@hel.lo" }, curve: "p256" }; + const options = { userIDs: { name: "Hi", email: "hi@hel.lo" }, curve: "p256" }; const firstKey = await openpgp.generateKey(options); const signature = await openpgp.sign({ message: openpgp.CleartextMessage.fromText(testData), privateKeys: firstKey.key }); const msg = await openpgp.readCleartextMessage({ cleartextMessage: signature }); @@ -64,9 +64,9 @@ module.exports = () => describe('Elliptic Curve Cryptography for NIST P-256,P-38 it('encrypt and sign message', async function () { const testData = input.createSomeMessage(); - let options = { userIds: { name: "Hi", email: "hi@hel.lo" }, curve: "p256" }; + let options = { userIDs: { name: "Hi", email: "hi@hel.lo" }, curve: "p256" }; const firstKey = await openpgp.generateKey(options); - options = { userIds: { name: "Bye", email: "bye@good.bye" }, curve: "p256" }; + options = { userIDs: { name: "Bye", email: "bye@good.bye" }, curve: "p256" }; const secondKey = await openpgp.generateKey(options); const encrypted = await openpgp.encrypt( { message: openpgp.Message.fromText(testData), diff --git a/test/general/ecc_secp256k1.js b/test/general/ecc_secp256k1.js index 217265b71..4147f8464 100644 --- a/test/general/ecc_secp256k1.js +++ b/test/general/ecc_secp256k1.js @@ -159,13 +159,13 @@ module.exports = () => describe('Elliptic Curve Cryptography for secp256k1 curve } it('Load public key', async function () { const romeoPublic = await load_pub_key('romeo'); - expect(romeoPublic.users[0].userId.name).to.equal('Romeo Montague'); - expect(romeoPublic.users[0].userId.email).to.equal('romeo@example.net'); - expect(romeoPublic.users[0].userId.comment).to.equal('secp256k1'); + expect(romeoPublic.users[0].userID.name).to.equal('Romeo Montague'); + expect(romeoPublic.users[0].userID.email).to.equal('romeo@example.net'); + expect(romeoPublic.users[0].userID.comment).to.equal('secp256k1'); const julietPublic = await load_pub_key('juliet'); - expect(julietPublic.users[0].userId.name).to.equal('Juliet Capulet'); - expect(julietPublic.users[0].userId.email).to.equal('juliet@example.net'); - expect(julietPublic.users[0].userId.comment).to.equal('secp256k1'); + expect(julietPublic.users[0].userID.name).to.equal('Juliet Capulet'); + expect(julietPublic.users[0].userID.email).to.equal('juliet@example.net'); + expect(julietPublic.users[0].userID.comment).to.equal('secp256k1'); }); it('Load private key', async function () { await load_priv_key('romeo'); @@ -222,7 +222,7 @@ module.exports = () => describe('Elliptic Curve Cryptography for secp256k1 curve }); it('Generate key', function () { const options = { - userIds: { name: "Hamlet (secp256k1)", email: "hamlet@example.net" }, + userIDs: { name: "Hamlet (secp256k1)", email: "hamlet@example.net" }, curve: "secp256k1", passphrase: "ophelia" }; diff --git a/test/general/key.js b/test/general/key.js index 2ccd666a6..5592e3ab3 100644 --- a/test/general/key.js +++ b/test/general/key.js @@ -2104,7 +2104,7 @@ function versionSpecificTests() { } expect(key.users[0].selfCertifications[0].features).to.eql(expectedFeatures); }; - const opt = { userIds: { name: 'test', email: 'a@b.com' }, passphrase: 'hello' }; + const opt = { userIDs: { name: 'test', email: 'a@b.com' }, passphrase: 'hello' }; return openpgp.generateKey(opt).then(async function(key) { testPref(key.key); testPref(await openpgp.readKey({ armoredKey: key.publicKeyArmored })); @@ -2149,7 +2149,7 @@ function versionSpecificTests() { } expect(key.users[0].selfCertifications[0].features).to.eql(expectedFeatures); }; - const opt = { userIds: { name: 'test', email: 'a@b.com' }, passphrase: 'hello' }; + const opt = { userIDs: { name: 'test', email: 'a@b.com' }, passphrase: 'hello' }; try { const key = await openpgp.generateKey(opt); testPref(key.key); @@ -2163,7 +2163,7 @@ function versionSpecificTests() { }); it('Generated key is not unlocked by default', async function() { - const opt = { userIds: { name: 'test', email: 'a@b.com' }, passphrase: '123' }; + const opt = { userIDs: { name: 'test', email: 'a@b.com' }, passphrase: '123' }; const { key } = await openpgp.generateKey(opt); return openpgp.encrypt({ message: openpgp.Message.fromText('hello'), @@ -2176,62 +2176,62 @@ function versionSpecificTests() { }); }); - it('Generate key - single userid', function() { - const userId = { name: 'test', email: 'a@b.com', comment: 'test comment' }; - const opt = { userIds: userId, passphrase: '123' }; + it('Generate key - single userID', function() { + const userID = { name: 'test', email: 'a@b.com', comment: 'test comment' }; + const opt = { userIDs: userID, passphrase: '123' }; return openpgp.generateKey(opt).then(function(key) { key = key.key; expect(key.users.length).to.equal(1); - expect(key.users[0].userId.userid).to.equal('test (test comment) '); - expect(key.users[0].userId.name).to.equal(userId.name); - expect(key.users[0].userId.email).to.equal(userId.email); - expect(key.users[0].userId.comment).to.equal(userId.comment); + expect(key.users[0].userID.userID).to.equal('test (test comment) '); + expect(key.users[0].userID.name).to.equal(userID.name); + expect(key.users[0].userID.email).to.equal(userID.email); + expect(key.users[0].userID.comment).to.equal(userID.comment); }); }); - it('Generate key - single userid (all missing)', function() { - const userId = { name: '', email: '', comment: '' }; - const opt = { userIds: userId, passphrase: '123' }; + it('Generate key - single userID (all missing)', function() { + const userID = { name: '', email: '', comment: '' }; + const opt = { userIDs: userID, passphrase: '123' }; return openpgp.generateKey(opt).then(function(key) { key = key.key; expect(key.users.length).to.equal(1); - expect(key.users[0].userId.userid).to.equal(''); - expect(key.users[0].userId.name).to.equal(userId.name); - expect(key.users[0].userId.email).to.equal(userId.email); - expect(key.users[0].userId.comment).to.equal(userId.comment); + expect(key.users[0].userID.userID).to.equal(''); + expect(key.users[0].userID.name).to.equal(userID.name); + expect(key.users[0].userID.email).to.equal(userID.email); + expect(key.users[0].userID.comment).to.equal(userID.comment); }); }); - it('Generate key - single userid (missing email)', function() { - const userId = { name: 'test', email: '', comment: 'test comment' }; - const opt = { userIds: userId, passphrase: '123' }; + it('Generate key - single userID (missing email)', function() { + const userID = { name: 'test', email: '', comment: 'test comment' }; + const opt = { userIDs: userID, passphrase: '123' }; return openpgp.generateKey(opt).then(function(key) { key = key.key; expect(key.users.length).to.equal(1); - expect(key.users[0].userId.userid).to.equal('test (test comment)'); - expect(key.users[0].userId.name).to.equal(userId.name); - expect(key.users[0].userId.email).to.equal(userId.email); - expect(key.users[0].userId.comment).to.equal(userId.comment); + expect(key.users[0].userID.userID).to.equal('test (test comment)'); + expect(key.users[0].userID.name).to.equal(userID.name); + expect(key.users[0].userID.email).to.equal(userID.email); + expect(key.users[0].userID.comment).to.equal(userID.comment); }); }); - it('Generate key - single userid (missing comment)', function() { - const userId = { name: 'test', email: 'a@b.com', comment: '' }; - const opt = { userIds: userId, passphrase: '123' }; + it('Generate key - single userID (missing comment)', function() { + const userID = { name: 'test', email: 'a@b.com', comment: '' }; + const opt = { userIDs: userID, passphrase: '123' }; return openpgp.generateKey(opt).then(function(key) { key = key.key; expect(key.users.length).to.equal(1); - expect(key.users[0].userId.userid).to.equal('test '); - expect(key.users[0].userId.name).to.equal(userId.name); - expect(key.users[0].userId.email).to.equal(userId.email); - expect(key.users[0].userId.comment).to.equal(userId.comment); + expect(key.users[0].userID.userID).to.equal('test '); + expect(key.users[0].userID.name).to.equal(userID.name); + expect(key.users[0].userID.email).to.equal(userID.email); + expect(key.users[0].userID.comment).to.equal(userID.comment); }); }); it('Generate key - setting date to the past', function() { const past = new Date(0); const opt = { - userIds: { name: 'Test User', email: 'text@example.com' }, + userIDs: { name: 'Test User', email: 'text@example.com' }, passphrase: 'secret', date: past }; @@ -2247,7 +2247,7 @@ function versionSpecificTests() { it('Generate key - setting date to the future', function() { const future = new Date(Math.ceil(Date.now() / 1000) * 1000 + 1000); const opt = { - userIds: { name: 'Test User', email: 'text@example.com' }, + userIDs: { name: 'Test User', email: 'text@example.com' }, passphrase: 'secret', date: future }; @@ -2260,28 +2260,28 @@ function versionSpecificTests() { }); }); - it('Generate key - multi userid', function() { - const userId1 = { name: 'test', email: 'a@b.com' }; - const userId2 = { name: 'test', email: 'b@c.com' }; - const opt = { userIds: [userId1, userId2], passphrase: '123' }; + it('Generate key - multi userID', function() { + const userID1 = { name: 'test', email: 'a@b.com' }; + const userID2 = { name: 'test', email: 'b@c.com' }; + const opt = { userIDs: [userID1, userID2], passphrase: '123' }; return openpgp.generateKey(opt).then(function(key) { key = key.key; expect(key.users.length).to.equal(2); - expect(key.users[0].userId.userid).to.equal('test '); + expect(key.users[0].userID.userID).to.equal('test '); expect(key.users[0].selfCertifications[0].isPrimaryUserID).to.be.true; - expect(key.users[1].userId.userid).to.equal('test '); + expect(key.users[1].userID.userID).to.equal('test '); expect(key.users[1].selfCertifications[0].isPrimaryUserID).to.be.null; }); }); it('Generate key - default values', function() { - const userId = { name: 'test', email: 'a@b.com' }; - const opt = { userIds: [userId] }; + const userID = { name: 'test', email: 'a@b.com' }; + const opt = { userIDs: [userID] }; return openpgp.generateKey(opt).then(function({ key }) { expect(key.isDecrypted()).to.be.true; expect(key.getAlgorithmInfo().algorithm).to.equal('eddsa'); expect(key.users.length).to.equal(1); - expect(key.users[0].userId.userid).to.equal('test '); + expect(key.users[0].userID.userID).to.equal('test '); expect(key.users[0].selfCertifications[0].isPrimaryUserID).to.be.true; expect(key.subKeys).to.have.length(1); expect(key.subKeys[0].getAlgorithmInfo().algorithm).to.equal('ecdh'); @@ -2289,12 +2289,12 @@ function versionSpecificTests() { }); it('Generate key - two subkeys with default values', function() { - const userId = { name: 'test', email: 'a@b.com' }; - const opt = { userIds: [userId], passphrase: '123', subkeys:[{},{}] }; + const userID = { name: 'test', email: 'a@b.com' }; + const opt = { userIDs: [userID], passphrase: '123', subkeys:[{},{}] }; return openpgp.generateKey(opt).then(function(key) { key = key.key; expect(key.users.length).to.equal(1); - expect(key.users[0].userId.userid).to.equal('test '); + expect(key.users[0].userID.userID).to.equal('test '); expect(key.users[0].selfCertifications[0].isPrimaryUserID).to.be.true; expect(key.subKeys).to.have.length(2); expect(key.subKeys[0].getAlgorithmInfo().algorithm).to.equal('ecdh'); @@ -2307,12 +2307,12 @@ function versionSpecificTests() { const minRSABits = openpgp.config.minRSABits; openpgp.config.minRSABits = rsaBits; - const userId = { name: 'test', email: 'a@b.com' }; - const opt = { type: 'rsa', rsaBits, userIds: [userId], passphrase: '123', subkeys:[{},{}] }; + const userID = { name: 'test', email: 'a@b.com' }; + const opt = { type: 'rsa', rsaBits, userIDs: [userID], passphrase: '123', subkeys:[{},{}] }; try { const { key } = await openpgp.generateKey(opt); expect(key.users.length).to.equal(1); - expect(key.users[0].userId.userid).to.equal('test '); + expect(key.users[0].userID.userID).to.equal('test '); expect(key.users[0].selfCertifications[0].isPrimaryUserID).to.be.true; expect(key.subKeys).to.have.length(2); expect(key.subKeys[0].getAlgorithmInfo().algorithm).to.equal('rsaEncryptSign'); @@ -2323,12 +2323,12 @@ function versionSpecificTests() { }); it('Generate key - one signing subkey', function() { - const userId = { name: 'test', email: 'a@b.com' }; - const opt = { userIds: [userId], passphrase: '123', subkeys:[{}, { sign: true }] }; + const userID = { name: 'test', email: 'a@b.com' }; + const opt = { userIDs: [userID], passphrase: '123', subkeys:[{}, { sign: true }] }; return openpgp.generateKey(opt).then(async function({ privateKeyArmored }) { const key = await openpgp.readKey({ armoredKey: privateKeyArmored }); expect(key.users.length).to.equal(1); - expect(key.users[0].userId.userid).to.equal('test '); + expect(key.users[0].userID.userID).to.equal('test '); expect(key.users[0].selfCertifications[0].isPrimaryUserID).to.be.true; expect(key.subKeys).to.have.length(2); expect(key.subKeys[0].getAlgorithmInfo().algorithm).to.equal('ecdh'); @@ -2339,15 +2339,15 @@ function versionSpecificTests() { }); it('Reformat key - one signing subkey', function() { - const userId = { name: 'test', email: 'a@b.com' }; - const opt = { userIds: [userId], passphrase: '123', subkeys:[{}, { sign: true }] }; + const userID = { name: 'test', email: 'a@b.com' }; + const opt = { userIDs: [userID], passphrase: '123', subkeys:[{}, { sign: true }] }; return openpgp.generateKey(opt).then(async function({ key }) { await key.decrypt('123'); - return openpgp.reformatKey({ privateKey: key, userIds: [userId] }); + return openpgp.reformatKey({ privateKey: key, userIDs: [userID] }); }).then(async function({ privateKeyArmored }) { const key = await openpgp.readKey({ armoredKey: privateKeyArmored }); expect(key.users.length).to.equal(1); - expect(key.users[0].userId.userid).to.equal('test '); + expect(key.users[0].userID.userID).to.equal('test '); expect(key.users[0].selfCertifications[0].isPrimaryUserID).to.be.true; expect(key.subKeys).to.have.length(2); expect(key.subKeys[0].getAlgorithmInfo().algorithm).to.equal('ecdh'); @@ -2362,12 +2362,12 @@ function versionSpecificTests() { const minRSABits = openpgp.config.minRSABits; openpgp.config.minRSABits = rsaBits; - const userId = { name: 'test', email: 'a@b.com' }; - const opt = { type: 'rsa', rsaBits, userIds: [userId], passphrase: '123', subkeys:[{ type: 'ecc', curve: 'curve25519' }] }; + const userID = { name: 'test', email: 'a@b.com' }; + const opt = { type: 'rsa', rsaBits, userIDs: [userID], passphrase: '123', subkeys:[{ type: 'ecc', curve: 'curve25519' }] }; try { const { key } = await openpgp.generateKey(opt); expect(key.users.length).to.equal(1); - expect(key.users[0].userId.userid).to.equal('test '); + expect(key.users[0].userID.userID).to.equal('test '); expect(key.users[0].selfCertifications[0].isPrimaryUserID).to.be.true; expect(key.getAlgorithmInfo().algorithm).to.equal('rsaEncryptSign'); expect(key.getAlgorithmInfo().bits).to.equal(opt.rsaBits); @@ -2378,8 +2378,8 @@ function versionSpecificTests() { }); it('Encrypt key with new passphrase', async function() { - const userId = { name: 'test', email: 'a@b.com' }; - const opt = { userIds: userId, passphrase: 'passphrase' }; + const userID = { name: 'test', email: 'a@b.com' }; + const opt = { userIDs: userID, passphrase: 'passphrase' }; const key = (await openpgp.generateKey(opt)).key; const armor1 = key.armor(); const armor2 = key.armor(); @@ -2398,8 +2398,8 @@ function versionSpecificTests() { it('Generate key - ensure keyExpirationTime works', function() { const expect_delta = 365 * 24 * 60 * 60; - const userId = { name: 'test', email: 'a@b.com' }; - const opt = { userIds: userId, passphrase: '123', keyExpirationTime: expect_delta }; + const userID = { name: 'test', email: 'a@b.com' }; + const opt = { userIDs: userID, passphrase: '123', keyExpirationTime: expect_delta }; return openpgp.generateKey(opt).then(async function(key) { key = key.key; @@ -2475,16 +2475,16 @@ function versionSpecificTests() { const publicSigningKey = await publicKey.getSigningKey(); const privateSigningKey = await privateKey.getSigningKey(); expect(signatures.length).to.equal(4); - expect(signatures[0].userid).to.equal(publicKey.users[0].userId.userid); + expect(signatures[0].userID).to.equal(publicKey.users[0].userID.userID); expect(signatures[0].keyID.toHex()).to.equal(publicSigningKey.getKeyID().toHex()); expect(signatures[0].valid).to.be.null; - expect(signatures[1].userid).to.equal(publicKey.users[0].userId.userid); + expect(signatures[1].userID).to.equal(publicKey.users[0].userID.userID); expect(signatures[1].keyID.toHex()).to.equal(privateSigningKey.getKeyID().toHex()); expect(signatures[1].valid).to.be.true; - expect(signatures[2].userid).to.equal(publicKey.users[1].userId.userid); + expect(signatures[2].userID).to.equal(publicKey.users[1].userID.userID); expect(signatures[2].keyID.toHex()).to.equal(publicSigningKey.getKeyID().toHex()); expect(signatures[2].valid).to.be.null; - expect(signatures[3].userid).to.equal(publicKey.users[1].userId.userid); + expect(signatures[3].userID).to.equal(publicKey.users[1].userID.userID); expect(signatures[3].keyID.toHex()).to.equal(privateSigningKey.getKeyID().toHex()); expect(signatures[3].valid).to.be.true; } finally { @@ -2506,16 +2506,16 @@ function versionSpecificTests() { const publicSigningKey = await publicKey.getSigningKey(); const privateSigningKey = await privateKey.getSigningKey(); expect(signatures.length).to.equal(4); - expect(signatures[0].userid).to.equal(publicKey.users[0].userId.userid); + expect(signatures[0].userID).to.equal(publicKey.users[0].userID.userID); expect(signatures[0].keyID.toHex()).to.equal(publicSigningKey.getKeyID().toHex()); expect(signatures[0].valid).to.be.null; - expect(signatures[1].userid).to.equal(publicKey.users[0].userId.userid); + expect(signatures[1].userID).to.equal(publicKey.users[0].userID.userID); expect(signatures[1].keyID.toHex()).to.equal(privateSigningKey.getKeyID().toHex()); expect(signatures[1].valid).to.be.null; - expect(signatures[2].userid).to.equal(publicKey.users[1].userId.userid); + expect(signatures[2].userID).to.equal(publicKey.users[1].userID.userID); expect(signatures[2].keyID.toHex()).to.equal(publicSigningKey.getKeyID().toHex()); expect(signatures[2].valid).to.be.null; - expect(signatures[3].userid).to.equal(publicKey.users[1].userId.userid); + expect(signatures[3].userID).to.equal(publicKey.users[1].userID.userID); expect(signatures[3].keyID.toHex()).to.equal(privateSigningKey.getKeyID().toHex()); expect(signatures[3].valid).to.be.null; } finally { @@ -2524,67 +2524,67 @@ function versionSpecificTests() { }); it('Reformat key without passphrase', function() { - const userId1 = { name: 'test', email: 'a@b.com' }; - const userId2 = { name: 'test', email: 'b@c.com' }; - const opt = { userIds: userId1 }; + const userID1 = { name: 'test', email: 'a@b.com' }; + const userID2 = { name: 'test', email: 'b@c.com' }; + const opt = { userIDs: userID1 }; return openpgp.generateKey(opt).then(function(key) { key = key.key; expect(key.users.length).to.equal(1); - expect(key.users[0].userId.userid).to.equal('test '); + expect(key.users[0].userID.userID).to.equal('test '); expect(key.isDecrypted()).to.be.true; opt.privateKey = key; - opt.userIds = userId2; + opt.userIDs = userID2; return openpgp.reformatKey(opt).then(function(newKey) { newKey = newKey.key; expect(newKey.users.length).to.equal(1); - expect(newKey.users[0].userId.userid).to.equal('test '); + expect(newKey.users[0].userID.userID).to.equal('test '); expect(newKey.isDecrypted()).to.be.true; }); }); }); it('Reformat key with no subkey with passphrase', async function() { - const userId = { name: 'test', email: 'a@b.com' }; + const userID = { name: 'test', email: 'a@b.com' }; const key = await openpgp.readKey({ armoredKey: key_without_subkey }); - const opt = { privateKey: key, userIds: [userId], passphrase: "test" }; + const opt = { privateKey: key, userIDs: [userID], passphrase: "test" }; return openpgp.reformatKey(opt).then(function(newKey) { newKey = newKey.key; expect(newKey.users.length).to.equal(1); - expect(newKey.users[0].userId.userid).to.equal('test '); + expect(newKey.users[0].userID.userID).to.equal('test '); expect(newKey.isDecrypted()).to.be.false; }); }); it('Reformat key with two subkeys with passphrase', function() { - const userId1 = { name: 'test', email: 'a@b.com' }; - const userId2 = { name: 'test', email: 'b@c.com' }; + const userID1 = { name: 'test', email: 'a@b.com' }; + const userID2 = { name: 'test', email: 'b@c.com' }; const now = util.normalizeDate(new Date()); const before = util.normalizeDate(new Date(0)); - const opt1 = { userIds: [userId1], date: now }; + const opt1 = { userIDs: [userID1], date: now }; return openpgp.generateKey(opt1).then(function(newKey) { newKey = newKey.key; - expect(newKey.users[0].userId.userid).to.equal('test '); + expect(newKey.users[0].userID.userID).to.equal('test '); expect(+newKey.getCreationTime()).to.equal(+now); expect(+newKey.subKeys[0].getCreationTime()).to.equal(+now); expect(+newKey.subKeys[0].bindingSignatures[0].created).to.equal(+now); - const opt2 = { privateKey: newKey, userIds: [userId2], date: before }; + const opt2 = { privateKey: newKey, userIDs: [userID2], date: before }; return openpgp.reformatKey(opt2).then(function(refKey) { refKey = refKey.key; expect(refKey.users.length).to.equal(1); - expect(refKey.users[0].userId.userid).to.equal('test '); + expect(refKey.users[0].userID.userID).to.equal('test '); expect(+refKey.subKeys[0].bindingSignatures[0].created).to.equal(+before); }); }); }); it('Reformat key with no subkey without passphrase', async function() { - const userId = { name: 'test', email: 'a@b.com' }; + const userID = { name: 'test', email: 'a@b.com' }; const key = await openpgp.readKey({ armoredKey: key_without_subkey }); - const opt = { privateKey: key, userIds: [userId] }; + const opt = { privateKey: key, userIDs: [userID] }; return openpgp.reformatKey(opt).then(function(newKey) { newKey = newKey.key; expect(newKey.users.length).to.equal(1); - expect(newKey.users[0].userId.userid).to.equal('test '); + expect(newKey.users[0].userID.userID).to.equal('test '); expect(newKey.isDecrypted()).to.be.true; return openpgp.sign({ message: openpgp.CleartextMessage.fromText('hello'), privateKeys: newKey, armor: true }).then(async function(signed) { return openpgp.verify( @@ -2600,19 +2600,19 @@ function versionSpecificTests() { }); it('Reformat and encrypt key', function() { - const userId1 = { name: 'test1', email: 'a@b.com' }; - const userId2 = { name: 'test2', email: 'b@c.com' }; - const userId3 = { name: 'test3', email: 'c@d.com' }; - const opt = { userIds: userId1 }; + const userID1 = { name: 'test1', email: 'a@b.com' }; + const userID2 = { name: 'test2', email: 'b@c.com' }; + const userID3 = { name: 'test3', email: 'c@d.com' }; + const opt = { userIDs: userID1 }; return openpgp.generateKey(opt).then(function(key) { key = key.key; opt.privateKey = key; - opt.userIds = [userId2, userId3]; + opt.userIDs = [userID2, userID3]; opt.passphrase = '123'; return openpgp.reformatKey(opt).then(async function(newKey) { newKey = newKey.key; expect(newKey.users.length).to.equal(2); - expect(newKey.users[0].userId.userid).to.equal('test2 '); + expect(newKey.users[0].userID.userID).to.equal('test2 '); expect(newKey.isDecrypted()).to.be.false; await newKey.decrypt('123'); expect(newKey.isDecrypted()).to.be.true; @@ -2621,13 +2621,13 @@ function versionSpecificTests() { }); it('Sign and encrypt with reformatted key', function() { - const userId1 = { name: 'test1', email: 'a@b.com' }; - const userId2 = { name: 'test2', email: 'b@c.com' }; - const opt = { userIds: userId1 }; + const userID1 = { name: 'test1', email: 'a@b.com' }; + const userID2 = { name: 'test2', email: 'b@c.com' }; + const opt = { userIDs: userID1 }; return openpgp.generateKey(opt).then(function(key) { key = key.key; opt.privateKey = key; - opt.userIds = userId2; + opt.userIDs = userID2; return openpgp.reformatKey(opt).then(function(newKey) { newKey = newKey.key; return openpgp.encrypt({ message: openpgp.Message.fromText('hello'), publicKeys: newKey.toPublic(), privateKeys: newKey, armor: true }).then(async function(encrypted) { @@ -2641,9 +2641,9 @@ function versionSpecificTests() { }); it('Reject with user-friendly error when reformatting encrypted key', function() { - const opt = { userIds: { name: 'test', email: 'a@b.com' }, passphrase: '1234' }; + const opt = { userIDs: { name: 'test', email: 'a@b.com' }, passphrase: '1234' }; return openpgp.generateKey(opt).then(function(original) { - return openpgp.reformatKey({ privateKey: original.key, userIds: { name: 'test2', email: 'a@b.com' }, passphrase: '1234' }).then(function() { + return openpgp.reformatKey({ privateKey: original.key, userIDs: { name: 'test2', email: 'a@b.com' }, passphrase: '1234' }).then(function() { throw new Error('reformatKey should result in error when key not decrypted'); }).catch(function(error) { expect(error.message).to.equal('Error reformatting keypair: Key is not decrypted'); @@ -2652,7 +2652,7 @@ function versionSpecificTests() { }); it('Revoke generated key with revocation certificate', function() { - const opt = { userIds: { name: 'test', email: 'a@b.com' }, passphrase: '1234' }; + const opt = { userIDs: { name: 'test', email: 'a@b.com' }, passphrase: '1234' }; return openpgp.generateKey(opt).then(function(original) { return openpgp.revokeKey({ key: original.key.toPublic(), revocationCertificate: original.revocationCertificate }).then(async function(revKey) { revKey = revKey.publicKey; @@ -2664,7 +2664,7 @@ function versionSpecificTests() { }); it('Revoke generated key with private key', function() { - const opt = { userIds: { name: 'test', email: 'a@b.com' }, passphrase: '1234' }; + const opt = { userIDs: { name: 'test', email: 'a@b.com' }, passphrase: '1234' }; return openpgp.generateKey(opt).then(async function(original) { await original.key.decrypt('1234'); return openpgp.revokeKey({ key: original.key, reasonForRevocation: { string: 'Testing key revocation' } }).then(async function(revKey) { @@ -2933,7 +2933,7 @@ module.exports = () => describe('Key', function() { }); it("validate() - don't throw if key parameters correspond", async function() { - const { key } = await openpgp.generateKey({ userIds: {}, curve: 'ed25519' }); + const { key } = await openpgp.generateKey({ userIDs: {}, curve: 'ed25519' }); await expect(key.validate()).to.not.be.rejected; }); @@ -2959,7 +2959,7 @@ module.exports = () => describe('Key', function() { it("isDecrypted() - should reflect whether all (sub)keys are encrypted", async function() { const passphrase = '12345678'; - const { key } = await openpgp.generateKey({ userIds: {}, curve: 'ed25519', passphrase }); + const { key } = await openpgp.generateKey({ userIDs: {}, curve: 'ed25519', passphrase }); expect(key.isDecrypted()).to.be.false; await key.decrypt(passphrase, key.subKeys[0].getKeyID()); expect(key.isDecrypted()).to.be.true; @@ -2978,14 +2978,14 @@ module.exports = () => describe('Key', function() { }); it('makeDummy() - the converted key can be parsed', async function() { - const { key } = await openpgp.generateKey({ userIds: { name: 'dummy', email: 'dummy@alice.com' } }); + const { key } = await openpgp.generateKey({ userIDs: { name: 'dummy', email: 'dummy@alice.com' } }); key.primaryKey.makeDummy(); const parsedKeys = await openpgp.readKey({ armoredKey: key.armor() }); expect(parsedKeys).to.not.be.empty; }); it('makeDummy() - the converted key can be encrypted and decrypted', async function() { - const { key } = await openpgp.generateKey({ userIds: { name: 'dummy', email: 'dummy@alice.com' } }); + const { key } = await openpgp.generateKey({ userIDs: { name: 'dummy', email: 'dummy@alice.com' } }); const passphrase = 'passphrase'; key.primaryKey.makeDummy(); expect(key.isDecrypted()).to.be.true; @@ -3002,7 +3002,7 @@ module.exports = () => describe('Key', function() { key.primaryKey.makeDummy(); expect(key.primaryKey.isDummy()).to.be.true; await key.validate(); - await expect(openpgp.reformatKey({ privateKey: key, userIds: { name: 'test', email: 'a@b.com' } })).to.be.rejectedWith(/Cannot reformat a gnu-dummy primary key/); + await expect(openpgp.reformatKey({ privateKey: key, userIDs: { name: 'test', email: 'a@b.com' } })).to.be.rejectedWith(/Cannot reformat a gnu-dummy primary key/); }); it('makeDummy() - subkeys of the converted key can still sign', async function() { @@ -3092,7 +3092,7 @@ module.exports = () => describe('Key', function() { dest.users.pop(); return dest.update(source).then(() => { expect(dest.users[1]).to.exist; - expect(dest.users[1].userId).to.equal(source.users[1].userId); + expect(dest.users[1].userID).to.equal(source.users[1].userID); }); }); @@ -3360,10 +3360,10 @@ module.exports = () => describe('Key', function() { const key = await openpgp.readKey({ armoredKey: pub_sig_test }); const primUser = await key.getPrimaryUser(); expect(primUser).to.exist; - expect(primUser.user.userId.userid).to.equal('Signature Test '); - 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.user.userID.userID).to.equal('Signature Test '); + 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.SignaturePacket); }); @@ -3414,14 +3414,14 @@ VYGdb3eNlV8CfoEC publicKey.users[0].selfCertifications[0].isPrimaryUserID = true; // Set second user to prefer aes128. We will select this user. publicKey.users[1].selfCertifications[0].preferredSymmetricAlgorithms = [openpgp.enums.symmetric.aes128]; - const sessionKey = await openpgp.generateSessionKey({ publicKeys: publicKey, toUserIds: { name: 'Test User', email: 'b@c.com' } }); + const sessionKey = await openpgp.generateSessionKey({ publicKeys: publicKey, toUserIDs: { name: 'Test User', email: 'b@c.com' } }); expect(sessionKey.algorithm).to.equal('aes128'); const config = { minRSABits: 1024 }; await openpgp.encrypt({ - message: openpgp.Message.fromText('hello'), publicKeys: publicKey, privateKeys: privateKey, toUserIds: { name: 'Test User', email: 'b@c.com' }, armor: false, config + message: openpgp.Message.fromText('hello'), publicKeys: publicKey, privateKeys: privateKey, toUserIDs: { name: 'Test User', email: 'b@c.com' }, armor: false, config }); await expect(openpgp.encrypt({ - message: openpgp.Message.fromText('hello'), publicKeys: publicKey, privateKeys: privateKey, toUserIds: { name: 'Test User', email: 'c@c.com' }, armor: false, config + message: openpgp.Message.fromText('hello'), publicKeys: publicKey, privateKeys: privateKey, toUserIDs: { name: 'Test User', email: 'c@c.com' }, armor: false, config })).to.be.rejectedWith('Could not find user that matches that user ID'); }); @@ -3442,23 +3442,23 @@ VYGdb3eNlV8CfoEC privateKey.users.push(privateKeyClone.users[0]); // Set first user to primary. We won't select this user, this is to test that. privateKey.users[0].selfCertifications[0].isPrimaryUserID = true; - // Change userid of the first user so that we don't select it. This also makes this user invalid. - privateKey.users[0].userId = openpgp.UserIDPacket.fromObject({ name: 'Test User', email: 'b@c.com' }); + // Change userID of the first user so that we don't select it. This also makes this user invalid. + privateKey.users[0].userID = openpgp.UserIDPacket.fromObject({ name: 'Test User', email: 'b@c.com' }); // Set second user to prefer aes128. We will select this user. privateKey.users[1].selfCertifications[0].preferredHashAlgorithms = [openpgp.enums.hash.sha512]; const config = { minRSABits: 1024 }; const signed = await openpgp.sign({ - message: openpgp.Message.fromText('hello'), privateKeys: privateKey, fromUserIds: { name: 'Test McTestington', email: 'test@example.com' }, armor: false, config + message: openpgp.Message.fromText('hello'), privateKeys: privateKey, fromUserIDs: { name: 'Test McTestington', email: 'test@example.com' }, armor: false, config }); const signature = await openpgp.readMessage({ binaryMessage: signed }); expect(signature.packets[0].hashAlgorithm).to.equal(openpgp.enums.hash.sha512); const encrypted = await openpgp.encrypt({ - message: openpgp.Message.fromText('hello'), passwords: 'test', privateKeys: privateKey, fromUserIds: { name: 'Test McTestington', email: 'test@example.com' }, armor: false, config + message: openpgp.Message.fromText('hello'), passwords: 'test', privateKeys: privateKey, fromUserIDs: { name: 'Test McTestington', email: 'test@example.com' }, armor: false, config }); const { signatures } = await openpgp.decrypt({ message: await openpgp.readMessage({ binaryMessage: encrypted }), passwords: 'test' }); expect(signatures[0].signature.packets[0].hashAlgorithm).to.equal(openpgp.enums.hash.sha512); await expect(openpgp.encrypt({ - message: openpgp.Message.fromText('hello'), publicKeys: publicKey, privateKeys: privateKey, fromUserIds: { name: 'Not Test McTestington', email: 'test@example.com' }, armor: false, config + message: openpgp.Message.fromText('hello'), publicKeys: publicKey, privateKeys: privateKey, fromUserIDs: { name: 'Not Test McTestington', email: 'test@example.com' }, armor: false, config })).to.be.rejectedWith('Could not find user that matches that user ID'); }); @@ -3531,13 +3531,13 @@ VYGdb3eNlV8CfoEC expect(key.getFingerprint()).to.equal( updateKey.getFingerprint()); expect(key.users).to.have.length(2); - expect(key.users[1].userId).to.be.null; + expect(key.users[1].userID).to.be.null; }); }); it("Should throw when trying to encrypt a key that's already encrypted", async function() { await expect((async function() { - const { privateKeyArmored } = await openpgp.generateKey({ userIds: [{ email: 'hello@user.com' }], passphrase: 'pass' }); + const { privateKeyArmored } = await openpgp.generateKey({ userIDs: [{ email: 'hello@user.com' }], passphrase: 'pass' }); const k = await openpgp.readKey({ armoredKey: privateKeyArmored }); await k.decrypt('pass'); await k.encrypt('pass'); @@ -3576,8 +3576,8 @@ VYGdb3eNlV8CfoEC }); it('Add a new default subkey to an rsaSign key', async function() { - const userId = { name: 'test', email: 'a@b.com' }; - const opt = { type: 'rsa', rsaBits, userIds: [userId], subkeys: [] }; + const userID = { name: 'test', email: 'a@b.com' }; + const opt = { type: 'rsa', rsaBits, userIDs: [userID], subkeys: [] }; const { key } = await openpgp.generateKey(opt); expect(key.subKeys).to.have.length(0); key.keyPacket.algorithm = "rsaSign"; @@ -3586,8 +3586,8 @@ VYGdb3eNlV8CfoEC }); it('Add a new default subkey to an ecc key', async function() { - const userId = { name: 'test', email: 'a@b.com' }; - const opt = { type: 'ecc', userIds: [userId], subkeys: [] }; + const userID = { name: 'test', email: 'a@b.com' }; + const opt = { type: 'ecc', userIDs: [userID], subkeys: [] }; const { key } = await openpgp.generateKey(opt); expect(key.subKeys).to.have.length(0); const newKey = await key.addSubkey(); @@ -3627,11 +3627,11 @@ VYGdb3eNlV8CfoEC }); it('create and add a new ec subkey to a ec key', async function() { - const userId = { name: 'test', email: 'a@b.com' }; - const opt = { curve: 'curve25519', userIds: [userId], subkeys:[] }; + const userID = { name: 'test', email: 'a@b.com' }; + const opt = { curve: 'curve25519', userIDs: [userID], subkeys:[] }; const privateKey = (await openpgp.generateKey(opt)).key; const total = privateKey.subKeys.length; - const opt2 = { curve: 'curve25519', userIds: [userId], sign: true }; + const opt2 = { curve: 'curve25519', userIDs: [userID], sign: true }; let newPrivateKey = await privateKey.addSubkey(opt2); const subKey1 = newPrivateKey.subKeys[total]; await newPrivateKey.encrypt('12345678'); @@ -3651,8 +3651,8 @@ VYGdb3eNlV8CfoEC }); it('create and add a new ecdsa subkey to a eddsa key', async function() { - const userId = { name: 'test', email: 'a@b.com' }; - const opt = { curve: 'ed25519', userIds: [userId], subkeys:[] }; + const userID = { name: 'test', email: 'a@b.com' }; + const opt = { curve: 'ed25519', userIDs: [userID], subkeys:[] }; const privateKey = (await openpgp.generateKey(opt)).key; const total = privateKey.subKeys.length; let newPrivateKey = await privateKey.addSubkey({ curve: 'p256', sign: true }); @@ -3685,8 +3685,8 @@ VYGdb3eNlV8CfoEC }); it('create and add a new rsa subkey to a ecc key', async function() { - const userId = { name: 'test', email: 'a@b.com' }; - const opt = { curve: 'ed25519', userIds: [userId], subkeys:[] }; + const userID = { name: 'test', email: 'a@b.com' }; + const opt = { curve: 'ed25519', userIDs: [userID], subkeys:[] }; const privateKey = (await openpgp.generateKey(opt)).key; const total = privateKey.subKeys.length; let newPrivateKey = await privateKey.addSubkey({ type: 'rsa' }); @@ -3714,8 +3714,8 @@ VYGdb3eNlV8CfoEC }); it('sign/verify data with the new subkey correctly using curve25519', async function() { - const userId = { name: 'test', email: 'a@b.com' }; - const opt = { curve: 'curve25519', userIds: [userId], subkeys:[] }; + const userID = { name: 'test', email: 'a@b.com' }; + const opt = { curve: 'curve25519', userIDs: [userID], subkeys:[] }; const privateKey = (await openpgp.generateKey(opt)).key; const total = privateKey.subKeys.length; const opt2 = { sign: true }; @@ -3739,9 +3739,9 @@ VYGdb3eNlV8CfoEC }); it('encrypt/decrypt data with the new subkey correctly using curve25519', async function() { - const userId = { name: 'test', email: 'a@b.com' }; + const userID = { name: 'test', email: 'a@b.com' }; const vData = 'the data to encrypted!'; - const opt = { curve: 'curve25519', userIds: [userId], subkeys:[] }; + const opt = { curve: 'curve25519', userIDs: [userID], subkeys:[] }; const privateKey = (await openpgp.generateKey(opt)).key; const total = privateKey.subKeys.length; let newPrivateKey = await privateKey.addSubkey(); @@ -3809,12 +3809,12 @@ VYGdb3eNlV8CfoEC }); it('Subkey.verify returns the latest valid signature', async function () { - const { key: encryptionKey } = await openpgp.generateKey({ userIds: { name: "purple" } }); + const { key: encryptionKey } = await openpgp.generateKey({ userIDs: { name: "purple" } }); const encryptionKeySignature = await encryptionKey.getSubkeys()[0].verify(encryptionKey); expect(encryptionKeySignature instanceof openpgp.SignaturePacket).to.be.true; expect(encryptionKeySignature.keyFlags[0] & openpgp.enums.keyFlags.encryptCommunication).to.be.equals(openpgp.enums.keyFlags.encryptCommunication); expect(encryptionKeySignature.keyFlags[0] & openpgp.enums.keyFlags.encryptStorage).to.be.equals(openpgp.enums.keyFlags.encryptStorage); - const { key: signingKey } = await openpgp.generateKey({ userIds: { name: "purple" }, subkeys: [{ sign: true }] }); + const { key: signingKey } = await openpgp.generateKey({ userIDs: { name: "purple" }, subkeys: [{ sign: true }] }); const signingKeySignature = await signingKey.getSubkeys()[0].verify(signingKey); expect(signingKeySignature instanceof openpgp.SignaturePacket).to.be.true; expect(signingKeySignature.keyFlags[0] & openpgp.enums.keyFlags.signData).to.be.equals(openpgp.enums.keyFlags.signData); diff --git a/test/general/openpgp.js b/test/general/openpgp.js index fe28d075e..aa940e27d 100644 --- a/test/general/openpgp.js +++ b/test/general/openpgp.js @@ -710,7 +710,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { describe('generateKey - validate user ids', function() { it('should fail for invalid user name', async function() { const opt = { - userIds: [{ name: {}, email: 'text@example.com' }] + userIDs: [{ name: {}, email: 'text@example.com' }] }; const test = openpgp.generateKey(opt); await expect(test).to.eventually.be.rejectedWith(/Invalid user ID format/); @@ -718,7 +718,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { it('should fail for invalid user email address', async function() { const opt = { - userIds: [{ name: 'Test User', email: 'textexample.com' }] + userIDs: [{ name: 'Test User', email: 'textexample.com' }] }; const test = openpgp.generateKey(opt); await expect(test).to.eventually.be.rejectedWith(/Invalid user ID format/); @@ -726,7 +726,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { it('should fail for invalid user email address', async function() { const opt = { - userIds: [{ name: 'Test User', email: 'text@examplecom' }] + userIDs: [{ name: 'Test User', email: 'text@examplecom' }] }; const test = openpgp.generateKey(opt); await expect(test).to.eventually.be.rejectedWith(/Invalid user ID format/); @@ -734,7 +734,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { it('should fail for string user ID', async function() { const opt = { - userIds: 'Test User ' + userIDs: 'Test User ' }; const test = openpgp.generateKey(opt); await expect(test).to.eventually.be.rejectedWith(/Invalid user ID format/); @@ -742,28 +742,28 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { it('should work for valid single user ID object', function() { const opt = { - userIds: { name: 'Test User', email: 'text@example.com' } + userIDs: { name: 'Test User', email: 'text@example.com' } }; return openpgp.generateKey(opt); }); it('should work for array of user ID objects', function() { const opt = { - userIds: [{ name: 'Test User', email: 'text@example.com' }] + userIDs: [{ name: 'Test User', email: 'text@example.com' }] }; return openpgp.generateKey(opt); }); it('should work for undefined name', function() { const opt = { - userIds: { email: 'text@example.com' } + userIDs: { email: 'text@example.com' } }; return openpgp.generateKey(opt); }); it('should work for an undefined email address', function() { const opt = { - userIds: { name: 'Test User' } + userIDs: { name: 'Test User' } }; return openpgp.generateKey(opt); }); @@ -773,15 +773,15 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { it('should have default params set', function() { const now = util.normalizeDate(new Date()); const opt = { - userIds: { name: 'Test User', email: 'text@example.com' }, + userIDs: { name: 'Test User', email: 'text@example.com' }, passphrase: 'secret', date: now }; return openpgp.generateKey(opt).then(async function(newKey) { expect(newKey.key).to.exist; expect(newKey.key.users.length).to.equal(1); - expect(newKey.key.users[0].userId.name).to.equal('Test User'); - expect(newKey.key.users[0].userId.email).to.equal('text@example.com'); + expect(newKey.key.users[0].userID.name).to.equal('Test User'); + expect(newKey.key.users[0].userID.email).to.equal('text@example.com'); expect(newKey.key.getAlgorithmInfo().rsaBits).to.equal(undefined); expect(newKey.key.getAlgorithmInfo().curve).to.equal('ed25519'); expect(+newKey.key.getCreationTime()).to.equal(+now); @@ -800,11 +800,11 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { describe('generateKey - integration tests', function() { it('should work', function() { const opt = { - userIds: [{ name: 'Test User', email: 'text@example.com' }] + userIDs: [{ name: 'Test User', email: 'text@example.com' }] }; return openpgp.generateKey(opt).then(function(newKey) { - expect(newKey.key.getUserIds()[0]).to.equal('Test User '); + expect(newKey.key.getUserIDs()[0]).to.equal('Test User '); expect(newKey.publicKeyArmored).to.match(/^-----BEGIN PGP PUBLIC/); expect(newKey.privateKeyArmored).to.match(/^-----BEGIN PGP PRIVATE/); }); @@ -945,7 +945,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { describe('encryptKey', function() { it('should not change original key', async function() { - const { privateKeyArmored } = await openpgp.generateKey({ userIds: [{ name: 'test', email: 'test@test.com' }] }); + const { privateKeyArmored } = await openpgp.generateKey({ userIDs: [{ name: 'test', email: 'test@test.com' }] }); // read both keys from armored data to make sure all fields are exactly the same const key = await openpgp.readKey({ armoredKey: privateKeyArmored }); const originalKey = await openpgp.readKey({ armoredKey: privateKeyArmored }); @@ -966,7 +966,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }); it('encrypted key can be decrypted', async function() { - const { key } = await openpgp.generateKey({ userIds: [{ name: 'test', email: 'test@test.com' }] }); + const { key } = await openpgp.generateKey({ userIDs: [{ name: 'test', email: 'test@test.com' }] }); const locked = await openpgp.encryptKey({ privateKey: key, passphrase: passphrase @@ -980,7 +980,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }); it('should support multiple passphrases', async function() { - const { key } = await openpgp.generateKey({ userIds: [{ name: 'test', email: 'test@test.com' }] }); + const { key } = await openpgp.generateKey({ userIDs: [{ name: 'test', email: 'test@test.com' }] }); const passphrases = ['123', '456']; const locked = await openpgp.encryptKey({ privateKey: key, @@ -1446,7 +1446,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { it('should encrypt/sign and decrypt/verify with generated key', function () { const genOpt = { - userIds: [{ name: 'Test User', email: 'text@example.com' }] + userIDs: [{ name: 'Test User', email: 'text@example.com' }] }; return openpgp.generateKey(genOpt).then(async function(newKey) { @@ -1478,7 +1478,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { it('should encrypt/sign and decrypt/verify with generated key and detached signatures', async function () { const newKey = await openpgp.generateKey({ - userIds: [{ name: 'Test User', email: 'text@example.com' }] + userIDs: [{ name: 'Test User', email: 'text@example.com' }] }); const newPublicKey = await openpgp.readKey({ armoredKey: newKey.publicKeyArmored }); const newPrivateKey = await openpgp.readKey({ armoredKey: newKey.privateKeyArmored }); @@ -1771,7 +1771,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }); it('should fail to decrypt modified message', async function() { - const { privateKeyArmored } = await openpgp.generateKey({ curve: 'curve25519', userIds: [{ email: 'test@email.com' }] }); + const { privateKeyArmored } = await openpgp.generateKey({ curve: 'curve25519', userIDs: [{ email: 'test@email.com' }] }); const key = await openpgp.readKey({ armoredKey: privateKeyArmored }); const data = await openpgp.encrypt({ message: openpgp.Message.fromBinary(new Uint8Array(500)), publicKeys: [key.toPublic()] }); let badSumEncrypted = data.replace(/\n=[a-zA-Z0-9/+]{4}/, '\n=aaaa'); @@ -1825,7 +1825,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }); it('should fail to decrypt unarmored message with garbage data appended', async function() { - const { key } = await openpgp.generateKey({ userIds: {} }); + const { key } = await openpgp.generateKey({ userIDs: {} }); const message = await openpgp.encrypt({ message: openpgp.Message.fromText('test'), publicKeys: key, privateKeys: key, armor: false }); const encrypted = util.concat([message, new Uint8Array([11])]); await expect( @@ -2709,7 +2709,7 @@ amnR6g== curves.forEach(curve => { it(`sign/verify with ${curve}`, async function() { const plaintext = 'short message'; - const key = (await openpgp.generateKey({ curve, userIds: { name: 'Alice', email: 'info@alice.com' } })).key; + const key = (await openpgp.generateKey({ curve, userIDs: { name: 'Alice', email: 'info@alice.com' } })).key; const signed = await openpgp.sign({ privateKeys:[key], message: openpgp.CleartextMessage.fromText(plaintext) }); const verified = await openpgp.verify({ publicKeys:[key], message: await openpgp.readCleartextMessage({ cleartextMessage: signed }) }); expect(verified.signatures[0].valid).to.be.true; diff --git a/test/general/packet.js b/test/general/packet.js index f09e38ad4..d9752af24 100644 --- a/test/general/packet.js +++ b/test/general/packet.js @@ -703,12 +703,12 @@ module.exports = () => describe("Packet", function() { it('Secret key reading with signature verification.', async function() { const packets = new openpgp.PacketList(); await packets.read((await openpgp.unarmor(armored_key)).data, openpgp); - const [keyPacket, userIdPacket, keySigPacket, subkeyPacket, subkeySigPacket] = packets; + const [keyPacket, userIDPacket, keySigPacket, subkeyPacket, subkeySigPacket] = packets; expect(keySigPacket.verified).to.be.null; expect(subkeySigPacket.verified).to.be.null; await keySigPacket.verify( - keyPacket, openpgp.enums.signature.certGeneric, { userId: userIdPacket, key: keyPacket } + keyPacket, openpgp.enums.signature.certGeneric, { userID: userIDPacket, key: keyPacket } ).then(async () => expect(keySigPacket.verified).to.be.true); await subkeySigPacket.verify( keyPacket, openpgp.enums.signature.keyBinding, { key: keyPacket, bind: subkeyPacket } @@ -757,7 +757,7 @@ module.exports = () => describe("Packet", function() { }); }); - it('Reading signersUserId from armored signature', async function() { + it('Reading signersUserID from armored signature', async function() { const armoredSignature = `-----BEGIN PGP SIGNATURE----- @@ -773,7 +773,7 @@ kePFjAnu9cpynKXu3usf8+FuBw2zLsg1Id1n7ttxoAte416KjBN9lFBt8mcu const signature = await openpgp.readSignature({ armoredSignature }); - expect(signature.packets[0].signersUserId).to.equal('test-wkd@metacode.biz'); + expect(signature.packets[0].signersUserID).to.equal('test-wkd@metacode.biz'); }); it('Reading notations from armored key', async function() { diff --git a/test/general/signature.js b/test/general/signature.js index 298e1f2be..88445efb5 100644 --- a/test/general/signature.js +++ b/test/general/signature.js @@ -884,8 +884,8 @@ hUhMKMuiM3pRwdIyDOItkUWQmjEEw7/XmhgInkXsCw== await expect(openpgp.sign({ message: openpgp.Message.fromText('test'), privateKeys: [priv_key_gnupg_ext], config: { rejectPublicKeyAlgorithms: new Set() } })).to.eventually.be.rejectedWith(/Cannot sign with a gnu-dummy key/); - await expect(openpgp.reformatKey({ userIds: { name: 'test' }, privateKey: priv_key_gnupg_ext })).to.eventually.be.rejectedWith(/Cannot reformat a gnu-dummy primary key/); - await expect(openpgp.reformatKey({ userIds: { name: 'test' }, privateKey: priv_key_gnupg_ext_2, passphrase: 'test' })).to.eventually.be.rejectedWith(/Cannot reformat a gnu-dummy primary key/); + await expect(openpgp.reformatKey({ userIDs: { name: 'test' }, privateKey: priv_key_gnupg_ext })).to.eventually.be.rejectedWith(/Cannot reformat a gnu-dummy primary key/); + await expect(openpgp.reformatKey({ userIDs: { name: 'test' }, privateKey: priv_key_gnupg_ext_2, passphrase: 'test' })).to.eventually.be.rejectedWith(/Cannot reformat a gnu-dummy primary key/); await priv_key_gnupg_ext.encrypt("abcd"); expect(priv_key_gnupg_ext.isDecrypted()).to.be.false; const primaryKey_packet2 = priv_key_gnupg_ext.primaryKey.write(); @@ -1581,7 +1581,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA const privKey2 = await openpgp.readKey({ armoredKey: priv_key_arm2 }); await privKey2.decrypt('hello world'); - const opt = { rsaBits: 2048, userIds: { name:'test', email:'a@b.com' }, passphrase: null }; + const opt = { rsaBits: 2048, userIDs: { name:'test', email:'a@b.com' }, passphrase: null }; const { key: generatedKey } = await openpgp.generateKey(opt); const armoredSignature = await openpgp.sign({ privateKeys:[generatedKey, privKey2], message, detached: true, config: { minRSABits: 1024 } }); const signature = await openpgp.readSignature({ armoredSignature }); @@ -1592,7 +1592,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA }); it('Sign message with key without password', function() { - const opt = { userIds: { name:'test', email:'a@b.com' }, passphrase: null }; + const opt = { userIDs: { name:'test', email:'a@b.com' }, passphrase: null }; return openpgp.generateKey(opt).then(function(gen) { const key = gen.key; const message = openpgp.Message.fromText('hello world'); diff --git a/test/general/x25519.js b/test/general/x25519.js index 19a08742e..b90cf0e26 100644 --- a/test/general/x25519.js +++ b/test/general/x25519.js @@ -379,7 +379,7 @@ module.exports = () => (openpgp.config.ci ? describe.skip : describe)('X25519 Cr function omnibus() { it('Omnibus Ed25519/Curve25519 Test', function() { const options = { - userIds: { name: "Hi", email: "hi@hel.lo" }, + userIDs: { name: "Hi", email: "hi@hel.lo" }, curve: "ed25519" }; return openpgp.generateKey(options).then(async function(firstKey) { @@ -404,7 +404,7 @@ function omnibus() { const certificate = user.selfCertifications[0]; certificate.verified = null; await certificate.verify( - primaryKey, openpgp.enums.signature.certGeneric, { userId: user.userId, key: primaryKey } + primaryKey, openpgp.enums.signature.certGeneric, { userID: user.userID, key: primaryKey } ).then(async () => expect(certificate.verified).to.be.true); certificate.verified = null; @@ -413,7 +413,7 @@ function omnibus() { ).then(async () => expect(certificate.verified).to.be.true); const options = { - userIds: { name: "Bye", email: "bye@good.bye" }, + userIDs: { name: "Bye", email: "bye@good.bye" }, curve: "curve25519" }; return openpgp.generateKey(options).then(async function(secondKey) { @@ -428,7 +428,7 @@ function omnibus() { const certificate = user.selfCertifications[0]; certificate.verified = null; await certificate.verify( - bye.primaryKey, openpgp.enums.signature.certGeneric, { userId: user.userId, key: bye.primaryKey } + bye.primaryKey, openpgp.enums.signature.certGeneric, { userID: user.userID, key: bye.primaryKey } ).then(async () => expect(certificate.verified).to.be.true); certificate.verified = null; await user.verifyCertificate( @@ -442,7 +442,7 @@ function omnibus() { expect(hiCertificate.verified).to.be.true; hiCertificate.verified = null; return hiCertificate.verify( - primaryKey, openpgp.enums.signature.certGeneric, { userId: user.userId, key: bye.toPublic().primaryKey } + primaryKey, openpgp.enums.signature.certGeneric, { userID: user.userID, key: bye.toPublic().primaryKey } ).then(async () => expect(hiCertificate.verified).to.be.true); }), // Signing message diff --git a/test/security/subkey_trust.js b/test/security/subkey_trust.js index 8b9634f5d..213143bea 100644 --- a/test/security/subkey_trust.js +++ b/test/security/subkey_trust.js @@ -9,7 +9,7 @@ const expect = chai.expect; async function generateTestData() { const victimPrivKey = (await openpgp.generateKey({ - userIds: [{ name: 'Victim', email: 'victim@example.com' }], + userIDs: [{ name: 'Victim', email: 'victim@example.com' }], type: 'rsa', rsaBits: 2048, subkeys: [{ @@ -19,7 +19,7 @@ async function generateTestData() { victimPrivKey.revocationSignatures = []; const attackerPrivKey = (await openpgp.generateKey({ - userIds: [{ name: 'Attacker', email: 'attacker@example.com' }], + userIDs: [{ name: 'Attacker', email: 'attacker@example.com' }], type: 'rsa', rsaBits: 2048, subkeys: [], diff --git a/test/typescript/definitions.ts b/test/typescript/definitions.ts index 84eae234a..5281bf481 100644 --- a/test/typescript/definitions.ts +++ b/test/typescript/definitions.ts @@ -13,7 +13,7 @@ import { expect } from 'chai'; (async () => { // Generate keys - const { publicKeyArmored, key } = await generateKey({ userIds: [{ email: "user@corp.co" }], config: { v5Keys: true } }); + const { publicKeyArmored, key } = await generateKey({ userIDs: [{ email: "user@corp.co" }], config: { v5Keys: true } }); expect(key).to.be.instanceOf(Key); const privateKeys = [key]; const publicKeys = [key.toPublic()]; From 52e9bb1f7c623f909a51f6a27a478b4d1a6c7a72 Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Thu, 18 Mar 2021 22:49:22 +0100 Subject: [PATCH 04/18] Always lowercase first word in camelCase --- README.md | 2 +- openpgp.d.ts | 2 +- src/config/config.js | 16 +++--- src/key/factory.js | 4 +- src/message.js | 2 +- src/packet/aead_encrypted_data.js | 2 +- src/packet/secret_key.js | 2 +- src/packet/sym_encrypted_session_key.js | 2 +- src/type/s2k.js | 2 +- test/general/config.js | 20 +++---- test/general/key.js | 16 +++--- test/general/openpgp.js | 30 +++++----- test/general/packet.js | 74 ++++++++++++------------- test/general/streaming.js | 36 ++++++------ test/unittests.js | 2 +- 15 files changed, 106 insertions(+), 106 deletions(-) diff --git a/README.md b/README.md index 759cb058b..90560acbf 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ library to convert back and forth between them. * If the user's browser supports [native WebCrypto](https://caniuse.com/#feat=cryptography) via the `window.crypto.subtle` API, this will be used. Under Node.js the native [crypto module](https://nodejs.org/api/crypto.html#crypto_crypto) is used. -* The library implements the [IETF proposal](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10) for authenticated encryption using native AES-EAX, OCB, or GCM. This makes symmetric encryption up to 30x faster on supported platforms. Since the specification has not been finalized and other OpenPGP implementations haven't adopted it yet, the feature is currently behind a flag. **Note: activating this setting can break compatibility with other OpenPGP implementations, and also with future versions of OpenPGP.js. Don't use it with messages you want to store on disk or in a database.** You can enable it by setting `openpgp.config.AEADProtect = true`. +* The library implements the [IETF proposal](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10) for authenticated encryption using native AES-EAX, OCB, or GCM. This makes symmetric encryption up to 30x faster on supported platforms. Since the specification has not been finalized and other OpenPGP implementations haven't adopted it yet, the feature is currently behind a flag. **Note: activating this setting can break compatibility with other OpenPGP implementations, and also with future versions of OpenPGP.js. Don't use it with messages you want to store on disk or in a database.** You can enable it by setting `openpgp.config.aeadProtect = true`. You can change the AEAD mode by setting one of the following options: diff --git a/openpgp.d.ts b/openpgp.d.ts index 510e3b3f9..f560b0ea2 100644 --- a/openpgp.d.ts +++ b/openpgp.d.ts @@ -316,7 +316,7 @@ interface Config { showVersion: boolean; showComment: boolean; deflateLevel: number; - AEADProtect: boolean; + aeadProtect: boolean; allowUnauthenticatedMessages: boolean; allowUnauthenticatedStream: boolean; checksumRequired: boolean; diff --git a/src/config/config.js b/src/config/config.js index 56be4c200..1ee56f8bc 100644 --- a/src/config/config.js +++ b/src/config/config.js @@ -49,24 +49,24 @@ export default { * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07} * @memberof module:config - * @property {Boolean} AEADProtect + * @property {Boolean} aeadProtect */ - AEADProtect: false, + aeadProtect: false, /** * Default Authenticated Encryption with Additional Data (AEAD) encryption mode - * Only has an effect when AEADProtect is set to true. + * Only has an effect when aeadProtect is set to true. * @memberof module:config * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead} */ preferredAEADAlgorithm: enums.aead.eax, /** * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode - * Only has an effect when AEADProtect is set to true. + * Only has an effect when aeadProtect is set to true. * Must be an integer value from 0 to 56. * @memberof module:config - * @property {Integer} AEADChunkSizeByte + * @property {Integer} aeadChunkSizeByte */ - AEADChunkSizeByte: 12, + aeadChunkSizeByte: 12, /** * Use V5 keys. * Note: not all OpenPGP implementations are compatible with this option. @@ -79,9 +79,9 @@ export default { * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}: * Iteration Count Byte for S2K (String to Key) * @memberof module:config - * @property {Integer} S2KIterationCountByte + * @property {Integer} s2kIterationCountByte */ - S2KIterationCountByte: 224, + s2kIterationCountByte: 224, /** * Allow decryption of messages without integrity protection. * This is an **insecure** setting: diff --git a/src/key/factory.js b/src/key/factory.js index 0b3c29d86..ec5095b1e 100644 --- a/src/key/factory.js +++ b/src/key/factory.js @@ -153,7 +153,7 @@ async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, conf enums.symmetric.aes128, enums.symmetric.aes192 ], config.preferredSymmetricAlgorithm); - if (config.AEADProtect) { + if (config.aeadProtect) { signaturePacket.preferredAEADAlgorithms = createPreferredAlgos([ enums.aead.eax, enums.aead.ocb @@ -175,7 +175,7 @@ async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, conf // integrity protection always enabled signaturePacket.features = [0]; signaturePacket.features[0] |= enums.features.modificationDetection; - if (config.AEADProtect) { + if (config.aeadProtect) { signaturePacket.features[0] |= enums.features.aead; } if (config.v5Keys) { diff --git a/src/message.js b/src/message.js index f853e355f..414996f25 100644 --- a/src/message.js +++ b/src/message.js @@ -283,7 +283,7 @@ export class Message { */ static async generateSessionKey(keys = [], date = new Date(), userIDs = [], config = defaultConfig) { const algorithm = enums.read(enums.symmetric, await getPreferredAlgo('symmetric', keys, date, userIDs, config)); - const aeadAlgorithm = config.AEADProtect && await isAeadSupported(keys, date, userIDs, config) ? + const aeadAlgorithm = config.aeadProtect && await isAeadSupported(keys, date, userIDs, config) ? enums.read(enums.aead, await getPreferredAlgo('aead', keys, date, userIDs, config)) : undefined; diff --git a/src/packet/aead_encrypted_data.js b/src/packet/aead_encrypted_data.js index cac47c3e4..94ffc776c 100644 --- a/src/packet/aead_encrypted_data.js +++ b/src/packet/aead_encrypted_data.js @@ -106,7 +106,7 @@ class AEADEncryptedDataPacket { this.aeadAlgo = enums.write(enums.aead, this.aeadAlgorithm); const mode = crypto[enums.read(enums.aead, this.aeadAlgo)]; this.iv = await crypto.random.getRandomBytes(mode.ivLength); // generate new random IV - this.chunkSizeByte = config.AEADChunkSizeByte; + this.chunkSizeByte = config.aeadChunkSizeByte; const data = this.packets.write(); this.encrypted = await this.crypt('encrypt', key, data, streaming); } diff --git a/src/packet/secret_key.js b/src/packet/secret_key.js index af3d93fa8..bef72d17a 100644 --- a/src/packet/secret_key.js +++ b/src/packet/secret_key.js @@ -296,7 +296,7 @@ class SecretKeyPacket extends PublicKeyPacket { const blockLen = crypto.cipher[this.symmetric].blockSize; this.iv = await crypto.random.getRandomBytes(blockLen); - if (config.AEADProtect) { + if (config.aeadProtect) { this.s2k_usage = 253; this.aead = 'eax'; const mode = crypto[this.aead]; diff --git a/src/packet/sym_encrypted_session_key.js b/src/packet/sym_encrypted_session_key.js index e07e8d9c9..0868c833d 100644 --- a/src/packet/sym_encrypted_session_key.js +++ b/src/packet/sym_encrypted_session_key.js @@ -40,7 +40,7 @@ class SymEncryptedSessionKeyPacket { */ constructor(config = defaultConfig) { this.tag = enums.packet.symEncryptedSessionKey; - this.version = config.AEADProtect ? 5 : 4; + this.version = config.aeadProtect ? 5 : 4; this.sessionKey = null; this.sessionKeyEncryptionAlgorithm = null; this.sessionKeyAlgorithm = 'aes256'; diff --git a/src/type/s2k.js b/src/type/s2k.js index 67ccaac10..6873fe6fe 100644 --- a/src/type/s2k.js +++ b/src/type/s2k.js @@ -43,7 +43,7 @@ class S2K { /** @type {module:enums.s2k} */ this.type = 'iterated'; /** @type {Integer} */ - this.c = config.S2KIterationCountByte; + this.c = config.s2kIterationCountByte; /** Eight bytes of salt in a binary string. * @type {String} */ diff --git a/test/general/config.js b/test/general/config.js index 1e2c0243c..462fffab9 100644 --- a/test/general/config.js +++ b/test/general/config.js @@ -122,8 +122,8 @@ module.exports = () => describe('Custom configuration', function() { }); it('openpgp.encryptKey', async function() { - const S2KIterationCountByteVal = openpgp.config.S2KIterationCountByte; - openpgp.config.S2KIterationCountByte = 224; + const s2kIterationCountByteVal = openpgp.config.s2kIterationCountByte; + openpgp.config.s2kIterationCountByte = 224; try { const passphrase = '12345678'; @@ -131,20 +131,20 @@ module.exports = () => describe('Custom configuration', function() { const { key: privateKey } = await openpgp.generateKey({ userIDs }); const encKey = await openpgp.encryptKey({ privateKey, userIDs, passphrase }); - expect(encKey.keyPacket.s2k.c).to.equal(openpgp.config.S2KIterationCountByte); + expect(encKey.keyPacket.s2k.c).to.equal(openpgp.config.s2kIterationCountByte); - const config = { S2KIterationCountByte: 123 }; + const config = { s2kIterationCountByte: 123 }; const encKey2 = await openpgp.encryptKey({ privateKey, userIDs, passphrase, config }); - expect(encKey2.keyPacket.s2k.c).to.equal(config.S2KIterationCountByte); + expect(encKey2.keyPacket.s2k.c).to.equal(config.s2kIterationCountByte); } finally { - openpgp.config.S2KIterationCountByte = S2KIterationCountByteVal; + openpgp.config.s2kIterationCountByte = s2kIterationCountByteVal; } }); it('openpgp.encrypt', async function() { - const AEADProtectVal = openpgp.config.AEADProtect; + const aeadProtectVal = openpgp.config.aeadProtect; const preferredCompressionAlgorithmVal = openpgp.config.preferredCompressionAlgorithm; - openpgp.config.AEADProtect = false; + openpgp.config.aeadProtect = false; openpgp.config.preferredCompressionAlgorithm = openpgp.enums.compression.uncompressed; try { @@ -160,7 +160,7 @@ module.exports = () => describe('Custom configuration', function() { expect(literal.tag).to.equal(openpgp.enums.packet.literalData); const config = { - AEADProtect: true, + aeadProtect: true, preferredCompressionAlgorithm: openpgp.enums.compression.zip, deflateLevel: 1 }; @@ -179,7 +179,7 @@ module.exports = () => describe('Custom configuration', function() { message, publicKeys: [key], config: { rejectPublicKeyAlgorithms: new Set([openpgp.enums.publicKey.ecdh]) } })).to.be.eventually.rejectedWith(/ecdh keys are considered too weak/); } finally { - openpgp.config.AEADProtect = AEADProtectVal; + openpgp.config.aeadProtect = aeadProtectVal; openpgp.config.preferredCompressionAlgorithm = preferredCompressionAlgorithmVal; } }); diff --git a/test/general/key.js b/test/general/key.js index 5592e3ab3..27ab9872f 100644 --- a/test/general/key.js +++ b/test/general/key.js @@ -2085,7 +2085,7 @@ function versionSpecificTests() { expect(key.subKeys[0].bindingSignatures[0].keyFlags[0] & keyFlags.encryptStorage).to.equal(keyFlags.encryptStorage); const sym = openpgp.enums.symmetric; expect(key.users[0].selfCertifications[0].preferredSymmetricAlgorithms).to.eql([sym.aes256, sym.aes128, sym.aes192]); - if (openpgp.config.AEADProtect) { + if (openpgp.config.aeadProtect) { const aead = openpgp.enums.aead; expect(key.users[0].selfCertifications[0].preferredAEADAlgorithms).to.eql([aead.eax, aead.ocb]); } @@ -2097,7 +2097,7 @@ function versionSpecificTests() { let expectedFeatures; if (openpgp.config.v5Keys) { expectedFeatures = [7]; // v5 + aead + mdc - } else if (openpgp.config.AEADProtect) { + } else if (openpgp.config.aeadProtect) { expectedFeatures = [3]; // aead + mdc } else { expectedFeatures = [1]; // mdc @@ -2130,7 +2130,7 @@ function versionSpecificTests() { expect(key.subKeys[0].bindingSignatures[0].keyFlags[0] & keyFlags.encryptStorage).to.equal(keyFlags.encryptStorage); const sym = openpgp.enums.symmetric; expect(key.users[0].selfCertifications[0].preferredSymmetricAlgorithms).to.eql([sym.aes192, sym.aes256, sym.aes128]); - if (openpgp.config.AEADProtect) { + if (openpgp.config.aeadProtect) { const aead = openpgp.enums.aead; expect(key.users[0].selfCertifications[0].preferredAEADAlgorithms).to.eql([aead.experimentalGcm, aead.eax, aead.ocb]); } @@ -2142,7 +2142,7 @@ function versionSpecificTests() { let expectedFeatures; if (openpgp.config.v5Keys) { expectedFeatures = [7]; // v5 + aead + mdc - } else if (openpgp.config.AEADProtect) { + } else if (openpgp.config.aeadProtect) { expectedFeatures = [3]; // aead + mdc } else { expectedFeatures = [1]; // mdc @@ -2691,7 +2691,7 @@ function versionSpecificTests() { module.exports = () => describe('Key', function() { let v5KeysVal; - let AEADProtectVal; + let aeadProtectVal; tryTests('V4', versionSpecificTests, { if: !openpgp.config.ci, @@ -2708,13 +2708,13 @@ module.exports = () => describe('Key', function() { if: !openpgp.config.ci, beforeEach: function() { v5KeysVal = openpgp.config.v5Keys; - AEADProtectVal = openpgp.config.AEADProtect; + aeadProtectVal = openpgp.config.aeadProtect; openpgp.config.v5Keys = true; - openpgp.config.AEADProtect = true; + openpgp.config.aeadProtect = true; }, afterEach: function() { openpgp.config.v5Keys = v5KeysVal; - openpgp.config.AEADProtect = AEADProtectVal; + openpgp.config.aeadProtect = aeadProtectVal; } }); diff --git a/test/general/openpgp.js b/test/general/openpgp.js index aa940e27d..3e72c8660 100644 --- a/test/general/openpgp.js +++ b/test/general/openpgp.js @@ -823,9 +823,9 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { let publicKeyNoAEAD; let privateKeyMismatchingParams; - let AEADProtectVal; + let aeadProtectVal; let preferredAEADAlgorithmVal; - let AEADChunkSizeByteVal; + let aeadChunkSizeByteVal; let v5KeysVal; let minRSABitsVal; @@ -841,9 +841,9 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { publicKey_1337 = privateKey_1337.toPublic(); privateKeyMismatchingParams = await openpgp.readKey({ armoredKey: mismatchingKeyParams }); - AEADProtectVal = openpgp.config.AEADProtect; + aeadProtectVal = openpgp.config.aeadProtect; preferredAEADAlgorithmVal = openpgp.config.preferredAEADAlgorithm; - AEADChunkSizeByteVal = openpgp.config.AEADChunkSizeByte; + aeadChunkSizeByteVal = openpgp.config.aeadChunkSizeByte; v5KeysVal = openpgp.config.v5Keys; minRSABitsVal = openpgp.config.minRSABits; @@ -851,9 +851,9 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }); afterEach(function() { - openpgp.config.AEADProtect = AEADProtectVal; + openpgp.config.aeadProtect = aeadProtectVal; openpgp.config.preferredAEADAlgorithm = preferredAEADAlgorithmVal; - openpgp.config.AEADChunkSizeByte = AEADChunkSizeByteVal; + openpgp.config.aeadChunkSizeByte = aeadChunkSizeByteVal; openpgp.config.v5Keys = v5KeysVal; openpgp.config.minRSABits = minRSABitsVal; }); @@ -1033,14 +1033,14 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { tryTests('CFB mode (asm.js)', tests, { if: true, beforeEach: function() { - openpgp.config.AEADProtect = false; + openpgp.config.aeadProtect = false; } }); tryTests('GCM mode (V5 keys)', tests, { if: true, beforeEach: function() { - openpgp.config.AEADProtect = true; + openpgp.config.aeadProtect = true; openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.experimentalGcm; openpgp.config.v5Keys = true; @@ -1054,8 +1054,8 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { tryTests('EAX mode (small chunk size)', tests, { if: true, beforeEach: function() { - openpgp.config.AEADProtect = true; - openpgp.config.AEADChunkSizeByte = 0; + openpgp.config.aeadProtect = true; + openpgp.config.aeadChunkSizeByte = 0; // Monkey-patch AEAD feature flag publicKey.users[0].selfCertifications[0].features = [7]; @@ -1067,7 +1067,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { tryTests('OCB mode', tests, { if: !openpgp.config.ci, beforeEach: function() { - openpgp.config.AEADProtect = true; + openpgp.config.aeadProtect = true; openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.ocb; // Monkey-patch AEAD feature flag @@ -1410,7 +1410,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }; return openpgp.encrypt(encOpt).then(async function (encrypted) { decOpt.message = await openpgp.readMessage({ armoredMessage: encrypted }); - expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(openpgp.config.AEADProtect); + expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(openpgp.config.aeadProtect); return openpgp.decrypt(decOpt); }).then(async function (decrypted) { expect(decrypted.data).to.equal(plaintext); @@ -1464,7 +1464,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }; return openpgp.encrypt(encOpt).then(async function (encrypted) { decOpt.message = await openpgp.readMessage({ armoredMessage: encrypted }); - expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(openpgp.config.AEADProtect); + expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(openpgp.config.aeadProtect); return openpgp.decrypt(decOpt); }).then(async function (decrypted) { expect(decrypted.data).to.equal(plaintext); @@ -1493,7 +1493,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { detached: true }); const message = await openpgp.readMessage({ armoredMessage: encrypted }); - expect(!!message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(openpgp.config.AEADProtect); + expect(!!message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(openpgp.config.aeadProtect); const decrypted = await openpgp.decrypt({ message, signature: await openpgp.readSignature({ armoredSignature: signed }), @@ -1813,7 +1813,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(e.message).to.match(/Ascii armor integrity check on message failed/); expect(stepReached).to.equal( j === 0 ? 0 : - (openpgp.config.AEADChunkSizeByte === 0 && (j === 2 || util.detectNode() || util.getHardwareConcurrency() < 8)) || (!openpgp.config.AEADProtect && openpgp.config.allowUnauthenticatedStream) ? 2 : + (openpgp.config.aeadChunkSizeByte === 0 && (j === 2 || util.detectNode() || util.getHardwareConcurrency() < 8)) || (!openpgp.config.aeadProtect && openpgp.config.allowUnauthenticatedStream) ? 2 : 1 ); return; diff --git a/test/general/packet.js b/test/general/packet.js index d9752af24..2490fe469 100644 --- a/test/general/packet.js +++ b/test/general/packet.js @@ -66,9 +66,9 @@ module.exports = () => describe("Packet", function() { '-----END PGP PRIVATE KEY BLOCK-----'; it('Symmetrically encrypted packet without integrity protection - allow decryption', async function() { - const AEADProtectVal = openpgp.config.AEADProtect; + const aeadProtectVal = openpgp.config.aeadProtect; const allowUnauthenticatedMessagesVal = openpgp.config.allowUnauthenticatedMessages; - openpgp.config.AEADProtect = false; + openpgp.config.aeadProtect = false; openpgp.config.allowUnauthenticatedMessages = true; const message = new openpgp.PacketList(); @@ -93,14 +93,14 @@ module.exports = () => describe("Packet", function() { expect(await stringify(msg2[0].packets[0].data)).to.equal(stringify(literal.data)); } finally { - openpgp.config.AEADProtect = AEADProtectVal; + openpgp.config.aeadProtect = aeadProtectVal; openpgp.config.allowUnauthenticatedMessages = allowUnauthenticatedMessagesVal; } }); it('Symmetrically encrypted packet without integrity protection - disallow decryption by default', async function() { - const AEADProtectVal = openpgp.config.AEADProtect; - openpgp.config.AEADProtect = false; + const aeadProtectVal = openpgp.config.aeadProtect; + openpgp.config.aeadProtect = false; try { const message = new openpgp.PacketList(); @@ -122,7 +122,7 @@ module.exports = () => describe("Packet", function() { await msg2.read(message.write(), { SymmetricallyEncryptedDataPacket: openpgp.SymmetricallyEncryptedDataPacket }); await expect(msg2[0].decrypt(algo, key, undefined, openpgp.config)).to.eventually.be.rejectedWith('Message is not authenticated.'); } finally { - openpgp.config.AEADProtect = AEADProtectVal; + openpgp.config.aeadProtect = aeadProtectVal; } }); @@ -149,8 +149,8 @@ module.exports = () => describe("Packet", function() { }); it('Sym. encrypted AEAD protected packet', function() { - const AEADProtectVal = openpgp.config.AEADProtect; - openpgp.config.AEADProtect = false; + const aeadProtectVal = openpgp.config.aeadProtect; + openpgp.config.aeadProtect = false; try { 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]); @@ -173,7 +173,7 @@ module.exports = () => describe("Packet", function() { expect(await openpgp.stream.readToEnd(msg2[0].packets[0].data)).to.deep.equal(literal.data); }); } finally { - openpgp.config.AEADProtect = AEADProtectVal; + openpgp.config.aeadProtect = aeadProtectVal; } }); @@ -220,7 +220,7 @@ module.exports = () => describe("Packet", function() { const msg2 = new openpgp.PacketList(); try { - await enc.encrypt(algo, key, undefined, { ...openpgp.config, AEADChunkSizeByte: 0 }); + await enc.encrypt(algo, key, undefined, { ...openpgp.config, aeadChunkSizeByte: 0 }); 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); @@ -265,7 +265,7 @@ module.exports = () => describe("Packet", function() { randomBytesStub.returns(iv); try { - await enc.encrypt(algo, key, undefined, { ...openpgp.config, AEADChunkSizeByte: 14 }); + await enc.encrypt(algo, key, undefined, { ...openpgp.config, aeadChunkSizeByte: 14 }); const data = msg.write(); expect(await openpgp.stream.readToEnd(openpgp.stream.clone(data))).to.deep.equal(packetBytes); await msg2.read(data, openpgp); @@ -436,8 +436,8 @@ module.exports = () => describe("Packet", function() { }); it('Sym. encrypted session key reading/writing (CFB)', async function() { - const AEADProtectVal = openpgp.config.AEADProtect; - openpgp.config.AEADProtect = false; + const aeadProtectVal = openpgp.config.aeadProtect; + openpgp.config.aeadProtect = false; try { const passphrase = 'hello'; @@ -470,13 +470,13 @@ module.exports = () => describe("Packet", function() { expect(await stringify(msg2[1].packets[0].data)).to.equal(stringify(literal.data)); } finally { - openpgp.config.AEADProtect = AEADProtectVal; + openpgp.config.aeadProtect = aeadProtectVal; } }); it('Sym. encrypted session key reading/writing (AEAD)', async function() { - const AEADProtectVal = openpgp.config.AEADProtect; - openpgp.config.AEADProtect = true; + const aeadProtectVal = openpgp.config.aeadProtect; + openpgp.config.aeadProtect = true; try { const passphrase = 'hello'; @@ -509,7 +509,7 @@ module.exports = () => describe("Packet", function() { expect(await stringify(msg2[1].packets[0].data)).to.equal(stringify(literal.data)); } finally { - openpgp.config.AEADProtect = AEADProtectVal; + openpgp.config.aeadProtect = aeadProtectVal; } }); @@ -519,12 +519,12 @@ module.exports = () => describe("Packet", function() { const nodeCrypto = util.getNodeCrypto(); if (!nodeCrypto) return; - const AEADProtectVal = openpgp.config.AEADProtect; - const AEADChunkSizeByteVal = openpgp.config.AEADChunkSizeByte; - const S2KIterationCountByteVal = openpgp.config.S2KIterationCountByte; - openpgp.config.AEADProtect = true; - openpgp.config.AEADChunkSizeByte = 14; - openpgp.config.S2KIterationCountByte = 0x90; + const aeadProtectVal = openpgp.config.aeadProtect; + const aeadChunkSizeByteVal = openpgp.config.aeadChunkSizeByte; + const s2kIterationCountByteVal = openpgp.config.s2kIterationCountByte; + openpgp.config.aeadProtect = true; + openpgp.config.aeadChunkSizeByte = 14; + openpgp.config.s2kIterationCountByte = 0x90; const salt = util.hexToUint8Array(`cd5a9f70fbe0bc65`); const sessionKey = util.hexToUint8Array(`86 f1 ef b8 69 52 32 9f 24 ac d3 bf d0 e5 34 6d`.replace(/\s+/g, '')); @@ -584,9 +584,9 @@ module.exports = () => describe("Packet", function() { expect(await stringify(msg2[1].packets[0].data)).to.equal(stringify(literal.data)); } finally { - openpgp.config.AEADProtect = AEADProtectVal; - openpgp.config.AEADChunkSizeByte = AEADChunkSizeByteVal; - openpgp.config.S2KIterationCountByte = S2KIterationCountByteVal; + openpgp.config.aeadProtect = aeadProtectVal; + openpgp.config.aeadChunkSizeByte = aeadChunkSizeByteVal; + openpgp.config.s2kIterationCountByte = s2kIterationCountByteVal; randomBytesStub.restore(); } }); @@ -597,12 +597,12 @@ module.exports = () => describe("Packet", function() { const nodeCrypto = util.getNodeCrypto(); if (!nodeCrypto) return; - const AEADProtectVal = openpgp.config.AEADProtect; - const AEADChunkSizeByteVal = openpgp.config.AEADChunkSizeByte; - const S2KIterationCountByteVal = openpgp.config.S2KIterationCountByte; - openpgp.config.AEADProtect = true; - openpgp.config.AEADChunkSizeByte = 14; - openpgp.config.S2KIterationCountByte = 0x90; + const aeadProtectVal = openpgp.config.aeadProtect; + const aeadChunkSizeByteVal = openpgp.config.aeadChunkSizeByte; + const s2kIterationCountByteVal = openpgp.config.s2kIterationCountByte; + openpgp.config.aeadProtect = true; + openpgp.config.aeadChunkSizeByte = 14; + openpgp.config.s2kIterationCountByte = 0x90; const salt = util.hexToUint8Array(`9f0b7da3e5ea6477`); const sessionKey = util.hexToUint8Array(`d1 f0 1b a3 0e 13 0a a7 d2 58 2c 16 e0 50 ae 44`.replace(/\s+/g, '')); @@ -663,9 +663,9 @@ module.exports = () => describe("Packet", function() { expect(await stringify(msg2[1].packets[0].data)).to.equal(stringify(literal.data)); } finally { - openpgp.config.AEADProtect = AEADProtectVal; - openpgp.config.AEADChunkSizeByte = AEADChunkSizeByteVal; - openpgp.config.S2KIterationCountByte = S2KIterationCountByteVal; + openpgp.config.aeadProtect = aeadProtectVal; + openpgp.config.aeadChunkSizeByte = aeadChunkSizeByteVal; + openpgp.config.s2kIterationCountByte = s2kIterationCountByteVal; randomBytesStub.restore(); } }); @@ -843,7 +843,7 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ secretKeyPacket.publicParams = publicParams; secretKeyPacket.algorithm = "rsaSign"; secretKeyPacket.isEncrypted = false; - await secretKeyPacket.encrypt('hello', { ...openpgp.config, AEADProtect: true }); + await secretKeyPacket.encrypt('hello', { ...openpgp.config, aeadProtect: true }); expect(secretKeyPacket.s2k_usage).to.equal(253); const raw = new openpgp.PacketList(); @@ -865,7 +865,7 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ secretKeyPacket.publicParams = publicParams; secretKeyPacket.algorithm = "rsaSign"; secretKeyPacket.isEncrypted = false; - await secretKeyPacket.encrypt('hello', { ...openpgp.config, AEADProtect: false }); + await secretKeyPacket.encrypt('hello', { ...openpgp.config, aeadProtect: false }); expect(secretKeyPacket.s2k_usage).to.equal(254); const raw = new openpgp.PacketList(); diff --git a/test/general/streaming.js b/test/general/streaming.js index 305e3b4d5..8f99e3086 100644 --- a/test/general/streaming.js +++ b/test/general/streaming.js @@ -249,8 +249,8 @@ function tests() { }); it('Encrypt and decrypt larger message roundtrip', async function() { - const AEADProtectValue = openpgp.config.AEADProtect; - openpgp.config.AEADProtect = false; + const aeadProtectValue = openpgp.config.aeadProtect; + openpgp.config.aeadProtect = false; const encrypted = await openpgp.encrypt({ message: openpgp.Message.fromBinary(data), passwords: ['test'], @@ -270,13 +270,13 @@ function tests() { expect(await reader.peekBytes(1024)).to.deep.equal(plaintext[0]); if (i <= 10) throw new Error('Data arrived early.'); expect(await reader.readToEnd()).to.deep.equal(util.concatUint8Array(plaintext)); - openpgp.config.AEADProtect = AEADProtectValue; + openpgp.config.aeadProtect = aeadProtectValue; }); it('Encrypt and decrypt larger message roundtrip (allowUnauthenticatedStream=true)', async function() { - const AEADProtectValue = openpgp.config.AEADProtect; + const aeadProtectValue = openpgp.config.aeadProtect; const allowUnauthenticatedStreamValue = openpgp.config.allowUnauthenticatedStream; - openpgp.config.AEADProtect = false; + openpgp.config.aeadProtect = false; openpgp.config.allowUnauthenticatedStream = true; try { const encrypted = await openpgp.encrypt({ @@ -300,7 +300,7 @@ function tests() { expect(await reader.readToEnd()).to.deep.equal(util.concatUint8Array(plaintext)); expect(decrypted.signatures).to.exist.and.have.length(0); } finally { - openpgp.config.AEADProtect = AEADProtectValue; + openpgp.config.aeadProtect = aeadProtectValue; openpgp.config.allowUnauthenticatedStream = allowUnauthenticatedStreamValue; } }); @@ -400,8 +400,8 @@ function tests() { }); it('Detect MDC modifications (allowUnauthenticatedStream=true)', async function() { - const AEADProtectValue = openpgp.config.AEADProtect; - openpgp.config.AEADProtect = false; + const aeadProtectValue = openpgp.config.aeadProtect; + openpgp.config.aeadProtect = false; const allowUnauthenticatedStreamValue = openpgp.config.allowUnauthenticatedStream; openpgp.config.allowUnauthenticatedStream = true; try { @@ -433,7 +433,7 @@ function tests() { await expect(reader.readToEnd()).to.be.rejectedWith('Modification detected.'); expect(decrypted.signatures).to.exist.and.have.length(0); } finally { - openpgp.config.AEADProtect = AEADProtectValue; + openpgp.config.aeadProtect = aeadProtectValue; openpgp.config.allowUnauthenticatedStream = allowUnauthenticatedStreamValue; } }); @@ -800,17 +800,17 @@ function tests() { }); describe('AEAD', function() { - let AEADProtectValue; - let AEADChunkSizeByteValue; + let aeadProtectValue; + let aeadChunkSizeByteValue; beforeEach(function() { - AEADProtectValue = openpgp.config.AEADProtect; - AEADChunkSizeByteValue = openpgp.config.AEADChunkSizeByte; - openpgp.config.AEADProtect = true; - openpgp.config.AEADChunkSizeByte = 4; + aeadProtectValue = openpgp.config.aeadProtect; + aeadChunkSizeByteValue = openpgp.config.aeadChunkSizeByte; + openpgp.config.aeadProtect = true; + openpgp.config.aeadChunkSizeByte = 4; }); afterEach(function() { - openpgp.config.AEADProtect = AEADProtectValue; - openpgp.config.AEADChunkSizeByte = AEADChunkSizeByteValue; + openpgp.config.aeadProtect = aeadProtectValue; + openpgp.config.aeadChunkSizeByte = aeadChunkSizeByteValue; }); @@ -836,7 +836,7 @@ function tests() { }); it('Encrypt and decrypt larger text message roundtrip (AEAD)', async function() { - openpgp.config.AEADChunkSizeByte = 0; + openpgp.config.aeadChunkSizeByte = 0; const plaintext = []; let i = 0; diff --git a/test/unittests.js b/test/unittests.js index 65ad0a6d7..756612684 100644 --- a/test/unittests.js +++ b/test/unittests.js @@ -29,7 +29,7 @@ describe('Unit Tests', function () { if (typeof window !== 'undefined') { - openpgp.config.S2KIterationCountByte = 0; + openpgp.config.s2kIterationCountByte = 0; window.location.search.substr(1).split('&').forEach(param => { const [key, value] = param.split('='); From 32e61c305962082b849822b021f299a18eb02d6e Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Thu, 18 Mar 2021 23:54:04 +0100 Subject: [PATCH 05/18] Uniform variable and class names --- README.md | 2 +- openpgp.d.ts | 4 +- src/crypto/cipher/aes.js | 6 +- src/crypto/cipher/blowfish.js | 14 ++--- src/crypto/cipher/cast5.js | 12 ++-- src/crypto/cipher/des.js | 24 ++++---- src/crypto/cipher/index.js | 4 +- src/crypto/cmac.js | 6 +- src/crypto/hash/index.js | 52 ++++++++--------- src/crypto/index.js | 6 +- src/crypto/pkcs1.js | 4 +- src/crypto/public_key/dsa.js | 8 +-- src/crypto/public_key/elliptic/curves.js | 22 +++---- src/crypto/public_key/elliptic/ecdh.js | 26 ++++----- src/crypto/public_key/elliptic/ecdsa.js | 40 ++++++------- src/crypto/public_key/elliptic/eddsa.js | 10 ++-- src/crypto/public_key/rsa.js | 62 ++++++++++---------- src/enums.js | 2 +- src/key/helper.js | 16 ++--- src/key/index.js | 4 +- src/message.js | 6 +- src/openpgp.js | 2 +- src/packet/packet.js | 34 +++++------ src/packet/secret_key.js | 2 +- src/packet/signature.js | 74 ++++++++++++------------ src/packet/sym_encrypted_session_key.js | 4 +- src/type/keyid.js | 2 +- src/type/s2k.js | 6 +- src/util.js | 12 ++-- test/crypto/aes_kw.js | 6 +- test/crypto/cipher/cast5.js | 4 +- test/crypto/rsa.js | 26 ++++----- test/general/key.js | 14 ++--- test/general/openpgp.js | 14 ++--- test/general/packet.js | 2 +- test/security/unsigned_subpackets.js | 2 +- 36 files changed, 267 insertions(+), 267 deletions(-) diff --git a/README.md b/README.md index 90560acbf..6d7443f1a 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ library to convert back and forth between them. ``` openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.eax // Default, native openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.ocb // Non-native - openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.experimentalGcm // **Non-standard**, fastest + openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.experimentalGCM // **Non-standard**, fastest ``` * For environments that don't provide native crypto, the library falls back to [asm.js](https://caniuse.com/#feat=asmjs) implementations of AES, SHA-1, and SHA-256. diff --git a/openpgp.d.ts b/openpgp.d.ts index f560b0ea2..2271eb5c6 100644 --- a/openpgp.d.ts +++ b/openpgp.d.ts @@ -663,7 +663,7 @@ declare class KeyID { bytes: string; equals(keyID: KeyID, matchWildcard?: boolean): boolean; toHex(): string; - static fromId(hex: string): KeyID; + static fromID(hex: string): KeyID; } interface DecryptMessageResult { @@ -832,6 +832,6 @@ export namespace enums { enum aead { eax = 1, ocb = 2, - experimentalGcm = 100 // Private algorithm + experimentalGCM = 100 // Private algorithm } } diff --git a/src/crypto/cipher/aes.js b/src/crypto/cipher/aes.js index 7b1fa9416..ea61cc71f 100644 --- a/src/crypto/cipher/aes.js +++ b/src/crypto/cipher/aes.js @@ -3,14 +3,14 @@ import { AES_ECB } from '@openpgp/asmcrypto.js/dist_es8/aes/ecb'; // TODO use webCrypto or nodeCrypto when possible. function aes(length) { const C = function(key) { - const aes_ecb = new AES_ECB(key); + const aesECB = new AES_ECB(key); this.encrypt = function(block) { - return aes_ecb.encrypt(block); + return aesECB.encrypt(block); }; this.decrypt = function(block) { - return aes_ecb.decrypt(block); + return aesECB.decrypt(block); }; }; diff --git a/src/crypto/cipher/blowfish.js b/src/crypto/cipher/blowfish.js index c06a0c141..eb927ab36 100644 --- a/src/crypto/cipher/blowfish.js +++ b/src/crypto/cipher/blowfish.js @@ -258,7 +258,7 @@ Blowfish.prototype._F = function(xx) { //* This method takes an array with two values, left and right //* and does NN rounds of Blowfish on them. //* -Blowfish.prototype._encrypt_block = function(vals) { +Blowfish.prototype._encryptBlock = function(vals) { let dataL = vals[0]; let dataR = vals[1]; @@ -289,7 +289,7 @@ Blowfish.prototype._encrypt_block = function(vals) { //* instead. That will involve more looping, but it won't require //* the F() method to deconstruct the vector. //* -Blowfish.prototype.encrypt_block = function(vector) { +Blowfish.prototype.encryptBlock = function(vector) { let ii; const vals = [0, 0]; const off = this.BLOCKSIZE / 2; @@ -298,7 +298,7 @@ Blowfish.prototype.encrypt_block = function(vector) { vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF); } - this._encrypt_block(vals); + this._encryptBlock(vals); const ret = []; for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { @@ -315,7 +315,7 @@ Blowfish.prototype.encrypt_block = function(vector) { //* This method takes an array with two values, left and right //* and undoes NN rounds of Blowfish on them. //* -Blowfish.prototype._decrypt_block = function(vals) { +Blowfish.prototype._decryptBlock = function(vals) { let dataL = vals[0]; let dataR = vals[1]; @@ -368,14 +368,14 @@ Blowfish.prototype.init = function(key) { const vals = [0x00000000, 0x00000000]; for (ii = 0; ii < this.NN + 2; ii += 2) { - this._encrypt_block(vals); + this._encryptBlock(vals); this.parray[ii + 0] = vals[0]; this.parray[ii + 1] = vals[1]; } for (ii = 0; ii < 4; ++ii) { for (jj = 0; jj < 256; jj += 2) { - this._encrypt_block(vals); + this._encryptBlock(vals); this.sboxes[ii][jj + 0] = vals[0]; this.sboxes[ii][jj + 1] = vals[1]; } @@ -388,7 +388,7 @@ function BF(key) { this.bf.init(key); this.encrypt = function(block) { - return this.bf.encrypt_block(block); + return this.bf.encryptBlock(block); }; } diff --git a/src/crypto/cipher/cast5.js b/src/crypto/cipher/cast5.js index 9b17050bf..85307420d 100644 --- a/src/crypto/cipher/cast5.js +++ b/src/crypto/cipher/cast5.js @@ -14,7 +14,7 @@ // CAST5 constructor -function OpenpgpSymencCast5() { +function OpenPGPSymEncCAST5() { this.BlockSize = 8; this.KeySize = 16; @@ -595,8 +595,8 @@ function OpenpgpSymencCast5() { ]; } -function Cast5(key) { - this.cast5 = new OpenpgpSymencCast5(); +function CAST5(key) { + this.cast5 = new OpenPGPSymEncCAST5(); this.cast5.setKey(key); this.encrypt = function(block) { @@ -604,7 +604,7 @@ function Cast5(key) { }; } -Cast5.blockSize = Cast5.prototype.blockSize = 8; -Cast5.keySize = Cast5.prototype.keySize = 16; +CAST5.blockSize = CAST5.prototype.blockSize = 8; +CAST5.keySize = CAST5.prototype.keySize = 16; -export default Cast5; +export default CAST5; diff --git a/src/crypto/cipher/des.js b/src/crypto/cipher/des.js index 7c335d342..8a2038c74 100644 --- a/src/crypto/cipher/des.js +++ b/src/crypto/cipher/des.js @@ -118,7 +118,7 @@ function des(keys, message, encrypt, mode, iv, padding) { //pad the message depending on the padding parameter //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt if (encrypt) { - message = des_addPadding(message, padding); + message = desAddPadding(message, padding); len = message.length; } @@ -234,18 +234,18 @@ function des(keys, message, encrypt, mode, iv, padding) { //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt if (!encrypt) { - result = des_removePadding(result, padding); + result = desRemovePadding(result, padding); } return result; } //end of des -//des_createKeys +//desCreateKeys //this takes as input a 64 bit key (even though only 56 bits are used) //as an array of 2 integers, and returns 16 48 bit keys -function des_createKeys(key) { +function desCreateKeys(key) { //declaring this locally speeds things up a bit const pc2bytes0 = [ 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204, @@ -376,10 +376,10 @@ function des_createKeys(key) { } //for each iterations //return the keys we've created return keys; -} //end of des_createKeys +} //end of desCreateKeys -function des_addPadding(message, padding) { +function desAddPadding(message, padding) { const padLength = 8 - (message.length % 8); let pad; @@ -406,7 +406,7 @@ function des_addPadding(message, padding) { return paddedMessage; } -function des_removePadding(message, padding) { +function desRemovePadding(message, padding) { let padLength = null; let pad; if (padding === 2) { // space padded @@ -441,11 +441,11 @@ export function TripleDES(key) { this.encrypt = function(block) { return des( - des_createKeys(this.key[2]), + desCreateKeys(this.key[2]), des( - des_createKeys(this.key[1]), + desCreateKeys(this.key[1]), des( - des_createKeys(this.key[0]), + desCreateKeys(this.key[0]), block, true, 0, null, null ), false, 0, null, null @@ -463,12 +463,12 @@ export function DES(key) { this.key = key; this.encrypt = function(block, padding) { - const keys = des_createKeys(this.key); + const keys = desCreateKeys(this.key); return des(keys, block, true, 0, null, padding); }; this.decrypt = function(block, padding) { - const keys = des_createKeys(this.key); + const keys = desCreateKeys(this.key); return des(keys, block, false, 0, null, padding); }; } diff --git a/src/crypto/cipher/index.js b/src/crypto/cipher/index.js index 0e8607c0a..ef8dd7e51 100644 --- a/src/crypto/cipher/index.js +++ b/src/crypto/cipher/index.js @@ -6,7 +6,7 @@ import aes from './aes'; import { DES, TripleDES } from './des.js'; -import Cast5 from './cast5'; +import CAST5 from './cast5'; import TF from './twofish'; import BF from './blowfish'; @@ -54,7 +54,7 @@ export const tripledes = TripleDES; * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm} * @returns {Object} */ -export const cast5 = Cast5; +export const cast5 = CAST5; /** * Twofish Block Cipher (ID 10) * @function diff --git a/src/crypto/cmac.js b/src/crypto/cmac.js index ba912a206..1632c45ef 100644 --- a/src/crypto/cmac.js +++ b/src/crypto/cmac.js @@ -37,7 +37,7 @@ const blockLength = 16; * @param {Uint8Array} data * @param {Uint8Array} padding */ -function rightXorMut(data, padding) { +function rightXORMut(data, padding) { const offset = data.length - blockLength; for (let i = 0; i < blockLength; i++) { data[i + offset] ^= padding[i]; @@ -49,13 +49,13 @@ function pad(data, padding, padding2) { // if |M| in {n, 2n, 3n, ...} if (data.length && data.length % blockLength === 0) { // then return M xor→ B, - return rightXorMut(data, padding); + return rightXORMut(data, padding); } // else return (M || 10^(n−1−(|M| mod n))) xor→ P const padded = new Uint8Array(data.length + (blockLength - data.length % blockLength)); padded.set(data); padded[data.length] = 0b10000000; - return rightXorMut(padded, padding2); + return rightXORMut(padded, padding2); } const zeroBlock = new Uint8Array(blockLength); diff --git a/src/crypto/hash/index.js b/src/crypto/hash/index.js index d29d65ab5..1065665bc 100644 --- a/src/crypto/hash/index.js +++ b/src/crypto/hash/index.js @@ -21,7 +21,7 @@ const webCrypto = util.getWebCrypto(); const nodeCrypto = util.getNodeCrypto(); const Buffer = util.getNodeBuffer(); -function node_hash(type) { +function nodeHash(type) { return async function (data) { const shasum = nodeCrypto.createHash(type); return stream.transform(data, value => { @@ -30,7 +30,7 @@ function node_hash(type) { }; } -function hashjs_hash(hash, webCryptoHash) { +function hashjsHash(hash, webCryptoHash) { return async function(data, config = defaultConfig) { if (!util.isStream(data) && webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) { return new Uint8Array(await webCrypto.digest(webCryptoHash, data)); @@ -42,7 +42,7 @@ function hashjs_hash(hash, webCryptoHash) { }; } -function asmcrypto_hash(hash, webCryptoHash) { +function asmcryptoHash(hash, webCryptoHash) { return async function(data, config = defaultConfig) { if (util.isStream(data)) { const hashInstance = new hash(); @@ -57,45 +57,45 @@ function asmcrypto_hash(hash, webCryptoHash) { }; } -let hash_fns; +let hashFunctions; if (nodeCrypto) { // Use Node native crypto for all hash functions - hash_fns = { - md5: node_hash('md5'), - sha1: node_hash('sha1'), - sha224: node_hash('sha224'), - sha256: node_hash('sha256'), - sha384: node_hash('sha384'), - sha512: node_hash('sha512'), - ripemd: node_hash('ripemd160') + hashFunctions = { + md5: nodeHash('md5'), + sha1: nodeHash('sha1'), + sha224: nodeHash('sha224'), + sha256: nodeHash('sha256'), + sha384: nodeHash('sha384'), + sha512: nodeHash('sha512'), + ripemd: nodeHash('ripemd160') }; } else { // Use JS fallbacks - hash_fns = { + hashFunctions = { md5: md5, - sha1: asmcrypto_hash(Sha1, navigator.userAgent.indexOf('Edge') === -1 && 'SHA-1'), - sha224: hashjs_hash(sha224), - sha256: asmcrypto_hash(Sha256, 'SHA-256'), - sha384: hashjs_hash(sha384, 'SHA-384'), - sha512: hashjs_hash(sha512, 'SHA-512'), // asmcrypto sha512 is huge. - ripemd: hashjs_hash(ripemd160) + sha1: asmcryptoHash(Sha1, navigator.userAgent.indexOf('Edge') === -1 && 'SHA-1'), + sha224: hashjsHash(sha224), + sha256: asmcryptoHash(Sha256, 'SHA-256'), + sha384: hashjsHash(sha384, 'SHA-384'), + sha512: hashjsHash(sha512, 'SHA-512'), // asmcrypto sha512 is huge. + ripemd: hashjsHash(ripemd160) }; } export default { /** @see module:md5 */ - md5: hash_fns.md5, + md5: hashFunctions.md5, /** @see asmCrypto */ - sha1: hash_fns.sha1, + sha1: hashFunctions.sha1, /** @see hash.js */ - sha224: hash_fns.sha224, + sha224: hashFunctions.sha224, /** @see asmCrypto */ - sha256: hash_fns.sha256, + sha256: hashFunctions.sha256, /** @see hash.js */ - sha384: hash_fns.sha384, + sha384: hashFunctions.sha384, /** @see asmCrypto */ - sha512: hash_fns.sha512, + sha512: hashFunctions.sha512, /** @see hash.js */ - ripemd: hash_fns.ripemd, + ripemd: hashFunctions.ripemd, /** * Create a hash on the specified data using the specified algorithm diff --git a/src/crypto/index.js b/src/crypto/index.js index eecab5bb7..767a9e12d 100644 --- a/src/crypto/index.js +++ b/src/crypto/index.js @@ -22,7 +22,7 @@ import * as random from './random'; import * as pkcs1 from './pkcs1'; import * as pkcs5 from './pkcs5'; import * as crypto from './crypto'; -import * as aes_kw from './aes_kw'; +import * as aesKW from './aes_kw'; // TODO move cfb and gcm to cipher const mod = { @@ -34,7 +34,7 @@ const mod = { cfb: cfb, /** @see module:crypto/gcm */ gcm: gcm, - experimentalGcm: gcm, + experimentalGCM: gcm, /** @see module:crypto/eax */ eax: eax, /** @see module:crypto/ocb */ @@ -50,7 +50,7 @@ const mod = { /** @see module:crypto/pkcs5 */ pkcs5: pkcs5, /** @see module:crypto/aes_kw */ - aes_kw: aes_kw + aesKW: aesKW }; Object.assign(mod, crypto); diff --git a/src/crypto/pkcs1.js b/src/crypto/pkcs1.js index d7442c55a..16aeef174 100644 --- a/src/crypto/pkcs1.js +++ b/src/crypto/pkcs1.js @@ -52,7 +52,7 @@ hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, * @returns {Uint8Array} Random padding. * @async */ -async function getPkcs1Padding(length) { +async function getPKCS1Padding(length) { const result = new Uint8Array(length); let count = 0; while (count < length) { @@ -82,7 +82,7 @@ export async function emeEncode(message, keyLength) { } // Generate an octet string PS of length k - mLen - 3 consisting of // pseudo-randomly generated nonzero octets - const PS = await getPkcs1Padding(keyLength - mLength - 3); + const PS = await getPKCS1Padding(keyLength - mLength - 3); // Concatenate PS, the message M, and other padding to form an // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M. const encoded = new Uint8Array(keyLength); diff --git a/src/crypto/public_key/dsa.js b/src/crypto/public_key/dsa.js index fef1178a2..ff94ed49b 100644 --- a/src/crypto/public_key/dsa.js +++ b/src/crypto/public_key/dsa.js @@ -32,7 +32,7 @@ import { isProbablePrime } from './prime'; /** * DSA Sign function - * @param {Integer} hash_algo + * @param {Integer} hashAlgo * @param {Uint8Array} hashed * @param {Uint8Array} g * @param {Uint8Array} p @@ -41,7 +41,7 @@ import { isProbablePrime } from './prime'; * @returns {{ r: Uint8Array, s: Uint8Array }} * @async */ -export async function sign(hash_algo, hashed, g, p, q, x) { +export async function sign(hashAlgo, hashed, g, p, q, x) { const BigInteger = await util.getBigInteger(); const one = new BigInteger(1); p = new BigInteger(p); @@ -89,7 +89,7 @@ export async function sign(hash_algo, hashed, g, p, q, x) { /** * DSA Verify function - * @param {Integer} hash_algo + * @param {Integer} hashAlgo * @param {Uint8Array} r * @param {Uint8Array} s * @param {Uint8Array} hashed @@ -100,7 +100,7 @@ export async function sign(hash_algo, hashed, g, p, q, x) { * @returns {boolean} * @async */ -export async function verify(hash_algo, r, s, hashed, g, p, q, y) { +export async function verify(hashAlgo, r, s, hashed, g, p, q, y) { const BigInteger = await util.getBigInteger(); const zero = new BigInteger(0); r = new BigInteger(r); diff --git a/src/crypto/public_key/elliptic/curves.js b/src/crypto/public_key/elliptic/curves.js index 612e286b0..a45f6e025 100644 --- a/src/crypto/public_key/elliptic/curves.js +++ b/src/crypto/public_key/elliptic/curves.js @@ -131,19 +131,19 @@ const curves = { }; class Curve { - constructor(oid_or_name, params) { + constructor(oidOrName, params) { try { - if (util.isArray(oid_or_name) || - util.isUint8Array(oid_or_name)) { + if (util.isArray(oidOrName) || + util.isUint8Array(oidOrName)) { // by oid byte array - oid_or_name = new OID(oid_or_name); + oidOrName = new OID(oidOrName); } - if (oid_or_name instanceof OID) { + if (oidOrName instanceof OID) { // by curve OID - oid_or_name = oid_or_name.getName(); + oidOrName = oidOrName.getName(); } // by curve name or oid string - this.name = enums.write(enums.curve, oid_or_name); + this.name = enums.write(enums.curve, oidOrName); } catch (err) { throw new Error('Not valid curve'); } @@ -287,7 +287,7 @@ async function validateStandardParams(algo, oid, Q, d) { } export { - Curve, curves, webCurves, nodeCurves, generate, getPreferredHashAlgo, jwkToRawPublic, rawPublicToJwk, privateToJwk, validateStandardParams + Curve, curves, webCurves, nodeCurves, generate, getPreferredHashAlgo, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams }; ////////////////////////// @@ -348,7 +348,7 @@ function jwkToRawPublic(jwk) { * * @returns {JsonWebKey} Public key in jwk format. */ -function rawPublicToJwk(payloadSize, name, publicKey) { +function rawPublicToJWK(payloadSize, name, publicKey) { const len = payloadSize; const bufX = publicKey.slice(1, len + 1); const bufY = publicKey.slice(len + 1, len * 2 + 1); @@ -371,8 +371,8 @@ function rawPublicToJwk(payloadSize, name, publicKey) { * * @returns {JsonWebKey} Private key in jwk format. */ -function privateToJwk(payloadSize, name, publicKey, privateKey) { - const jwk = rawPublicToJwk(payloadSize, name, publicKey); +function privateToJWK(payloadSize, name, publicKey, privateKey) { + const jwk = rawPublicToJWK(payloadSize, name, publicKey); jwk.d = uint8ArrayToB64(privateKey, true); return jwk; } diff --git a/src/crypto/public_key/elliptic/ecdh.js b/src/crypto/public_key/elliptic/ecdh.js index ef2dfede1..7cc438ffd 100644 --- a/src/crypto/public_key/elliptic/ecdh.js +++ b/src/crypto/public_key/elliptic/ecdh.js @@ -22,8 +22,8 @@ */ import nacl from '@openpgp/tweetnacl/nacl-fast-light.js'; -import { Curve, jwkToRawPublic, rawPublicToJwk, privateToJwk, validateStandardParams } from './curves'; -import * as aes_kw from '../../aes_kw'; +import { Curve, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams } from './curves'; +import * as aesKW from '../../aes_kw'; import * as cipher from '../../cipher'; import { getRandomBytes } from '../../random'; import hash from '../../hash'; @@ -60,7 +60,7 @@ function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) { } // Key Derivation Function (RFC 6637) -async function kdf(hash_algo, X, length, param, stripLeading = false, stripTrailing = false) { +async function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) { // Note: X is little endian for Curve25519, big-endian for all others. // This is not ideal, but the RFC's are unclear // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B @@ -75,7 +75,7 @@ async function kdf(hash_algo, X, length, param, stripLeading = false, stripTrail for (i = X.length - 1; i >= 0 && X[i] === 0; i--); X = X.subarray(0, i + 1); } - const digest = await hash.digest(hash_algo, util.concatUint8Array([ + const digest = await hash.digest(hashAlgo, util.concatUint8Array([ new Uint8Array([0, 0, 0, 1]), X, param @@ -132,9 +132,9 @@ export async function encrypt(oid, kdfParams, data, Q, fingerprint) { const curve = new Curve(oid); const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q); const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); - const cipher_algo = enums.read(enums.symmetric, kdfParams.cipher); - const Z = await kdf(kdfParams.hash, sharedKey, cipher[cipher_algo].keySize, param); - const wrappedKey = aes_kw.wrap(Z, m); + const cipherAlgo = enums.read(enums.symmetric, kdfParams.cipher); + const Z = await kdf(kdfParams.hash, sharedKey, cipher[cipherAlgo].keySize, param); + const wrappedKey = aesKW.wrap(Z, m); return { publicKey, wrappedKey }; } @@ -192,13 +192,13 @@ export async function decrypt(oid, kdfParams, V, C, Q, d, fingerprint) { const curve = new Curve(oid); const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d); const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); - const cipher_algo = enums.read(enums.symmetric, kdfParams.cipher); + const cipherAlgo = enums.read(enums.symmetric, kdfParams.cipher); let err; for (let i = 0; i < 3; i++) { try { // Work around old go crypto bug and old OpenPGP.js bug, respectively. - const Z = await kdf(kdfParams.hash, sharedKey, cipher[cipher_algo].keySize, param, i === 1, i === 2); - return pkcs5.decode(aes_kw.unwrap(Z, C)); + const Z = await kdf(kdfParams.hash, sharedKey, cipher[cipherAlgo].keySize, param, i === 1, i === 2); + return pkcs5.decode(aesKW.unwrap(Z, C)); } catch (e) { err = e; } @@ -217,7 +217,7 @@ export async function decrypt(oid, kdfParams, V, C, Q, d, fingerprint) { * @async */ async function webPrivateEphemeralKey(curve, V, Q, d) { - const recipient = privateToJwk(curve.payloadSize, curve.web.web, Q, d); + const recipient = privateToJWK(curve.payloadSize, curve.web.web, Q, d); let privateKey = webCrypto.importKey( "jwk", recipient, @@ -228,7 +228,7 @@ async function webPrivateEphemeralKey(curve, V, Q, d) { true, ["deriveKey", "deriveBits"] ); - const jwk = rawPublicToJwk(curve.payloadSize, curve.web.web, V); + const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, V); let sender = webCrypto.importKey( "jwk", jwk, @@ -268,7 +268,7 @@ async function webPrivateEphemeralKey(curve, V, Q, d) { * @async */ async function webPublicEphemeralKey(curve, Q) { - const jwk = rawPublicToJwk(curve.payloadSize, curve.web.web, Q); + const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, Q); let keyPair = webCrypto.generateKey( { name: "ECDH", diff --git a/src/crypto/public_key/elliptic/ecdsa.js b/src/crypto/public_key/elliptic/ecdsa.js index cbe25b637..d3518aeb6 100644 --- a/src/crypto/public_key/elliptic/ecdsa.js +++ b/src/crypto/public_key/elliptic/ecdsa.js @@ -25,7 +25,7 @@ import enums from '../../../enums'; import util from '../../../util'; import { getRandomBytes } from '../../random'; import hash from '../../hash'; -import { Curve, webCurves, privateToJwk, rawPublicToJwk, validateStandardParams } from './curves'; +import { Curve, webCurves, privateToJWK, rawPublicToJWK, validateStandardParams } from './curves'; import { getIndutnyCurve, keyFromPrivate, keyFromPublic } from './indutnyKey'; const webCrypto = util.getWebCrypto(); @@ -34,7 +34,7 @@ const nodeCrypto = util.getNodeCrypto(); /** * Sign a message using the provided key * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hash_algo - Hash algorithm used to sign + * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign * @param {Uint8Array} message - Message to sign * @param {Uint8Array} publicKey - Public key * @param {Uint8Array} privateKey - Private key used to sign the message @@ -43,7 +43,7 @@ const nodeCrypto = util.getNodeCrypto(); * s: Uint8Array}} Signature of the message * @async */ -export async function sign(oid, hash_algo, message, publicKey, privateKey, hashed) { +export async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) { const curve = new Curve(oid); if (message && !util.isStream(message)) { const keyPair = { publicKey, privateKey }; @@ -52,7 +52,7 @@ export async function sign(oid, hash_algo, message, publicKey, privateKey, hashe // If browser doesn't support a curve, we'll catch it try { // Need to await to make sure browser succeeds - return await webSign(curve, hash_algo, message, keyPair); + return await webSign(curve, hashAlgo, message, keyPair); } catch (err) { // We do not fallback if the error is related to key integrity // Unfortunaley Safari does not support p521 and throws a DataError when using it @@ -65,7 +65,7 @@ export async function sign(oid, hash_algo, message, publicKey, privateKey, hashe break; } case 'node': { - const signature = await nodeSign(curve, hash_algo, message, keyPair); + const signature = await nodeSign(curve, hashAlgo, message, keyPair); return { r: signature.r.toArrayLike(Uint8Array), s: signature.s.toArrayLike(Uint8Array) @@ -79,7 +79,7 @@ export async function sign(oid, hash_algo, message, publicKey, privateKey, hashe /** * Verifies if a signature is valid for a message * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hash_algo - Hash algorithm used in the signature + * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature * @param {{r: Uint8Array, s: Uint8Array}} signature Signature to verify * @param {Uint8Array} message - Message to verify @@ -88,14 +88,14 @@ export async function sign(oid, hash_algo, message, publicKey, privateKey, hashe * @returns {Boolean} * @async */ -export async function verify(oid, hash_algo, signature, message, publicKey, hashed) { +export async function verify(oid, hashAlgo, signature, message, publicKey, hashed) { const curve = new Curve(oid); if (message && !util.isStream(message)) { switch (curve.type) { case 'web': try { // Need to await to make sure browser succeeds - return await webVerify(curve, hash_algo, signature, message, publicKey); + return await webVerify(curve, hashAlgo, signature, message, publicKey); } catch (err) { // We do not fallback if the error is related to key integrity // Unfortunately Safari does not support p521 and throws a DataError when using it @@ -107,10 +107,10 @@ export async function verify(oid, hash_algo, signature, message, publicKey, hash } break; case 'node': - return nodeVerify(curve, hash_algo, signature, message, publicKey); + return nodeVerify(curve, hashAlgo, signature, message, publicKey); } } - const digest = (typeof hash_algo === 'undefined') ? message : hashed; + const digest = (typeof hashAlgo === 'undefined') ? message : hashed; return ellipticVerify(curve, signature, digest, publicKey); } @@ -172,9 +172,9 @@ async function ellipticVerify(curve, signature, digest, publicKey) { return key.verify(digest, signature); } -async function webSign(curve, hash_algo, message, keyPair) { +async function webSign(curve, hashAlgo, message, keyPair) { const len = curve.payloadSize; - const jwk = privateToJwk(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey); + const jwk = privateToJWK(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey); const key = await webCrypto.importKey( "jwk", jwk, @@ -191,7 +191,7 @@ async function webSign(curve, hash_algo, message, keyPair) { { "name": 'ECDSA', "namedCurve": webCurves[curve.name], - "hash": { name: enums.read(enums.webHash, hash_algo) } + "hash": { name: enums.read(enums.webHash, hashAlgo) } }, key, message @@ -203,8 +203,8 @@ async function webSign(curve, hash_algo, message, keyPair) { }; } -async function webVerify(curve, hash_algo, { r, s }, message, publicKey) { - const jwk = rawPublicToJwk(curve.payloadSize, webCurves[curve.name], publicKey); +async function webVerify(curve, hashAlgo, { r, s }, message, publicKey) { + const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey); const key = await webCrypto.importKey( "jwk", jwk, @@ -223,7 +223,7 @@ async function webVerify(curve, hash_algo, { r, s }, message, publicKey) { { "name": 'ECDSA', "namedCurve": webCurves[curve.name], - "hash": { name: enums.read(enums.webHash, hash_algo) } + "hash": { name: enums.read(enums.webHash, hashAlgo) } }, key, signature, @@ -231,8 +231,8 @@ async function webVerify(curve, hash_algo, { r, s }, message, publicKey) { ); } -async function nodeSign(curve, hash_algo, message, keyPair) { - const sign = nodeCrypto.createSign(enums.read(enums.hash, hash_algo)); +async function nodeSign(curve, hashAlgo, message, keyPair) { + const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo)); sign.write(message); sign.end(); const key = ECPrivateKey.encode({ @@ -247,10 +247,10 @@ async function nodeSign(curve, hash_algo, message, keyPair) { return ECDSASignature.decode(sign.sign(key), 'der'); } -async function nodeVerify(curve, hash_algo, { r, s }, message, publicKey) { +async function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) { const { default: BN } = await import('bn.js'); - const verify = nodeCrypto.createVerify(enums.read(enums.hash, hash_algo)); + const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo)); verify.write(message); verify.end(); const key = SubjectPublicKeyInfo.encode({ diff --git a/src/crypto/public_key/elliptic/eddsa.js b/src/crypto/public_key/elliptic/eddsa.js index 16aa97d5f..8458d213a 100644 --- a/src/crypto/public_key/elliptic/eddsa.js +++ b/src/crypto/public_key/elliptic/eddsa.js @@ -32,7 +32,7 @@ nacl.hash = bytes => new Uint8Array(sha512().update(bytes).digest()); /** * Sign a message using the provided key * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hash_algo - Hash algorithm used to sign (must be sha256 or stronger) + * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) * @param {Uint8Array} message - Message to sign * @param {Uint8Array} publicKey - Public key * @param {Uint8Array} privateKey - Private key used to sign the message @@ -41,8 +41,8 @@ nacl.hash = bytes => new Uint8Array(sha512().update(bytes).digest()); * s: Uint8Array}} Signature of the message * @async */ -export async function sign(oid, hash_algo, message, publicKey, privateKey, hashed) { - if (hash.getHashByteLength(hash_algo) < hash.getHashByteLength(enums.hash.sha256)) { +export async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) { + if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) { // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2 throw new Error('Hash algorithm too weak: sha256 or stronger is required for EdDSA.'); } @@ -58,7 +58,7 @@ export async function sign(oid, hash_algo, message, publicKey, privateKey, hashe /** * Verifies if a signature is valid for a message * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hash_algo - Hash algorithm used in the signature + * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature * @param {{r: Uint8Array, s: Uint8Array}} signature Signature to verify the message * @param {Uint8Array} m - Message to verify @@ -67,7 +67,7 @@ export async function sign(oid, hash_algo, message, publicKey, privateKey, hashe * @returns {Boolean} * @async */ -export async function verify(oid, hash_algo, { r, s }, m, publicKey, hashed) { +export async function verify(oid, hashAlgo, { r, s }, m, publicKey, hashed) { const signature = util.concatUint8Array([r, s]); return nacl.sign.detached.verify(hashed, signature, publicKey.subarray(1)); } diff --git a/src/crypto/public_key/rsa.js b/src/crypto/public_key/rsa.js index db46e79df..bec4b3ad0 100644 --- a/src/crypto/public_key/rsa.js +++ b/src/crypto/public_key/rsa.js @@ -71,7 +71,7 @@ const RSAPublicKey = util.detectNode() ? asn1.define('RSAPubliceKey', function ( /* eslint-enable no-invalid-this */ /** Create signature - * @param {module:enums.hash} hash_algo - Hash algorithm + * @param {module:enums.hash} hashAlgo - Hash algorithm * @param {Uint8Array} data - Message * @param {Uint8Array} n - RSA public modulus * @param {Uint8Array} e - RSA public exponent @@ -83,24 +83,24 @@ const RSAPublicKey = util.detectNode() ? asn1.define('RSAPubliceKey', function ( * @returns {Uint8Array} RSA Signature. * @async */ -export async function sign(hash_algo, data, n, e, d, p, q, u, hashed) { +export async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) { if (data && !util.isStream(data)) { if (util.getWebCrypto()) { try { - return await webSign(enums.read(enums.webHash, hash_algo), data, n, e, d, p, q, u); + return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u); } catch (err) { util.printDebugError(err); } } else if (util.getNodeCrypto()) { - return nodeSign(hash_algo, data, n, e, d, p, q, u); + return nodeSign(hashAlgo, data, n, e, d, p, q, u); } } - return bnSign(hash_algo, n, d, hashed); + return bnSign(hashAlgo, n, d, hashed); } /** * Verify signature - * @param {module:enums.hash} hash_algo - Hash algorithm + * @param {module:enums.hash} hashAlgo - Hash algorithm * @param {Uint8Array} data - Message * @param {Uint8Array} s - Signature * @param {Uint8Array} n - RSA public modulus @@ -109,19 +109,19 @@ export async function sign(hash_algo, data, n, e, d, p, q, u, hashed) { * @returns {Boolean} * @async */ -export async function verify(hash_algo, data, s, n, e, hashed) { +export async function verify(hashAlgo, data, s, n, e, hashed) { if (data && !util.isStream(data)) { if (util.getWebCrypto()) { try { - return await webVerify(enums.read(enums.webHash, hash_algo), data, s, n, e); + return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e); } catch (err) { util.printDebugError(err); } } else if (util.getNodeCrypto()) { - return nodeVerify(hash_algo, data, s, n, e); + return nodeVerify(hashAlgo, data, s, n, e); } } - return bnVerify(hash_algo, s, n, e, hashed); + return bnVerify(hashAlgo, s, n, e, hashed); } /** @@ -330,10 +330,10 @@ export async function validateParams(n, e, d, p, q, u) { return true; } -async function bnSign(hash_algo, n, d, hashed) { +async function bnSign(hashAlgo, n, d, hashed) { const BigInteger = await util.getBigInteger(); n = new BigInteger(n); - const m = new BigInteger(await emsaEncode(hash_algo, hashed, n.byteLength())); + const m = new BigInteger(await emsaEncode(hashAlgo, hashed, n.byteLength())); d = new BigInteger(d); if (m.gte(n)) { throw new Error('Message size cannot exceed modulus size'); @@ -341,31 +341,31 @@ async function bnSign(hash_algo, n, d, hashed) { return m.modExp(d, n).toUint8Array('be', n.byteLength()); } -async function webSign(hash_name, data, n, e, d, p, q, u) { +async function webSign(hashName, data, n, e, d, p, q, u) { /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q. - * We swap them in privateToJwk, so it usually works out, but nevertheless, + * We swap them in privateToJWK, so it usually works out, but nevertheless, * not all OpenPGP keys are compatible with this requirement. * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still * does if the underlying Web Crypto does so (e.g. old MS Edge 50% of the time). */ - const jwk = await privateToJwk(n, e, d, p, q, u); + const jwk = await privateToJWK(n, e, d, p, q, u); const algo = { name: "RSASSA-PKCS1-v1_5", - hash: { name: hash_name } + hash: { name: hashName } }; const key = await webCrypto.importKey("jwk", jwk, algo, false, ["sign"]); // add hash field for ms edge support - return new Uint8Array(await webCrypto.sign({ "name": "RSASSA-PKCS1-v1_5", "hash": hash_name }, key, data)); + return new Uint8Array(await webCrypto.sign({ "name": "RSASSA-PKCS1-v1_5", "hash": hashName }, key, data)); } -async function nodeSign(hash_algo, data, n, e, d, p, q, u) { +async function nodeSign(hashAlgo, data, n, e, d, p, q, u) { const { default: BN } = await import('bn.js'); const pBNum = new BN(p); const qBNum = new BN(q); const dBNum = new BN(d); const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1) const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1) - const sign = nodeCrypto.createSign(enums.read(enums.hash, hash_algo)); + const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo)); sign.write(data); sign.end(); const keyObject = { @@ -391,7 +391,7 @@ async function nodeSign(hash_algo, data, n, e, d, p, q, u) { return new Uint8Array(sign.sign(pem)); } -async function bnVerify(hash_algo, s, n, e, hashed) { +async function bnVerify(hashAlgo, s, n, e, hashed) { const BigInteger = await util.getBigInteger(); n = new BigInteger(n); s = new BigInteger(s); @@ -400,24 +400,24 @@ async function bnVerify(hash_algo, s, n, e, hashed) { throw new Error('Signature size cannot exceed modulus size'); } const EM1 = s.modExp(e, n).toUint8Array('be', n.byteLength()); - const EM2 = await emsaEncode(hash_algo, hashed, n.byteLength()); + const EM2 = await emsaEncode(hashAlgo, hashed, n.byteLength()); return util.equalsUint8Array(EM1, EM2); } -async function webVerify(hash_name, data, s, n, e) { - const jwk = publicToJwk(n, e); +async function webVerify(hashName, data, s, n, e) { + const jwk = publicToJWK(n, e); const key = await webCrypto.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", - hash: { name: hash_name } + hash: { name: hashName } }, false, ["verify"]); // add hash field for ms edge support - return webCrypto.verify({ "name": "RSASSA-PKCS1-v1_5", "hash": hash_name }, key, s, data); + return webCrypto.verify({ "name": "RSASSA-PKCS1-v1_5", "hash": hashName }, key, s, data); } -async function nodeVerify(hash_algo, data, s, n, e) { +async function nodeVerify(hashAlgo, data, s, n, e) { const { default: BN } = await import('bn.js'); - const verify = nodeCrypto.createVerify(enums.read(enums.hash, hash_algo)); + const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo)); verify.write(data); verify.end(); const keyObject = { @@ -543,7 +543,7 @@ async function bnDecrypt(data, n, e, d, p, q, u) { /** Convert Openpgp private key params to jwk key according to * @link https://tools.ietf.org/html/rfc7517 - * @param {String} hash_algo + * @param {String} hashAlgo * @param {Uint8Array} n * @param {Uint8Array} e * @param {Uint8Array} d @@ -551,7 +551,7 @@ async function bnDecrypt(data, n, e, d, p, q, u) { * @param {Uint8Array} q * @param {Uint8Array} u */ -async function privateToJwk(n, e, d, p, q, u) { +async function privateToJWK(n, e, d, p, q, u) { const BigInteger = await util.getBigInteger(); const pNum = new BigInteger(p); const qNum = new BigInteger(q); @@ -579,11 +579,11 @@ async function privateToJwk(n, e, d, p, q, u) { /** Convert Openpgp key public params to jwk key according to * @link https://tools.ietf.org/html/rfc7517 - * @param {String} hash_algo + * @param {String} hashAlgo * @param {Uint8Array} n * @param {Uint8Array} e */ -function publicToJwk(n, e) { +function publicToJWK(n, e) { return { kty: 'RSA', n: uint8ArrayToB64(n, true), diff --git a/src/enums.js b/src/enums.js index 592d61895..5c10f10b1 100644 --- a/src/enums.js +++ b/src/enums.js @@ -180,7 +180,7 @@ export default { aead: { eax: 1, ocb: 2, - experimentalGcm: 100 // Private algorithm + experimentalGCM: 100 // Private algorithm }, /** A list of packet types and numeric tags associated with them. diff --git a/src/key/helper.js b/src/key/helper.js index ec98021eb..2ee2c81cd 100644 --- a/src/key/helper.js +++ b/src/key/helper.js @@ -132,14 +132,14 @@ export async function createBindingSignature(subkey, primaryKey, options, config * @async */ export async function getPreferredHashAlgo(key, keyPacket, date = new Date(), userID = {}, config) { - let hash_algo = config.preferredHashAlgorithm; - let pref_algo = hash_algo; + let hashAlgo = config.preferredHashAlgorithm; + let pref_algo = hashAlgo; if (key) { const primaryUser = await key.getPrimaryUser(date, userID, config); if (primaryUser.selfCertification.preferredHashAlgorithms) { [pref_algo] = primaryUser.selfCertification.preferredHashAlgorithms; - hash_algo = crypto.hash.getHashByteLength(hash_algo) <= crypto.hash.getHashByteLength(pref_algo) ? - pref_algo : hash_algo; + hashAlgo = crypto.hash.getHashByteLength(hashAlgo) <= crypto.hash.getHashByteLength(pref_algo) ? + pref_algo : hashAlgo; } } switch (Object.getPrototypeOf(keyPacket)) { @@ -154,8 +154,8 @@ export async function getPreferredHashAlgo(key, keyPacket, date = new Date(), us pref_algo = crypto.publicKey.elliptic.getPreferredHashAlgo(keyPacket.publicParams.oid); } } - return crypto.hash.getHashByteLength(hash_algo) <= crypto.hash.getHashByteLength(pref_algo) ? - pref_algo : hash_algo; + return crypto.hash.getHashByteLength(hashAlgo) <= crypto.hash.getHashByteLength(pref_algo) ? + pref_algo : hashAlgo; } /** @@ -241,7 +241,7 @@ export async function mergeSignatures(source, dest, attr, checkFn) { await Promise.all(source.map(async function(sourceSig) { if (!sourceSig.isExpired() && (!checkFn || await checkFn(sourceSig)) && !dest[attr].some(function(destSig) { - return util.equalsUint8Array(destSig.write_params(), sourceSig.write_params()); + return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams()); })) { dest[attr].push(sourceSig); } @@ -318,7 +318,7 @@ export function getExpirationTime(keyPacket, signature) { * @returns {Boolean} * @async */ -export async function isAeadSupported(keys, date = new Date(), userIDs = [], config = defaultConfig) { +export async function isAEADSupported(keys, date = new Date(), userIDs = [], config = defaultConfig) { let supported = true; // TODO replace when Promise.some or Promise.any are implemented await Promise.all(keys.map(async function(key, i) { diff --git a/src/key/index.js b/src/key/index.js index 87ddb08f8..db14dba4d 100644 --- a/src/key/index.js +++ b/src/key/index.js @@ -7,7 +7,7 @@ import { import { getPreferredAlgo, - isAeadSupported, + isAEADSupported, getPreferredHashAlgo, createSignaturePacket } from './helper'; @@ -20,7 +20,7 @@ export { generate, reformat, getPreferredAlgo, - isAeadSupported, + isAEADSupported, getPreferredHashAlgo, createSignaturePacket, Key diff --git a/src/message.js b/src/message.js index 414996f25..49cb2cfe8 100644 --- a/src/message.js +++ b/src/message.js @@ -35,7 +35,7 @@ import { SignaturePacket } from './packet'; import { Signature } from './signature'; -import { getPreferredHashAlgo, getPreferredAlgo, isAeadSupported, createSignaturePacket } from './key'; +import { getPreferredHashAlgo, getPreferredAlgo, isAEADSupported, createSignaturePacket } from './key'; /** * Class that represents an OpenPGP message. @@ -283,7 +283,7 @@ export class Message { */ static async generateSessionKey(keys = [], date = new Date(), userIDs = [], config = defaultConfig) { const algorithm = enums.read(enums.symmetric, await getPreferredAlgo('symmetric', keys, date, userIDs, config)); - const aeadAlgorithm = config.aeadProtect && await isAeadSupported(keys, date, userIDs, config) ? + const aeadAlgorithm = config.aeadProtect && await isAEADSupported(keys, date, userIDs, config) ? enums.read(enums.aead, await getPreferredAlgo('aead', keys, date, userIDs, config)) : undefined; @@ -342,7 +342,7 @@ export class Message { * Encrypt a session key either with public keys, passwords, or both at once. * @param {Uint8Array} sessionKey - session key for encryption * @param {String} algorithm - session key algorithm - * @param {String} [aeadAlgorithm] - Aead algorithm, e.g. 'eax' or 'ocb' + * @param {String} [aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb' * @param {Array} [publicKeys] - Public key(s) for message encryption * @param {Array} [passwords] - For message encryption * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs diff --git a/src/openpgp.js b/src/openpgp.js index 2e943265d..40b7011e0 100644 --- a/src/openpgp.js +++ b/src/openpgp.js @@ -461,7 +461,7 @@ export function generateSessionKey({ publicKeys, date = new Date(), toUserIDs = * @param {Object} options * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128) * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256' - * @param {String} [options.aeadAlgorithm] - Aead algorithm, e.g. 'eax' or 'ocb' + * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb' * @param {Key|Array} [options.publicKeys] - Array of public keys or single key, used to encrypt the key * @param {String|Array} [options.passwords] - Passwords for the message * @param {Boolean} [options.armor=true] - Whether the return values should be ascii armored (true, the default) or binary (false) diff --git a/src/packet/packet.js b/src/packet/packet.js index 6492085a0..c2f933fc1 100644 --- a/src/packet/packet.js +++ b/src/packet/packet.js @@ -130,21 +130,21 @@ export async function readPackets(input, streaming, callback) { const headerByte = await reader.readByte(); let tag = -1; let format = -1; - let packet_length; + let packetLength; format = 0; // 0 = old format; 1 = new format if ((headerByte & 0x40) !== 0) { format = 1; } - let packet_length_type; + let packetLengthType; if (format) { // new format header tag = headerByte & 0x3F; // bit 5-0 } else { // old format header tag = (headerByte & 0x3F) >> 2; // bit 5-2 - packet_length_type = headerByte & 0x03; // bit 1-0 + packetLengthType = headerByte & 0x03; // bit 1-0 } const packetSupportsStreaming = supportsStreaming(tag); @@ -162,21 +162,21 @@ export async function readPackets(input, streaming, callback) { do { if (!format) { // 4.2.1. Old Format Packet Lengths - switch (packet_length_type) { + switch (packetLengthType) { case 0: // The packet has a one-octet length. The header is 2 octets // long. - packet_length = await reader.readByte(); + packetLength = await reader.readByte(); break; case 1: // The packet has a two-octet length. The header is 3 octets // long. - packet_length = (await reader.readByte() << 8) | await reader.readByte(); + packetLength = (await reader.readByte() << 8) | await reader.readByte(); break; case 2: // The packet has a four-octet length. The header is 5 // octets long. - packet_length = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << + packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << 8) | await reader.readByte(); break; default: @@ -190,7 +190,7 @@ export async function readPackets(input, streaming, callback) { // definite length, or a new format header. The new format // headers described below have a mechanism for precisely // encoding data of indeterminate length. - packet_length = Infinity; + packetLength = Infinity; break; } } else { // 4.2.2. New Format Packet Lengths @@ -198,38 +198,38 @@ export async function readPackets(input, streaming, callback) { const lengthByte = await reader.readByte(); wasPartialLength = false; if (lengthByte < 192) { - packet_length = lengthByte; + packetLength = lengthByte; // 4.2.2.2. Two-Octet Lengths } else if (lengthByte >= 192 && lengthByte < 224) { - packet_length = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192; + packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192; // 4.2.2.4. Partial Body Lengths } else if (lengthByte > 223 && lengthByte < 255) { - packet_length = 1 << (lengthByte & 0x1F); + packetLength = 1 << (lengthByte & 0x1F); wasPartialLength = true; if (!packetSupportsStreaming) { throw new TypeError('This packet type does not support partial lengths.'); } // 4.2.2.3. Five-Octet Lengths } else { - packet_length = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << + packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << 8) | await reader.readByte(); } } - if (packet_length > 0) { + if (packetLength > 0) { let bytesRead = 0; while (true) { if (writer) await writer.ready; const { done, value } = await reader.read(); if (done) { - if (packet_length === Infinity) break; + if (packetLength === Infinity) break; throw new Error('Unexpected end of packet'); } - const chunk = packet_length === Infinity ? value : value.subarray(0, packet_length - bytesRead); + const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead); if (writer) await writer.write(chunk); else packet.push(chunk); bytesRead += value.length; - if (bytesRead >= packet_length) { - reader.unshift(value.subarray(packet_length - bytesRead + value.length)); + if (bytesRead >= packetLength) { + reader.unshift(value.subarray(packetLength - bytesRead + value.length)); break; } } diff --git a/src/packet/secret_key.js b/src/packet/secret_key.js index bef72d17a..d032ccf17 100644 --- a/src/packet/secret_key.js +++ b/src/packet/secret_key.js @@ -427,7 +427,7 @@ class SecretKeyPacket extends PublicKeyPacket { } async function produceEncryptionKey(s2k, passphrase, algorithm) { - return s2k.produce_key( + return s2k.produceKey( passphrase, crypto.cipher[algorithm].keySize ); diff --git a/src/packet/signature.js b/src/packet/signature.js index 6b3b54879..f4e82cb76 100644 --- a/src/packet/signature.js +++ b/src/packet/signature.js @@ -104,7 +104,7 @@ class SignaturePacket { this.hashAlgorithm = bytes[i++]; // hashed subpackets - i += this.read_sub_packets(bytes.subarray(i, bytes.length), true); + i += this.readSubPackets(bytes.subarray(i, bytes.length), true); // A V4 signature hashes the packet body // starting from its first field, the version number, through the end @@ -115,7 +115,7 @@ class SignaturePacket { this.signatureData = bytes.subarray(0, i); // unhashed subpackets - i += this.read_sub_packets(bytes.subarray(i, bytes.length), false); + i += this.readSubPackets(bytes.subarray(i, bytes.length), false); // Two-octet field holding left 16 bits of signed hash value. this.signedHashValue = bytes.subarray(i, i + 2); @@ -127,7 +127,7 @@ class SignaturePacket { /** * @returns {Uint8Array | ReadableStream} */ - write_params() { + writeParams() { if (this.params instanceof Promise) { return stream.fromAsync( async () => crypto.serializeParams(this.publicKeyAlgorithm, await this.params) @@ -139,9 +139,9 @@ class SignaturePacket { write() { const arr = []; arr.push(this.signatureData); - arr.push(this.write_unhashed_sub_packets()); + arr.push(this.writeUnhashedSubPackets()); arr.push(this.signedHashValue); - arr.push(this.write_params()); + arr.push(this.writeParams()); return util.concat(arr); } @@ -169,7 +169,7 @@ class SignaturePacket { this.issuerKeyID = key.getKeyID(); // Add hashed subpackets - arr.push(this.write_hashed_sub_packets()); + arr.push(this.writeHashedSubPackets()); this.signatureData = util.concat(arr); @@ -197,40 +197,40 @@ class SignaturePacket { * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets * @returns {Uint8Array} Subpacket data. */ - write_hashed_sub_packets() { + writeHashedSubPackets() { const sub = enums.signatureSubpacket; const arr = []; let bytes; if (this.created !== null) { - arr.push(write_sub_packet(sub.signatureCreationTime, util.writeDate(this.created))); + arr.push(writeSubPacket(sub.signatureCreationTime, util.writeDate(this.created))); } if (this.signatureExpirationTime !== null) { - arr.push(write_sub_packet(sub.signatureExpirationTime, util.writeNumber(this.signatureExpirationTime, 4))); + arr.push(writeSubPacket(sub.signatureExpirationTime, util.writeNumber(this.signatureExpirationTime, 4))); } if (this.exportable !== null) { - arr.push(write_sub_packet(sub.exportableCertification, new Uint8Array([this.exportable ? 1 : 0]))); + arr.push(writeSubPacket(sub.exportableCertification, new Uint8Array([this.exportable ? 1 : 0]))); } if (this.trustLevel !== null) { bytes = new Uint8Array([this.trustLevel, this.trustAmount]); - arr.push(write_sub_packet(sub.trustSignature, bytes)); + arr.push(writeSubPacket(sub.trustSignature, bytes)); } if (this.regularExpression !== null) { - arr.push(write_sub_packet(sub.regularExpression, this.regularExpression)); + arr.push(writeSubPacket(sub.regularExpression, this.regularExpression)); } if (this.revocable !== null) { - arr.push(write_sub_packet(sub.revocable, new Uint8Array([this.revocable ? 1 : 0]))); + arr.push(writeSubPacket(sub.revocable, new Uint8Array([this.revocable ? 1 : 0]))); } if (this.keyExpirationTime !== null) { - arr.push(write_sub_packet(sub.keyExpirationTime, util.writeNumber(this.keyExpirationTime, 4))); + arr.push(writeSubPacket(sub.keyExpirationTime, util.writeNumber(this.keyExpirationTime, 4))); } if (this.preferredSymmetricAlgorithms !== null) { bytes = util.strToUint8Array(util.uint8ArrayToStr(this.preferredSymmetricAlgorithms)); - arr.push(write_sub_packet(sub.preferredSymmetricAlgorithms, bytes)); + arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, bytes)); } if (this.revocationKeyClass !== null) { bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]); bytes = util.concat([bytes, this.revocationKeyFingerprint]); - arr.push(write_sub_packet(sub.revocationKey, bytes)); + arr.push(writeSubPacket(sub.revocationKey, bytes)); } this.rawNotations.forEach(([{ name, value, humanReadable }]) => { bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])]; @@ -241,53 +241,53 @@ class SignaturePacket { bytes.push(util.strToUint8Array(name)); bytes.push(value); bytes = util.concat(bytes); - arr.push(write_sub_packet(sub.notationData, bytes)); + arr.push(writeSubPacket(sub.notationData, bytes)); }); if (this.preferredHashAlgorithms !== null) { bytes = util.strToUint8Array(util.uint8ArrayToStr(this.preferredHashAlgorithms)); - arr.push(write_sub_packet(sub.preferredHashAlgorithms, bytes)); + arr.push(writeSubPacket(sub.preferredHashAlgorithms, bytes)); } if (this.preferredCompressionAlgorithms !== null) { bytes = util.strToUint8Array(util.uint8ArrayToStr(this.preferredCompressionAlgorithms)); - arr.push(write_sub_packet(sub.preferredCompressionAlgorithms, bytes)); + arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, bytes)); } if (this.keyServerPreferences !== null) { bytes = util.strToUint8Array(util.uint8ArrayToStr(this.keyServerPreferences)); - arr.push(write_sub_packet(sub.keyServerPreferences, bytes)); + arr.push(writeSubPacket(sub.keyServerPreferences, bytes)); } if (this.preferredKeyServer !== null) { - arr.push(write_sub_packet(sub.preferredKeyServer, util.strToUint8Array(this.preferredKeyServer))); + arr.push(writeSubPacket(sub.preferredKeyServer, util.strToUint8Array(this.preferredKeyServer))); } if (this.isPrimaryUserID !== null) { - arr.push(write_sub_packet(sub.primaryUserID, new Uint8Array([this.isPrimaryUserID ? 1 : 0]))); + arr.push(writeSubPacket(sub.primaryUserID, new Uint8Array([this.isPrimaryUserID ? 1 : 0]))); } if (this.policyURI !== null) { - arr.push(write_sub_packet(sub.policyUri, util.strToUint8Array(this.policyURI))); + arr.push(writeSubPacket(sub.policyUri, util.strToUint8Array(this.policyURI))); } if (this.keyFlags !== null) { bytes = util.strToUint8Array(util.uint8ArrayToStr(this.keyFlags)); - arr.push(write_sub_packet(sub.keyFlags, bytes)); + arr.push(writeSubPacket(sub.keyFlags, bytes)); } if (this.signersUserID !== null) { - arr.push(write_sub_packet(sub.signersUserID, util.strToUint8Array(this.signersUserID))); + arr.push(writeSubPacket(sub.signersUserID, util.strToUint8Array(this.signersUserID))); } if (this.reasonForRevocationFlag !== null) { bytes = util.strToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString); - arr.push(write_sub_packet(sub.reasonForRevocation, bytes)); + arr.push(writeSubPacket(sub.reasonForRevocation, bytes)); } if (this.features !== null) { bytes = util.strToUint8Array(util.uint8ArrayToStr(this.features)); - arr.push(write_sub_packet(sub.features, bytes)); + arr.push(writeSubPacket(sub.features, bytes)); } if (this.signatureTargetPublicKeyAlgorithm !== null) { bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])]; bytes.push(util.strToUint8Array(this.signatureTargetHash)); bytes = util.concat(bytes); - arr.push(write_sub_packet(sub.signatureTarget, bytes)); + arr.push(writeSubPacket(sub.signatureTarget, bytes)); } if (this.preferredAEADAlgorithms !== null) { bytes = util.strToUint8Array(util.uint8ArrayToStr(this.preferredAEADAlgorithms)); - arr.push(write_sub_packet(sub.preferredAEADAlgorithms, bytes)); + arr.push(writeSubPacket(sub.preferredAEADAlgorithms, bytes)); } const result = util.concat(arr); @@ -300,22 +300,22 @@ class SignaturePacket { * Creates Uint8Array of bytes of Issuer and Embedded Signature subpackets * @returns {Uint8Array} Subpacket data. */ - write_unhashed_sub_packets() { + writeUnhashedSubPackets() { const sub = enums.signatureSubpacket; const arr = []; let bytes; if (!this.issuerKeyID.isNull() && this.issuerKeyVersion !== 5) { // If the version of [the] key is greater than 4, this subpacket // MUST NOT be included in the signature. - arr.push(write_sub_packet(sub.issuer, this.issuerKeyID.write())); + arr.push(writeSubPacket(sub.issuer, this.issuerKeyID.write())); } if (this.embeddedSignature !== null) { - arr.push(write_sub_packet(sub.embeddedSignature, this.embeddedSignature.write())); + arr.push(writeSubPacket(sub.embeddedSignature, this.embeddedSignature.write())); } if (this.issuerFingerprint !== null) { bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint]; bytes = util.concat(bytes); - arr.push(write_sub_packet(sub.issuerFingerprint, bytes)); + arr.push(writeSubPacket(sub.issuerFingerprint, bytes)); } this.unhashedSubpackets.forEach(data => { arr.push(writeSimpleLength(data.length)); @@ -522,14 +522,14 @@ class SignaturePacket { } } - read_sub_packets(bytes, trusted = true, config) { + readSubPackets(bytes, trusted = true, config) { // Two-octet scalar octet count for following subpacket data. - const subpacket_length = util.readNumber(bytes.subarray(0, 2)); + const subpacketLength = util.readNumber(bytes.subarray(0, 2)); let i = 2; // subpacket data set (zero or more subpackets) - while (i < 2 + subpacket_length) { + while (i < 2 + subpacketLength) { const len = readSimpleLength(bytes.subarray(i, bytes.length)); i += len.offset; @@ -743,7 +743,7 @@ class SignaturePacket { * @returns {String} A string-representation of a sub signature packet. * @private */ -function write_sub_packet(type, data) { +function writeSubPacket(type, data) { const arr = []; arr.push(writeSimpleLength(data.length + 1)); arr.push(new Uint8Array([type])); diff --git a/src/packet/sym_encrypted_session_key.js b/src/packet/sym_encrypted_session_key.js index 0868c833d..d28f24aa9 100644 --- a/src/packet/sym_encrypted_session_key.js +++ b/src/packet/sym_encrypted_session_key.js @@ -128,7 +128,7 @@ class SymEncryptedSessionKeyPacket { this.sessionKeyAlgorithm; const length = crypto.cipher[algo].keySize; - const key = await this.s2k.produce_key(passphrase, length); + const key = await this.s2k.produceKey(passphrase, length); if (this.version === 5) { const mode = crypto[this.aeadAlgorithm]; @@ -163,7 +163,7 @@ class SymEncryptedSessionKeyPacket { this.s2k.salt = await crypto.random.getRandomBytes(8); const length = crypto.cipher[algo].keySize; - const key = await this.s2k.produce_key(passphrase, length); + const key = await this.s2k.produceKey(passphrase, length); if (this.sessionKey === null) { this.sessionKey = await crypto.generateSessionKey(this.sessionKeyAlgorithm); diff --git a/src/type/keyid.js b/src/type/keyid.js index d7b24f318..44624656e 100644 --- a/src/type/keyid.js +++ b/src/type/keyid.js @@ -89,7 +89,7 @@ class KeyID { return keyID.toHex(); } - static fromId(hex) { + static fromID(hex) { const keyID = new KeyID(); keyID.read(util.hexToUint8Array(hex)); return keyID; diff --git a/src/type/s2k.js b/src/type/s2k.js index 6873fe6fe..a16999d26 100644 --- a/src/type/s2k.js +++ b/src/type/s2k.js @@ -50,7 +50,7 @@ class S2K { this.salt = null; } - get_count() { + getCount() { // Exponent bias, defined in RFC4880 const expbias = 6; @@ -146,7 +146,7 @@ class S2K { * @returns {Uint8Array} Produced key with a length corresponding to. * hashAlgorithm hash length */ - async produce_key(passphrase, numBytes) { + async produceKey(passphrase, numBytes) { passphrase = util.encodeUtf8(passphrase); const algorithm = enums.write(enums.hash, this.algorithm); @@ -166,7 +166,7 @@ class S2K { case 'iterated': { const data = util.concatUint8Array([this.salt, passphrase]); let datalen = data.length; - const count = Math.max(this.get_count(), datalen); + const count = Math.max(this.getCount(), datalen); toHash = new Uint8Array(prefixlen + count); toHash.set(data, prefixlen); for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) { diff --git a/src/util.js b/src/util.js index 612d6c8d9..d14782b20 100644 --- a/src/util.js +++ b/src/util.js @@ -379,7 +379,7 @@ const util = { /** * Helper function to print a debug message. Debug * messages are only printed if - * Different than print_debug because will call Uint8ArrayToHex iff necessary. + * Different than printDebug because will call Uint8ArrayToHex iff necessary. * @param {String} str - String of the debug message */ printDebugHexArrayDump: function (str, arrToHex) { @@ -392,7 +392,7 @@ const util = { /** * Helper function to print a debug message. Debug * messages are only printed if - * Different than print_debug because will call strToHex iff necessary. + * Different than printDebug because will call strToHex iff necessary. * @param {String} str - String of the debug message */ printDebugHexStrDump: function (str, strToHex) { @@ -466,13 +466,13 @@ const util = { * @param {Uint8Array} data */ double: function(data) { - const double_var = new Uint8Array(data.length); + const doubleVar = new Uint8Array(data.length); const last = data.length - 1; for (let i = 0; i < last; i++) { - double_var[i] = (data[i] << 1) ^ (data[i + 1] >> 7); + doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7); } - double_var[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87); - return double_var; + doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87); + return doubleVar; }, /** diff --git a/test/crypto/aes_kw.js b/test/crypto/aes_kw.js index dcf7f689c..8e6ac4271 100644 --- a/test/crypto/aes_kw.js +++ b/test/crypto/aes_kw.js @@ -1,4 +1,4 @@ -const aes_kw = require('../../src/crypto/aes_kw'); +const aesKW = require('../../src/crypto/aes_kw'); const util = require('../../src/util'); const expect = require('chai').expect; @@ -50,8 +50,8 @@ module.exports = () => describe('AES Key Wrap and Unwrap', function () { const input_bin = util.hexToStr(input); const output = test[3].replace(/\s/g, ""); const output_bin = util.hexToStr(output); - expect(util.uint8ArrayToHex(aes_kw.wrap(kek, input_bin)).toUpperCase()).to.equal(output); - expect(util.uint8ArrayToHex(aes_kw.unwrap(kek, output_bin)).toUpperCase()).to.equal(input); + expect(util.uint8ArrayToHex(aesKW.wrap(kek, input_bin)).toUpperCase()).to.equal(output); + expect(util.uint8ArrayToHex(aesKW.unwrap(kek, output_bin)).toUpperCase()).to.equal(input); done(); }); }); diff --git a/test/crypto/cipher/cast5.js b/test/crypto/cipher/cast5.js index 513af6425..19b129fa5 100644 --- a/test/crypto/cipher/cast5.js +++ b/test/crypto/cipher/cast5.js @@ -1,4 +1,4 @@ -const Cast5 = require('../../../src/crypto/cipher/cast5'); +const CAST5 = require('../../../src/crypto/cipher/cast5'); const util = require('../../../src/util'); const chai = require('chai'); @@ -7,7 +7,7 @@ const { expect } = chai; module.exports = () => it('CAST-128 cipher test with test vectors from RFC2144', function (done) { function test_cast(input, key, output) { - const cast5 = new Cast5(key); + const cast5 = new CAST5(key); const result = util.uint8ArrayToStr(cast5.encrypt(input)); return util.strToHex(result) === util.strToHex(util.uint8ArrayToStr(output)); diff --git a/test/crypto/rsa.js b/test/crypto/rsa.js index 1afd67d1b..6a5811f59 100644 --- a/test/crypto/rsa.js +++ b/test/crypto/rsa.js @@ -53,12 +53,12 @@ module.exports = () => (!native ? describe.skip : describe)('basic RSA cryptogra const bits = 1024; const { publicParams, privateParams } = await crypto.generateParams(openpgp.enums.publicKey.rsaSign, bits); const message = await random.getRandomBytes(64); - const hash_algo = openpgp.enums.write(openpgp.enums.hash, 'sha256'); - const hashed = await crypto.hash.digest(hash_algo, message); + const hashAlgo = openpgp.enums.write(openpgp.enums.hash, 'sha256'); + const hashed = await crypto.hash.digest(hashAlgo, message); const { n, e, d, p, q, u } = { ...publicParams, ...privateParams }; - const signature = await crypto.publicKey.rsa.sign(hash_algo, message, n, e, d, p, q, u, hashed); + const signature = await crypto.publicKey.rsa.sign(hashAlgo, message, n, e, d, p, q, u, hashed); expect(signature).to.exist; - const verify = await crypto.publicKey.rsa.verify(hash_algo, message, signature, n, e, hashed); + const verify = await crypto.publicKey.rsa.verify(hashAlgo, message, signature, n, e, hashed); expect(verify).to.be.true; }); @@ -97,12 +97,12 @@ module.exports = () => (!native ? describe.skip : describe)('basic RSA cryptogra const { n, e, d, p, q, u } = { ...publicParams, ...privateParams }; const message = await random.getRandomBytes(64); const hashName = 'sha256'; - const hash_algo = openpgp.enums.write(openpgp.enums.hash, hashName); - const hashed = await crypto.hash.digest(hash_algo, message); + const hashAlgo = openpgp.enums.write(openpgp.enums.hash, hashName); + const hashed = await crypto.hash.digest(hashAlgo, message); enableNative(); - const signatureNative = await crypto.publicKey.rsa.sign(hash_algo, message, n, e, d, p, q, u, hashed); + const signatureNative = await crypto.publicKey.rsa.sign(hashAlgo, message, n, e, d, p, q, u, hashed); disableNative(); - const signatureBN = await crypto.publicKey.rsa.sign(hash_algo, message, n, e, d, p, q, u, hashed); + const signatureBN = await crypto.publicKey.rsa.sign(hashAlgo, message, n, e, d, p, q, u, hashed); expect(util.uint8ArrayToHex(signatureNative)).to.be.equal(util.uint8ArrayToHex(signatureBN)); }); @@ -112,13 +112,13 @@ module.exports = () => (!native ? describe.skip : describe)('basic RSA cryptogra const { n, e, d, p, q, u } = { ...publicParams, ...privateParams }; const message = await random.getRandomBytes(64); const hashName = 'sha256'; - const hash_algo = openpgp.enums.write(openpgp.enums.hash, hashName); - const hashed = await crypto.hash.digest(hash_algo, message); + const hashAlgo = openpgp.enums.write(openpgp.enums.hash, hashName); + const hashed = await crypto.hash.digest(hashAlgo, message); enableNative(); - const signatureNative = await crypto.publicKey.rsa.sign(hash_algo, message, n, e, d, p, q, u, hashed); - const verifyNative = await crypto.publicKey.rsa.verify(hash_algo, message, signatureNative, n, e); + const signatureNative = await crypto.publicKey.rsa.sign(hashAlgo, message, n, e, d, p, q, u, hashed); + const verifyNative = await crypto.publicKey.rsa.verify(hashAlgo, message, signatureNative, n, e); disableNative(); - const verifyBN = await crypto.publicKey.rsa.verify(hash_algo, message, signatureNative, n, e, hashed); + const verifyBN = await crypto.publicKey.rsa.verify(hashAlgo, message, signatureNative, n, e, hashed); expect(verifyNative).to.be.true; expect(verifyBN).to.be.true; }); diff --git a/test/general/key.js b/test/general/key.js index 27ab9872f..38717496d 100644 --- a/test/general/key.js +++ b/test/general/key.js @@ -2119,7 +2119,7 @@ function versionSpecificTests() { openpgp.config.preferredSymmetricAlgorithm = openpgp.enums.symmetric.aes192; openpgp.config.preferredHashAlgorithm = openpgp.enums.hash.sha224; openpgp.config.preferredCompressionAlgorithm = openpgp.enums.compression.zip; - openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.experimentalGcm; + openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.experimentalGCM; const testPref = function(key) { // key flags @@ -2132,7 +2132,7 @@ function versionSpecificTests() { expect(key.users[0].selfCertifications[0].preferredSymmetricAlgorithms).to.eql([sym.aes192, sym.aes256, sym.aes128]); if (openpgp.config.aeadProtect) { const aead = openpgp.enums.aead; - expect(key.users[0].selfCertifications[0].preferredAEADAlgorithms).to.eql([aead.experimentalGcm, aead.eax, aead.ocb]); + expect(key.users[0].selfCertifications[0].preferredAEADAlgorithms).to.eql([aead.experimentalGCM, aead.eax, aead.ocb]); } const hash = openpgp.enums.hash; expect(key.users[0].selfCertifications[0].preferredHashAlgorithms).to.eql([hash.sha224, hash.sha256, hash.sha512]); @@ -2771,10 +2771,10 @@ module.exports = () => describe('Key', function() { expect(pubKeyV4.getFingerprint()).to.equal('f470e50dcb1ad5f1e64e08644a63613a4d6e4094'); }); - it('Create new key ID with fromId()', async function() { + it('Create new key ID with fromID()', async function() { const [pubKeyV4] = await openpgp.readKeys({ armoredKeys: twoKeys }); const keyID = pubKeyV4.getKeyID(); - const newKeyID = keyID.constructor.fromId(keyID.toHex()); + const newKeyID = keyID.constructor.fromID(keyID.toHex()); expect(newKeyID.toHex()).to.equal(keyID.toHex()); }); @@ -3318,7 +3318,7 @@ module.exports = () => describe('Key', function() { ...openpgp.config, preferredAEADAlgorithm: openpgp.enums.aead.ocb }); expect(prefAlgo).to.equal(openpgp.enums.aead.ocb); - const supported = await key.isAeadSupported([key1]); + const supported = await key.isAEADSupported([key1]); expect(supported).to.be.true; }); @@ -3333,7 +3333,7 @@ module.exports = () => describe('Key', function() { primaryUser2.selfCertification.features = [7]; // Monkey-patch AEAD feature flag const prefAlgo = await key.getPreferredAlgo('aead', [key1, key2]); expect(prefAlgo).to.equal(openpgp.enums.aead.eax); - const supported = await key.isAeadSupported([key1, key2]); + const supported = await key.isAEADSupported([key1, key2]); expect(supported).to.be.true; }); @@ -3346,7 +3346,7 @@ module.exports = () => describe('Key', function() { primaryUser.selfCertification.preferredAEADAlgorithms = [2,1]; const prefAlgo = await key.getPreferredAlgo('aead', [key1, key2]); expect(prefAlgo).to.equal(openpgp.enums.aead.eax); - const supported = await key.isAeadSupported([key1, key2]); + const supported = await key.isAEADSupported([key1, key2]); expect(supported).to.be.false; }); diff --git a/test/general/openpgp.js b/test/general/openpgp.js index 3e72c8660..12ef5c55e 100644 --- a/test/general/openpgp.js +++ b/test/general/openpgp.js @@ -1041,7 +1041,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { if: true, beforeEach: function() { openpgp.config.aeadProtect = true; - openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.experimentalGcm; + openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.experimentalGCM; openpgp.config.v5Keys = true; // Monkey-patch AEAD feature flag @@ -2838,14 +2838,14 @@ bsZgJWVlAa5eil6J9ePX2xbo1vVAkLQdzE9+1jL+l7PRIZuVBQ== describe('Specific encryption/signing key testing', async function () { const encryptionKeyIDs = [ - keyIDType.fromId("87EAE0977B2185EA"), - keyIDType.fromId("F94F9B34AF93FA14"), - keyIDType.fromId("08F7D4C7C59545C0") + keyIDType.fromID("87EAE0977B2185EA"), + keyIDType.fromID("F94F9B34AF93FA14"), + keyIDType.fromID("08F7D4C7C59545C0") ]; const signingKeyIDs = [ - keyIDType.fromId("663277AF60400638"), - keyIDType.fromId("BBE14491E6EE6366"), - keyIDType.fromId("3E0F20F1A71D6DFD") + keyIDType.fromID("663277AF60400638"), + keyIDType.fromID("BBE14491E6EE6366"), + keyIDType.fromID("3E0F20F1A71D6DFD") ]; const getPrimaryKey = async () => openpgp.readKey({ armoredKey: multipleEncryptionAndSigningSubkeys diff --git a/test/general/packet.js b/test/general/packet.js index 2490fe469..bf3a9aeb7 100644 --- a/test/general/packet.js +++ b/test/general/packet.js @@ -211,7 +211,7 @@ module.exports = () => describe("Packet", function() { const literal = new openpgp.LiteralDataPacket(); const enc = new openpgp.AEADEncryptedDataPacket(); const msg = new openpgp.PacketList(); - enc.aeadAlgorithm = 'experimentalGcm'; + enc.aeadAlgorithm = 'experimentalGCM'; msg.push(enc); literal.setText(testText); diff --git a/test/security/unsigned_subpackets.js b/test/security/unsigned_subpackets.js index 747ab4986..57467352c 100644 --- a/test/security/unsigned_subpackets.js +++ b/test/security/unsigned_subpackets.js @@ -78,7 +78,7 @@ async function makeKeyValid() { // add key capability fake.keyFlags[0] |= enums.keyFlags.encryptCommunication; // create modified subpacket data - pusersig.read_sub_packets(fake.write_hashed_sub_packets(), false); + pusersig.readSubPackets(fake.writeHashedSubPackets(), false); // reconstruct the modified key const newlist = new PacketList(); newlist.concat([pubkey, puser, pusersig]); From a6d9f2c4832b011a8b57b718322ca6c725fb806a Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Fri, 19 Mar 2021 00:00:18 +0100 Subject: [PATCH 06/18] Uniform/extend util function names --- src/crypto/crypto.js | 2 +- src/crypto/hash/md5.js | 2 +- src/crypto/public_key/elliptic/curves.js | 2 +- src/crypto/public_key/elliptic/ecdh.js | 2 +- src/encoding/base64.js | 4 +-- src/message.js | 2 +- src/packet/literal_data.js | 8 ++--- src/packet/signature.js | 42 ++++++++++++------------ src/packet/user_attribute.js | 4 +-- src/packet/userid.js | 4 +-- src/type/ecdh_symkey.js | 2 +- src/type/keyid.js | 6 ++-- src/type/s2k.js | 6 ++-- src/util.js | 22 ++++++------- test/crypto/aes_kw.js | 4 +-- test/crypto/cipher/blowfish.js | 6 ++-- test/crypto/cipher/cast5.js | 4 +-- test/crypto/cipher/des.js | 18 +++++----- test/crypto/cipher/twofish.js | 30 ++++++++--------- test/crypto/crypto.js | 6 ++-- test/crypto/ecdh.js | 14 ++++---- test/crypto/elliptic.js | 2 +- test/crypto/gcm.js | 6 ++-- test/crypto/hash/md5.js | 12 +++---- test/crypto/hash/ripemd.js | 8 ++--- test/crypto/hash/sha.js | 20 +++++------ test/general/openpgp.js | 2 +- test/general/packet.js | 6 ++-- test/general/signature.js | 12 +++---- test/general/streaming.js | 20 +++++------ test/general/util.js | 6 ++-- test/general/x25519.js | 10 +++--- 32 files changed, 147 insertions(+), 147 deletions(-) diff --git a/src/crypto/crypto.js b/src/crypto/crypto.js index cd75134c9..053f16f49 100644 --- a/src/crypto/crypto.js +++ b/src/crypto/crypto.js @@ -243,7 +243,7 @@ export function parseEncSessionKeyParams(algo, bytes) { export function serializeParams(algo, params) { const orderedParams = Object.keys(params).map(name => { const param = params[name]; - return util.isUint8Array(param) ? util.uint8ArrayToMpi(param) : param.write(); + return util.isUint8Array(param) ? util.uint8ArrayToMPI(param) : param.write(); }); return util.concatUint8Array(orderedParams); } diff --git a/src/crypto/hash/md5.js b/src/crypto/hash/md5.js index ce2b592cc..2baf3c0bf 100644 --- a/src/crypto/hash/md5.js +++ b/src/crypto/hash/md5.js @@ -16,7 +16,7 @@ import util from '../../util'; // MD5 Digest async function md5(entree) { - const digest = md51(util.uint8ArrayToStr(entree)); + const digest = md51(util.uint8ArrayToString(entree)); return util.hexToUint8Array(hex(digest)); } diff --git a/src/crypto/public_key/elliptic/curves.js b/src/crypto/public_key/elliptic/curves.js index a45f6e025..d35f67381 100644 --- a/src/crypto/public_key/elliptic/curves.js +++ b/src/crypto/public_key/elliptic/curves.js @@ -198,7 +198,7 @@ class Curve { } const indutnyCurve = await getIndutnyCurve(this.name); keyPair = await indutnyCurve.genKeyPair({ - entropy: util.uint8ArrayToStr(await getRandomBytes(32)) + entropy: util.uint8ArrayToString(await getRandomBytes(32)) }); return { publicKey: new Uint8Array(keyPair.getPublic('array', false)), privateKey: keyPair.getPrivate().toArrayLike(Uint8Array) }; } diff --git a/src/crypto/public_key/elliptic/ecdh.js b/src/crypto/public_key/elliptic/ecdh.js index 7cc438ffd..39fd893d4 100644 --- a/src/crypto/public_key/elliptic/ecdh.js +++ b/src/crypto/public_key/elliptic/ecdh.js @@ -54,7 +54,7 @@ function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) { oid.write(), new Uint8Array([public_algo]), kdfParams.write(), - util.strToUint8Array("Anonymous Sender "), + util.stringToUint8Array("Anonymous Sender "), fingerprint.subarray(0, 20) ]); } diff --git a/src/encoding/base64.js b/src/encoding/base64.js index e5522a359..20df84ac5 100644 --- a/src/encoding/base64.js +++ b/src/encoding/base64.js @@ -30,8 +30,8 @@ if (Buffer) { return new Uint8Array(b.buffer, b.byteOffset, b.byteLength); }; } else { - encodeChunk = buf => btoa(util.uint8ArrayToStr(buf)); - decodeChunk = str => util.strToUint8Array(atob(str)); + encodeChunk = buf => btoa(util.uint8ArrayToString(buf)); + decodeChunk = str => util.stringToUint8Array(atob(str)); } /** diff --git a/src/message.js b/src/message.js index 49cb2cfe8..cb461ad12 100644 --- a/src/message.js +++ b/src/message.js @@ -225,7 +225,7 @@ export class Message { if (keyPackets.length > 1) { const seen = {}; keyPackets = keyPackets.filter(function(item) { - const k = item.sessionKeyAlgorithm + util.uint8ArrayToStr(item.sessionKey); + const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey); if (seen.hasOwnProperty(k)) { return false; } diff --git a/src/packet/literal_data.js b/src/packet/literal_data.js index c23a49223..38c5ec1b7 100644 --- a/src/packet/literal_data.js +++ b/src/packet/literal_data.js @@ -59,7 +59,7 @@ class LiteralDataPacket { */ getText(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))); + this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone))); } return this.text; } @@ -84,7 +84,7 @@ class LiteralDataPacket { getBytes(clone = false) { if (this.data === null) { // encode UTF8 and normalize EOL to \r\n - this.data = util.canonicalizeEOL(util.encodeUtf8(this.text)); + this.data = util.canonicalizeEOL(util.encodeUTF8(this.text)); } if (clone) { return stream.passiveClone(this.data); @@ -123,7 +123,7 @@ class LiteralDataPacket { const format = enums.read(enums.literal, await reader.readByte()); const filename_len = await reader.readByte(); - this.filename = util.decodeUtf8(await reader.readBytes(filename_len)); + this.filename = util.decodeUTF8(await reader.readBytes(filename_len)); this.date = util.readDate(await reader.readBytes(4)); @@ -139,7 +139,7 @@ class LiteralDataPacket { * @returns {Uint8Array} Uint8Array representation of the packet. */ writeHeader() { - const filename = util.encodeUtf8(this.filename); + const filename = util.encodeUTF8(this.filename); const filename_length = new Uint8Array([filename.length]); const format = new Uint8Array([enums.write(enums.literal, this.format)]); diff --git a/src/packet/signature.js b/src/packet/signature.js index f4e82cb76..b32c17fe9 100644 --- a/src/packet/signature.js +++ b/src/packet/signature.js @@ -224,7 +224,7 @@ class SignaturePacket { arr.push(writeSubPacket(sub.keyExpirationTime, util.writeNumber(this.keyExpirationTime, 4))); } if (this.preferredSymmetricAlgorithms !== null) { - bytes = util.strToUint8Array(util.uint8ArrayToStr(this.preferredSymmetricAlgorithms)); + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms)); arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, bytes)); } if (this.revocationKeyClass !== null) { @@ -238,55 +238,55 @@ class SignaturePacket { bytes.push(util.writeNumber(name.length, 2)); // 2 octets of value length bytes.push(util.writeNumber(value.length, 2)); - bytes.push(util.strToUint8Array(name)); + bytes.push(util.stringToUint8Array(name)); bytes.push(value); bytes = util.concat(bytes); arr.push(writeSubPacket(sub.notationData, bytes)); }); if (this.preferredHashAlgorithms !== null) { - bytes = util.strToUint8Array(util.uint8ArrayToStr(this.preferredHashAlgorithms)); + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms)); arr.push(writeSubPacket(sub.preferredHashAlgorithms, bytes)); } if (this.preferredCompressionAlgorithms !== null) { - bytes = util.strToUint8Array(util.uint8ArrayToStr(this.preferredCompressionAlgorithms)); + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms)); arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, bytes)); } if (this.keyServerPreferences !== null) { - bytes = util.strToUint8Array(util.uint8ArrayToStr(this.keyServerPreferences)); + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences)); arr.push(writeSubPacket(sub.keyServerPreferences, bytes)); } if (this.preferredKeyServer !== null) { - arr.push(writeSubPacket(sub.preferredKeyServer, util.strToUint8Array(this.preferredKeyServer))); + arr.push(writeSubPacket(sub.preferredKeyServer, util.stringToUint8Array(this.preferredKeyServer))); } if (this.isPrimaryUserID !== null) { arr.push(writeSubPacket(sub.primaryUserID, new Uint8Array([this.isPrimaryUserID ? 1 : 0]))); } if (this.policyURI !== null) { - arr.push(writeSubPacket(sub.policyUri, util.strToUint8Array(this.policyURI))); + arr.push(writeSubPacket(sub.policyUri, util.stringToUint8Array(this.policyURI))); } if (this.keyFlags !== null) { - bytes = util.strToUint8Array(util.uint8ArrayToStr(this.keyFlags)); + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags)); arr.push(writeSubPacket(sub.keyFlags, bytes)); } if (this.signersUserID !== null) { - arr.push(writeSubPacket(sub.signersUserID, util.strToUint8Array(this.signersUserID))); + arr.push(writeSubPacket(sub.signersUserID, util.stringToUint8Array(this.signersUserID))); } if (this.reasonForRevocationFlag !== null) { - bytes = util.strToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString); + bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString); arr.push(writeSubPacket(sub.reasonForRevocation, bytes)); } if (this.features !== null) { - bytes = util.strToUint8Array(util.uint8ArrayToStr(this.features)); + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features)); arr.push(writeSubPacket(sub.features, bytes)); } if (this.signatureTargetPublicKeyAlgorithm !== null) { bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])]; - bytes.push(util.strToUint8Array(this.signatureTargetHash)); + bytes.push(util.stringToUint8Array(this.signatureTargetHash)); bytes = util.concat(bytes); arr.push(writeSubPacket(sub.signatureTarget, bytes)); } if (this.preferredAEADAlgorithms !== null) { - bytes = util.strToUint8Array(util.uint8ArrayToStr(this.preferredAEADAlgorithms)); + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms)); arr.push(writeSubPacket(sub.preferredAEADAlgorithms, bytes)); } @@ -430,13 +430,13 @@ class SignaturePacket { const n = util.readNumber(bytes.subarray(mypos, mypos + 2)); mypos += 2; - const name = util.uint8ArrayToStr(bytes.subarray(mypos, mypos + m)); + const name = util.uint8ArrayToString(bytes.subarray(mypos, mypos + m)); const value = bytes.subarray(mypos + m, mypos + m + n); this.rawNotations.push({ name, humanReadable, value, critical }); if (humanReadable) { - this.notations[name] = util.uint8ArrayToStr(value); + this.notations[name] = util.uint8ArrayToString(value); } break; } @@ -454,7 +454,7 @@ class SignaturePacket { break; case 24: // Preferred Key Server - this.preferredKeyServer = util.uint8ArrayToStr(bytes.subarray(mypos, bytes.length)); + this.preferredKeyServer = util.uint8ArrayToString(bytes.subarray(mypos, bytes.length)); break; case 25: // Primary User ID @@ -462,7 +462,7 @@ class SignaturePacket { break; case 26: // Policy URI - this.policyURI = util.uint8ArrayToStr(bytes.subarray(mypos, bytes.length)); + this.policyURI = util.uint8ArrayToString(bytes.subarray(mypos, bytes.length)); break; case 27: // Key Flags @@ -470,12 +470,12 @@ class SignaturePacket { break; case 28: // Signer's User ID - this.signersUserID = util.uint8ArrayToStr(bytes.subarray(mypos, bytes.length)); + this.signersUserID = util.uint8ArrayToString(bytes.subarray(mypos, bytes.length)); break; case 29: // Reason for Revocation this.reasonForRevocationFlag = bytes[mypos++]; - this.reasonForRevocationString = util.uint8ArrayToStr(bytes.subarray(mypos, bytes.length)); + this.reasonForRevocationString = util.uint8ArrayToString(bytes.subarray(mypos, bytes.length)); break; case 30: // Features @@ -489,7 +489,7 @@ class SignaturePacket { const len = crypto.getHashByteLength(this.signatureTargetHashAlgorithm); - this.signatureTargetHash = util.uint8ArrayToStr(bytes.subarray(mypos, mypos + len)); + this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len)); break; } case 32: @@ -548,7 +548,7 @@ class SignaturePacket { switch (type) { case t.binary: if (data.text !== null) { - return util.encodeUtf8(data.getText(true)); + return util.encodeUTF8(data.getText(true)); } return data.getBytes(true); diff --git a/src/packet/user_attribute.js b/src/packet/user_attribute.js index fe0ac8949..9f1b9111b 100644 --- a/src/packet/user_attribute.js +++ b/src/packet/user_attribute.js @@ -52,7 +52,7 @@ class UserAttributePacket { const len = readSimpleLength(bytes.subarray(i, bytes.length)); i += len.offset; - this.attributes.push(util.uint8ArrayToStr(bytes.subarray(i, i + len.len))); + this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len))); i += len.len; } } @@ -65,7 +65,7 @@ class UserAttributePacket { const arr = []; for (let i = 0; i < this.attributes.length; i++) { arr.push(writeSimpleLength(this.attributes[i].length)); - arr.push(util.strToUint8Array(this.attributes[i])); + arr.push(util.stringToUint8Array(this.attributes[i])); } return util.concatUint8Array(arr); } diff --git a/src/packet/userid.js b/src/packet/userid.js index ec6e50910..7b0facf9f 100644 --- a/src/packet/userid.js +++ b/src/packet/userid.js @@ -72,7 +72,7 @@ class UserIDPacket { * @param {Uint8Array} input - Payload of a tag 13 packet */ read(bytes, config = defaultConfig) { - const userID = util.decodeUtf8(bytes); + const userID = util.decodeUTF8(bytes); if (userID.length > config.maxUserIDLength) { throw new Error('User ID string is too long'); } @@ -90,7 +90,7 @@ class UserIDPacket { * @returns {Uint8Array} Binary representation. */ write() { - return util.encodeUtf8(this.userID); + return util.encodeUTF8(this.userID); } } diff --git a/src/type/ecdh_symkey.js b/src/type/ecdh_symkey.js index 059fd79e9..f3e178793 100644 --- a/src/type/ecdh_symkey.js +++ b/src/type/ecdh_symkey.js @@ -29,7 +29,7 @@ class ECDHSymmetricKey { if (typeof data === 'undefined') { data = new Uint8Array([]); } else if (util.isString(data)) { - data = util.strToUint8Array(data); + data = util.stringToUint8Array(data); } else { data = new Uint8Array(data); } diff --git a/src/type/keyid.js b/src/type/keyid.js index 44624656e..0132d977e 100644 --- a/src/type/keyid.js +++ b/src/type/keyid.js @@ -41,7 +41,7 @@ class KeyID { * @param {Uint8Array} bytes - Input to read the key id from */ read(bytes) { - this.bytes = util.uint8ArrayToStr(bytes.subarray(0, 8)); + this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8)); } /** @@ -49,7 +49,7 @@ class KeyID { * @returns {Uint8Array} Key ID as a Uint8Array. */ write() { - return util.strToUint8Array(this.bytes); + return util.stringToUint8Array(this.bytes); } /** @@ -57,7 +57,7 @@ class KeyID { * @returns {String} Key ID as a hexadecimal string. */ toHex() { - return util.strToHex(this.bytes); + return util.stringToHex(this.bytes); } /** diff --git a/src/type/s2k.js b/src/type/s2k.js index a16999d26..a29183df5 100644 --- a/src/type/s2k.js +++ b/src/type/s2k.js @@ -88,7 +88,7 @@ class S2K { break; case 'gnu': - if (util.uint8ArrayToStr(bytes.subarray(i, i + 3)) === "GNU") { + if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === "GNU") { i += 3; // GNU const gnuExtType = 1000 + bytes[i++]; if (gnuExtType === 1001) { @@ -115,7 +115,7 @@ class S2K { */ write() { if (this.type === 'gnu-dummy') { - return new Uint8Array([101, 0, ...util.strToUint8Array('GNU'), 1]); + return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]); } const arr = [new Uint8Array([enums.write(enums.s2k, this.type), enums.write(enums.hash, this.algorithm)])]; @@ -147,7 +147,7 @@ class S2K { * hashAlgorithm hash length */ async produceKey(passphrase, numBytes) { - passphrase = util.encodeUtf8(passphrase); + passphrase = util.encodeUTF8(passphrase); const algorithm = enums.write(enums.hash, this.algorithm); const arr = []; diff --git a/src/util.js b/src/util.js index d14782b20..b26e4f3ed 100644 --- a/src/util.js +++ b/src/util.js @@ -131,7 +131,7 @@ const util = { * @param {String} str - String to convert * @returns {String} String containing the hexadecimal values. */ - strToHex: function (str) { + stringToHex: function (str) { if (str === null) { return ""; } @@ -154,7 +154,7 @@ const util = { * @param {String} str - Hex string to convert * @returns {String} */ - hexToStr: function (hex) { + hexToString: function (hex) { let str = ''; for (let i = 0; i < hex.length; i += 2) { str += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); @@ -191,7 +191,7 @@ const util = { * @param {Uint8Array} bin - An array of 8-bit integers to convert * @returns {Uint8Array} MPI-formatted Uint8Array. */ - uint8ArrayToMpi: function (bin) { + uint8ArrayToMPI: function (bin) { const bitSize = util.uint8ArrayBitLength(bin); if (bitSize === 0) { throw new Error('Zero MPI'); @@ -254,10 +254,10 @@ const util = { * @param {String} str - String to convert * @returns {Uint8Array} An array of 8-bit integers. */ - strToUint8Array: function (str) { + stringToUint8Array: function (str) { return stream.transform(str, str => { if (!util.isString(str)) { - throw new Error('strToUint8Array: Data must be in the form of a string'); + throw new Error('stringToUint8Array: Data must be in the form of a string'); } const result = new Uint8Array(str.length); @@ -273,7 +273,7 @@ const util = { * @param {Uint8Array} bytes - An array of 8-bit integers to convert * @returns {String} String representation of the array. */ - uint8ArrayToStr: function (bytes) { + uint8ArrayToString: function (bytes) { bytes = new Uint8Array(bytes); const result = []; const bs = 1 << 14; @@ -290,7 +290,7 @@ const util = { * @param {String|ReadableStream} str - The string to convert * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes. */ - encodeUtf8: function (str) { + encodeUTF8: function (str) { const encoder = new TextEncoder('utf-8'); // eslint-disable-next-line no-inner-declarations function process(value, lastChunk = false) { @@ -304,7 +304,7 @@ const util = { * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes * @returns {String|ReadableStream} A native javascript string. */ - decodeUtf8: function (utf8) { + decodeUTF8: function (utf8) { const decoder = new TextDecoder('utf-8'); // eslint-disable-next-line no-inner-declarations function process(value, lastChunk = false) { @@ -392,12 +392,12 @@ const util = { /** * Helper function to print a debug message. Debug * messages are only printed if - * Different than printDebug because will call strToHex iff necessary. + * Different than printDebug because will call stringToHex iff necessary. * @param {String} str - String of the debug message */ - printDebugHexStrDump: function (str, strToHex) { + printDebugHexStrDump: function (str, stringToHex) { if (debugMode) { - str += util.strToHex(strToHex); + str += util.stringToHex(stringToHex); console.log(str); } }, diff --git a/test/crypto/aes_kw.js b/test/crypto/aes_kw.js index 8e6ac4271..d27e468b9 100644 --- a/test/crypto/aes_kw.js +++ b/test/crypto/aes_kw.js @@ -47,9 +47,9 @@ module.exports = () => describe('AES Key Wrap and Unwrap', function () { it(test[0], function(done) { const kek = util.hexToUint8Array(test[1]); const input = test[2].replace(/\s/g, ""); - const input_bin = util.hexToStr(input); + const input_bin = util.hexToString(input); const output = test[3].replace(/\s/g, ""); - const output_bin = util.hexToStr(output); + const output_bin = util.hexToString(output); expect(util.uint8ArrayToHex(aesKW.wrap(kek, input_bin)).toUpperCase()).to.equal(output); expect(util.uint8ArrayToHex(aesKW.unwrap(kek, output_bin)).toUpperCase()).to.equal(input); done(); diff --git a/test/crypto/cipher/blowfish.js b/test/crypto/cipher/blowfish.js index 1d2dc3b06..f77575848 100644 --- a/test/crypto/cipher/blowfish.js +++ b/test/crypto/cipher/blowfish.js @@ -7,10 +7,10 @@ const { expect } = chai; module.exports = () => it('Blowfish cipher test with test vectors from https://www.schneier.com/code/vectors.txt', function(done) { function test_bf(input, key, output) { - const blowfish = new BF(util.uint8ArrayToStr(key)); - const result = util.uint8ArrayToStr(blowfish.encrypt(input)); + const blowfish = new BF(util.uint8ArrayToString(key)); + const result = util.uint8ArrayToString(blowfish.encrypt(input)); - return (util.strToHex(result) === util.strToHex(util.uint8ArrayToStr(output))); + return (util.stringToHex(result) === util.stringToHex(util.uint8ArrayToString(output))); } const testvectors = [[[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x4E,0xF9,0x97,0x45,0x61,0x98,0xDD,0x78]], diff --git a/test/crypto/cipher/cast5.js b/test/crypto/cipher/cast5.js index 19b129fa5..583dcf924 100644 --- a/test/crypto/cipher/cast5.js +++ b/test/crypto/cipher/cast5.js @@ -8,9 +8,9 @@ const { expect } = chai; module.exports = () => it('CAST-128 cipher test with test vectors from RFC2144', function (done) { function test_cast(input, key, output) { const cast5 = new CAST5(key); - const result = util.uint8ArrayToStr(cast5.encrypt(input)); + const result = util.uint8ArrayToString(cast5.encrypt(input)); - return util.strToHex(result) === util.strToHex(util.uint8ArrayToStr(output)); + return util.stringToHex(result) === util.stringToHex(util.uint8ArrayToString(output)); } const testvectors = [[[0x01,0x23,0x45,0x67,0x12,0x34,0x56,0x78,0x23,0x45,0x67,0x89,0x34,0x56,0x78,0x9A],[0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF],[0x23,0x8B,0x4F,0xE5,0x84,0x7E,0x44,0xB2]]]; diff --git a/test/crypto/cipher/des.js b/test/crypto/cipher/des.js index 9bcbb20f8..12f386ad9 100644 --- a/test/crypto/cipher/des.js +++ b/test/crypto/cipher/des.js @@ -77,12 +77,12 @@ module.exports = () => describe('TripleDES (EDE) cipher test with test vectors f for (let i = 0; i < testvectors.length; i++) { const des = new TripleDES(key); - const encr = util.uint8ArrayToStr(des.encrypt(testvectors[i][0], key)); + const encr = util.uint8ArrayToString(des.encrypt(testvectors[i][0], key)); expect(encr, 'vector with block ' + util.uint8ArrayToHex(testvectors[i][0]) + - ' and key ' + util.strToHex(util.uint8ArrayToStr(key)) + + ' and key ' + util.stringToHex(util.uint8ArrayToString(key)) + ' should be ' + util.uint8ArrayToHex(testvectors[i][1]) + - ' != ' + util.uint8ArrayToHex(encr)).to.be.equal(util.uint8ArrayToStr(testvectors[i][1])); + ' != ' + util.uint8ArrayToHex(encr)).to.be.equal(util.uint8ArrayToString(testvectors[i][1])); } done(); }); @@ -124,18 +124,18 @@ module.exports = () => describe('TripleDES (EDE) cipher test with test vectors f const encrypted = des.encrypt(thisVectorSet[i][0], padding); const decrypted = des.decrypt(encrypted, padding); - expect(util.uint8ArrayToStr(encrypted), 'vector with block [' + util.uint8ArrayToHex(thisVectorSet[i][0]) + - '] and key [' + util.strToHex(util.uint8ArrayToStr(key)) + + expect(util.uint8ArrayToString(encrypted), 'vector with block [' + util.uint8ArrayToHex(thisVectorSet[i][0]) + + '] and key [' + util.stringToHex(util.uint8ArrayToString(key)) + '] and padding [' + padding + '] should be ' + util.uint8ArrayToHex(thisVectorSet[i][1]) + ' - Actually [' + util.uint8ArrayToHex(encrypted) + - ']').to.equal(util.uint8ArrayToStr(thisVectorSet[i][1])); - expect(util.uint8ArrayToStr(decrypted), 'vector with block [' + util.uint8ArrayToHex(thisVectorSet[i][0]) + - '] and key [' + util.strToHex(util.uint8ArrayToStr(key)) + + ']').to.equal(util.uint8ArrayToString(thisVectorSet[i][1])); + expect(util.uint8ArrayToString(decrypted), 'vector with block [' + util.uint8ArrayToHex(thisVectorSet[i][0]) + + '] and key [' + util.stringToHex(util.uint8ArrayToString(key)) + '] and padding [' + padding + '] should be ' + util.uint8ArrayToHex(thisVectorSet[i][0]) + ' - Actually [' + util.uint8ArrayToHex(decrypted) + - ']').to.equal(util.uint8ArrayToStr(thisVectorSet[i][0])); + ']').to.equal(util.uint8ArrayToString(thisVectorSet[i][0])); } } done(); diff --git a/test/crypto/cipher/twofish.js b/test/crypto/cipher/twofish.js index 838c37f49..77d3cd4c6 100644 --- a/test/crypto/cipher/twofish.js +++ b/test/crypto/cipher/twofish.js @@ -7,7 +7,7 @@ const { expect } = chai; module.exports = () => it('Twofish with test vectors from https://www.schneier.com/code/ecb_ival.txt', function(done) { function tfencrypt(block, key) { - const tf = new TF(util.strToUint8Array(key)); + const tf = new TF(util.stringToUint8Array(key)); return tf.encrypt(block); } @@ -36,34 +36,34 @@ module.exports = () => it('Twofish with test vectors from https://www.schneier.c if (i === 0) { blk = start_short; - key = util.uint8ArrayToStr(start); + key = util.uint8ArrayToString(start); ct = testvectors[0]; - res = util.uint8ArrayToStr(tfencrypt(blk,key)); - exp = util.uint8ArrayToStr(ct); + res = util.uint8ArrayToString(tfencrypt(blk,key)); + exp = util.uint8ArrayToString(ct); } else if (i === 1) { blk = testvectors[0]; - key = util.uint8ArrayToStr(start); + key = util.uint8ArrayToString(start); ct = testvectors[1]; - res = util.uint8ArrayToStr(tfencrypt(blk,key)); - exp = util.uint8ArrayToStr(ct); + res = util.uint8ArrayToString(tfencrypt(blk,key)); + exp = util.uint8ArrayToString(ct); } else if (i === 2) { blk = testvectors[i - 1]; - key = util.uint8ArrayToStr(testvectors[i - 2].concat(start_short)); + key = util.uint8ArrayToString(testvectors[i - 2].concat(start_short)); ct = testvectors[i]; - res = util.uint8ArrayToStr(tfencrypt(blk,key)); - exp = util.uint8ArrayToStr(ct); + res = util.uint8ArrayToString(tfencrypt(blk,key)); + exp = util.uint8ArrayToString(ct); } else if (i < 10 || i > 46) { blk = testvectors[i - 1]; - key = util.uint8ArrayToStr(testvectors[i - 2].concat(testvectors[i - 3])); + key = util.uint8ArrayToString(testvectors[i - 2].concat(testvectors[i - 3])); ct = testvectors[i]; - res = util.uint8ArrayToStr(tfencrypt(blk,key)); - exp = util.uint8ArrayToStr(ct); + res = util.uint8ArrayToString(tfencrypt(blk,key)); + exp = util.uint8ArrayToString(ct); } else { - testvectors[i] = tfencrypt(testvectors[i - 1],util.uint8ArrayToStr(testvectors[i - 2].concat(testvectors[i - 3]))); + testvectors[i] = tfencrypt(testvectors[i - 1],util.uint8ArrayToString(testvectors[i - 2].concat(testvectors[i - 3]))); continue; } expect(res, 'vector with block ' + util.uint8ArrayToHex(blk) + - ' with key ' + util.strToHex(key) + + ' with key ' + util.stringToHex(key) + ' should be ' + util.uint8ArrayToHex(ct) + ' but is ' + util.uint8ArrayToHex(tfencrypt(blk,key))).to.equal(exp); } diff --git a/test/crypto/crypto.js b/test/crypto/crypto.js index 7bb61d0de..71518ad37 100644 --- a/test/crypto/crypto.js +++ b/test/crypto/crypto.js @@ -207,7 +207,7 @@ module.exports = () => describe('API functional testing', function() { const elGamalPublicParams = crypto.parsePublicKeyParams(algoElGamal, elGamalPublicKeyMaterial).publicParams; const elGamalPrivateParams = crypto.parsePrivateKeyParams(algoElGamal, elGamalPrivateKeyMaterial).privateParams; - const data = util.strToUint8Array("foobar"); + const data = util.stringToUint8Array("foobar"); describe('Sign and verify', function () { it('RSA', async function () { @@ -242,8 +242,8 @@ module.exports = () => describe('API functional testing', function() { await Promise.all(symmAlgos.map(async function(algo) { const symmKey = await crypto.generateSessionKey(algo); const IV = new Uint8Array(crypto.cipher[algo].blockSize); - const symmencData = await crypto.cfb.encrypt(algo, symmKey, util.strToUint8Array(plaintext), IV, openpgp.config); - const text = util.uint8ArrayToStr(await crypto.cfb.decrypt(algo, symmKey, symmencData, new Uint8Array(crypto.cipher[algo].blockSize))); + const symmencData = await crypto.cfb.encrypt(algo, symmKey, util.stringToUint8Array(plaintext), IV, openpgp.config); + const text = util.uint8ArrayToString(await crypto.cfb.decrypt(algo, symmKey, symmencData, new Uint8Array(crypto.cipher[algo].blockSize))); expect(text).to.equal(plaintext); })); } diff --git a/test/crypto/ecdh.js b/test/crypto/ecdh.js index beff91ea7..82444cea3 100644 --- a/test/crypto/ecdh.js +++ b/test/crypto/ecdh.js @@ -16,7 +16,7 @@ const key_data = elliptic_data.key_data; module.exports = () => describe('ECDH key exchange @lightweight', function () { const decrypt_message = function (oid, hash, cipher, priv, pub, ephemeral, data, fingerprint) { if (util.isString(data)) { - data = util.strToUint8Array(data); + data = util.stringToUint8Array(data); } else { data = new Uint8Array(data); } @@ -143,7 +143,7 @@ module.exports = () => describe('ECDH key exchange @lightweight', function () { const curve = new elliptic_curves.Curve('secp256k1'); const oid = new OID(curve.oid); const kdfParams = new KDFParams({ hash: curve.hash, cipher: curve.cipher }); - const data = util.strToUint8Array('test'); + const data = util.stringToUint8Array('test'); expect( ecdh.encrypt(oid, kdfParams, data, Q1, fingerprint1) ).to.be.rejectedWith(Error, /Public key is not valid for specified curve|Failed to translate Buffer to a EC_POINT|Unknown point format/); @@ -152,7 +152,7 @@ module.exports = () => describe('ECDH key exchange @lightweight', function () { const curve = new elliptic_curves.Curve('curve25519'); const oid = new OID(curve.oid); const kdfParams = new KDFParams({ hash: curve.hash, cipher: curve.cipher }); - const data = util.strToUint8Array('test'); + const data = util.stringToUint8Array('test'); const { publicKey: V, wrappedKey: C } = await ecdh.encrypt(oid, kdfParams, data, Q1, fingerprint1); await expect( ecdh.decrypt(oid, kdfParams, V, C, Q2, d2, fingerprint1) @@ -162,7 +162,7 @@ module.exports = () => describe('ECDH key exchange @lightweight', function () { const curve = new elliptic_curves.Curve('curve25519'); const oid = new OID(curve.oid); const kdfParams = new KDFParams({ hash: curve.hash, cipher: curve.cipher }); - const data = util.strToUint8Array('test'); + const data = util.stringToUint8Array('test'); const { publicKey: V, wrappedKey: C } = await ecdh.encrypt(oid, kdfParams, data, Q2, fingerprint1); await expect( ecdh.decrypt(oid, kdfParams, V, C, Q2, d2, fingerprint2) @@ -172,7 +172,7 @@ module.exports = () => describe('ECDH key exchange @lightweight', function () { const curve = new elliptic_curves.Curve('curve25519'); const oid = new OID(curve.oid); const kdfParams = new KDFParams({ hash: curve.hash, cipher: curve.cipher }); - const data = util.strToUint8Array('test'); + const data = util.stringToUint8Array('test'); const { publicKey: V, wrappedKey: C } = await ecdh.encrypt(oid, kdfParams, data, Q1, fingerprint1); expect(await ecdh.decrypt(oid, kdfParams, V, C, Q1, d1, fingerprint1)).to.deep.equal(data); }); @@ -182,7 +182,7 @@ module.exports = () => describe('ECDH key exchange @lightweight', function () { const curve = new elliptic_curves.Curve(curveName); const oid = new OID(curve.oid); const kdfParams = new KDFParams({ hash: curve.hash, cipher: curve.cipher }); - const data = util.strToUint8Array('test'); + const data = util.stringToUint8Array('test'); const Q = key_data[curveName].pub; const d = key_data[curveName].priv; const { publicKey: V, wrappedKey: C } = await ecdh.encrypt(oid, kdfParams, data, Q, fingerprint1); @@ -225,7 +225,7 @@ module.exports = () => describe('ECDH key exchange @lightweight', function () { const curve = new elliptic_curves.Curve(curveName); const oid = new OID(curve.oid); const kdfParams = new KDFParams({ hash: curve.hash, cipher: curve.cipher }); - const data = util.strToUint8Array('test'); + const data = util.stringToUint8Array('test'); const Q = key_data[curveName].pub; const d = key_data[curveName].priv; const { publicKey: V, wrappedKey: C } = await ecdh.encrypt(oid, kdfParams, data, Q, fingerprint1); diff --git a/test/crypto/elliptic.js b/test/crypto/elliptic.js index 5ec7e8715..e6b16caea 100644 --- a/test/crypto/elliptic.js +++ b/test/crypto/elliptic.js @@ -125,7 +125,7 @@ module.exports = () => describe('Elliptic Curve Cryptography @lightweight', func const verify_signature = async function (oid, hash, r, s, message, pub) { if (util.isString(message)) { - message = util.strToUint8Array(message); + message = util.stringToUint8Array(message); } else if (!util.isUint8Array(message)) { message = new Uint8Array(message); } diff --git a/test/crypto/gcm.js b/test/crypto/gcm.js index 5619e8c50..53baa9c8a 100644 --- a/test/crypto/gcm.js +++ b/test/crypto/gcm.js @@ -52,15 +52,15 @@ module.exports = () => describe('Symmetric AES-GCM (experimental)', function() { nativeEncrypt || disableNative(); let modeInstance = await crypto.gcm(algo, key); - const ciphertext = await modeInstance.encrypt(util.strToUint8Array(plaintext), iv); + const ciphertext = await modeInstance.encrypt(util.stringToUint8Array(plaintext), iv); enableNative(); nativeDecrypt || disableNative(); modeInstance = await crypto.gcm(algo, key); - const decrypted = await modeInstance.decrypt(util.strToUint8Array(util.uint8ArrayToStr(ciphertext)), iv); + const decrypted = await modeInstance.decrypt(util.stringToUint8Array(util.uint8ArrayToString(ciphertext)), iv); enableNative(); - const decryptedStr = util.uint8ArrayToStr(decrypted); + const decryptedStr = util.uint8ArrayToString(decrypted); expect(decryptedStr).to.equal(plaintext); if (algo !== 'aes192') { // not implemented by webcrypto diff --git a/test/crypto/hash/md5.js b/test/crypto/hash/md5.js index e75a7e439..d6d1dbb3e 100644 --- a/test/crypto/hash/md5.js +++ b/test/crypto/hash/md5.js @@ -6,10 +6,10 @@ const chai = require('chai'); const { expect } = chai; module.exports = () => it('MD5 with test vectors from RFC 1321', async function() { - expect(util.strToHex(util.uint8ArrayToStr(await md5(util.strToUint8Array(''))), 'MD5("") = d41d8cd98f00b204e9800998ecf8427e')).to.equal('d41d8cd98f00b204e9800998ecf8427e'); - expect(util.strToHex(util.uint8ArrayToStr(await md5(util.strToUint8Array('abc'))), 'MD5("a") = 0cc175b9c0f1b6a831c399e269772661')).to.equal('900150983cd24fb0d6963f7d28e17f72'); - expect(util.strToHex(util.uint8ArrayToStr(await md5(util.strToUint8Array('message digest'))), 'MD5("message digest") = f96b697d7cb7938d525a2f31aaf161d0')).to.equal('f96b697d7cb7938d525a2f31aaf161d0'); - expect(util.strToHex(util.uint8ArrayToStr(await md5(util.strToUint8Array('abcdefghijklmnopqrstuvwxyz'))), 'MD5("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b')).to.equal('c3fcd3d76192e4007dfb496cca67e13b'); - expect(util.strToHex(util.uint8ArrayToStr(await md5(util.strToUint8Array('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'))), 'MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") = d174ab98d277d9f5a5611c2c9f419d9f')).to.equal('d174ab98d277d9f5a5611c2c9f419d9f'); - expect(util.strToHex(util.uint8ArrayToStr(await md5(util.strToUint8Array('12345678901234567890123456789012345678901234567890123456789012345678901234567890'))), 'MD5("12345678901234567890123456789012345678901234567890123456789012345678901234567890") = 57edf4a22be3c955ac49da2e2107b67a')).to.equal('57edf4a22be3c955ac49da2e2107b67a'); + expect(util.stringToHex(util.uint8ArrayToString(await md5(util.stringToUint8Array(''))), 'MD5("") = d41d8cd98f00b204e9800998ecf8427e')).to.equal('d41d8cd98f00b204e9800998ecf8427e'); + expect(util.stringToHex(util.uint8ArrayToString(await md5(util.stringToUint8Array('abc'))), 'MD5("a") = 0cc175b9c0f1b6a831c399e269772661')).to.equal('900150983cd24fb0d6963f7d28e17f72'); + expect(util.stringToHex(util.uint8ArrayToString(await md5(util.stringToUint8Array('message digest'))), 'MD5("message digest") = f96b697d7cb7938d525a2f31aaf161d0')).to.equal('f96b697d7cb7938d525a2f31aaf161d0'); + expect(util.stringToHex(util.uint8ArrayToString(await md5(util.stringToUint8Array('abcdefghijklmnopqrstuvwxyz'))), 'MD5("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b')).to.equal('c3fcd3d76192e4007dfb496cca67e13b'); + expect(util.stringToHex(util.uint8ArrayToString(await md5(util.stringToUint8Array('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'))), 'MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") = d174ab98d277d9f5a5611c2c9f419d9f')).to.equal('d174ab98d277d9f5a5611c2c9f419d9f'); + expect(util.stringToHex(util.uint8ArrayToString(await md5(util.stringToUint8Array('12345678901234567890123456789012345678901234567890123456789012345678901234567890'))), 'MD5("12345678901234567890123456789012345678901234567890123456789012345678901234567890") = 57edf4a22be3c955ac49da2e2107b67a')).to.equal('57edf4a22be3c955ac49da2e2107b67a'); }); diff --git a/test/crypto/hash/ripemd.js b/test/crypto/hash/ripemd.js index 6f56367d5..12ec1dd52 100644 --- a/test/crypto/hash/ripemd.js +++ b/test/crypto/hash/ripemd.js @@ -6,8 +6,8 @@ const chai = require('chai'); const { expect } = chai; module.exports = () => it("RIPE-MD 160 bits with test vectors from https://homes.esat.kuleuven.be/~bosselae/ripemd160.html", async function() { - expect(util.strToHex(util.uint8ArrayToStr(await rmdString(util.strToUint8Array(''))), 'RMDstring("") = 9c1185a5c5e9fc54612808977ee8f548b2258d31')).to.equal('9c1185a5c5e9fc54612808977ee8f548b2258d31'); - expect(util.strToHex(util.uint8ArrayToStr(await rmdString(util.strToUint8Array('a'))), 'RMDstring("a") = 0bdc9d2d256b3ee9daae347be6f4dc835a467ffe')).to.equal('0bdc9d2d256b3ee9daae347be6f4dc835a467ffe'); - expect(util.strToHex(util.uint8ArrayToStr(await rmdString(util.strToUint8Array('abc'))), 'RMDstring("abc") = 8eb208f7e05d987a9b044a8e98c6b087f15a0bfc')).to.equal('8eb208f7e05d987a9b044a8e98c6b087f15a0bfc'); - expect(util.strToHex(util.uint8ArrayToStr(await rmdString(util.strToUint8Array('message digest'))), 'RMDstring("message digest") = 5d0689ef49d2fae572b881b123a85ffa21595f36')).to.equal('5d0689ef49d2fae572b881b123a85ffa21595f36'); + expect(util.stringToHex(util.uint8ArrayToString(await rmdString(util.stringToUint8Array(''))), 'RMDstring("") = 9c1185a5c5e9fc54612808977ee8f548b2258d31')).to.equal('9c1185a5c5e9fc54612808977ee8f548b2258d31'); + expect(util.stringToHex(util.uint8ArrayToString(await rmdString(util.stringToUint8Array('a'))), 'RMDstring("a") = 0bdc9d2d256b3ee9daae347be6f4dc835a467ffe')).to.equal('0bdc9d2d256b3ee9daae347be6f4dc835a467ffe'); + expect(util.stringToHex(util.uint8ArrayToString(await rmdString(util.stringToUint8Array('abc'))), 'RMDstring("abc") = 8eb208f7e05d987a9b044a8e98c6b087f15a0bfc')).to.equal('8eb208f7e05d987a9b044a8e98c6b087f15a0bfc'); + expect(util.stringToHex(util.uint8ArrayToString(await rmdString(util.stringToUint8Array('message digest'))), 'RMDstring("message digest") = 5d0689ef49d2fae572b881b123a85ffa21595f36')).to.equal('5d0689ef49d2fae572b881b123a85ffa21595f36'); }); diff --git a/test/crypto/hash/sha.js b/test/crypto/hash/sha.js index 597f917b5..faf78ef07 100644 --- a/test/crypto/hash/sha.js +++ b/test/crypto/hash/sha.js @@ -6,14 +6,14 @@ const chai = require('chai'); const { expect } = chai; module.exports = () => it('SHA* with test vectors from NIST FIPS 180-2', async function() { - expect(util.strToHex(util.uint8ArrayToStr(await hash.sha1(util.strToUint8Array('abc'))), 'hash.sha1("abc") = a9993e364706816aba3e25717850c26c9cd0d89d')).to.equal('a9993e364706816aba3e25717850c26c9cd0d89d'); - expect(util.strToHex(util.uint8ArrayToStr(await hash.sha1(util.strToUint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 84983e441c3bd26ebaae4aa1f95129e5e54670f1')).to.equal('84983e441c3bd26ebaae4aa1f95129e5e54670f1'); - expect(util.strToHex(util.uint8ArrayToStr(await hash.sha224(util.strToUint8Array('abc'))), 'hash.sha224("abc") = 23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7')).to.equal('23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7'); - expect(util.strToHex(util.uint8ArrayToStr(await hash.sha224(util.strToUint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha224("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525')).to.equal('75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525'); - expect(util.strToHex(util.uint8ArrayToStr(await hash.sha256(util.strToUint8Array('abc'))), 'hash.sha256("abc") = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad')).to.equal('ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'); - expect(util.strToHex(util.uint8ArrayToStr(await hash.sha256(util.strToUint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha256("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1')).to.equal('248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1'); - expect(util.strToHex(util.uint8ArrayToStr(await hash.sha384(util.strToUint8Array('abc'))), 'hash.sha384("abc") = cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7')).to.equal('cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7'); - expect(util.strToHex(util.uint8ArrayToStr(await hash.sha384(util.strToUint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha384("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b')).to.equal('3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b'); - expect(util.strToHex(util.uint8ArrayToStr(await hash.sha512(util.strToUint8Array('abc'))), 'hash.sha512("abc") = ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f')).to.equal('ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f'); - expect(util.strToHex(util.uint8ArrayToStr(await hash.sha512(util.strToUint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha512("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445')).to.equal('204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445'); + expect(util.stringToHex(util.uint8ArrayToString(await hash.sha1(util.stringToUint8Array('abc'))), 'hash.sha1("abc") = a9993e364706816aba3e25717850c26c9cd0d89d')).to.equal('a9993e364706816aba3e25717850c26c9cd0d89d'); + expect(util.stringToHex(util.uint8ArrayToString(await hash.sha1(util.stringToUint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 84983e441c3bd26ebaae4aa1f95129e5e54670f1')).to.equal('84983e441c3bd26ebaae4aa1f95129e5e54670f1'); + expect(util.stringToHex(util.uint8ArrayToString(await hash.sha224(util.stringToUint8Array('abc'))), 'hash.sha224("abc") = 23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7')).to.equal('23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7'); + expect(util.stringToHex(util.uint8ArrayToString(await hash.sha224(util.stringToUint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha224("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525')).to.equal('75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525'); + expect(util.stringToHex(util.uint8ArrayToString(await hash.sha256(util.stringToUint8Array('abc'))), 'hash.sha256("abc") = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad')).to.equal('ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'); + expect(util.stringToHex(util.uint8ArrayToString(await hash.sha256(util.stringToUint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha256("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1')).to.equal('248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1'); + expect(util.stringToHex(util.uint8ArrayToString(await hash.sha384(util.stringToUint8Array('abc'))), 'hash.sha384("abc") = cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7')).to.equal('cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7'); + expect(util.stringToHex(util.uint8ArrayToString(await hash.sha384(util.stringToUint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha384("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b')).to.equal('3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b'); + expect(util.stringToHex(util.uint8ArrayToString(await hash.sha512(util.stringToUint8Array('abc'))), 'hash.sha512("abc") = ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f')).to.equal('ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f'); + expect(util.stringToHex(util.uint8ArrayToString(await hash.sha512(util.stringToUint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha512("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445')).to.equal('204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445'); }); diff --git a/test/general/openpgp.js b/test/general/openpgp.js index 12ef5c55e..0ff026657 100644 --- a/test/general/openpgp.js +++ b/test/general/openpgp.js @@ -2700,7 +2700,7 @@ amnR6g== message: await openpgp.readMessage({ armoredMessage: encrypted }), format: 'binary' }); - expect(util.decodeUtf8(decrypted.data)).to.equal('"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:123\r\nDTSTART:20191211T121212Z\r\nDTEND:20191212T121212Z\r\nEND:VEVENT\r\nEND:VCALENDAR"'); + expect(util.decodeUTF8(decrypted.data)).to.equal('"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:123\r\nDTSTART:20191211T121212Z\r\nDTEND:20191212T121212Z\r\nEND:VEVENT\r\nEND:VCALENDAR"'); }); }); diff --git a/test/general/packet.js b/test/general/packet.js index bf3a9aeb7..c9f30da07 100644 --- a/test/general/packet.js +++ b/test/general/packet.js @@ -255,7 +255,7 @@ module.exports = () => describe("Packet", function() { const msg = new openpgp.PacketList(); msg.push(enc); - literal.setBytes(util.strToUint8Array('Hello, world!\n'), openpgp.enums.literal.binary); + literal.setBytes(util.stringToUint8Array('Hello, world!\n'), openpgp.enums.literal.binary); literal.filename = ''; enc.packets.push(literal); @@ -567,7 +567,7 @@ module.exports = () => describe("Packet", function() { const key = skesk.sessionKey; - literal.setBytes(util.strToUint8Array('Hello, world!\n'), openpgp.enums.literal.binary); + literal.setBytes(util.stringToUint8Array('Hello, world!\n'), openpgp.enums.literal.binary); literal.filename = ''; encData.packets.push(literal); await encData.encrypt(algo, key, undefined, openpgp.config); @@ -646,7 +646,7 @@ module.exports = () => describe("Packet", function() { const key = key_enc.sessionKey; - literal.setBytes(util.strToUint8Array('Hello, world!\n'), openpgp.enums.literal.binary); + literal.setBytes(util.stringToUint8Array('Hello, world!\n'), openpgp.enums.literal.binary); literal.filename = ''; enc.packets.push(literal); await enc.encrypt(algo, key, undefined, openpgp.config); diff --git a/test/general/signature.js b/test/general/signature.js index 88445efb5..9a036da8e 100644 --- a/test/general/signature.js +++ b/test/general/signature.js @@ -1363,7 +1363,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA }); it('Sign text with openpgp.sign and verify with openpgp.verify leads to same bytes cleartext and valid signatures - armored', async function() { - const plaintext = util.strToUint8Array('short message\nnext line \n한국어/조선말'); + const plaintext = util.stringToUint8Array('short message\nnext line \n한국어/조선말'); const pubKey = await openpgp.readKey({ armoredKey: pub_key_arm2 }); const privKey = await openpgp.readKey({ armoredKey: priv_key_arm2 }); await privKey.decrypt('hello world'); @@ -1383,7 +1383,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA }); it('Sign text with openpgp.sign and verify with openpgp.verify leads to same bytes cleartext and valid signatures - not armored', async function() { - const plaintext = util.strToUint8Array('short message\nnext line \n한국어/조선말'); + const plaintext = util.stringToUint8Array('short message\nnext line \n한국어/조선말'); const pubKey = await openpgp.readKey({ armoredKey: pub_key_arm2 }); const privKey = await openpgp.readKey({ armoredKey: priv_key_arm2 }); await privKey.decrypt('hello world'); @@ -1411,7 +1411,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA const config = { minRSABits: 1024 }; return openpgp.sign({ privateKeys:[privKey], message: openpgp.Message.fromText(plaintext), detached: true, config }).then(async function(armoredSignature) { const signature = await openpgp.readSignature({ armoredSignature }); - return openpgp.verify({ publicKeys:[pubKey], message: openpgp.Message.fromBinary(util.encodeUtf8(plaintext)), signature, config }); + return openpgp.verify({ publicKeys:[pubKey], message: openpgp.Message.fromBinary(util.encodeUTF8(plaintext)), signature, config }); }).then(function({ data, signatures }) { expect(data).to.equal(plaintext); expect(signatures).to.have.length(1); @@ -1421,8 +1421,8 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA }); it('Should verify cleartext message correctly when using a detached binary signature and text literal data', async function () { - const plaintext = util.encodeUtf8('short message\nnext line \n한국어/조선말'); - const binaryPlaintext = util.encodeUtf8(plaintext); + const plaintext = util.encodeUTF8('short message\nnext line \n한국어/조선말'); + const binaryPlaintext = util.encodeUTF8(plaintext); const pubKey = await openpgp.readKey({ armoredKey: pub_key_arm2 }); const privKey = await openpgp.readKey({ armoredKey: priv_key_arm2 }); await privKey.decrypt('hello world'); @@ -1448,7 +1448,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA const config = { minRSABits: 1024 }; return openpgp.sign({ privateKeys:[privKey], message: openpgp.Message.fromText(plaintext), detached: true, config }).then(async function(armoredSignature) { const signature = await openpgp.readSignature({ armoredSignature }); - return openpgp.encrypt({ message: openpgp.Message.fromBinary(util.encodeUtf8(plaintext)), publicKeys: [pubKey], signature, config }); + return openpgp.encrypt({ message: openpgp.Message.fromBinary(util.encodeUTF8(plaintext)), publicKeys: [pubKey], signature, config }); }).then(async armoredMessage => { const message = await openpgp.readMessage({ armoredMessage }); diff --git a/test/general/streaming.js b/test/general/streaming.js index 8f99e3086..c8a82e4d9 100644 --- a/test/general/streaming.js +++ b/test/general/streaming.js @@ -184,8 +184,8 @@ function tests() { dataArrived(); // Do not wait until data arrived. const data = new ReadableStream({ async start(controller) { - controller.enqueue(util.strToUint8Array('hello ')); - controller.enqueue(util.strToUint8Array('world')); + controller.enqueue(util.stringToUint8Array('hello ')); + controller.enqueue(util.stringToUint8Array('world')); controller.close(); } }); @@ -650,8 +650,8 @@ function tests() { dataArrived(); // Do not wait until data arrived. const data = new ReadableStream({ async start(controller) { - controller.enqueue(util.strToUint8Array('hello ')); - controller.enqueue(util.strToUint8Array('world')); + controller.enqueue(util.stringToUint8Array('hello ')); + controller.enqueue(util.stringToUint8Array('world')); controller.close(); } }); @@ -680,8 +680,8 @@ function tests() { dataArrived(); // Do not wait until data arrived. const data = new ReadableStream({ async start(controller) { - controller.enqueue(util.strToUint8Array('hello ')); - controller.enqueue(util.strToUint8Array('world')); + controller.enqueue(util.stringToUint8Array('hello ')); + controller.enqueue(util.stringToUint8Array('world')); controller.close(); } }); @@ -710,8 +710,8 @@ function tests() { dataArrived(); // Do not wait until data arrived. const data = new ReadableStream({ async start(controller) { - controller.enqueue(util.strToUint8Array('hello ')); - controller.enqueue(util.strToUint8Array('world')); + controller.enqueue(util.stringToUint8Array('hello ')); + controller.enqueue(util.stringToUint8Array('world')); controller.close(); } }); @@ -741,8 +741,8 @@ function tests() { dataArrived(); // Do not wait until data arrived. const data = new ReadableStream({ async start(controller) { - controller.enqueue(util.strToUint8Array('hello ')); - controller.enqueue(util.strToUint8Array('world')); + controller.enqueue(util.stringToUint8Array('hello ')); + controller.enqueue(util.stringToUint8Array('world')); controller.close(); } }); diff --git a/test/general/util.js b/test/general/util.js index a4aca65bc..2d73f4fca 100644 --- a/test/general/util.js +++ b/test/general/util.js @@ -94,15 +94,15 @@ module.exports = () => describe('Util unit tests', function() { }); }); - describe('uint8ArrayToMpi', function() { + describe('uint8ArrayToMPI', function() { it('should strip leading zeros', function() { const bytes = new Uint8Array([0, 0, 1, 2]); - const mpi = util.uint8ArrayToMpi(bytes); + const mpi = util.uint8ArrayToMPI(bytes); expect(mpi).to.deep.equal(new Uint8Array([0, 9, 1, 2])); }); it('should throw on array of all zeros', function() { const bytes = new Uint8Array([0, 0]); - expect(() => util.uint8ArrayToMpi(bytes)).to.throw('Zero MPI'); + expect(() => util.uint8ArrayToMPI(bytes)).to.throw('Zero MPI'); }); }); diff --git a/test/general/x25519.js b/test/general/x25519.js index b90cf0e26..b3976aea3 100644 --- a/test/general/x25519.js +++ b/test/general/x25519.js @@ -220,7 +220,7 @@ module.exports = () => (openpgp.config.ci ? describe.skip : describe)('X25519 Cr const curve = new elliptic.Curve('ed25519'); const { publicKey } = nacl.sign.keyPair.fromSeed(util.hexToUint8Array(vector.SECRET_KEY)); expect(publicKey).to.deep.equal(util.hexToUint8Array(vector.PUBLIC_KEY)); - const data = util.strToUint8Array(vector.MESSAGE); + const data = util.stringToUint8Array(vector.MESSAGE); const privateParams = { seed: util.hexToUint8Array(vector.SECRET_KEY) }; @@ -257,7 +257,7 @@ module.exports = () => (openpgp.config.ci ? describe.skip : describe)('X25519 Cr return testVector({ SECRET_KEY: '4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb', PUBLIC_KEY: '3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c', - MESSAGE: util.hexToStr('72'), + MESSAGE: util.hexToString('72'), SIGNATURE: { R: '92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da', S: '085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00' @@ -269,7 +269,7 @@ module.exports = () => (openpgp.config.ci ? describe.skip : describe)('X25519 Cr return testVector({ SECRET_KEY: 'c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7', PUBLIC_KEY: 'fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025', - MESSAGE: util.hexToStr('af82'), + MESSAGE: util.hexToString('af82'), SIGNATURE: { R: '6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac', S: '18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a' @@ -281,7 +281,7 @@ module.exports = () => (openpgp.config.ci ? describe.skip : describe)('X25519 Cr return testVector({ SECRET_KEY: 'f5e5767cf153319517630f226876b86c8160cc583bc013744c6bf255f5cc0ee5', PUBLIC_KEY: '278117fc144c72340f67d0f2316e8386ceffbf2b2428c9c51fef7c597f1d426e', - MESSAGE: util.hexToStr([ + MESSAGE: util.hexToString([ '08b8b2b733424243760fe426a4b54908', '632110a66c2f6591eabd3345e3e4eb98', 'fa6e264bf09efe12ee50f8f54e9f77b1', @@ -358,7 +358,7 @@ module.exports = () => (openpgp.config.ci ? describe.skip : describe)('X25519 Cr return testVector({ SECRET_KEY: '833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42', PUBLIC_KEY: 'ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf', - MESSAGE: util.hexToStr([ + MESSAGE: util.hexToString([ 'ddaf35a193617abacc417349ae204131', '12e6fa4e89a97ea20a9eeee64b55d39a', '2192992a274fc1a836ba3c23a3feebbd', From 000ebcc635cf2cf9b2c264901443b8d8add85f04 Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Fri, 19 Mar 2021 00:23:24 +0100 Subject: [PATCH 07/18] Move cipher modes under crypto.mode --- src/crypto/index.js | 16 +++----------- src/crypto/{ => mode}/cfb.js | 6 ++--- src/crypto/{ => mode}/eax.js | 6 ++--- src/crypto/{ => mode}/gcm.js | 4 ++-- src/crypto/mode/index.js | 22 +++++++++++++++++++ src/crypto/{ => mode}/ocb.js | 6 ++--- src/packet/aead_encrypted_data.js | 6 ++--- src/packet/secret_key.js | 8 +++---- .../sym_encrypted_integrity_protected_data.js | 4 ++-- src/packet/sym_encrypted_session_key.js | 10 ++++----- src/packet/symmetrically_encrypted_data.js | 6 ++--- test/crypto/crypto.js | 4 ++-- test/crypto/eax.js | 2 +- test/crypto/gcm.js | 6 ++--- test/crypto/ocb.js | 2 +- 15 files changed, 60 insertions(+), 48 deletions(-) rename src/crypto/{ => mode}/cfb.js (98%) rename src/crypto/{ => mode}/eax.js (98%) rename src/crypto/{ => mode}/gcm.js (98%) create mode 100644 src/crypto/mode/index.js rename src/crypto/{ => mode}/ocb.js (98%) diff --git a/src/crypto/index.js b/src/crypto/index.js index 767a9e12d..ab6b166af 100644 --- a/src/crypto/index.js +++ b/src/crypto/index.js @@ -12,10 +12,7 @@ import * as cipher from './cipher'; import hash from './hash'; -import * as cfb from './cfb'; -import gcm from './gcm'; -import eax from './eax'; -import ocb from './ocb'; +import mode from './mode'; import publicKey from './public_key'; import * as signature from './signature'; import * as random from './random'; @@ -30,15 +27,8 @@ const mod = { cipher: cipher, /** @see module:crypto/hash */ hash: hash, - /** @see module:crypto/cfb */ - cfb: cfb, - /** @see module:crypto/gcm */ - gcm: gcm, - experimentalGCM: gcm, - /** @see module:crypto/eax */ - eax: eax, - /** @see module:crypto/ocb */ - ocb: ocb, + /** @see module:crypto/mode */ + mode: mode, /** @see module:crypto/public_key */ publicKey: publicKey, /** @see module:crypto/signature */ diff --git a/src/crypto/cfb.js b/src/crypto/mode/cfb.js similarity index 98% rename from src/crypto/cfb.js rename to src/crypto/mode/cfb.js index e5ae39e72..67b322779 100644 --- a/src/crypto/cfb.js +++ b/src/crypto/mode/cfb.js @@ -18,15 +18,15 @@ */ /** - * @module crypto/cfb + * @module crypto/mode/cfb * @private */ import { AES_CFB } from '@openpgp/asmcrypto.js/dist_es8/aes/cfb'; import stream from '@openpgp/web-stream-tools'; -import * as cipher from './cipher'; -import util from '../util'; +import * as cipher from '../cipher'; +import util from '../../util'; const webCrypto = util.getWebCrypto(); const nodeCrypto = util.getNodeCrypto(); diff --git a/src/crypto/eax.js b/src/crypto/mode/eax.js similarity index 98% rename from src/crypto/eax.js rename to src/crypto/mode/eax.js index 0be81cd39..c07c27b27 100644 --- a/src/crypto/eax.js +++ b/src/crypto/mode/eax.js @@ -18,13 +18,13 @@ /** * @fileoverview This module implements AES-EAX en/decryption on top of * native AES-CTR using either the WebCrypto API or Node.js' crypto API. - * @module crypto/eax + * @module crypto/mode/eax * @private */ import { AES_CTR } from '@openpgp/asmcrypto.js/dist_es8/aes/ctr'; -import CMAC from './cmac'; -import util from '../util'; +import CMAC from '../cmac'; +import util from '../../util'; const webCrypto = util.getWebCrypto(); const nodeCrypto = util.getNodeCrypto(); diff --git a/src/crypto/gcm.js b/src/crypto/mode/gcm.js similarity index 98% rename from src/crypto/gcm.js rename to src/crypto/mode/gcm.js index c8baa239d..576c4908e 100644 --- a/src/crypto/gcm.js +++ b/src/crypto/mode/gcm.js @@ -18,12 +18,12 @@ /** * @fileoverview This module wraps native AES-GCM en/decryption for both * the WebCrypto api as well as node.js' crypto api. - * @module crypto/gcm + * @module crypto/mode/gcm * @private */ import { AES_GCM } from '@openpgp/asmcrypto.js/dist_es8/aes/gcm'; -import util from '../util'; +import util from '../../util'; const webCrypto = util.getWebCrypto(); // no GCM support in IE11, Safari 9 const nodeCrypto = util.getNodeCrypto(); diff --git a/src/crypto/mode/index.js b/src/crypto/mode/index.js new file mode 100644 index 000000000..c1ae364fa --- /dev/null +++ b/src/crypto/mode/index.js @@ -0,0 +1,22 @@ +/** + * @fileoverview Cipher modes + * @module crypto/mode + * @private + */ + +import * as cfb from './cfb'; +import eax from './eax'; +import ocb from './ocb'; +import gcm from './gcm'; + +export default { + /** @see module:crypto/mode/cfb */ + cfb: cfb, + /** @see module:crypto/mode/gcm */ + gcm: gcm, + experimentalGCM: gcm, + /** @see module:crypto/mode/eax */ + eax: eax, + /** @see module:crypto/mode/ocb */ + ocb: ocb +}; diff --git a/src/crypto/ocb.js b/src/crypto/mode/ocb.js similarity index 98% rename from src/crypto/ocb.js rename to src/crypto/mode/ocb.js index 302cf4470..a3cca0d30 100644 --- a/src/crypto/ocb.js +++ b/src/crypto/mode/ocb.js @@ -17,12 +17,12 @@ /** * @fileoverview This module implements AES-OCB en/decryption. - * @module crypto/ocb + * @module crypto/mode/ocb * @private */ -import * as ciphers from './cipher'; -import util from '../util'; +import * as ciphers from '../cipher'; +import util from '../../util'; const blockLength = 16; diff --git a/src/packet/aead_encrypted_data.js b/src/packet/aead_encrypted_data.js index 94ffc776c..f717f9f86 100644 --- a/src/packet/aead_encrypted_data.js +++ b/src/packet/aead_encrypted_data.js @@ -61,7 +61,7 @@ class AEADEncryptedDataPacket { this.cipherAlgo = await reader.readByte(); this.aeadAlgo = await reader.readByte(); this.chunkSizeByte = await reader.readByte(); - const mode = crypto[enums.read(enums.aead, this.aeadAlgo)]; + const mode = crypto.mode[enums.read(enums.aead, this.aeadAlgo)]; this.iv = await reader.readBytes(mode.ivLength); this.encrypted = reader.remainder(); }); @@ -104,7 +104,7 @@ class AEADEncryptedDataPacket { async encrypt(sessionKeyAlgorithm, key, streaming, config = defaultConfig) { this.cipherAlgo = enums.write(enums.symmetric, sessionKeyAlgorithm); this.aeadAlgo = enums.write(enums.aead, this.aeadAlgorithm); - const mode = crypto[enums.read(enums.aead, this.aeadAlgo)]; + const mode = crypto.mode[enums.read(enums.aead, this.aeadAlgo)]; this.iv = await crypto.random.getRandomBytes(mode.ivLength); // generate new random IV this.chunkSizeByte = config.aeadChunkSizeByte; const data = this.packets.write(); @@ -122,7 +122,7 @@ class AEADEncryptedDataPacket { */ async crypt(fn, key, data, streaming) { const cipher = enums.read(enums.symmetric, this.cipherAlgo); - const mode = crypto[enums.read(enums.aead, this.aeadAlgo)]; + const mode = crypto.mode[enums.read(enums.aead, this.aeadAlgo)]; const modeInstance = await mode(cipher, key); const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0; const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0; diff --git a/src/packet/secret_key.js b/src/packet/secret_key.js index d032ccf17..1fd46558f 100644 --- a/src/packet/secret_key.js +++ b/src/packet/secret_key.js @@ -299,12 +299,12 @@ class SecretKeyPacket extends PublicKeyPacket { if (config.aeadProtect) { this.s2k_usage = 253; this.aead = 'eax'; - const mode = crypto[this.aead]; + const mode = crypto.mode[this.aead]; const modeInstance = await mode(this.symmetric, key); this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array()); } else { this.s2k_usage = 254; - this.keyMaterial = await crypto.cfb.encrypt(this.symmetric, key, util.concatUint8Array([ + this.keyMaterial = await crypto.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([ cleartext, await crypto.hash.sha1(cleartext, config) ]), this.iv, config); @@ -339,7 +339,7 @@ class SecretKeyPacket extends PublicKeyPacket { let cleartext; if (this.s2k_usage === 253) { - const mode = crypto[this.aead]; + const mode = crypto.mode[this.aead]; try { const modeInstance = await mode(this.symmetric, key); cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), new Uint8Array()); @@ -350,7 +350,7 @@ class SecretKeyPacket extends PublicKeyPacket { throw err; } } else { - const cleartextWithHash = await crypto.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv); + const cleartextWithHash = await crypto.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv); cleartext = cleartextWithHash.subarray(0, -20); const hash = await crypto.hash.sha1(cleartext); diff --git a/src/packet/sym_encrypted_integrity_protected_data.js b/src/packet/sym_encrypted_integrity_protected_data.js index 6c6250fce..9a7fdab4c 100644 --- a/src/packet/sym_encrypted_integrity_protected_data.js +++ b/src/packet/sym_encrypted_integrity_protected_data.js @@ -93,7 +93,7 @@ class SymEncryptedIntegrityProtectedDataPacket { const hash = await crypto.hash.sha1(stream.passiveClone(tohash)); const plaintext = util.concat([tohash, hash]); - this.encrypted = await crypto.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(crypto.cipher[sessionKeyAlgorithm].blockSize), config); + this.encrypted = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(crypto.cipher[sessionKeyAlgorithm].blockSize), config); return true; } @@ -109,7 +109,7 @@ class SymEncryptedIntegrityProtectedDataPacket { async decrypt(sessionKeyAlgorithm, key, streaming, config = defaultConfig) { 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)); + const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(crypto.cipher[sessionKeyAlgorithm].blockSize)); // there must be a modification detection code packet as the // last packet and everything gets hashed except the hash itself diff --git a/src/packet/sym_encrypted_session_key.js b/src/packet/sym_encrypted_session_key.js index d28f24aa9..c5183219f 100644 --- a/src/packet/sym_encrypted_session_key.js +++ b/src/packet/sym_encrypted_session_key.js @@ -74,7 +74,7 @@ class SymEncryptedSessionKeyPacket { offset += this.s2k.read(bytes.subarray(offset, bytes.length)); if (this.version === 5) { - const mode = crypto[this.aeadAlgorithm]; + const mode = crypto.mode[this.aeadAlgorithm]; // A starting initialization vector of size specified by the AEAD // algorithm. @@ -131,12 +131,12 @@ class SymEncryptedSessionKeyPacket { const key = await this.s2k.produceKey(passphrase, length); if (this.version === 5) { - const mode = crypto[this.aeadAlgorithm]; + const mode = crypto.mode[this.aeadAlgorithm]; const adata = new Uint8Array([0xC0 | this.tag, this.version, enums.write(enums.symmetric, this.sessionKeyEncryptionAlgorithm), enums.write(enums.aead, this.aeadAlgorithm)]); const modeInstance = await mode(algo, key); this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata); } else if (this.encrypted !== null) { - const decrypted = await crypto.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(crypto.cipher[algo].blockSize)); + const decrypted = await crypto.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(crypto.cipher[algo].blockSize)); this.sessionKeyAlgorithm = enums.read(enums.symmetric, decrypted[0]); this.sessionKey = decrypted.subarray(1, decrypted.length); @@ -170,7 +170,7 @@ class SymEncryptedSessionKeyPacket { } if (this.version === 5) { - const mode = crypto[this.aeadAlgorithm]; + const mode = crypto.mode[this.aeadAlgorithm]; this.iv = await crypto.random.getRandomBytes(mode.ivLength); // generate new random IV const adata = new Uint8Array([0xC0 | this.tag, this.version, enums.write(enums.symmetric, this.sessionKeyEncryptionAlgorithm), enums.write(enums.aead, this.aeadAlgorithm)]); const modeInstance = await mode(algo, key); @@ -178,7 +178,7 @@ class SymEncryptedSessionKeyPacket { } else { const algo_enum = new Uint8Array([enums.write(enums.symmetric, this.sessionKeyAlgorithm)]); const private_key = util.concatUint8Array([algo_enum, this.sessionKey]); - this.encrypted = await crypto.cfb.encrypt(algo, key, private_key, new Uint8Array(crypto.cipher[algo].blockSize), config); + this.encrypted = await crypto.mode.cfb.encrypt(algo, key, private_key, new Uint8Array(crypto.cipher[algo].blockSize), config); } } } diff --git a/src/packet/symmetrically_encrypted_data.js b/src/packet/symmetrically_encrypted_data.js index 5ffb2997e..08040f97c 100644 --- a/src/packet/symmetrically_encrypted_data.js +++ b/src/packet/symmetrically_encrypted_data.js @@ -80,7 +80,7 @@ class SymmetricallyEncryptedDataPacket { } const encrypted = await stream.readToEnd(stream.clone(this.encrypted)); - const decrypted = await crypto.cfb.decrypt(sessionKeyAlgorithm, key, + const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted.subarray(crypto.cipher[sessionKeyAlgorithm].blockSize + 2), encrypted.subarray(2, crypto.cipher[sessionKeyAlgorithm].blockSize + 2) ); @@ -106,8 +106,8 @@ class SymmetricallyEncryptedDataPacket { const data = this.packets.write(); const prefix = await crypto.getPrefixRandom(algo); - const FRE = await crypto.cfb.encrypt(algo, key, prefix, new Uint8Array(crypto.cipher[algo].blockSize), config); - const ciphertext = await crypto.cfb.encrypt(algo, key, data, FRE.subarray(2), config); + const FRE = await crypto.mode.cfb.encrypt(algo, key, prefix, new Uint8Array(crypto.cipher[algo].blockSize), config); + const ciphertext = await crypto.mode.cfb.encrypt(algo, key, data, FRE.subarray(2), config); this.encrypted = util.concat([FRE, ciphertext]); } } diff --git a/test/crypto/crypto.js b/test/crypto/crypto.js index 71518ad37..a9190dee2 100644 --- a/test/crypto/crypto.js +++ b/test/crypto/crypto.js @@ -242,8 +242,8 @@ module.exports = () => describe('API functional testing', function() { await Promise.all(symmAlgos.map(async function(algo) { const symmKey = await crypto.generateSessionKey(algo); const IV = new Uint8Array(crypto.cipher[algo].blockSize); - const symmencData = await crypto.cfb.encrypt(algo, symmKey, util.stringToUint8Array(plaintext), IV, openpgp.config); - const text = util.uint8ArrayToString(await crypto.cfb.decrypt(algo, symmKey, symmencData, new Uint8Array(crypto.cipher[algo].blockSize))); + const symmencData = await crypto.mode.cfb.encrypt(algo, symmKey, util.stringToUint8Array(plaintext), IV, openpgp.config); + const text = util.uint8ArrayToString(await crypto.mode.cfb.decrypt(algo, symmKey, symmencData, new Uint8Array(crypto.cipher[algo].blockSize))); expect(text).to.equal(plaintext); })); } diff --git a/test/crypto/eax.js b/test/crypto/eax.js index 809eb4185..be9934b37 100644 --- a/test/crypto/eax.js +++ b/test/crypto/eax.js @@ -2,7 +2,7 @@ // Adapted from https://github.com/artjomb/cryptojs-extension/blob/8c61d159/test/eax.js -const EAX = require('../../src/crypto/eax'); +const EAX = require('../../src/crypto/mode/eax'); const util = require('../../src/util'); const sandbox = require('sinon/lib/sinon/sandbox'); diff --git a/test/crypto/gcm.js b/test/crypto/gcm.js index 53baa9c8a..474a52297 100644 --- a/test/crypto/gcm.js +++ b/test/crypto/gcm.js @@ -45,18 +45,18 @@ module.exports = () => describe('Symmetric AES-GCM (experimental)', function() { this.skip(); // eslint-disable-line no-invalid-this } const key = await crypto.generateSessionKey(algo); - const iv = await crypto.random.getRandomBytes(crypto.gcm.ivLength); + const iv = await crypto.random.getRandomBytes(crypto.mode.gcm.ivLength); const nativeEncryptSpy = webCrypto ? sinonSandbox.spy(webCrypto, 'encrypt') : sinonSandbox.spy(nodeCrypto, 'createCipheriv'); const nativeDecryptSpy = webCrypto ? sinonSandbox.spy(webCrypto, 'decrypt') : sinonSandbox.spy(nodeCrypto, 'createDecipheriv'); nativeEncrypt || disableNative(); - let modeInstance = await crypto.gcm(algo, key); + let modeInstance = await crypto.mode.gcm(algo, key); const ciphertext = await modeInstance.encrypt(util.stringToUint8Array(plaintext), iv); enableNative(); nativeDecrypt || disableNative(); - modeInstance = await crypto.gcm(algo, key); + modeInstance = await crypto.mode.gcm(algo, key); const decrypted = await modeInstance.decrypt(util.stringToUint8Array(util.uint8ArrayToString(ciphertext)), iv); enableNative(); diff --git a/test/crypto/ocb.js b/test/crypto/ocb.js index e2c7f89ff..588a888d7 100644 --- a/test/crypto/ocb.js +++ b/test/crypto/ocb.js @@ -2,7 +2,7 @@ // Adapted from https://github.com/artjomb/cryptojs-extension/blob/8c61d159/test/eax.js -const OCB = require('../../src/crypto/ocb'); +const OCB = require('../../src/crypto/mode/ocb'); const util = require('../../src/util'); const chai = require('chai'); From fbd51d75f9f45cc6cbd719f9629ff262f8d105a5 Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Fri, 19 Mar 2021 00:25:56 +0100 Subject: [PATCH 08/18] Uniform s2k-related naming --- src/packet/secret_key.js | 50 ++++++++++++------------- src/packet/sym_encrypted_session_key.js | 6 +-- test/general/packet.js | 4 +- 3 files changed, 30 insertions(+), 30 deletions(-) diff --git a/src/packet/secret_key.js b/src/packet/secret_key.js index 1fd46558f..6098d6fe4 100644 --- a/src/packet/secret_key.js +++ b/src/packet/secret_key.js @@ -16,7 +16,7 @@ // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA import PublicKeyPacket from './public_key'; -import type_s2k from '../type/s2k'; +import S2K from '../type/s2k'; import crypto from '../crypto'; import enums from '../enums'; import util from '../util'; @@ -52,7 +52,7 @@ class SecretKeyPacket extends PublicKeyPacket { * S2K usage * @type {Integer} */ - this.s2k_usage = 0; + this.s2kUsage = 0; /** * S2K object * @type {type/s2k} @@ -90,7 +90,7 @@ class SecretKeyPacket extends PublicKeyPacket { // indicates that the secret-key data is not encrypted. 255 or 254 // indicates that a string-to-key specifier is being given. Any // other value is a symmetric-key encryption algorithm identifier. - this.s2k_usage = bytes[i++]; + this.s2kUsage = bytes[i++]; // - Only for a version 5 packet, a one-octet scalar octet count of // the next 4 optional fields. @@ -100,13 +100,13 @@ class SecretKeyPacket extends PublicKeyPacket { // - [Optional] If string-to-key usage octet was 255, 254, or 253, a // one-octet symmetric encryption algorithm. - if (this.s2k_usage === 255 || this.s2k_usage === 254 || this.s2k_usage === 253) { + if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { this.symmetric = bytes[i++]; this.symmetric = enums.read(enums.symmetric, this.symmetric); // - [Optional] If string-to-key usage octet was 253, a one-octet // AEAD algorithm. - if (this.s2k_usage === 253) { + if (this.s2kUsage === 253) { this.aead = bytes[i++]; this.aead = enums.read(enums.aead, this.aead); } @@ -114,21 +114,21 @@ class SecretKeyPacket extends PublicKeyPacket { // - [Optional] If string-to-key usage octet was 255, 254, or 253, a // string-to-key specifier. The length of the string-to-key // specifier is implied by its type, as described above. - this.s2k = new type_s2k(); + this.s2k = new S2K(); i += this.s2k.read(bytes.subarray(i, bytes.length)); if (this.s2k.type === 'gnu-dummy') { return; } - } else if (this.s2k_usage) { - this.symmetric = this.s2k_usage; + } else if (this.s2kUsage) { + this.symmetric = this.s2kUsage; this.symmetric = enums.read(enums.symmetric, this.symmetric); } // - [Optional] If secret data is encrypted (string-to-key usage octet // not zero), an Initial Vector (IV) of the same length as the // cipher's block size. - if (this.s2k_usage) { + if (this.s2kUsage) { this.iv = bytes.subarray( i, i + crypto.cipher[this.symmetric].blockSize @@ -147,7 +147,7 @@ class SecretKeyPacket extends PublicKeyPacket { // key data. These algorithm-specific fields are as described // below. this.keyMaterial = bytes.subarray(i); - this.isEncrypted = !!this.s2k_usage; + this.isEncrypted = !!this.s2kUsage; if (!this.isEncrypted) { const cleartext = this.keyMaterial.subarray(0, -2); @@ -171,17 +171,17 @@ class SecretKeyPacket extends PublicKeyPacket { write() { const arr = [this.writePublicKey()]; - arr.push(new Uint8Array([this.s2k_usage])); + arr.push(new Uint8Array([this.s2kUsage])); const optionalFieldsArr = []; // - [Optional] If string-to-key usage octet was 255, 254, or 253, a // one- octet symmetric encryption algorithm. - if (this.s2k_usage === 255 || this.s2k_usage === 254 || this.s2k_usage === 253) { + if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { optionalFieldsArr.push(enums.write(enums.symmetric, this.symmetric)); // - [Optional] If string-to-key usage octet was 253, a one-octet // AEAD algorithm. - if (this.s2k_usage === 253) { + if (this.s2kUsage === 253) { optionalFieldsArr.push(enums.write(enums.aead, this.aead)); } @@ -194,7 +194,7 @@ class SecretKeyPacket extends PublicKeyPacket { // - [Optional] If secret data is encrypted (string-to-key usage octet // not zero), an Initial Vector (IV) of the same length as the // cipher's block size. - if (this.s2k_usage && this.s2k.type !== 'gnu-dummy') { + if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') { optionalFieldsArr.push(...this.iv); } @@ -204,7 +204,7 @@ class SecretKeyPacket extends PublicKeyPacket { arr.push(new Uint8Array(optionalFieldsArr)); if (!this.isDummy()) { - if (!this.s2k_usage) { + if (!this.s2kUsage) { const algo = enums.write(enums.publicKey, this.algorithm); const cleartextParams = crypto.serializeParams(algo, this.privateParams); this.keyMaterial = util.concatUint8Array([ @@ -253,11 +253,11 @@ class SecretKeyPacket extends PublicKeyPacket { } this.isEncrypted = null; this.keyMaterial = null; - this.s2k = new type_s2k(config); + this.s2k = new S2K(config); this.s2k.algorithm = 0; this.s2k.c = 0; this.s2k.type = 'gnu-dummy'; - this.s2k_usage = 254; + this.s2kUsage = 254; this.symmetric = 'aes256'; } @@ -281,13 +281,13 @@ class SecretKeyPacket extends PublicKeyPacket { } if (this.isDecrypted() && !passphrase) { - this.s2k_usage = 0; + this.s2kUsage = 0; return; } else if (!passphrase) { throw new Error('The key must be decrypted before removing passphrase protection.'); } - this.s2k = new type_s2k(config); + this.s2k = new S2K(config); this.s2k.salt = await crypto.random.getRandomBytes(8); const algo = enums.write(enums.publicKey, this.algorithm); const cleartext = crypto.serializeParams(algo, this.privateParams); @@ -297,13 +297,13 @@ class SecretKeyPacket extends PublicKeyPacket { this.iv = await crypto.random.getRandomBytes(blockLen); if (config.aeadProtect) { - this.s2k_usage = 253; + this.s2kUsage = 253; this.aead = 'eax'; const mode = crypto.mode[this.aead]; const modeInstance = await mode(this.symmetric, key); this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array()); } else { - this.s2k_usage = 254; + this.s2kUsage = 254; this.keyMaterial = await crypto.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([ cleartext, await crypto.hash.sha1(cleartext, config) @@ -329,16 +329,16 @@ class SecretKeyPacket extends PublicKeyPacket { } let key; - if (this.s2k_usage === 254 || this.s2k_usage === 253) { + if (this.s2kUsage === 254 || this.s2kUsage === 253) { key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric); - } else if (this.s2k_usage === 255) { + } else if (this.s2kUsage === 255) { throw new Error('Encrypted private key is authenticated using an insecure two-byte hash'); } else { throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5'); } let cleartext; - if (this.s2k_usage === 253) { + if (this.s2kUsage === 253) { const mode = crypto.mode[this.aead]; try { const modeInstance = await mode(this.symmetric, key); @@ -369,7 +369,7 @@ class SecretKeyPacket extends PublicKeyPacket { } this.isEncrypted = false; this.keyMaterial = null; - this.s2k_usage = 0; + this.s2kUsage = 0; } /** diff --git a/src/packet/sym_encrypted_session_key.js b/src/packet/sym_encrypted_session_key.js index c5183219f..012c8e367 100644 --- a/src/packet/sym_encrypted_session_key.js +++ b/src/packet/sym_encrypted_session_key.js @@ -15,7 +15,7 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -import type_s2k from '../type/s2k'; +import S2K from '../type/s2k'; import defaultConfig from '../config'; import crypto from '../crypto'; import enums from '../enums'; @@ -70,7 +70,7 @@ class SymEncryptedSessionKeyPacket { } // A string-to-key (S2K) specifier, length as defined above. - this.s2k = new type_s2k(); + this.s2k = new S2K(); offset += this.s2k.read(bytes.subarray(offset, bytes.length)); if (this.version === 5) { @@ -159,7 +159,7 @@ class SymEncryptedSessionKeyPacket { this.sessionKeyEncryptionAlgorithm = algo; - this.s2k = new type_s2k(config); + this.s2k = new S2K(config); this.s2k.salt = await crypto.random.getRandomBytes(8); const length = crypto.cipher[algo].keySize; diff --git a/test/general/packet.js b/test/general/packet.js index c9f30da07..43a61359a 100644 --- a/test/general/packet.js +++ b/test/general/packet.js @@ -844,7 +844,7 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ secretKeyPacket.algorithm = "rsaSign"; secretKeyPacket.isEncrypted = false; await secretKeyPacket.encrypt('hello', { ...openpgp.config, aeadProtect: true }); - expect(secretKeyPacket.s2k_usage).to.equal(253); + expect(secretKeyPacket.s2kUsage).to.equal(253); const raw = new openpgp.PacketList(); raw.push(secretKeyPacket); @@ -866,7 +866,7 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ secretKeyPacket.algorithm = "rsaSign"; secretKeyPacket.isEncrypted = false; await secretKeyPacket.encrypt('hello', { ...openpgp.config, aeadProtect: false }); - expect(secretKeyPacket.s2k_usage).to.equal(254); + expect(secretKeyPacket.s2kUsage).to.equal(254); const raw = new openpgp.PacketList(); raw.push(secretKeyPacket); From dbe43d55d7034f55bd102f65c7479b548f0e743c Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Fri, 19 Mar 2021 00:34:31 +0100 Subject: [PATCH 09/18] Remove underscores --- src/key/helper.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/key/helper.js b/src/key/helper.js index 2ee2c81cd..0470c563c 100644 --- a/src/key/helper.js +++ b/src/key/helper.js @@ -133,13 +133,13 @@ export async function createBindingSignature(subkey, primaryKey, options, config */ export async function getPreferredHashAlgo(key, keyPacket, date = new Date(), userID = {}, config) { let hashAlgo = config.preferredHashAlgorithm; - let pref_algo = hashAlgo; + let prefAlgo = hashAlgo; if (key) { const primaryUser = await key.getPrimaryUser(date, userID, config); if (primaryUser.selfCertification.preferredHashAlgorithms) { - [pref_algo] = primaryUser.selfCertification.preferredHashAlgorithms; - hashAlgo = crypto.hash.getHashByteLength(hashAlgo) <= crypto.hash.getHashByteLength(pref_algo) ? - pref_algo : hashAlgo; + [prefAlgo] = primaryUser.selfCertification.preferredHashAlgorithms; + hashAlgo = crypto.hash.getHashByteLength(hashAlgo) <= crypto.hash.getHashByteLength(prefAlgo) ? + prefAlgo : hashAlgo; } } switch (Object.getPrototypeOf(keyPacket)) { @@ -151,11 +151,11 @@ export async function getPreferredHashAlgo(key, keyPacket, date = new Date(), us case 'ecdh': case 'ecdsa': case 'eddsa': - pref_algo = crypto.publicKey.elliptic.getPreferredHashAlgo(keyPacket.publicParams.oid); + prefAlgo = crypto.publicKey.elliptic.getPreferredHashAlgo(keyPacket.publicParams.oid); } } - return crypto.hash.getHashByteLength(hashAlgo) <= crypto.hash.getHashByteLength(pref_algo) ? - pref_algo : hashAlgo; + return crypto.hash.getHashByteLength(hashAlgo) <= crypto.hash.getHashByteLength(prefAlgo) ? + prefAlgo : hashAlgo; } /** From 68a61405ba3188da147023e01257edde187219c6 Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Fri, 19 Mar 2021 12:42:01 +0100 Subject: [PATCH 10/18] Make packet tag static --- src/cleartext.js | 2 +- src/key/key.js | 8 ++-- src/key/subkey.js | 4 +- src/key/user.js | 4 +- src/packet/aead_encrypted_data.js | 5 ++- src/packet/all_packets.js | 24 ---------- src/packet/compressed_data.js | 7 +-- src/packet/literal_data.js | 3 +- src/packet/marker.js | 4 +- src/packet/one_pass_signature.js | 9 ++-- src/packet/packetlist.js | 45 ++++++++++++++----- src/packet/public_key.js | 7 +-- .../public_key_encrypted_session_key.js | 3 +- src/packet/public_subkey.js | 4 +- src/packet/secret_key.js | 7 +-- src/packet/secret_subkey.js | 3 +- src/packet/signature.js | 3 +- .../sym_encrypted_integrity_protected_data.js | 3 +- src/packet/sym_encrypted_session_key.js | 7 +-- src/packet/symmetrically_encrypted_data.js | 7 +-- src/packet/trust.js | 4 +- src/packet/user_attribute.js | 3 +- src/packet/userid.js | 3 +- test/general/config.js | 8 ++-- 24 files changed, 83 insertions(+), 94 deletions(-) diff --git a/src/cleartext.js b/src/cleartext.js index 93002add5..f6b3dfc02 100644 --- a/src/cleartext.js +++ b/src/cleartext.js @@ -164,7 +164,7 @@ function verifyHeaders(headers, packetlist) { const check = packet => algo => packet.hashAlgorithm === algo; for (let i = 0; i < packetlist.length; i++) { - if (packetlist[i].tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) { + if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) { return false; } } diff --git a/src/key/key.js b/src/key/key.js index 159df8ae8..91cd83d76 100644 --- a/src/key/key.js +++ b/src/key/key.js @@ -71,7 +71,7 @@ class Key { let primaryKeyID; let subKey; for (let i = 0; i < packetlist.length; i++) { - switch (packetlist[i].tag) { + switch (packetlist[i].constructor.tag) { case enums.packet.publicKey: case enums.packet.secretKey: if (this.keyPacket) { @@ -216,7 +216,7 @@ class Key { * @returns {Boolean} */ isPublic() { - return this.keyPacket.tag === enums.packet.publicKey; + return this.keyPacket.constructor.tag === enums.packet.publicKey; } /** @@ -224,7 +224,7 @@ class Key { * @returns {Boolean} */ isPrivate() { - return this.keyPacket.tag === enums.packet.secretKey; + return this.keyPacket.constructor.tag === enums.packet.secretKey; } /** @@ -239,7 +239,7 @@ class Key { let pubKeyPacket; let pubSubkeyPacket; for (let i = 0; i < keyPackets.length; i++) { - switch (keyPackets[i].tag) { + switch (keyPackets[i].constructor.tag) { case enums.packet.secretKey: bytes = keyPackets[i].writePublicKey(); pubKeyPacket = new PublicKeyPacket(); diff --git a/src/key/subkey.js b/src/key/subkey.js index 655889af4..10fd62b4d 100644 --- a/src/key/subkey.js +++ b/src/key/subkey.js @@ -125,8 +125,8 @@ class SubKey { throw new Error('SubKey update method: fingerprints of subkeys not equal'); } // key packet - if (this.keyPacket.tag === enums.packet.publicSubkey && - subKey.keyPacket.tag === enums.packet.secretSubkey) { + if (this.keyPacket.constructor.tag === enums.packet.publicSubkey && + subKey.keyPacket.constructor.tag === enums.packet.secretSubkey) { this.keyPacket = subKey.keyPacket; } // update missing binding signatures diff --git a/src/key/user.js b/src/key/user.js index 91aa25bb3..544e80c6b 100644 --- a/src/key/user.js +++ b/src/key/user.js @@ -16,8 +16,8 @@ class User { if (!(this instanceof User)) { return new User(userPacket); } - this.userID = userPacket.tag === enums.packet.userID ? userPacket : null; - this.userAttribute = userPacket.tag === enums.packet.userAttribute ? userPacket : null; + this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null; + this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null; this.selfCertifications = []; this.otherCertifications = []; this.revocationSignatures = []; diff --git a/src/packet/aead_encrypted_data.js b/src/packet/aead_encrypted_data.js index f717f9f86..b1b0eb00f 100644 --- a/src/packet/aead_encrypted_data.js +++ b/src/packet/aead_encrypted_data.js @@ -37,8 +37,9 @@ const VERSION = 1; // A one-octet version number of the data packet. * AEAD Protected Data Packet */ class AEADEncryptedDataPacket { + static tag = enums.packet.AEADEncryptedData; + constructor() { - this.tag = enums.packet.AEADEncryptedData; this.version = VERSION; this.cipherAlgo = null; this.aeadAlgorithm = 'eax'; @@ -132,7 +133,7 @@ class AEADEncryptedDataPacket { const adataTagArray = new Uint8Array(adataBuffer); const adataView = new DataView(adataBuffer); const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8); - adataArray.set([0xC0 | this.tag, this.version, this.cipherAlgo, this.aeadAlgo, this.chunkSizeByte], 0); + adataArray.set([0xC0 | this.constructor.tag, this.version, this.cipherAlgo, this.aeadAlgo, this.chunkSizeByte], 0); let chunkIndex = 0; let latestPromise = Promise.resolve(); let cryptedBytes = 0; diff --git a/src/packet/all_packets.js b/src/packet/all_packets.js index 6ec3347d7..5a9420abd 100644 --- a/src/packet/all_packets.js +++ b/src/packet/all_packets.js @@ -21,27 +21,3 @@ export { default as UserIDPacket } from './userid.js'; export { default as SecretSubkeyPacket } from './secret_subkey.js'; export { default as SignaturePacket } from './signature.js'; export { default as TrustPacket } from './trust.js'; - -/** - * Allocate a new packet - * @function newPacketFromTag - * @param {String} tag - Property name from {@link module:enums.packet} - * @returns {Object} New packet object with type based on 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](); -} - -/** - * Convert tag name to class name - * @param {String} tag - Property name from {@link module:enums.packet} - * @returns {String} - * @private - */ -function packetClassFromTagName(tag) { - return tag.substr(0, 1).toUpperCase() + tag.substr(1) + 'Packet'; -} diff --git a/src/packet/compressed_data.js b/src/packet/compressed_data.js index afd2e901e..257149fba 100644 --- a/src/packet/compressed_data.js +++ b/src/packet/compressed_data.js @@ -38,15 +38,12 @@ import { * a Signature or One-Pass Signature packet, and contains a literal data packet. */ class CompressedDataPacket { + static tag = enums.packet.compressedData; + /** * @param {Object} [config] - Full configuration, defaults to openpgp.config */ constructor(config = defaultConfig) { - /** - * Packet type - * @type {module:enums.packet} - */ - this.tag = enums.packet.compressedData; /** * List of packets * @type {PacketList} diff --git a/src/packet/literal_data.js b/src/packet/literal_data.js index 38c5ec1b7..d96fd62b1 100644 --- a/src/packet/literal_data.js +++ b/src/packet/literal_data.js @@ -27,11 +27,12 @@ import util from '../util'; * further interpreted. */ class LiteralDataPacket { + static tag = enums.packet.literalData; + /** * @param {Date} date - The creation date of the literal package */ constructor(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 diff --git a/src/packet/marker.js b/src/packet/marker.js index f6cfc52af..2150092ef 100644 --- a/src/packet/marker.js +++ b/src/packet/marker.js @@ -31,9 +31,7 @@ import enums from '../enums'; * Such a packet MUST be ignored when received. */ class MarkerPacket { - constructor() { - this.tag = enums.packet.marker; - } + static tag = enums.packet.marker; /** * Parsing function for a literal data packet (tag 10). diff --git a/src/packet/one_pass_signature.js b/src/packet/one_pass_signature.js index ac4c980e7..ab9a14196 100644 --- a/src/packet/one_pass_signature.js +++ b/src/packet/one_pass_signature.js @@ -32,12 +32,9 @@ import util from '../util'; * can compute the entire signed message in one pass. */ class OnePassSignaturePacket { + static tag = enums.packet.onePassSignature; + constructor() { - /** - * Packet type - * @type {module:enums.packet} - */ - this.tag = enums.packet.onePassSignature; /** A one-octet version number. The current version is 3. */ this.version = null; /** @@ -119,7 +116,7 @@ class OnePassSignaturePacket { async verify() { const correspondingSig = await this.correspondingSig; - if (!correspondingSig || correspondingSig.tag !== enums.packet.signature) { + if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) { throw new Error('Corresponding signature packet missing'); } if ( diff --git a/src/packet/packetlist.js b/src/packet/packetlist.js index 7081a63a0..00410a616 100644 --- a/src/packet/packetlist.js +++ b/src/packet/packetlist.js @@ -1,14 +1,36 @@ import stream from '@openpgp/web-stream-tools'; -import * as packets from './all_packets'; +import * as packetClasses from './all_packets'; import { readPackets, supportsStreaming, writeTag, writeHeader, writePartialLength, writeSimpleLength } from './packet'; -import enums from '../enums'; import util from '../util'; import defaultConfig from '../config'; +const mapPacketTagToClassName = (() => { + const map = {}; + for (const className of Object.keys(packetClasses)) { + const PacketClass = packetClasses[className]; + map[PacketClass.tag] = className; + } + return map; +})(); + +/** + * Allocate a new packet + * @function newPacketFromTag + * @param {module:enums.packet} tag - Property name from {@link module:enums.packet} + * @returns {Object} New packet object with type based on tag. + */ +export function newPacketFromTag(tag, allowedPackets) { + const className = mapPacketTagToClassName[tag]; + if (!allowedPackets[className]) { + throw new Error(`Packet not allowed in this context: ${className}`); + } + return new allowedPackets[className](); +} + /** * This class represents a list of openpgp packets. * Take care when iterating over it - the packets themselves @@ -28,8 +50,7 @@ class PacketList extends Array { await writer.ready; const done = await readPackets(readable, streaming, async parsed => { try { - const tag = enums.read(enums.packet, parsed.tag); - const packet = packets.newPacketFromTag(tag, allowedPackets); + const packet = newPacketFromTag(parsed.tag, allowedPackets); packet.packets = new PacketList(); packet.fromStream = util.isStream(parsed.packet); await packet.read(parsed.packet, config, streaming); @@ -64,7 +85,7 @@ class PacketList extends Array { } else { this.stream = null; } - if (done || supportsStreaming(value.tag)) { + if (done || supportsStreaming(value.constructor.tag)) { break; } } @@ -81,11 +102,11 @@ class PacketList extends Array { for (let i = 0; i < this.length; i++) { const packetbytes = this[i].write(); - if (util.isStream(packetbytes) && supportsStreaming(this[i].tag)) { + if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) { let buffer = []; let bufferLength = 0; const minLength = 512; - arr.push(writeTag(this[i].tag)); + arr.push(writeTag(this[i].constructor.tag)); arr.push(stream.transform(packetbytes, value => { buffer.push(value); bufferLength += value.length; @@ -103,9 +124,9 @@ class PacketList extends Array { let length = 0; arr.push(stream.transform(stream.clone(packetbytes), value => { length += value.length; - }, () => writeHeader(this[i].tag, length))); + }, () => writeHeader(this[i].constructor.tag, length))); } else { - arr.push(writeHeader(this[i].tag, packetbytes.length)); + arr.push(writeHeader(this[i].constructor.tag, packetbytes.length)); } arr.push(packetbytes); } @@ -138,7 +159,7 @@ class PacketList extends Array { const handle = tag => packetType => tag === packetType; for (let i = 0; i < this.length; i++) { - if (args.some(handle(this[i].tag))) { + if (args.some(handle(this[i].constructor.tag))) { filtered.push(this[i]); } } @@ -152,7 +173,7 @@ class PacketList extends Array { * @returns {Packet|undefined} */ findPacket(type) { - return this.find(packet => packet.tag === type); + return this.find(packet => packet.constructor.tag === type); } /** @@ -165,7 +186,7 @@ class PacketList extends Array { const handle = tag => packetType => tag === packetType; for (let i = 0; i < this.length; i++) { - if (args.some(handle(that[i].tag))) { + if (args.some(handle(that[i].constructor.tag))) { tagIndex.push(i); } } diff --git a/src/packet/public_key.js b/src/packet/public_key.js index 32d674827..780cd6cbb 100644 --- a/src/packet/public_key.js +++ b/src/packet/public_key.js @@ -37,16 +37,13 @@ import util from '../util'; * key (sometimes called an OpenPGP certificate). */ class PublicKeyPacket { + static tag = enums.packet.publicKey; + /** * @param {Date} [date] - Creation date * @param {Object} [config] - Full configuration, defaults to openpgp.config */ constructor(date = new Date(), config = defaultConfig) { - /** - * Packet type - * @type {module:enums.packet} - */ - this.tag = enums.packet.publicKey; /** * Packet version * @type {Integer} diff --git a/src/packet/public_key_encrypted_session_key.js b/src/packet/public_key_encrypted_session_key.js index ce758b1bd..061c3e123 100644 --- a/src/packet/public_key_encrypted_session_key.js +++ b/src/packet/public_key_encrypted_session_key.js @@ -37,8 +37,9 @@ import util from '../util'; * decrypt the message. */ class PublicKeyEncryptedSessionKeyPacket { + static tag = enums.packet.publicKeyEncryptedSessionKey; + constructor() { - this.tag = enums.packet.publicKeyEncryptedSessionKey; this.version = 3; this.publicKeyID = new KeyID(); diff --git a/src/packet/public_subkey.js b/src/packet/public_subkey.js index a808cc360..85b4bf442 100644 --- a/src/packet/public_subkey.js +++ b/src/packet/public_subkey.js @@ -27,13 +27,15 @@ import enums from '../enums'; * @extends PublicKeyPacket */ class PublicSubkeyPacket extends PublicKeyPacket { + static tag = enums.packet.publicSubkey; + /** * @param {Date} [date] - Creation date * @param {Object} [config] - Full configuration, defaults to openpgp.config */ + // eslint-disable-next-line no-useless-constructor constructor(date, config) { super(date, config); - this.tag = enums.packet.publicSubkey; } } diff --git a/src/packet/secret_key.js b/src/packet/secret_key.js index 6098d6fe4..619dbe1d0 100644 --- a/src/packet/secret_key.js +++ b/src/packet/secret_key.js @@ -29,17 +29,14 @@ import defaultConfig from '../config'; * @extends PublicKeyPacket */ class SecretKeyPacket extends PublicKeyPacket { + static tag = enums.packet.secretKey; + /** * @param {Date} [date] - Creation date * @param {Object} [config] - Full configuration, defaults to openpgp.config */ constructor(date = new Date(), config = defaultConfig) { super(date, config); - /** - * Packet type - * @type {module:enums.packet} - */ - this.tag = enums.packet.secretKey; /** * Secret-key data */ diff --git a/src/packet/secret_subkey.js b/src/packet/secret_subkey.js index 110b7692b..368f7554b 100644 --- a/src/packet/secret_subkey.js +++ b/src/packet/secret_subkey.js @@ -25,13 +25,14 @@ import defaultConfig from '../config'; * @extends SecretKeyPacket */ class SecretSubkeyPacket extends SecretKeyPacket { + static tag = enums.packet.secretSubkey; + /** * @param {Date} [date] - Creation date * @param {Object} [config] - Full configuration, defaults to openpgp.config */ constructor(date = new Date(), config = defaultConfig) { super(date, config); - this.tag = enums.packet.secretSubkey; } } diff --git a/src/packet/signature.js b/src/packet/signature.js index b32c17fe9..5895542c9 100644 --- a/src/packet/signature.js +++ b/src/packet/signature.js @@ -32,11 +32,12 @@ import defaultConfig from '../config'; * block of text, and a signature that is a certification of a User ID. */ class SignaturePacket { + static tag = enums.packet.signature; + /** * @param {Date} date - The creation date of the signature */ constructor(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; this.hashAlgorithm = null; diff --git a/src/packet/sym_encrypted_integrity_protected_data.js b/src/packet/sym_encrypted_integrity_protected_data.js index 9a7fdab4c..ff6a748ce 100644 --- a/src/packet/sym_encrypted_integrity_protected_data.js +++ b/src/packet/sym_encrypted_integrity_protected_data.js @@ -40,8 +40,9 @@ const VERSION = 1; // A one-octet version number of the data packet. * packet. */ class SymEncryptedIntegrityProtectedDataPacket { + static tag = enums.packet.symEncryptedIntegrityProtectedData; + constructor() { - this.tag = enums.packet.symEncryptedIntegrityProtectedData; this.version = VERSION; /** The encrypted payload. */ this.encrypted = null; // string diff --git a/src/packet/sym_encrypted_session_key.js b/src/packet/sym_encrypted_session_key.js index 012c8e367..0673c18f2 100644 --- a/src/packet/sym_encrypted_session_key.js +++ b/src/packet/sym_encrypted_session_key.js @@ -35,11 +35,12 @@ import util from '../util'; * the Symmetric-Key Encrypted Session Key packet. */ class SymEncryptedSessionKeyPacket { + static tag = enums.packet.symEncryptedSessionKey; + /** * @param {Object} [config] - Full configuration, defaults to openpgp.config */ constructor(config = defaultConfig) { - this.tag = enums.packet.symEncryptedSessionKey; this.version = config.aeadProtect ? 5 : 4; this.sessionKey = null; this.sessionKeyEncryptionAlgorithm = null; @@ -132,7 +133,7 @@ class SymEncryptedSessionKeyPacket { if (this.version === 5) { const mode = crypto.mode[this.aeadAlgorithm]; - const adata = new Uint8Array([0xC0 | this.tag, this.version, enums.write(enums.symmetric, this.sessionKeyEncryptionAlgorithm), enums.write(enums.aead, this.aeadAlgorithm)]); + const adata = new Uint8Array([0xC0 | this.constructor.tag, this.version, enums.write(enums.symmetric, this.sessionKeyEncryptionAlgorithm), enums.write(enums.aead, this.aeadAlgorithm)]); const modeInstance = await mode(algo, key); this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata); } else if (this.encrypted !== null) { @@ -172,7 +173,7 @@ class SymEncryptedSessionKeyPacket { if (this.version === 5) { const mode = crypto.mode[this.aeadAlgorithm]; this.iv = await crypto.random.getRandomBytes(mode.ivLength); // generate new random IV - const adata = new Uint8Array([0xC0 | this.tag, this.version, enums.write(enums.symmetric, this.sessionKeyEncryptionAlgorithm), enums.write(enums.aead, this.aeadAlgorithm)]); + const adata = new Uint8Array([0xC0 | this.constructor.tag, this.version, enums.write(enums.symmetric, this.sessionKeyEncryptionAlgorithm), enums.write(enums.aead, this.aeadAlgorithm)]); const modeInstance = await mode(algo, key); this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, adata); } else { diff --git a/src/packet/symmetrically_encrypted_data.js b/src/packet/symmetrically_encrypted_data.js index 08040f97c..31b44341c 100644 --- a/src/packet/symmetrically_encrypted_data.js +++ b/src/packet/symmetrically_encrypted_data.js @@ -38,12 +38,9 @@ import defaultConfig from '../config'; * that form whole OpenPGP messages). */ class SymmetricallyEncryptedDataPacket { + static tag = enums.packet.symmetricallyEncryptedData; + constructor() { - /** - * Packet type - * @type {module:enums.packet} - */ - this.tag = enums.packet.symmetricallyEncryptedData; /** * Encrypted secret-key data */ diff --git a/src/packet/trust.js b/src/packet/trust.js index b4d9475e2..66ea47fb1 100644 --- a/src/packet/trust.js +++ b/src/packet/trust.js @@ -18,9 +18,7 @@ import enums from '../enums'; * other than local keyring files. */ class TrustPacket { - constructor() { - this.tag = enums.packet.trust; - } + static tag = enums.packet.trust; /** * Parsing function for a trust packet (tag 12). diff --git a/src/packet/user_attribute.js b/src/packet/user_attribute.js index 9f1b9111b..88314b2c7 100644 --- a/src/packet/user_attribute.js +++ b/src/packet/user_attribute.js @@ -37,8 +37,9 @@ import util from '../util'; * an implementation may use any method desired. */ class UserAttributePacket { + static tag = enums.packet.userAttribute; + constructor() { - this.tag = enums.packet.userAttribute; this.attributes = []; } diff --git a/src/packet/userid.js b/src/packet/userid.js index 7b0facf9f..6e46470c6 100644 --- a/src/packet/userid.js +++ b/src/packet/userid.js @@ -31,8 +31,9 @@ import defaultConfig from '../config'; * specifies the length of the User ID. */ class UserIDPacket { + static tag = enums.packet.userID; + constructor() { - this.tag = enums.packet.userID; /** A string containing the user id. Usually in the form * John Doe * @type {String} diff --git a/test/general/config.js b/test/general/config.js index 462fffab9..efb6c1bf5 100644 --- a/test/general/config.js +++ b/test/general/config.js @@ -155,9 +155,9 @@ module.exports = () => describe('Custom configuration', function() { const encrypted = await openpgp.readMessage({ armoredMessage: armored }); const { packets: [skesk, encData] } = encrypted; expect(skesk.version).to.equal(4); // cfb - expect(encData.tag).to.equal(openpgp.enums.packet.symEncryptedIntegrityProtectedData); + expect(encData.constructor.tag).to.equal(openpgp.enums.packet.symEncryptedIntegrityProtectedData); const { packets: [literal] } = await encrypted.decrypt(null, passwords, null, encrypted.fromStream, openpgp.config); - expect(literal.tag).to.equal(openpgp.enums.packet.literalData); + expect(literal.constructor.tag).to.equal(openpgp.enums.packet.literalData); const config = { aeadProtect: true, @@ -168,9 +168,9 @@ module.exports = () => describe('Custom configuration', function() { const encrypted2 = await openpgp.readMessage({ armoredMessage: armored2 }); const { packets: [skesk2, encData2] } = encrypted2; expect(skesk2.version).to.equal(5); - expect(encData2.tag).to.equal(openpgp.enums.packet.AEADEncryptedData); + expect(encData2.constructor.tag).to.equal(openpgp.enums.packet.AEADEncryptedData); const { packets: [compressed] } = await encrypted2.decrypt(null, passwords, null, encrypted2.fromStream, openpgp.config); - expect(compressed.tag).to.equal(openpgp.enums.packet.compressedData); + expect(compressed.constructor.tag).to.equal(openpgp.enums.packet.compressedData); expect(compressed.algorithm).to.equal("zip"); const userIDs = { name: 'Test User', email: 'text2@example.com' }; From 08e92c08e6ba74131798cc50bafa094ac76ab8e5 Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Fri, 19 Mar 2021 12:47:06 +0100 Subject: [PATCH 11/18] Rename aead packet enum --- openpgp.d.ts | 9 +++++++-- src/enums.js | 2 +- src/message.js | 2 +- src/packet/aead_encrypted_data.js | 2 +- src/packet/packet.js | 2 +- test/general/config.js | 2 +- test/general/openpgp.js | 12 ++++++------ 7 files changed, 18 insertions(+), 13 deletions(-) diff --git a/openpgp.d.ts b/openpgp.d.ts index 2271eb5c6..e0386444e 100644 --- a/openpgp.d.ts +++ b/openpgp.d.ts @@ -396,7 +396,7 @@ export class SymEncryptedIntegrityProtectedDataPacket extends BasePacket { } export class AEADEncryptedDataPacket extends BasePacket { - public tag: enums.packet.AEADEncryptedData; + public tag: enums.packet.aeadEncryptedData; } export class PublicKeyEncryptedSessionKeyPaclet extends BasePacket { @@ -691,6 +691,9 @@ export function unarmor(input: string, config?: Config): Promise<{ text: string, /* ############## v5 ENUMS #################### */ export namespace enums { + type enumType = typeof armor | reasonForRevocation; + type enumValue = armor | reasonForRevocation; + type enumName = armorNames function read(type: typeof armor, e: armor): armorNames; function read(type: typeof compression, e: compression): compressionNames; @@ -701,6 +704,8 @@ export namespace enums { function read(type: typeof keyStatus, e: keyStatus): keyStatusNames; function read(type: typeof keyFlags, e: keyFlags): keyFlagsNames; + function write(type: enumType, e: string | number ) : enumValue; + export type armorNames = 'multipartSection' | 'multipartLast' | 'signed' | 'message' | 'publicKey' | 'privateKey'; enum armor { multipartSection = 0, @@ -760,7 +765,7 @@ export namespace enums { userAttribute = 17, symEncryptedIntegrityProtectedData = 18, modificationDetectionCode = 19, - AEADEncryptedData = 20, + aeadEncryptedData = 20, } export type publicKeyNames = 'rsaEncryptSign' | 'rsaEncrypt' | 'rsaSign' | 'elgamal' | 'dsa' | 'ecdh' | 'ecdsa' | 'eddsa' | 'aedh' | 'aedsa'; diff --git a/src/enums.js b/src/enums.js index 5c10f10b1..febb89722 100644 --- a/src/enums.js +++ b/src/enums.js @@ -205,7 +205,7 @@ export default { userAttribute: 17, symEncryptedIntegrityProtectedData: 18, modificationDetectionCode: 19, - AEADEncryptedData: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1 + aeadEncryptedData: 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/message.js b/src/message.js index cb461ad12..dbfb39744 100644 --- a/src/message.js +++ b/src/message.js @@ -101,7 +101,7 @@ export class Message { const symEncryptedPacketlist = this.packets.filterByTag( enums.packet.symmetricallyEncryptedData, enums.packet.symEncryptedIntegrityProtectedData, - enums.packet.AEADEncryptedData + enums.packet.aeadEncryptedData ); if (symEncryptedPacketlist.length === 0) { diff --git a/src/packet/aead_encrypted_data.js b/src/packet/aead_encrypted_data.js index b1b0eb00f..e417216dd 100644 --- a/src/packet/aead_encrypted_data.js +++ b/src/packet/aead_encrypted_data.js @@ -37,7 +37,7 @@ const VERSION = 1; // A one-octet version number of the data packet. * AEAD Protected Data Packet */ class AEADEncryptedDataPacket { - static tag = enums.packet.AEADEncryptedData; + static tag = enums.packet.aeadEncryptedData; constructor() { this.version = VERSION; diff --git a/src/packet/packet.js b/src/packet/packet.js index c2f933fc1..081681200 100644 --- a/src/packet/packet.js +++ b/src/packet/packet.js @@ -106,7 +106,7 @@ export function supportsStreaming(tag_type) { enums.packet.compressedData, enums.packet.symmetricallyEncryptedData, enums.packet.symEncryptedIntegrityProtectedData, - enums.packet.AEADEncryptedData + enums.packet.aeadEncryptedData ].includes(tag_type); } diff --git a/test/general/config.js b/test/general/config.js index efb6c1bf5..b80e508cf 100644 --- a/test/general/config.js +++ b/test/general/config.js @@ -168,7 +168,7 @@ module.exports = () => describe('Custom configuration', function() { const encrypted2 = await openpgp.readMessage({ armoredMessage: armored2 }); const { packets: [skesk2, encData2] } = encrypted2; expect(skesk2.version).to.equal(5); - expect(encData2.constructor.tag).to.equal(openpgp.enums.packet.AEADEncryptedData); + expect(encData2.constructor.tag).to.equal(openpgp.enums.packet.aeadEncryptedData); const { packets: [compressed] } = await encrypted2.decrypt(null, passwords, null, encrypted2.fromStream, openpgp.config); expect(compressed.constructor.tag).to.equal(openpgp.enums.packet.compressedData); expect(compressed.algorithm).to.equal("zip"); diff --git a/test/general/openpgp.js b/test/general/openpgp.js index 0ff026657..9fbf93b4a 100644 --- a/test/general/openpgp.js +++ b/test/general/openpgp.js @@ -1368,7 +1368,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.readMessage({ armoredMessage: encrypted }); - expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(false); + expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.aeadEncryptedData)).to.equal(false); return openpgp.decrypt(decOpt); }).then(function (decrypted) { expect(decrypted.data).to.equal(plaintext); @@ -1391,7 +1391,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.readMessage({ armoredMessage: encrypted }); - expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(false); + expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.aeadEncryptedData)).to.equal(false); return openpgp.decrypt(decOpt); }).then(function (decrypted) { expect(decrypted.data).to.equal(plaintext); @@ -1410,7 +1410,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }; return openpgp.encrypt(encOpt).then(async function (encrypted) { decOpt.message = await openpgp.readMessage({ armoredMessage: encrypted }); - expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(openpgp.config.aeadProtect); + expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.aeadEncryptedData)).to.equal(openpgp.config.aeadProtect); return openpgp.decrypt(decOpt); }).then(async function (decrypted) { expect(decrypted.data).to.equal(plaintext); @@ -1433,7 +1433,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }; return openpgp.encrypt(encOpt).then(async function (encrypted) { decOpt.message = await openpgp.readMessage({ armoredMessage: encrypted }); - expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(false); + expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.aeadEncryptedData)).to.equal(false); return openpgp.decrypt(decOpt); }).then(async function (decrypted) { expect(decrypted.data).to.equal(plaintext); @@ -1464,7 +1464,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }; return openpgp.encrypt(encOpt).then(async function (encrypted) { decOpt.message = await openpgp.readMessage({ armoredMessage: encrypted }); - expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(openpgp.config.aeadProtect); + expect(!!decOpt.message.packets.findPacket(openpgp.enums.packet.aeadEncryptedData)).to.equal(openpgp.config.aeadProtect); return openpgp.decrypt(decOpt); }).then(async function (decrypted) { expect(decrypted.data).to.equal(plaintext); @@ -1493,7 +1493,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { detached: true }); const message = await openpgp.readMessage({ armoredMessage: encrypted }); - expect(!!message.packets.findPacket(openpgp.enums.packet.AEADEncryptedData)).to.equal(openpgp.config.aeadProtect); + expect(!!message.packets.findPacket(openpgp.enums.packet.aeadEncryptedData)).to.equal(openpgp.config.aeadProtect); const decrypted = await openpgp.decrypt({ message, signature: await openpgp.readSignature({ armoredSignature: signed }), From e37b4aaa8300daead7c6202a0f56638066770285 Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Fri, 19 Mar 2021 12:47:16 +0100 Subject: [PATCH 12/18] Remove more underscores --- src/packet/signature.js | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/packet/signature.js b/src/packet/signature.js index 5895542c9..88ed1ffdf 100644 --- a/src/packet/signature.js +++ b/src/packet/signature.js @@ -331,10 +331,10 @@ class SignaturePacket { // V4 signature sub packets - read_sub_packet(bytes, trusted = true) { + readSubPacket(bytes, trusted = true) { let mypos = 0; - const read_array = (prop, bytes) => { + const readArray = (prop, bytes) => { this[prop] = []; for (let i = 0; i < bytes.length; i++) { @@ -403,7 +403,7 @@ class SignaturePacket { } case 11: // Preferred Symmetric Algorithms - read_array('preferredSymmetricAlgorithms', bytes.subarray(mypos, bytes.length)); + readArray('preferredSymmetricAlgorithms', bytes.subarray(mypos, bytes.length)); break; case 12: // Revocation Key @@ -443,15 +443,15 @@ class SignaturePacket { } case 21: // Preferred Hash Algorithms - read_array('preferredHashAlgorithms', bytes.subarray(mypos, bytes.length)); + readArray('preferredHashAlgorithms', bytes.subarray(mypos, bytes.length)); break; case 22: // Preferred Compression Algorithms - read_array('preferredCompressionAlgorithms', bytes.subarray(mypos, bytes.length)); + readArray('preferredCompressionAlgorithms', bytes.subarray(mypos, bytes.length)); break; case 23: // Key Server Preferences - read_array('keyServerPreferences', bytes.subarray(mypos, bytes.length)); + readArray('keyServerPreferences', bytes.subarray(mypos, bytes.length)); break; case 24: // Preferred Key Server @@ -467,7 +467,7 @@ class SignaturePacket { break; case 27: // Key Flags - read_array('keyFlags', bytes.subarray(mypos, bytes.length)); + readArray('keyFlags', bytes.subarray(mypos, bytes.length)); break; case 28: // Signer's User ID @@ -480,7 +480,7 @@ class SignaturePacket { break; case 30: // Features - read_array('features', bytes.subarray(mypos, bytes.length)); + readArray('features', bytes.subarray(mypos, bytes.length)); break; case 31: { // Signature Target @@ -510,7 +510,7 @@ class SignaturePacket { break; case 34: // Preferred AEAD Algorithms - read_array.call(this, 'preferredAEADAlgorithms', bytes.subarray(mypos, bytes.length)); + readArray.call(this, 'preferredAEADAlgorithms', bytes.subarray(mypos, bytes.length)); break; default: { const err = new Error("Unknown signature subpacket type " + type + " @:" + mypos); @@ -534,7 +534,7 @@ class SignaturePacket { const len = readSimpleLength(bytes.subarray(i, bytes.length)); i += len.offset; - this.read_sub_packet(bytes.subarray(i, i + len.len), trusted, config); + this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config); i += len.len; } From 418178031992a68746a11fccbd153a3c006cbd97 Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Fri, 19 Mar 2021 14:44:16 +0100 Subject: [PATCH 13/18] Revert type changes --- openpgp.d.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/openpgp.d.ts b/openpgp.d.ts index e0386444e..94f3e25af 100644 --- a/openpgp.d.ts +++ b/openpgp.d.ts @@ -691,10 +691,6 @@ export function unarmor(input: string, config?: Config): Promise<{ text: string, /* ############## v5 ENUMS #################### */ export namespace enums { - type enumType = typeof armor | reasonForRevocation; - type enumValue = armor | reasonForRevocation; - type enumName = armorNames - function read(type: typeof armor, e: armor): armorNames; function read(type: typeof compression, e: compression): compressionNames; function read(type: typeof hash, e: hash): hashNames; @@ -704,8 +700,6 @@ export namespace enums { function read(type: typeof keyStatus, e: keyStatus): keyStatusNames; function read(type: typeof keyFlags, e: keyFlags): keyFlagsNames; - function write(type: enumType, e: string | number ) : enumValue; - export type armorNames = 'multipartSection' | 'multipartLast' | 'signed' | 'message' | 'publicKey' | 'privateKey'; enum armor { multipartSection = 0, From cfe7119ec897a81b43dac9ee6055c5f3d0a65f88 Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Fri, 19 Mar 2021 15:33:22 +0100 Subject: [PATCH 14/18] Rename policyURI --- src/enums.js | 2 +- src/packet/signature.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/enums.js b/src/enums.js index febb89722..7b8f74eb9 100644 --- a/src/enums.js +++ b/src/enums.js @@ -368,7 +368,7 @@ export default { keyServerPreferences: 23, preferredKeyServer: 24, primaryUserID: 25, - policyUri: 26, + policyURI: 26, keyFlags: 27, signersUserID: 28, reasonForRevocation: 29, diff --git a/src/packet/signature.js b/src/packet/signature.js index 88ed1ffdf..ee4a3318c 100644 --- a/src/packet/signature.js +++ b/src/packet/signature.js @@ -263,7 +263,7 @@ class SignaturePacket { arr.push(writeSubPacket(sub.primaryUserID, new Uint8Array([this.isPrimaryUserID ? 1 : 0]))); } if (this.policyURI !== null) { - arr.push(writeSubPacket(sub.policyUri, util.stringToUint8Array(this.policyURI))); + arr.push(writeSubPacket(sub.policyURI, util.stringToUint8Array(this.policyURI))); } if (this.keyFlags !== null) { bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags)); From caa31194f123202e46cf01bd334798cb180877d4 Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Mon, 22 Mar 2021 13:30:20 +0100 Subject: [PATCH 15/18] Explicitly pass formatted allowed packets to Packetlist.read --- src/cleartext.js | 6 ++- src/key/factory.js | 26 ++++++++-- src/key/helper.js | 12 ----- src/key/key.js | 6 ++- src/message.js | 41 +++++++++------ src/packet/aead_encrypted_data.js | 26 +++++----- src/packet/compressed_data.js | 21 ++++---- src/packet/literal_data.js | 5 +- src/packet/marker.js | 4 +- src/packet/one_pass_signature.js | 4 +- src/packet/packetlist.js | 25 +++------ src/packet/public_key.js | 4 +- .../public_key_encrypted_session_key.js | 4 +- src/packet/public_subkey.js | 4 +- src/packet/secret_key.js | 4 +- src/packet/secret_subkey.js | 4 +- src/packet/signature.js | 8 +-- .../sym_encrypted_integrity_protected_data.js | 24 +++++---- src/packet/sym_encrypted_session_key.js | 8 +-- src/packet/symmetrically_encrypted_data.js | 24 +++++---- src/packet/trust.js | 4 +- src/packet/user_attribute.js | 4 +- src/packet/userid.js | 4 +- src/signature.js | 6 ++- src/util.js | 15 ++++++ test/general/key.js | 7 +-- test/general/packet.js | 52 ++++++++++--------- 27 files changed, 199 insertions(+), 153 deletions(-) diff --git a/src/cleartext.js b/src/cleartext.js index f6b3dfc02..797fb6c6b 100644 --- a/src/cleartext.js +++ b/src/cleartext.js @@ -23,6 +23,9 @@ import { Signature } from './signature'; import { createVerificationObjects, createSignaturePackets } from './message'; import defaultConfig from './config'; +// A Cleartext message can contain the following packets +const allowedPackets = util.constructAllowedPackets([SignaturePacket]); + /** * Class that represents an OpenPGP cleartext signed message. * See {@link https://tools.ietf.org/html/rfc4880#section-7} @@ -127,7 +130,6 @@ export class CleartextMessage { } } - /** * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object * @param {Object} options @@ -147,7 +149,7 @@ export async function readCleartextMessage({ cleartextMessage, config }) { throw new Error('No cleartext signed message.'); } const packetlist = new PacketList(); - await packetlist.read(input.data, { SignaturePacket }, undefined, config); + await packetlist.read(input.data, allowedPackets, undefined, config); verifyHeaders(input.headers, packetlist); const signature = new Signature(packetlist); return new CleartextMessage(input.text, signature); diff --git a/src/key/factory.js b/src/key/factory.js index ec5095b1e..e323df80a 100644 --- a/src/key/factory.js +++ b/src/key/factory.js @@ -15,7 +15,16 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -import { PacketList, UserIDPacket, SignaturePacket } from '../packet'; +import { + PacketList, + UserIDPacket, + SignaturePacket, + PublicKeyPacket, + PublicSubkeyPacket, + SecretKeyPacket, + SecretSubkeyPacket, + UserAttributePacket +} from '../packet'; import Key from './key'; import * as helper from './helper'; import enums from '../enums'; @@ -23,6 +32,17 @@ import util from '../util'; import defaultConfig from '../config'; import { unarmor } from '../encoding/armor'; +// A Key can contain the following packets +const allowedKeyPackets = util.constructAllowedPackets([ + PublicKeyPacket, + PublicSubkeyPacket, + SecretKeyPacket, + SecretSubkeyPacket, + UserIDPacket, + UserAttributePacket, + SignaturePacket +]); + /** * Generates a new OpenPGP key. Supports RSA and ECC keys. * By default, primary and subkeys will be of same type. @@ -256,7 +276,7 @@ export async function readKey({ armoredKey, binaryKey, config }) { input = binaryKey; } const packetlist = new PacketList(); - await packetlist.read(input, helper.allowedKeyPackets, undefined, config); + await packetlist.read(input, allowedKeyPackets, undefined, config); return new Key(packetlist); } @@ -285,7 +305,7 @@ export async function readKeys({ armoredKeys, binaryKeys, config }) { } const keys = []; const packetlist = new PacketList(); - await packetlist.read(input, helper.allowedKeyPackets, undefined, config); + await packetlist.read(input, allowedKeyPackets, undefined, config); 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 0470c563c..9d770d37b 100644 --- a/src/key/helper.js +++ b/src/key/helper.js @@ -9,8 +9,6 @@ import { PublicSubkeyPacket, SecretKeyPacket, SecretSubkeyPacket, - UserIDPacket, - UserAttributePacket, SignaturePacket } from '../packet'; import enums from '../enums'; @@ -18,16 +16,6 @@ import crypto from '../crypto'; import util from '../util'; import defaultConfig from '../config'; -export const allowedKeyPackets = { - PublicKeyPacket, - PublicSubkeyPacket, - SecretKeyPacket, - SecretSubkeyPacket, - UserIDPacket, - UserAttributePacket, - SignaturePacket -}; - export async function generateSecretSubkey(options, config) { const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config); secretSubkeyPacket.packets = null; diff --git a/src/key/key.js b/src/key/key.js index 91cd83d76..8e722c85a 100644 --- a/src/key/key.js +++ b/src/key/key.js @@ -29,6 +29,9 @@ import User from './user'; import SubKey from './subkey'; import * as helper from './helper'; +// A key revocation certificate can contain the following packets +const allowedRevocationPackets = util.constructAllowedPackets([SignaturePacket]); + /** * Class that represents an OpenPGP key. Must contain a primary key. * Can contain additional subkeys, signatures, user ids, user attributes. @@ -797,7 +800,7 @@ class Key { async applyRevocationCertificate(revocationCertificate, config = defaultConfig) { const input = await unarmor(revocationCertificate, config); const packetlist = new PacketList(); - await packetlist.read(input.data, { SignaturePacket }, undefined, config); + await packetlist.read(input.data, allowedRevocationPackets, undefined, config); const revocationSignature = packetlist.findPacket(enums.packet.signature); if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) { throw new Error('Could not find revocation signature packet'); @@ -950,3 +953,4 @@ class Key { }); export default Key; + diff --git a/src/message.js b/src/message.js index dbfb39744..58687a39d 100644 --- a/src/message.js +++ b/src/message.js @@ -22,6 +22,8 @@ import defaultConfig from './config'; import crypto from './crypto'; import enums from './enums'; import util from './util'; +import { Signature } from './signature'; +import { getPreferredHashAlgo, getPreferredAlgo, isAEADSupported, createSignaturePacket } from './key'; import { PacketList, LiteralDataPacket, @@ -34,8 +36,23 @@ import { OnePassSignaturePacket, SignaturePacket } from './packet'; -import { Signature } from './signature'; -import { getPreferredHashAlgo, getPreferredAlgo, isAEADSupported, createSignaturePacket } from './key'; + +// A Message can contain the following packets +const allowedMessagePackets = util.constructAllowedPackets([ + LiteralDataPacket, + CompressedDataPacket, + AEADEncryptedDataPacket, + SymEncryptedIntegrityProtectedDataPacket, + SymmetricallyEncryptedDataPacket, + PublicKeyEncryptedSessionKeyPacket, + SymEncryptedSessionKeyPacket, + OnePassSignaturePacket, + SignaturePacket +]); +// A SKESK packet can contain the following packets +const allowedSymSessionKeyPackets = util.constructAllowedPackets([SymEncryptedSessionKeyPacket]); +// A detached signature can contain the following packets +const allowedDetachedSignaturePackets = util.constructAllowedPackets([SignaturePacket]); /** * Class that represents an OpenPGP message. @@ -159,7 +176,7 @@ export class Message { let packets; if (i) { packets = new PacketList(); - await packets.read(symESKeyPacketlist.write(), { SymEncryptedSessionKeyPacket }); + await packets.read(symESKeyPacketlist.write(), allowedSymSessionKeyPackets); } else { packets = symESKeyPacketlist; } @@ -610,7 +627,10 @@ export class Message { * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature */ async appendSignature(detachedSignature) { - await this.packets.read(util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data, { SignaturePacket }); + await this.packets.read( + util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data, + allowedDetachedSignaturePackets + ); } /** @@ -853,18 +873,9 @@ export async function readMessage({ armoredMessage, binaryMessage, config }) { input = data; } const packetlist = new PacketList(); - await packetlist.read(input, { - LiteralDataPacket, - CompressedDataPacket, - AEADEncryptedDataPacket, - SymEncryptedIntegrityProtectedDataPacket, - SymmetricallyEncryptedDataPacket, - PublicKeyEncryptedSessionKeyPacket, - SymEncryptedSessionKeyPacket, - OnePassSignaturePacket, - SignaturePacket - }, streamType, config); + await packetlist.read(input, allowedMessagePackets, streamType, config); const message = new Message(packetlist); message.fromStream = streamType; return message; } + diff --git a/src/packet/aead_encrypted_data.js b/src/packet/aead_encrypted_data.js index e417216dd..012577529 100644 --- a/src/packet/aead_encrypted_data.js +++ b/src/packet/aead_encrypted_data.js @@ -19,13 +19,20 @@ import stream from '@openpgp/web-stream-tools'; import crypto from '../crypto'; import enums from '../enums'; import util from '../util'; -import { +import defaultConfig from '../config'; + +import LiteralDataPacket from './literal_data'; +import CompressedDataPacket from './compressed_data'; +import OnePassSignaturePacket from './one_pass_signature'; +import SignaturePacket from './signature'; + +// An AEAD-encrypted Data packet can contain the following packet types +const allowedPackets = util.constructAllowedPackets([ LiteralDataPacket, CompressedDataPacket, OnePassSignaturePacket, SignaturePacket -} from '../packet'; -import defaultConfig from '../config'; +]); const VERSION = 1; // A one-octet version number of the data packet. @@ -37,8 +44,6 @@ const VERSION = 1; // A one-octet version number of the data packet. * AEAD Protected Data Packet */ class AEADEncryptedDataPacket { - static tag = enums.packet.aeadEncryptedData; - constructor() { this.version = VERSION; this.cipherAlgo = null; @@ -85,12 +90,7 @@ class AEADEncryptedDataPacket { * @async */ async decrypt(sessionKeyAlgorithm, key, streaming) { - await this.packets.read(await this.crypt('decrypt', key, stream.clone(this.encrypted), streaming), { - LiteralDataPacket, - CompressedDataPacket, - OnePassSignaturePacket, - SignaturePacket - }, streaming); + await this.packets.read(await this.crypt('decrypt', key, stream.clone(this.encrypted), streaming), allowedPackets, streaming); } /** @@ -133,7 +133,7 @@ class AEADEncryptedDataPacket { const adataTagArray = new Uint8Array(adataBuffer); const adataView = new DataView(adataBuffer); const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8); - adataArray.set([0xC0 | this.constructor.tag, this.version, this.cipherAlgo, this.aeadAlgo, this.chunkSizeByte], 0); + adataArray.set([0xC0 | AEADEncryptedDataPacket.tag, this.version, this.cipherAlgo, this.aeadAlgo, this.chunkSizeByte], 0); let chunkIndex = 0; let latestPromise = Promise.resolve(); let cryptedBytes = 0; @@ -190,5 +190,7 @@ class AEADEncryptedDataPacket { }); } } +// Static fields (explicit declaration not fully supported by Safari) +AEADEncryptedDataPacket.tag = enums.packet.aeadEncryptedData; export default AEADEncryptedDataPacket; diff --git a/src/packet/compressed_data.js b/src/packet/compressed_data.js index 257149fba..6e53d89a9 100644 --- a/src/packet/compressed_data.js +++ b/src/packet/compressed_data.js @@ -23,11 +23,17 @@ import stream from '@openpgp/web-stream-tools'; import enums from '../enums'; import util from '../util'; import defaultConfig from '../config'; -import { + +import LiteralDataPacket from './literal_data'; +import OnePassSignaturePacket from './one_pass_signature'; +import SignaturePacket from './signature'; + +// A Compressed Data packet can contain the following packet types +const allowedPackets = util.constructAllowedPackets([ LiteralDataPacket, OnePassSignaturePacket, SignaturePacket -} from '../packet'; +]); /** * Implementation of the Compressed Data Packet (Tag 8) @@ -38,8 +44,6 @@ import { * a Signature or One-Pass Signature packet, and contains a literal data packet. */ class CompressedDataPacket { - static tag = enums.packet.compressedData; - /** * @param {Object} [config] - Full configuration, defaults to openpgp.config */ @@ -108,11 +112,7 @@ class CompressedDataPacket { throw new Error(this.algorithm + ' decompression not supported'); } - await this.packets.read(decompress_fns[this.algorithm](this.compressed), { - LiteralDataPacket, - OnePassSignaturePacket, - SignaturePacket - }, streaming); + await this.packets.read(decompress_fns[this.algorithm](this.compressed), allowedPackets, streaming); } /** @@ -126,6 +126,8 @@ class CompressedDataPacket { this.compressed = compress_fns[this.algorithm](this.packets.write(), this.deflateLevel); } } +// Static fields (explicit declaration not fully supported by Safari) +CompressedDataPacket.tag = enums.packet.compressedData; export default CompressedDataPacket; @@ -190,3 +192,4 @@ const decompress_fns = nodeZlib ? { zlib: /*#__PURE__*/ pako_zlib(Inflate), bzip2: /*#__PURE__*/ bzip2(BunzipDecode) }; + diff --git a/src/packet/literal_data.js b/src/packet/literal_data.js index d96fd62b1..8bfbbfe0d 100644 --- a/src/packet/literal_data.js +++ b/src/packet/literal_data.js @@ -27,8 +27,6 @@ import util from '../util'; * further interpreted. */ class LiteralDataPacket { - static tag = enums.packet.literalData; - /** * @param {Date} date - The creation date of the literal package */ @@ -111,7 +109,6 @@ class LiteralDataPacket { return this.filename; } - /** * Parsing function for a literal data packet (tag 11). * @@ -161,5 +158,7 @@ class LiteralDataPacket { return util.concat([header, data]); } } +// Static fields (explicit declaration not fully supported by Safari) +LiteralDataPacket.tag = enums.packet.literalData; export default LiteralDataPacket; diff --git a/src/packet/marker.js b/src/packet/marker.js index 2150092ef..a9b148ec0 100644 --- a/src/packet/marker.js +++ b/src/packet/marker.js @@ -31,8 +31,6 @@ import enums from '../enums'; * Such a packet MUST be ignored when received. */ class MarkerPacket { - static tag = enums.packet.marker; - /** * Parsing function for a literal data packet (tag 10). * @@ -54,5 +52,7 @@ class MarkerPacket { return false; } } +// Static fields (explicit declaration not fully supported by Safari) +MarkerPacket.tag = enums.packet.marker; export default MarkerPacket; diff --git a/src/packet/one_pass_signature.js b/src/packet/one_pass_signature.js index ab9a14196..0d36973a2 100644 --- a/src/packet/one_pass_signature.js +++ b/src/packet/one_pass_signature.js @@ -32,8 +32,6 @@ import util from '../util'; * can compute the entire signed message in one pass. */ class OnePassSignaturePacket { - static tag = enums.packet.onePassSignature; - constructor() { /** A one-octet version number. The current version is 3. */ this.version = null; @@ -135,5 +133,7 @@ class OnePassSignaturePacket { OnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash; OnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash; OnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign; +// Static fields (explicit declaration not fully supported by Safari) +OnePassSignaturePacket.tag = enums.packet.onePassSignature; export default OnePassSignaturePacket; diff --git a/src/packet/packetlist.js b/src/packet/packetlist.js index 00410a616..a986b7cf5 100644 --- a/src/packet/packetlist.js +++ b/src/packet/packetlist.js @@ -1,34 +1,25 @@ import stream from '@openpgp/web-stream-tools'; -import * as packetClasses from './all_packets'; import { readPackets, supportsStreaming, writeTag, writeHeader, writePartialLength, writeSimpleLength } from './packet'; import util from '../util'; +import enums from '../enums'; import defaultConfig from '../config'; -const mapPacketTagToClassName = (() => { - const map = {}; - for (const className of Object.keys(packetClasses)) { - const PacketClass = packetClasses[className]; - map[PacketClass.tag] = className; - } - return map; -})(); - /** - * Allocate a new packet + * Instantiate a new packet given its tag * @function newPacketFromTag - * @param {module:enums.packet} tag - Property name from {@link module:enums.packet} - * @returns {Object} New packet object with type based on tag. + * @param {module:enums.packet} tag - Property value from {@link module:enums.packet} + * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class + * @returns {Object} New packet object with type based on tag */ export function newPacketFromTag(tag, allowedPackets) { - const className = mapPacketTagToClassName[tag]; - if (!allowedPackets[className]) { - throw new Error(`Packet not allowed in this context: ${className}`); + if (!allowedPackets[tag]) { + throw new Error(`Packet not allowed in this context: ${enums.read(enums.packets, tag)}`); } - return new allowedPackets[className](); + return new allowedPackets[tag](); } /** diff --git a/src/packet/public_key.js b/src/packet/public_key.js index 780cd6cbb..4722d5207 100644 --- a/src/packet/public_key.js +++ b/src/packet/public_key.js @@ -37,8 +37,6 @@ import util from '../util'; * key (sometimes called an OpenPGP certificate). */ class PublicKeyPacket { - static tag = enums.packet.publicKey; - /** * @param {Date} [date] - Creation date * @param {Object} [config] - Full configuration, defaults to openpgp.config @@ -250,5 +248,7 @@ PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read; * @see PublicKeyPacket#write */ PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write; +// Static fields (explicit declaration not fully supported by Safari) +PublicKeyPacket.tag = enums.packet.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 061c3e123..b2be56de2 100644 --- a/src/packet/public_key_encrypted_session_key.js +++ b/src/packet/public_key_encrypted_session_key.js @@ -37,8 +37,6 @@ import util from '../util'; * decrypt the message. */ class PublicKeyEncryptedSessionKeyPacket { - static tag = enums.packet.publicKeyEncryptedSessionKey; - constructor() { this.version = 3; @@ -130,5 +128,7 @@ class PublicKeyEncryptedSessionKeyPacket { return true; } } +// Static fields (explicit declaration not fully supported by Safari) +PublicKeyEncryptedSessionKeyPacket.tag = enums.packet.publicKeyEncryptedSessionKey; export default PublicKeyEncryptedSessionKeyPacket; diff --git a/src/packet/public_subkey.js b/src/packet/public_subkey.js index 85b4bf442..85a7ef1c1 100644 --- a/src/packet/public_subkey.js +++ b/src/packet/public_subkey.js @@ -27,8 +27,6 @@ import enums from '../enums'; * @extends PublicKeyPacket */ class PublicSubkeyPacket extends PublicKeyPacket { - static tag = enums.packet.publicSubkey; - /** * @param {Date} [date] - Creation date * @param {Object} [config] - Full configuration, defaults to openpgp.config @@ -38,5 +36,7 @@ class PublicSubkeyPacket extends PublicKeyPacket { super(date, config); } } +// Static fields (explicit declaration not fully supported by Safari) +PublicSubkeyPacket.tag = enums.packet.publicSubkey; export default PublicSubkeyPacket; diff --git a/src/packet/secret_key.js b/src/packet/secret_key.js index 619dbe1d0..8f05716ff 100644 --- a/src/packet/secret_key.js +++ b/src/packet/secret_key.js @@ -29,8 +29,6 @@ import defaultConfig from '../config'; * @extends PublicKeyPacket */ class SecretKeyPacket extends PublicKeyPacket { - static tag = enums.packet.secretKey; - /** * @param {Date} [date] - Creation date * @param {Object} [config] - Full configuration, defaults to openpgp.config @@ -429,5 +427,7 @@ async function produceEncryptionKey(s2k, passphrase, algorithm) { crypto.cipher[algorithm].keySize ); } +// Static fields (explicit declaration not fully supported by Safari) +SecretKeyPacket.tag = enums.packet.secretKey; export default SecretKeyPacket; diff --git a/src/packet/secret_subkey.js b/src/packet/secret_subkey.js index 368f7554b..73ce5e62d 100644 --- a/src/packet/secret_subkey.js +++ b/src/packet/secret_subkey.js @@ -25,8 +25,6 @@ import defaultConfig from '../config'; * @extends SecretKeyPacket */ class SecretSubkeyPacket extends SecretKeyPacket { - static tag = enums.packet.secretSubkey; - /** * @param {Date} [date] - Creation date * @param {Object} [config] - Full configuration, defaults to openpgp.config @@ -35,5 +33,7 @@ class SecretSubkeyPacket extends SecretKeyPacket { super(date, config); } } +// Static fields (explicit declaration not fully supported by Safari) +SecretSubkeyPacket.tag = enums.packet.secretSubkey; export default SecretSubkeyPacket; diff --git a/src/packet/signature.js b/src/packet/signature.js index ee4a3318c..cfdf45d8c 100644 --- a/src/packet/signature.js +++ b/src/packet/signature.js @@ -32,8 +32,6 @@ import defaultConfig from '../config'; * block of text, and a signature that is a certification of a User ID. */ class SignaturePacket { - static tag = enums.packet.signature; - /** * @param {Date} date - The creation date of the signature */ @@ -734,6 +732,10 @@ class SignaturePacket { return !this.signatureNeverExpires ? new Date(this.created.getTime() + this.signatureExpirationTime * 1000) : Infinity; } } +// Static fields (explicit declaration not fully supported by Safari) +SignaturePacket.tag = enums.packet.signature; + +export default SignaturePacket; /** * Creates a string representation of a sub signature packet @@ -751,5 +753,3 @@ function writeSubPacket(type, data) { arr.push(data); return util.concat(arr); } - -export default SignaturePacket; diff --git a/src/packet/sym_encrypted_integrity_protected_data.js b/src/packet/sym_encrypted_integrity_protected_data.js index ff6a748ce..3e20c9767 100644 --- a/src/packet/sym_encrypted_integrity_protected_data.js +++ b/src/packet/sym_encrypted_integrity_protected_data.js @@ -19,13 +19,20 @@ import stream from '@openpgp/web-stream-tools'; import crypto from '../crypto'; import enums from '../enums'; import util from '../util'; -import { +import defaultConfig from '../config'; + +import LiteralDataPacket from './literal_data'; +import CompressedDataPacket from './compressed_data'; +import OnePassSignaturePacket from './one_pass_signature'; +import SignaturePacket from './signature'; + +// A SEIP packet can contain the following packet types +const allowedPackets = util.constructAllowedPackets([ LiteralDataPacket, CompressedDataPacket, OnePassSignaturePacket, SignaturePacket -} from '../packet'; -import defaultConfig from '../config'; +]); const VERSION = 1; // A one-octet version number of the data packet. @@ -40,8 +47,6 @@ const VERSION = 1; // A one-octet version number of the data packet. * packet. */ class SymEncryptedIntegrityProtectedDataPacket { - static tag = enums.packet.symEncryptedIntegrityProtectedData; - constructor() { this.version = VERSION; /** The encrypted payload. */ @@ -131,14 +136,11 @@ class SymEncryptedIntegrityProtectedDataPacket { if (!util.isStream(encrypted) || !config.allowUnauthenticatedStream) { packetbytes = await stream.readToEnd(packetbytes); } - await this.packets.read(packetbytes, { - LiteralDataPacket, - CompressedDataPacket, - OnePassSignaturePacket, - SignaturePacket - }, streaming); + await this.packets.read(packetbytes, allowedPackets, streaming); return true; } } +// Static fields (explicit declaration not fully supported by Safari) +SymEncryptedIntegrityProtectedDataPacket.tag = enums.packet.symEncryptedIntegrityProtectedData; export default SymEncryptedIntegrityProtectedDataPacket; diff --git a/src/packet/sym_encrypted_session_key.js b/src/packet/sym_encrypted_session_key.js index 0673c18f2..8b51a1f69 100644 --- a/src/packet/sym_encrypted_session_key.js +++ b/src/packet/sym_encrypted_session_key.js @@ -35,8 +35,6 @@ import util from '../util'; * the Symmetric-Key Encrypted Session Key packet. */ class SymEncryptedSessionKeyPacket { - static tag = enums.packet.symEncryptedSessionKey; - /** * @param {Object} [config] - Full configuration, defaults to openpgp.config */ @@ -133,7 +131,7 @@ class SymEncryptedSessionKeyPacket { if (this.version === 5) { const mode = crypto.mode[this.aeadAlgorithm]; - const adata = new Uint8Array([0xC0 | this.constructor.tag, this.version, enums.write(enums.symmetric, this.sessionKeyEncryptionAlgorithm), enums.write(enums.aead, this.aeadAlgorithm)]); + const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, enums.write(enums.symmetric, this.sessionKeyEncryptionAlgorithm), enums.write(enums.aead, this.aeadAlgorithm)]); const modeInstance = await mode(algo, key); this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata); } else if (this.encrypted !== null) { @@ -173,7 +171,7 @@ class SymEncryptedSessionKeyPacket { if (this.version === 5) { const mode = crypto.mode[this.aeadAlgorithm]; this.iv = await crypto.random.getRandomBytes(mode.ivLength); // generate new random IV - const adata = new Uint8Array([0xC0 | this.constructor.tag, this.version, enums.write(enums.symmetric, this.sessionKeyEncryptionAlgorithm), enums.write(enums.aead, this.aeadAlgorithm)]); + const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, enums.write(enums.symmetric, this.sessionKeyEncryptionAlgorithm), enums.write(enums.aead, this.aeadAlgorithm)]); const modeInstance = await mode(algo, key); this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, adata); } else { @@ -183,5 +181,7 @@ class SymEncryptedSessionKeyPacket { } } } +// Static fields (explicit declaration not fully supported by Safari) +SymEncryptedSessionKeyPacket.tag = enums.packet.symEncryptedSessionKey; export default SymEncryptedSessionKeyPacket; diff --git a/src/packet/symmetrically_encrypted_data.js b/src/packet/symmetrically_encrypted_data.js index 31b44341c..fc23ceaf0 100644 --- a/src/packet/symmetrically_encrypted_data.js +++ b/src/packet/symmetrically_encrypted_data.js @@ -19,13 +19,20 @@ import stream from '@openpgp/web-stream-tools'; import crypto from '../crypto'; import enums from '../enums'; import util from '../util'; -import { +import defaultConfig from '../config'; + +import LiteralDataPacket from './literal_data'; +import CompressedDataPacket from './compressed_data'; +import OnePassSignaturePacket from './one_pass_signature'; +import SignaturePacket from './signature'; + +// A SE packet can contain the following packet types +const allowedPackets = util.constructAllowedPackets([ LiteralDataPacket, CompressedDataPacket, OnePassSignaturePacket, SignaturePacket -} from '../packet'; -import defaultConfig from '../config'; +]); /** * Implementation of the Symmetrically Encrypted Data Packet (Tag 9) @@ -38,8 +45,6 @@ import defaultConfig from '../config'; * that form whole OpenPGP messages). */ class SymmetricallyEncryptedDataPacket { - static tag = enums.packet.symmetricallyEncryptedData; - constructor() { /** * Encrypted secret-key data @@ -82,12 +87,7 @@ class SymmetricallyEncryptedDataPacket { encrypted.subarray(2, crypto.cipher[sessionKeyAlgorithm].blockSize + 2) ); - await this.packets.read(decrypted, { - LiteralDataPacket, - CompressedDataPacket, - OnePassSignaturePacket, - SignaturePacket - }, streaming); + await this.packets.read(decrypted, allowedPackets, streaming); } /** @@ -108,5 +108,7 @@ class SymmetricallyEncryptedDataPacket { this.encrypted = util.concat([FRE, ciphertext]); } } +// Static fields (explicit declaration not fully supported by Safari) +SymmetricallyEncryptedDataPacket.tag = enums.packet.symmetricallyEncryptedData; export default SymmetricallyEncryptedDataPacket; diff --git a/src/packet/trust.js b/src/packet/trust.js index 66ea47fb1..e7d96f77a 100644 --- a/src/packet/trust.js +++ b/src/packet/trust.js @@ -18,8 +18,6 @@ import enums from '../enums'; * other than local keyring files. */ class TrustPacket { - static tag = enums.packet.trust; - /** * Parsing function for a trust packet (tag 12). * Currently not implemented as we ignore trust packets @@ -27,5 +25,7 @@ class TrustPacket { */ read() {} // TODO } +// Static fields (explicit declaration not fully supported by Safari) +TrustPacket.tag = enums.packet.trust; export default TrustPacket; diff --git a/src/packet/user_attribute.js b/src/packet/user_attribute.js index 88314b2c7..73e44b172 100644 --- a/src/packet/user_attribute.js +++ b/src/packet/user_attribute.js @@ -37,8 +37,6 @@ import util from '../util'; * an implementation may use any method desired. */ class UserAttributePacket { - static tag = enums.packet.userAttribute; - constructor() { this.attributes = []; } @@ -85,5 +83,7 @@ class UserAttributePacket { }); } } +// Static fields (explicit declaration not fully supported by Safari) +UserAttributePacket.tag = enums.packet.userAttribute; export default UserAttributePacket; diff --git a/src/packet/userid.js b/src/packet/userid.js index 6e46470c6..a188de267 100644 --- a/src/packet/userid.js +++ b/src/packet/userid.js @@ -31,8 +31,6 @@ import defaultConfig from '../config'; * specifies the length of the User ID. */ class UserIDPacket { - static tag = enums.packet.userID; - constructor() { /** A string containing the user id. Usually in the form * John Doe @@ -94,5 +92,7 @@ class UserIDPacket { return util.encodeUTF8(this.userID); } } +// Static fields (explicit declaration not fully supported by Safari) +UserIDPacket.tag = enums.packet.userID; export default UserIDPacket; diff --git a/src/signature.js b/src/signature.js index b5cab3efd..88588c109 100644 --- a/src/signature.js +++ b/src/signature.js @@ -18,8 +18,12 @@ import { armor, unarmor } from './encoding/armor'; import { PacketList, SignaturePacket } from './packet'; import enums from './enums'; +import util from './util'; import defaultConfig from './config'; +// A Signature can contain the following packets +const allowedPackets = util.constructAllowedPackets([SignaturePacket]); + /** * Class that represents an OpenPGP signature. */ @@ -73,6 +77,6 @@ export async function readSignature({ armoredSignature, binarySignature, config input = data; } const packetlist = new PacketList(); - await packetlist.read(input, { SignaturePacket }, undefined, config); + await packetlist.read(input, allowedPackets, undefined, config); return new Signature(packetlist); } diff --git a/src/util.js b/src/util.js index b26e4f3ed..b8627df96 100644 --- a/src/util.js +++ b/src/util.js @@ -674,6 +674,21 @@ const util = { } catch (e) {} return error; + }, + + /** + * Map allowed packet tags to corresponding classes + * Meant to be used to format `allowedPacket` for Packetlist.read + * @param {Array} allowedClasses + * @returns {Object} map from enum.packet to corresponding *Packet class + */ + constructAllowedPackets: /*#__PURE__*/ function(allowedClasses) { + const map = {}; + allowedClasses.forEach(PacketClass => { + if (!PacketClass.tag) return; + map[PacketClass.tag] = PacketClass; + }); + return map; } }; diff --git a/test/general/key.js b/test/general/key.js index 38717496d..1742d2348 100644 --- a/test/general/key.js +++ b/test/general/key.js @@ -4,6 +4,7 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const util = require('../../src/util'); const key = require('../../src/key'); +const allPackets = require('../../src/packet/all_packets'); const chai = require('chai'); chai.use(require('chai-as-promised')); @@ -2754,7 +2755,7 @@ module.exports = () => describe('Key', function() { `.replace(/\s+/g, '')); const packetlist = new openpgp.PacketList(); - await packetlist.read(packetBytes, { PublicKeyPacket: openpgp.PublicKeyPacket }, undefined, openpgp.config); + await packetlist.read(packetBytes, util.constructAllowedPackets([openpgp.PublicKeyPacket]), undefined, openpgp.config); const key = packetlist[0]; expect(key).to.exist; }); @@ -2784,7 +2785,7 @@ module.exports = () => describe('Key', function() { const packetlist = new openpgp.PacketList(); - await packetlist.read((await openpgp.unarmor(pub_sig_test)).data, openpgp, undefined, openpgp.config); + await packetlist.read((await openpgp.unarmor(pub_sig_test)).data, util.constructAllowedPackets([...Object.values(allPackets)]), undefined, openpgp.config); const subkeys = pubKey.getSubkeys(); expect(subkeys).to.exist; @@ -3264,7 +3265,7 @@ module.exports = () => describe('Key', function() { const input = await openpgp.unarmor(revocation_certificate_arm4); const packetlist = new openpgp.PacketList(); - await packetlist.read(input.data, { SignaturePacket: openpgp.SignaturePacket }, undefined, openpgp.config); + await packetlist.read(input.data, util.constructAllowedPackets([openpgp.SignaturePacket]), undefined, openpgp.config); const armored = openpgp.armor(openpgp.enums.armor.publicKey, packetlist.write()); expect(revocationCertificate.replace(/^Comment: .*$\n/mg, '')).to.equal(armored.replace(/^Comment: .*$\n/mg, '')); diff --git a/test/general/packet.js b/test/general/packet.js index 43a61359a..cbb0b7ab5 100644 --- a/test/general/packet.js +++ b/test/general/packet.js @@ -3,6 +3,7 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const crypto = require('../../src/crypto'); const util = require('../../src/util'); +const allPackets = require('../../src/packet/all_packets'); const stub = require('sinon/lib/sinon/stub'); const chai = require('chai'); @@ -28,6 +29,8 @@ function stringify(array) { } module.exports = () => describe("Packet", function() { + const allAllowedPackets = util.constructAllowedPackets([...Object.values(allPackets)]); + const armored_key = '-----BEGIN PGP PRIVATE KEY BLOCK-----\n' + 'Version: GnuPG v2.0.19 (GNU/Linux)\n' + @@ -88,7 +91,7 @@ module.exports = () => describe("Packet", function() { await enc.encrypt(algo, key, undefined, openpgp.config); const msg2 = new openpgp.PacketList(); - await msg2.read(message.write(), { SymmetricallyEncryptedDataPacket: openpgp.SymmetricallyEncryptedDataPacket }); + await msg2.read(message.write(), util.constructAllowedPackets([openpgp.SymmetricallyEncryptedDataPacket])); await msg2[0].decrypt(algo, key, undefined, openpgp.config); expect(await stringify(msg2[0].packets[0].data)).to.equal(stringify(literal.data)); @@ -119,7 +122,7 @@ module.exports = () => describe("Packet", function() { await enc.encrypt(algo, key, undefined, openpgp.config); const msg2 = new openpgp.PacketList(); - await msg2.read(message.write(), { SymmetricallyEncryptedDataPacket: openpgp.SymmetricallyEncryptedDataPacket }); + await msg2.read(message.write(), util.constructAllowedPackets([openpgp.SymmetricallyEncryptedDataPacket])); await expect(msg2[0].decrypt(algo, key, undefined, openpgp.config)).to.eventually.be.rejectedWith('Message is not authenticated.'); } finally { openpgp.config.aeadProtect = aeadProtectVal; @@ -141,8 +144,7 @@ module.exports = () => describe("Packet", function() { await enc.encrypt(algo, key, undefined, openpgp.config); const msg2 = new openpgp.PacketList(); - await msg2.read(msg.write(), openpgp); - + await msg2.read(msg.write(), allAllowedPackets); await msg2[0].decrypt(algo, key, undefined, openpgp.config); expect(await stringify(msg2[0].packets[0].data)).to.equal(stringify(literal.data)); @@ -167,7 +169,7 @@ module.exports = () => describe("Packet", function() { const msg2 = new openpgp.PacketList(); return enc.encrypt(algo, key, undefined, openpgp.config).then(async function() { - await msg2.read(msg.write(), openpgp); + await msg2.read(msg.write(), allAllowedPackets); return msg2[0].decrypt(algo, key); }).then(async function() { expect(await openpgp.stream.readToEnd(msg2[0].packets[0].data)).to.deep.equal(literal.data); @@ -221,7 +223,7 @@ module.exports = () => describe("Packet", function() { try { await enc.encrypt(algo, key, undefined, { ...openpgp.config, aeadChunkSizeByte: 0 }); - await msg2.read(msg.write(), openpgp); + await msg2.read(msg.write(), allAllowedPackets); 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; @@ -268,7 +270,7 @@ module.exports = () => describe("Packet", function() { await enc.encrypt(algo, key, undefined, { ...openpgp.config, aeadChunkSizeByte: 14 }); const data = msg.write(); expect(await openpgp.stream.readToEnd(openpgp.stream.clone(data))).to.deep.equal(packetBytes); - await msg2.read(data, openpgp); + await msg2.read(data, allAllowedPackets); await msg2[0].decrypt(algo, key); expect(await openpgp.stream.readToEnd(msg2[0].packets[0].data)).to.deep.equal(literal.data); } finally { @@ -276,7 +278,7 @@ module.exports = () => describe("Packet", function() { } }); - it('Sym encrypted session key with a compressed packet', async function() { + it('Sym. encrypted session key with a compressed packet', async function() { const msg = '-----BEGIN PGP MESSAGE-----\n' + 'Version: GnuPG v2.0.19 (GNU/Linux)\n' + @@ -289,7 +291,7 @@ module.exports = () => describe("Packet", function() { const msgbytes = (await openpgp.unarmor(msg)).data; const parsed = new openpgp.PacketList(); - await parsed.read(msgbytes, openpgp); + await parsed.read(msgbytes, allAllowedPackets); return parsed[0].decrypt('test').then(() => { const key = parsed[0].sessionKey; @@ -319,7 +321,7 @@ module.exports = () => describe("Packet", function() { return enc.encrypt({ publicParams, getFingerprintBytes() {} }).then(async () => { msg.push(enc); - await msg2.read(msg.write(), openpgp); + await msg2.read(msg.write(), allAllowedPackets); return msg2[0].decrypt({ algorithm: 'rsaEncryptSign', publicParams, privateParams, getFingerprintBytes() {} }).then(() => { expect(stringify(msg2[0].sessionKey)).to.equal(stringify(enc.sessionKey)); @@ -353,7 +355,7 @@ module.exports = () => describe("Packet", function() { '-----END PGP PRIVATE KEY BLOCK-----'; let key = new openpgp.PacketList(); - await key.read((await openpgp.unarmor(armored_key)).data, openpgp); + await key.read((await openpgp.unarmor(armored_key)).data, allAllowedPackets); key = key[0]; const enc = new openpgp.PublicKeyEncryptedSessionKeyPacket(); @@ -420,11 +422,11 @@ module.exports = () => describe("Packet", function() { '-----END PGP MESSAGE-----'; let key = new openpgp.PacketList(); - await key.read((await openpgp.unarmor(armored_key)).data, openpgp); + await key.read((await openpgp.unarmor(armored_key)).data, allAllowedPackets); key = key[3]; const msg = new openpgp.PacketList(); - await msg.read((await openpgp.unarmor(armored_msg)).data, openpgp); + await msg.read((await openpgp.unarmor(armored_msg)).data, allAllowedPackets); return msg[0].decrypt(key).then(async () => { await msg[1].decrypt(msg[0].sessionKeyAlgorithm, msg[0].sessionKey); @@ -462,7 +464,7 @@ module.exports = () => describe("Packet", function() { await seip.encrypt(algo, key, undefined, openpgp.config); const msg2 = new openpgp.PacketList(); - await msg2.read(msg.write(), openpgp); + await msg2.read(msg.write(), allAllowedPackets); await msg2[0].decrypt(passphrase); const key2 = msg2[0].sessionKey; @@ -501,7 +503,7 @@ module.exports = () => describe("Packet", function() { await aeadEnc.encrypt(algo, key, undefined, openpgp.config); const msg2 = new openpgp.PacketList(); - await msg2.read(msg.write(), openpgp); + await msg2.read(msg.write(), allAllowedPackets); await msg2[0].decrypt(passphrase); const key2 = msg2[0].sessionKey; @@ -576,7 +578,7 @@ module.exports = () => describe("Packet", function() { expect(await openpgp.stream.readToEnd(openpgp.stream.clone(data))).to.deep.equal(packetBytes); const msg2 = new openpgp.PacketList(); - await msg2.read(data, openpgp); + await msg2.read(data, allAllowedPackets); await msg2[0].decrypt(passphrase); const key2 = msg2[0].sessionKey; @@ -655,7 +657,7 @@ module.exports = () => describe("Packet", function() { expect(await openpgp.stream.readToEnd(openpgp.stream.clone(data))).to.deep.equal(packetBytes); const msg2 = new openpgp.PacketList(); - await msg2.read(data, openpgp); + await msg2.read(data, allAllowedPackets); await msg2[0].decrypt(passphrase); const key2 = msg2[0].sessionKey; @@ -684,12 +686,12 @@ module.exports = () => describe("Packet", function() { '-----END PGP MESSAGE-----'; let key = new openpgp.PacketList(); - await key.read((await openpgp.unarmor(armored_key)).data, openpgp); + await key.read((await openpgp.unarmor(armored_key)).data, allAllowedPackets); key = key[3]; await key.decrypt('test'); const msg = new openpgp.PacketList(); - await msg.read((await openpgp.unarmor(armored_msg)).data, openpgp); + await msg.read((await openpgp.unarmor(armored_msg)).data, allAllowedPackets); return msg[0].decrypt(key).then(async () => { await msg[1].decrypt(msg[0].sessionKeyAlgorithm, msg[0].sessionKey); @@ -702,7 +704,7 @@ module.exports = () => describe("Packet", function() { it('Secret key reading with signature verification.', async function() { const packets = new openpgp.PacketList(); - await packets.read((await openpgp.unarmor(armored_key)).data, openpgp); + await packets.read((await openpgp.unarmor(armored_key)).data, allAllowedPackets); const [keyPacket, userIDPacket, keySigPacket, subkeyPacket, subkeySigPacket] = packets; expect(keySigPacket.verified).to.be.null; expect(subkeySigPacket.verified).to.be.null; @@ -733,13 +735,13 @@ module.exports = () => describe("Packet", function() { '-----END PGP MESSAGE-----'; const packets = new openpgp.PacketList(); - await packets.read((await openpgp.unarmor(armored_key)).data, openpgp); + await packets.read((await openpgp.unarmor(armored_key)).data, allAllowedPackets); const keyPacket = packets[0]; const subkeyPacket = packets[3]; await subkeyPacket.decrypt('test'); const msg = new openpgp.PacketList(); - await msg.read((await openpgp.unarmor(armored_msg)).data, openpgp); + await msg.read((await openpgp.unarmor(armored_msg)).data, allAllowedPackets); const [pkesk, encData] = msg; return pkesk.decrypt(subkeyPacket).then(async () => { @@ -849,7 +851,7 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ const raw = new openpgp.PacketList(); raw.push(secretKeyPacket); const packetList = new openpgp.PacketList(); - await packetList.read(raw.write(), openpgp, undefined, openpgp.config); + await packetList.read(raw.write(), allAllowedPackets, undefined, openpgp.config); const secretKeyPacket2 = packetList[0]; await secretKeyPacket2.decrypt('hello'); @@ -871,7 +873,7 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ const raw = new openpgp.PacketList(); raw.push(secretKeyPacket); const packetList = new openpgp.PacketList(); - await packetList.read(raw.write(), openpgp, undefined, openpgp.config); + await packetList.read(raw.write(), allAllowedPackets, undefined, openpgp.config); const secretKeyPacket2 = packetList[0]; await secretKeyPacket2.decrypt('hello'); }); @@ -905,7 +907,7 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ const raw = signed.write(); const signed2 = new openpgp.PacketList(); - await signed2.read(raw, openpgp); + await signed2.read(raw, allAllowedPackets); signed2.concat(await openpgp.stream.readToEnd(signed2.stream, arr => arr)); await Promise.all([ From 09f169f620751776fb9b2e52177099e768d5720a Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Mon, 22 Mar 2021 14:30:29 +0100 Subject: [PATCH 16/18] Fix packet import --- src/util.js | 6 ++++-- test/general/key.js | 8 ++++++-- test/general/packet.js | 3 +-- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/util.js b/src/util.js index b8627df96..9c153c551 100644 --- a/src/util.js +++ b/src/util.js @@ -682,10 +682,12 @@ const util = { * @param {Array} allowedClasses * @returns {Object} map from enum.packet to corresponding *Packet class */ - constructAllowedPackets: /*#__PURE__*/ function(allowedClasses) { + constructAllowedPackets: function(allowedClasses) { const map = {}; allowedClasses.forEach(PacketClass => { - if (!PacketClass.tag) return; + if (!PacketClass.tag) { + throw new Error('Invalid input: expected a packet class'); + } map[PacketClass.tag] = PacketClass; }); return map; diff --git a/test/general/key.js b/test/general/key.js index 1742d2348..16b424a9e 100644 --- a/test/general/key.js +++ b/test/general/key.js @@ -4,7 +4,6 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const util = require('../../src/util'); const key = require('../../src/key'); -const allPackets = require('../../src/packet/all_packets'); const chai = require('chai'); chai.use(require('chai-as-promised')); @@ -2785,7 +2784,12 @@ module.exports = () => describe('Key', function() { const packetlist = new openpgp.PacketList(); - await packetlist.read((await openpgp.unarmor(pub_sig_test)).data, util.constructAllowedPackets([...Object.values(allPackets)]), undefined, openpgp.config); + await packetlist.read( + (await openpgp.unarmor(pub_sig_test)).data, + util.constructAllowedPackets([...Object.values(openpgp).filter(packetClass => !!packetClass.tag)]), + undefined, + openpgp.config + ); const subkeys = pubKey.getSubkeys(); expect(subkeys).to.exist; diff --git a/test/general/packet.js b/test/general/packet.js index cbb0b7ab5..bfcc3ca42 100644 --- a/test/general/packet.js +++ b/test/general/packet.js @@ -3,7 +3,6 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const crypto = require('../../src/crypto'); const util = require('../../src/util'); -const allPackets = require('../../src/packet/all_packets'); const stub = require('sinon/lib/sinon/stub'); const chai = require('chai'); @@ -29,7 +28,7 @@ function stringify(array) { } module.exports = () => describe("Packet", function() { - const allAllowedPackets = util.constructAllowedPackets([...Object.values(allPackets)]); + const allAllowedPackets = util.constructAllowedPackets([...Object.values(openpgp).filter(packetClass => !!packetClass.tag)]); const armored_key = '-----BEGIN PGP PRIVATE KEY BLOCK-----\n' + From 10811124fb389cee2e523f1c0dccf2b286646693 Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Thu, 25 Mar 2021 18:46:47 +0100 Subject: [PATCH 17/18] Use static getter for tag --- src/packet/aead_encrypted_data.js | 6 ++++-- src/packet/compressed_data.js | 6 ++++-- src/packet/literal_data.js | 6 ++++-- src/packet/marker.js | 6 ++++-- src/packet/one_pass_signature.js | 6 ++++-- src/packet/public_key.js | 6 ++++-- src/packet/public_key_encrypted_session_key.js | 6 ++++-- src/packet/public_subkey.js | 6 ++++-- src/packet/secret_key.js | 6 ++++-- src/packet/secret_subkey.js | 6 ++++-- src/packet/signature.js | 6 ++++-- src/packet/sym_encrypted_integrity_protected_data.js | 6 ++++-- src/packet/sym_encrypted_session_key.js | 6 ++++-- src/packet/symmetrically_encrypted_data.js | 6 ++++-- src/packet/trust.js | 6 ++++-- src/packet/user_attribute.js | 6 ++++-- src/packet/userid.js | 6 ++++-- 17 files changed, 68 insertions(+), 34 deletions(-) diff --git a/src/packet/aead_encrypted_data.js b/src/packet/aead_encrypted_data.js index 012577529..b7c0ff49f 100644 --- a/src/packet/aead_encrypted_data.js +++ b/src/packet/aead_encrypted_data.js @@ -44,6 +44,10 @@ const VERSION = 1; // A one-octet version number of the data packet. * AEAD Protected Data Packet */ class AEADEncryptedDataPacket { + static get tag() { + return enums.packet.aeadEncryptedData; + } + constructor() { this.version = VERSION; this.cipherAlgo = null; @@ -190,7 +194,5 @@ class AEADEncryptedDataPacket { }); } } -// Static fields (explicit declaration not fully supported by Safari) -AEADEncryptedDataPacket.tag = enums.packet.aeadEncryptedData; export default AEADEncryptedDataPacket; diff --git a/src/packet/compressed_data.js b/src/packet/compressed_data.js index 6e53d89a9..3436e030f 100644 --- a/src/packet/compressed_data.js +++ b/src/packet/compressed_data.js @@ -44,6 +44,10 @@ const allowedPackets = util.constructAllowedPackets([ * a Signature or One-Pass Signature packet, and contains a literal data packet. */ class CompressedDataPacket { + static get tag() { + return enums.packet.compressedData; + } + /** * @param {Object} [config] - Full configuration, defaults to openpgp.config */ @@ -126,8 +130,6 @@ class CompressedDataPacket { this.compressed = compress_fns[this.algorithm](this.packets.write(), this.deflateLevel); } } -// Static fields (explicit declaration not fully supported by Safari) -CompressedDataPacket.tag = enums.packet.compressedData; export default CompressedDataPacket; diff --git a/src/packet/literal_data.js b/src/packet/literal_data.js index 8bfbbfe0d..d9dc12178 100644 --- a/src/packet/literal_data.js +++ b/src/packet/literal_data.js @@ -27,6 +27,10 @@ import util from '../util'; * further interpreted. */ class LiteralDataPacket { + static get tag() { + return enums.packet.literalData; + } + /** * @param {Date} date - The creation date of the literal package */ @@ -158,7 +162,5 @@ class LiteralDataPacket { return util.concat([header, data]); } } -// Static fields (explicit declaration not fully supported by Safari) -LiteralDataPacket.tag = enums.packet.literalData; export default LiteralDataPacket; diff --git a/src/packet/marker.js b/src/packet/marker.js index a9b148ec0..d55df6d17 100644 --- a/src/packet/marker.js +++ b/src/packet/marker.js @@ -31,6 +31,10 @@ import enums from '../enums'; * Such a packet MUST be ignored when received. */ class MarkerPacket { + static get tag() { + return enums.packet.marker; + } + /** * Parsing function for a literal data packet (tag 10). * @@ -52,7 +56,5 @@ class MarkerPacket { return false; } } -// Static fields (explicit declaration not fully supported by Safari) -MarkerPacket.tag = enums.packet.marker; export default MarkerPacket; diff --git a/src/packet/one_pass_signature.js b/src/packet/one_pass_signature.js index 0d36973a2..f4eac15b3 100644 --- a/src/packet/one_pass_signature.js +++ b/src/packet/one_pass_signature.js @@ -32,6 +32,10 @@ import util from '../util'; * can compute the entire signed message in one pass. */ class OnePassSignaturePacket { + static get tag() { + return enums.packet.onePassSignature; + } + constructor() { /** A one-octet version number. The current version is 3. */ this.version = null; @@ -133,7 +137,5 @@ class OnePassSignaturePacket { OnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash; OnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash; OnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign; -// Static fields (explicit declaration not fully supported by Safari) -OnePassSignaturePacket.tag = enums.packet.onePassSignature; export default OnePassSignaturePacket; diff --git a/src/packet/public_key.js b/src/packet/public_key.js index 4722d5207..23b30945d 100644 --- a/src/packet/public_key.js +++ b/src/packet/public_key.js @@ -37,6 +37,10 @@ import util from '../util'; * key (sometimes called an OpenPGP certificate). */ class PublicKeyPacket { + static get tag() { + return enums.packet.publicKey; + } + /** * @param {Date} [date] - Creation date * @param {Object} [config] - Full configuration, defaults to openpgp.config @@ -248,7 +252,5 @@ PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read; * @see PublicKeyPacket#write */ PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write; -// Static fields (explicit declaration not fully supported by Safari) -PublicKeyPacket.tag = enums.packet.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 b2be56de2..79e2a1b96 100644 --- a/src/packet/public_key_encrypted_session_key.js +++ b/src/packet/public_key_encrypted_session_key.js @@ -37,6 +37,10 @@ import util from '../util'; * decrypt the message. */ class PublicKeyEncryptedSessionKeyPacket { + static get tag() { + return enums.packet.publicKeyEncryptedSessionKey; + } + constructor() { this.version = 3; @@ -128,7 +132,5 @@ class PublicKeyEncryptedSessionKeyPacket { return true; } } -// Static fields (explicit declaration not fully supported by Safari) -PublicKeyEncryptedSessionKeyPacket.tag = enums.packet.publicKeyEncryptedSessionKey; export default PublicKeyEncryptedSessionKeyPacket; diff --git a/src/packet/public_subkey.js b/src/packet/public_subkey.js index 85a7ef1c1..eb7514a72 100644 --- a/src/packet/public_subkey.js +++ b/src/packet/public_subkey.js @@ -27,6 +27,10 @@ import enums from '../enums'; * @extends PublicKeyPacket */ class PublicSubkeyPacket extends PublicKeyPacket { + static get tag() { + return enums.packet.publicSubkey; + } + /** * @param {Date} [date] - Creation date * @param {Object} [config] - Full configuration, defaults to openpgp.config @@ -36,7 +40,5 @@ class PublicSubkeyPacket extends PublicKeyPacket { super(date, config); } } -// Static fields (explicit declaration not fully supported by Safari) -PublicSubkeyPacket.tag = enums.packet.publicSubkey; export default PublicSubkeyPacket; diff --git a/src/packet/secret_key.js b/src/packet/secret_key.js index 8f05716ff..ff8706411 100644 --- a/src/packet/secret_key.js +++ b/src/packet/secret_key.js @@ -29,6 +29,10 @@ import defaultConfig from '../config'; * @extends PublicKeyPacket */ class SecretKeyPacket extends PublicKeyPacket { + static get tag() { + return enums.packet.secretKey; + } + /** * @param {Date} [date] - Creation date * @param {Object} [config] - Full configuration, defaults to openpgp.config @@ -427,7 +431,5 @@ async function produceEncryptionKey(s2k, passphrase, algorithm) { crypto.cipher[algorithm].keySize ); } -// Static fields (explicit declaration not fully supported by Safari) -SecretKeyPacket.tag = enums.packet.secretKey; export default SecretKeyPacket; diff --git a/src/packet/secret_subkey.js b/src/packet/secret_subkey.js index 73ce5e62d..a34e06ba6 100644 --- a/src/packet/secret_subkey.js +++ b/src/packet/secret_subkey.js @@ -25,6 +25,10 @@ import defaultConfig from '../config'; * @extends SecretKeyPacket */ class SecretSubkeyPacket extends SecretKeyPacket { + static get tag() { + return enums.packet.secretSubkey; + } + /** * @param {Date} [date] - Creation date * @param {Object} [config] - Full configuration, defaults to openpgp.config @@ -33,7 +37,5 @@ class SecretSubkeyPacket extends SecretKeyPacket { super(date, config); } } -// Static fields (explicit declaration not fully supported by Safari) -SecretSubkeyPacket.tag = enums.packet.secretSubkey; export default SecretSubkeyPacket; diff --git a/src/packet/signature.js b/src/packet/signature.js index cfdf45d8c..17a95971a 100644 --- a/src/packet/signature.js +++ b/src/packet/signature.js @@ -32,6 +32,10 @@ import defaultConfig from '../config'; * block of text, and a signature that is a certification of a User ID. */ class SignaturePacket { + static get tag() { + return enums.packet.signature; + } + /** * @param {Date} date - The creation date of the signature */ @@ -732,8 +736,6 @@ class SignaturePacket { return !this.signatureNeverExpires ? new Date(this.created.getTime() + this.signatureExpirationTime * 1000) : Infinity; } } -// Static fields (explicit declaration not fully supported by Safari) -SignaturePacket.tag = enums.packet.signature; export default SignaturePacket; diff --git a/src/packet/sym_encrypted_integrity_protected_data.js b/src/packet/sym_encrypted_integrity_protected_data.js index 3e20c9767..4f28829a0 100644 --- a/src/packet/sym_encrypted_integrity_protected_data.js +++ b/src/packet/sym_encrypted_integrity_protected_data.js @@ -47,6 +47,10 @@ const VERSION = 1; // A one-octet version number of the data packet. * packet. */ class SymEncryptedIntegrityProtectedDataPacket { + static get tag() { + return enums.packet.symEncryptedIntegrityProtectedData; + } + constructor() { this.version = VERSION; /** The encrypted payload. */ @@ -140,7 +144,5 @@ class SymEncryptedIntegrityProtectedDataPacket { return true; } } -// Static fields (explicit declaration not fully supported by Safari) -SymEncryptedIntegrityProtectedDataPacket.tag = enums.packet.symEncryptedIntegrityProtectedData; export default SymEncryptedIntegrityProtectedDataPacket; diff --git a/src/packet/sym_encrypted_session_key.js b/src/packet/sym_encrypted_session_key.js index 8b51a1f69..afd528d23 100644 --- a/src/packet/sym_encrypted_session_key.js +++ b/src/packet/sym_encrypted_session_key.js @@ -35,6 +35,10 @@ import util from '../util'; * the Symmetric-Key Encrypted Session Key packet. */ class SymEncryptedSessionKeyPacket { + static get tag() { + return enums.packet.symEncryptedSessionKey; + } + /** * @param {Object} [config] - Full configuration, defaults to openpgp.config */ @@ -181,7 +185,5 @@ class SymEncryptedSessionKeyPacket { } } } -// Static fields (explicit declaration not fully supported by Safari) -SymEncryptedSessionKeyPacket.tag = enums.packet.symEncryptedSessionKey; export default SymEncryptedSessionKeyPacket; diff --git a/src/packet/symmetrically_encrypted_data.js b/src/packet/symmetrically_encrypted_data.js index fc23ceaf0..42fb6513f 100644 --- a/src/packet/symmetrically_encrypted_data.js +++ b/src/packet/symmetrically_encrypted_data.js @@ -45,6 +45,10 @@ const allowedPackets = util.constructAllowedPackets([ * that form whole OpenPGP messages). */ class SymmetricallyEncryptedDataPacket { + static get tag() { + return enums.packet.symmetricallyEncryptedData; + } + constructor() { /** * Encrypted secret-key data @@ -108,7 +112,5 @@ class SymmetricallyEncryptedDataPacket { this.encrypted = util.concat([FRE, ciphertext]); } } -// Static fields (explicit declaration not fully supported by Safari) -SymmetricallyEncryptedDataPacket.tag = enums.packet.symmetricallyEncryptedData; export default SymmetricallyEncryptedDataPacket; diff --git a/src/packet/trust.js b/src/packet/trust.js index e7d96f77a..b1aeec4f4 100644 --- a/src/packet/trust.js +++ b/src/packet/trust.js @@ -18,6 +18,10 @@ import enums from '../enums'; * other than local keyring files. */ class TrustPacket { + static get tag() { + return enums.packet.trust; + } + /** * Parsing function for a trust packet (tag 12). * Currently not implemented as we ignore trust packets @@ -25,7 +29,5 @@ class TrustPacket { */ read() {} // TODO } -// Static fields (explicit declaration not fully supported by Safari) -TrustPacket.tag = enums.packet.trust; export default TrustPacket; diff --git a/src/packet/user_attribute.js b/src/packet/user_attribute.js index 73e44b172..b05052287 100644 --- a/src/packet/user_attribute.js +++ b/src/packet/user_attribute.js @@ -37,6 +37,10 @@ import util from '../util'; * an implementation may use any method desired. */ class UserAttributePacket { + static get tag() { + return enums.packet.userAttribute; + } + constructor() { this.attributes = []; } @@ -83,7 +87,5 @@ class UserAttributePacket { }); } } -// Static fields (explicit declaration not fully supported by Safari) -UserAttributePacket.tag = enums.packet.userAttribute; export default UserAttributePacket; diff --git a/src/packet/userid.js b/src/packet/userid.js index a188de267..da4863ec6 100644 --- a/src/packet/userid.js +++ b/src/packet/userid.js @@ -31,6 +31,10 @@ import defaultConfig from '../config'; * specifies the length of the User ID. */ class UserIDPacket { + static get tag() { + return enums.packet.userID; + } + constructor() { /** A string containing the user id. Usually in the form * John Doe @@ -92,7 +96,5 @@ class UserIDPacket { return util.encodeUTF8(this.userID); } } -// Static fields (explicit declaration not fully supported by Safari) -UserIDPacket.tag = enums.packet.userID; export default UserIDPacket; From 128d10fb43a6c0981960aac69e5e1c254ddf8f0c Mon Sep 17 00:00:00 2001 From: Daniel Huigens Date: Thu, 25 Mar 2021 18:13:52 +0100 Subject: [PATCH 18/18] Mark allowed packets as pure --- src/cleartext.js | 2 +- src/key/factory.js | 2 +- src/key/key.js | 2 +- src/message.js | 6 +++--- src/packet/aead_encrypted_data.js | 2 +- src/packet/compressed_data.js | 2 +- src/packet/sym_encrypted_integrity_protected_data.js | 2 +- src/packet/symmetrically_encrypted_data.js | 2 +- src/signature.js | 2 +- 9 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/cleartext.js b/src/cleartext.js index 797fb6c6b..8069051a0 100644 --- a/src/cleartext.js +++ b/src/cleartext.js @@ -24,7 +24,7 @@ import { createVerificationObjects, createSignaturePackets } from './message'; import defaultConfig from './config'; // A Cleartext message can contain the following packets -const allowedPackets = util.constructAllowedPackets([SignaturePacket]); +const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); /** * Class that represents an OpenPGP cleartext signed message. diff --git a/src/key/factory.js b/src/key/factory.js index e323df80a..a1e0b65c5 100644 --- a/src/key/factory.js +++ b/src/key/factory.js @@ -33,7 +33,7 @@ import defaultConfig from '../config'; import { unarmor } from '../encoding/armor'; // A Key can contain the following packets -const allowedKeyPackets = util.constructAllowedPackets([ +const allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([ PublicKeyPacket, PublicSubkeyPacket, SecretKeyPacket, diff --git a/src/key/key.js b/src/key/key.js index 8e722c85a..b9f7e4131 100644 --- a/src/key/key.js +++ b/src/key/key.js @@ -30,7 +30,7 @@ import SubKey from './subkey'; import * as helper from './helper'; // A key revocation certificate can contain the following packets -const allowedRevocationPackets = util.constructAllowedPackets([SignaturePacket]); +const allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); /** * Class that represents an OpenPGP key. Must contain a primary key. diff --git a/src/message.js b/src/message.js index 58687a39d..6b958c46b 100644 --- a/src/message.js +++ b/src/message.js @@ -38,7 +38,7 @@ import { } from './packet'; // A Message can contain the following packets -const allowedMessagePackets = util.constructAllowedPackets([ +const allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([ LiteralDataPacket, CompressedDataPacket, AEADEncryptedDataPacket, @@ -50,9 +50,9 @@ const allowedMessagePackets = util.constructAllowedPackets([ SignaturePacket ]); // A SKESK packet can contain the following packets -const allowedSymSessionKeyPackets = util.constructAllowedPackets([SymEncryptedSessionKeyPacket]); +const allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]); // A detached signature can contain the following packets -const allowedDetachedSignaturePackets = util.constructAllowedPackets([SignaturePacket]); +const allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); /** * Class that represents an OpenPGP message. diff --git a/src/packet/aead_encrypted_data.js b/src/packet/aead_encrypted_data.js index b7c0ff49f..db999de34 100644 --- a/src/packet/aead_encrypted_data.js +++ b/src/packet/aead_encrypted_data.js @@ -27,7 +27,7 @@ import OnePassSignaturePacket from './one_pass_signature'; import SignaturePacket from './signature'; // An AEAD-encrypted Data packet can contain the following packet types -const allowedPackets = util.constructAllowedPackets([ +const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([ LiteralDataPacket, CompressedDataPacket, OnePassSignaturePacket, diff --git a/src/packet/compressed_data.js b/src/packet/compressed_data.js index 3436e030f..fdf32dd08 100644 --- a/src/packet/compressed_data.js +++ b/src/packet/compressed_data.js @@ -29,7 +29,7 @@ import OnePassSignaturePacket from './one_pass_signature'; import SignaturePacket from './signature'; // A Compressed Data packet can contain the following packet types -const allowedPackets = util.constructAllowedPackets([ +const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([ LiteralDataPacket, OnePassSignaturePacket, SignaturePacket diff --git a/src/packet/sym_encrypted_integrity_protected_data.js b/src/packet/sym_encrypted_integrity_protected_data.js index 4f28829a0..020dedc42 100644 --- a/src/packet/sym_encrypted_integrity_protected_data.js +++ b/src/packet/sym_encrypted_integrity_protected_data.js @@ -27,7 +27,7 @@ import OnePassSignaturePacket from './one_pass_signature'; import SignaturePacket from './signature'; // A SEIP packet can contain the following packet types -const allowedPackets = util.constructAllowedPackets([ +const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([ LiteralDataPacket, CompressedDataPacket, OnePassSignaturePacket, diff --git a/src/packet/symmetrically_encrypted_data.js b/src/packet/symmetrically_encrypted_data.js index 42fb6513f..763eb7a0d 100644 --- a/src/packet/symmetrically_encrypted_data.js +++ b/src/packet/symmetrically_encrypted_data.js @@ -27,7 +27,7 @@ import OnePassSignaturePacket from './one_pass_signature'; import SignaturePacket from './signature'; // A SE packet can contain the following packet types -const allowedPackets = util.constructAllowedPackets([ +const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([ LiteralDataPacket, CompressedDataPacket, OnePassSignaturePacket, diff --git a/src/signature.js b/src/signature.js index 88588c109..ef8eb84d7 100644 --- a/src/signature.js +++ b/src/signature.js @@ -22,7 +22,7 @@ import util from './util'; import defaultConfig from './config'; // A Signature can contain the following packets -const allowedPackets = util.constructAllowedPackets([SignaturePacket]); +const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); /** * Class that represents an OpenPGP signature.