@protontech/openpgp 4.10.5 → 5.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +311 -239
  2. package/dist/lightweight/bn.interface.min.mjs +3 -0
  3. package/dist/lightweight/bn.interface.min.mjs.map +1 -0
  4. package/dist/lightweight/bn.interface.mjs +340 -0
  5. package/dist/lightweight/bn.min.mjs +3 -0
  6. package/dist/lightweight/bn.min.mjs.map +1 -0
  7. package/dist/lightweight/bn.mjs +3434 -0
  8. package/dist/lightweight/elliptic.min.mjs +3 -0
  9. package/dist/lightweight/elliptic.min.mjs.map +1 -0
  10. package/dist/lightweight/elliptic.mjs +4313 -0
  11. package/dist/lightweight/openpgp.min.mjs +3 -0
  12. package/dist/lightweight/openpgp.min.mjs.map +1 -0
  13. package/dist/lightweight/openpgp.mjs +31375 -0
  14. package/dist/lightweight/ponyfill.es6.min.mjs +3 -0
  15. package/dist/lightweight/ponyfill.es6.min.mjs.map +1 -0
  16. package/dist/lightweight/ponyfill.es6.mjs +3831 -0
  17. package/dist/lightweight/web-streams-adapter.min.mjs +17 -0
  18. package/dist/lightweight/web-streams-adapter.min.mjs.map +1 -0
  19. package/dist/lightweight/web-streams-adapter.mjs +561 -0
  20. package/dist/node/openpgp.js +43943 -0
  21. package/dist/node/openpgp.min.js +17 -0
  22. package/dist/node/openpgp.min.js.map +1 -0
  23. package/dist/node/openpgp.min.mjs +17 -0
  24. package/dist/node/openpgp.min.mjs.map +1 -0
  25. package/dist/node/openpgp.mjs +43880 -0
  26. package/dist/openpgp.js +41080 -41565
  27. package/dist/openpgp.min.js +17 -2
  28. package/dist/openpgp.min.js.map +1 -0
  29. package/dist/openpgp.min.mjs +17 -0
  30. package/dist/openpgp.min.mjs.map +1 -0
  31. package/dist/openpgp.mjs +43868 -0
  32. package/lightweight/package.json +5 -0
  33. package/openpgp.d.ts +889 -0
  34. package/package.json +63 -57
  35. package/dist/compat/openpgp.js +0 -61067
  36. package/dist/compat/openpgp.min.js +0 -2
  37. package/dist/compat/openpgp.worker.js +0 -173
  38. package/dist/compat/openpgp.worker.min.js +0 -2
  39. package/dist/lightweight/elliptic.min.js +0 -5
  40. package/dist/lightweight/openpgp.js +0 -40024
  41. package/dist/lightweight/openpgp.min.js +0 -2
  42. package/dist/lightweight/openpgp.worker.js +0 -173
  43. package/dist/lightweight/openpgp.worker.min.js +0 -2
  44. package/dist/openpgp.worker.js +0 -173
  45. package/dist/openpgp.worker.min.js +0 -2
  46. package/src/cleartext.js +0 -220
  47. package/src/config/config.js +0 -224
  48. package/src/config/index.js +0 -7
  49. package/src/config/localStorage.js +0 -35
  50. package/src/crypto/aes_kw.js +0 -153
  51. package/src/crypto/cfb.js +0 -169
  52. package/src/crypto/cipher/aes.js +0 -27
  53. package/src/crypto/cipher/blowfish.js +0 -398
  54. package/src/crypto/cipher/cast5.js +0 -610
  55. package/src/crypto/cipher/des.js +0 -476
  56. package/src/crypto/cipher/index.js +0 -91
  57. package/src/crypto/cipher/twofish.js +0 -346
  58. package/src/crypto/cmac.js +0 -98
  59. package/src/crypto/crypto.js +0 -394
  60. package/src/crypto/eax.js +0 -172
  61. package/src/crypto/gcm.js +0 -141
  62. package/src/crypto/hash/index.js +0 -163
  63. package/src/crypto/hash/md5.js +0 -205
  64. package/src/crypto/index.js +0 -57
  65. package/src/crypto/ocb.js +0 -274
  66. package/src/crypto/pkcs1.js +0 -170
  67. package/src/crypto/pkcs5.js +0 -55
  68. package/src/crypto/public_key/dsa.js +0 -188
  69. package/src/crypto/public_key/elgamal.js +0 -137
  70. package/src/crypto/public_key/elliptic/curves.js +0 -385
  71. package/src/crypto/public_key/elliptic/ecdh.js +0 -414
  72. package/src/crypto/public_key/elliptic/ecdsa.js +0 -348
  73. package/src/crypto/public_key/elliptic/eddsa.js +0 -119
  74. package/src/crypto/public_key/elliptic/index.js +0 -34
  75. package/src/crypto/public_key/elliptic/indutnyKey.js +0 -85
  76. package/src/crypto/public_key/index.js +0 -28
  77. package/src/crypto/public_key/prime.js +0 -275
  78. package/src/crypto/public_key/rsa.js +0 -597
  79. package/src/crypto/random.js +0 -145
  80. package/src/crypto/signature.js +0 -137
  81. package/src/encoding/armor.js +0 -433
  82. package/src/encoding/base64.js +0 -96
  83. package/src/enums.js +0 -493
  84. package/src/hkp.js +0 -89
  85. package/src/index.js +0 -161
  86. package/src/key/factory.js +0 -326
  87. package/src/key/helper.js +0 -363
  88. package/src/key/index.js +0 -32
  89. package/src/key/key.js +0 -890
  90. package/src/key/subkey.js +0 -187
  91. package/src/key/user.js +0 -230
  92. package/src/keyring/index.js +0 -12
  93. package/src/keyring/keyring.js +0 -229
  94. package/src/keyring/localstore.js +0 -119
  95. package/src/lightweight_helper.js +0 -26
  96. package/src/message.js +0 -825
  97. package/src/openpgp.js +0 -717
  98. package/src/packet/all_packets.js +0 -116
  99. package/src/packet/clone.js +0 -189
  100. package/src/packet/compressed.js +0 -194
  101. package/src/packet/index.js +0 -20
  102. package/src/packet/literal.js +0 -168
  103. package/src/packet/marker.js +0 -62
  104. package/src/packet/one_pass_signature.js +0 -156
  105. package/src/packet/packet.js +0 -300
  106. package/src/packet/packetlist.js +0 -232
  107. package/src/packet/public_key.js +0 -280
  108. package/src/packet/public_key_encrypted_session_key.js +0 -156
  109. package/src/packet/public_subkey.js +0 -44
  110. package/src/packet/secret_key.js +0 -448
  111. package/src/packet/secret_subkey.js +0 -41
  112. package/src/packet/signature.js +0 -782
  113. package/src/packet/sym_encrypted_aead_protected.js +0 -189
  114. package/src/packet/sym_encrypted_integrity_protected.js +0 -139
  115. package/src/packet/sym_encrypted_session_key.js +0 -204
  116. package/src/packet/symmetrically_encrypted.js +0 -118
  117. package/src/packet/trust.js +0 -35
  118. package/src/packet/user_attribute.js +0 -94
  119. package/src/packet/userid.js +0 -87
  120. package/src/polyfills.js +0 -64
  121. package/src/signature.js +0 -73
  122. package/src/type/ecdh_symkey.js +0 -69
  123. package/src/type/kdf_params.js +0 -114
  124. package/src/type/keyid.js +0 -110
  125. package/src/type/mpi.js +0 -138
  126. package/src/type/oid.js +0 -110
  127. package/src/type/s2k.js +0 -203
  128. package/src/util.js +0 -836
  129. package/src/wkd.js +0 -88
  130. package/src/worker/async_proxy.js +0 -190
  131. package/src/worker/worker.js +0 -167
  132. package/test/crypto/aes_kw.js +0 -57
  133. package/test/crypto/cipher/aes.js +0 -86
  134. package/test/crypto/cipher/blowfish.js +0 -58
  135. package/test/crypto/cipher/cast5.js +0 -25
  136. package/test/crypto/cipher/des.js +0 -143
  137. package/test/crypto/cipher/index.js +0 -7
  138. package/test/crypto/cipher/twofish.js +0 -71
  139. package/test/crypto/crypto.js +0 -383
  140. package/test/crypto/eax.js +0 -150
  141. package/test/crypto/ecdh.js +0 -359
  142. package/test/crypto/elliptic.js +0 -251
  143. package/test/crypto/elliptic_data.js +0 -102
  144. package/test/crypto/hash/index.js +0 -5
  145. package/test/crypto/hash/md5.js +0 -16
  146. package/test/crypto/hash/ripemd.js +0 -14
  147. package/test/crypto/hash/sha.js +0 -20
  148. package/test/crypto/index.js +0 -14
  149. package/test/crypto/ocb.js +0 -183
  150. package/test/crypto/pkcs5.js +0 -39
  151. package/test/crypto/random.js +0 -79
  152. package/test/crypto/rsa.js +0 -180
  153. package/test/crypto/validate.js +0 -387
  154. package/test/general/armor.js +0 -408
  155. package/test/general/brainpool.js +0 -360
  156. package/test/general/decompression.js +0 -60
  157. package/test/general/ecc_nist.js +0 -115
  158. package/test/general/ecc_secp256k1.js +0 -242
  159. package/test/general/forwarding.js +0 -43
  160. package/test/general/hkp.js +0 -165
  161. package/test/general/index.js +0 -20
  162. package/test/general/key.js +0 -3402
  163. package/test/general/keyring.js +0 -336
  164. package/test/general/oid.js +0 -39
  165. package/test/general/openpgp.js +0 -2542
  166. package/test/general/packet.js +0 -937
  167. package/test/general/signature.js +0 -1665
  168. package/test/general/streaming.js +0 -944
  169. package/test/general/testInputs.js +0 -18
  170. package/test/general/util.js +0 -183
  171. package/test/general/wkd.js +0 -48
  172. package/test/general/x25519.js +0 -556
  173. package/test/unittests.js +0 -64
package/src/message.js DELETED
@@ -1,825 +0,0 @@
1
- // GPG4Browsers - An OpenPGP implementation in javascript
2
- // Copyright (C) 2011 Recurity Labs GmbH
3
- //
4
- // This library is free software; you can redistribute it and/or
5
- // modify it under the terms of the GNU Lesser General Public
6
- // License as published by the Free Software Foundation; either
7
- // version 3.0 of the License, or (at your option) any later version.
8
- //
9
- // This library is distributed in the hope that it will be useful,
10
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12
- // Lesser General Public License for more details.
13
- //
14
- // You should have received a copy of the GNU Lesser General Public
15
- // License along with this library; if not, write to the Free Software
16
- // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
-
18
- /**
19
- * @requires web-stream-tools
20
- * @requires encoding/armor
21
- * @requires type/keyid
22
- * @requires config
23
- * @requires crypto
24
- * @requires enums
25
- * @requires util
26
- * @requires packet
27
- * @requires signature
28
- * @requires key
29
- * @module message
30
- */
31
-
32
- import stream from 'web-stream-tools';
33
- import armor from './encoding/armor';
34
- import type_keyid from './type/keyid';
35
- import config from './config';
36
- import crypto from './crypto';
37
- import enums from './enums';
38
- import util from './util';
39
- import packet from './packet';
40
- import { Signature } from './signature';
41
- import { getPreferredHashAlgo, getPreferredAlgo, isAeadSupported, createSignaturePacket } from './key';
42
-
43
-
44
- /**
45
- * @class
46
- * @classdesc Class that represents an OpenPGP message.
47
- * Can be an encrypted message, signed message, compressed message or literal message
48
- * @param {module:packet.List} packetlist The packets that form this message
49
- * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}
50
- */
51
-
52
- export function Message(packetlist) {
53
- if (!(this instanceof Message)) {
54
- return new Message(packetlist);
55
- }
56
- this.packets = packetlist || new packet.List();
57
- }
58
-
59
- /**
60
- * Returns the key IDs of the keys to which the session key is encrypted
61
- * @returns {Array<module:type/keyid>} array of keyid objects
62
- */
63
- Message.prototype.getEncryptionKeyIds = function() {
64
- const keyIds = [];
65
- const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);
66
- pkESKeyPacketlist.forEach(function(packet) {
67
- keyIds.push(packet.publicKeyId);
68
- });
69
- return keyIds;
70
- };
71
-
72
- /**
73
- * Returns the key IDs of the keys that signed the message
74
- * @returns {Array<module:type/keyid>} array of keyid objects
75
- */
76
- Message.prototype.getSigningKeyIds = function() {
77
- const keyIds = [];
78
- const msg = this.unwrapCompressed();
79
- // search for one pass signatures
80
- const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature);
81
- onePassSigList.forEach(function(packet) {
82
- keyIds.push(packet.issuerKeyId);
83
- });
84
- // if nothing found look for signature packets
85
- if (!keyIds.length) {
86
- const signatureList = msg.packets.filterByTag(enums.packet.signature);
87
- signatureList.forEach(function(packet) {
88
- keyIds.push(packet.issuerKeyId);
89
- });
90
- }
91
- return keyIds;
92
- };
93
-
94
- /**
95
- * Decrypt the message. Either a private key, a session key, or a password must be specified.
96
- * @param {Array<Key>} privateKeys (optional) private keys with decrypted secret data
97
- * @param {Array<String>} passwords (optional) passwords used to decrypt
98
- * @param {Array<Object>} sessionKeys (optional) session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
99
- * @param {Boolean} streaming (optional) whether to process data as a stream
100
- * @returns {Promise<Message>} new message with decrypted content
101
- * @async
102
- */
103
- Message.prototype.decrypt = async function(privateKeys, passwords, sessionKeys, streaming) {
104
- const keyObjs = sessionKeys || await this.decryptSessionKeys(privateKeys, passwords);
105
-
106
- const symEncryptedPacketlist = this.packets.filterByTag(
107
- enums.packet.symmetricallyEncrypted,
108
- enums.packet.symEncryptedIntegrityProtected,
109
- enums.packet.symEncryptedAEADProtected
110
- );
111
-
112
- if (symEncryptedPacketlist.length === 0) {
113
- return this;
114
- }
115
-
116
- const symEncryptedPacket = symEncryptedPacketlist[0];
117
- let exception = null;
118
- const decryptedPromise = Promise.all(keyObjs.map(async keyObj => {
119
- if (!keyObj || !util.isUint8Array(keyObj.data) || !util.isString(keyObj.algorithm)) {
120
- throw new Error('Invalid session key for decryption.');
121
- }
122
-
123
- try {
124
- await symEncryptedPacket.decrypt(keyObj.algorithm, keyObj.data, streaming);
125
- } catch (e) {
126
- util.print_debug_error(e);
127
- exception = e;
128
- }
129
- }));
130
- // We don't await stream.cancel here because it only returns when the other copy is canceled too.
131
- stream.cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.
132
- symEncryptedPacket.encrypted = null;
133
- await decryptedPromise;
134
-
135
- if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {
136
- throw exception || new Error('Decryption failed.');
137
- }
138
-
139
- const resultMsg = new Message(symEncryptedPacket.packets);
140
- symEncryptedPacket.packets = new packet.List(); // remove packets after decryption
141
-
142
- return resultMsg;
143
- };
144
-
145
- /**
146
- * Decrypt encrypted session keys either with private keys or passwords.
147
- * @param {Array<Key>} privateKeys (optional) private keys with decrypted secret data
148
- * @param {Array<String>} passwords (optional) passwords used to decrypt
149
- * @returns {Promise<Array<{ data: Uint8Array,
150
- algorithm: String }>>} array of object with potential sessionKey, algorithm pairs
151
- * @async
152
- */
153
- Message.prototype.decryptSessionKeys = async function(privateKeys, passwords) {
154
- let keyPackets = [];
155
-
156
- let exception;
157
- if (passwords) {
158
- const symESKeyPacketlist = this.packets.filterByTag(enums.packet.symEncryptedSessionKey);
159
- if (!symESKeyPacketlist) {
160
- throw new Error('No symmetrically encrypted session key packet found.');
161
- }
162
- await Promise.all(passwords.map(async function(password, i) {
163
- let packets;
164
- if (i) {
165
- packets = new packet.List();
166
- await packets.read(symESKeyPacketlist.write());
167
- } else {
168
- packets = symESKeyPacketlist;
169
- }
170
- await Promise.all(packets.map(async function(keyPacket) {
171
- try {
172
- await keyPacket.decrypt(password);
173
- keyPackets.push(keyPacket);
174
- } catch (err) {
175
- util.print_debug_error(err);
176
- }
177
- }));
178
- }));
179
- } else if (privateKeys) {
180
- const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);
181
- if (!pkESKeyPacketlist) {
182
- throw new Error('No public key encrypted session key packet found.');
183
- }
184
- await Promise.all(pkESKeyPacketlist.map(async function(keyPacket) {
185
- await Promise.all(privateKeys.map(async function(privateKey) {
186
- let algos = [
187
- enums.symmetric.aes256, // Old OpenPGP.js default fallback
188
- enums.symmetric.aes128, // RFC4880bis fallback
189
- enums.symmetric.tripledes, // RFC4880 fallback
190
- enums.symmetric.cast5 // Golang OpenPGP fallback
191
- ];
192
- try {
193
- const primaryUser = await privateKey.getPrimaryUser(); // TODO: Pass userId from somewhere.
194
- if (primaryUser.selfCertification.preferredSymmetricAlgorithms) {
195
- algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms);
196
- }
197
- } catch (e) {}
198
-
199
- // do not check key expiration to allow decryption of old messages
200
- const privateKeyPackets = (await privateKey.getDecryptionKeys(keyPacket.publicKeyId, null)).map(key => key.keyPacket);
201
- await Promise.all(privateKeyPackets.map(async function(privateKeyPacket) {
202
- if (!privateKeyPacket) {
203
- return;
204
- }
205
- if (!privateKeyPacket.isDecrypted()) {
206
- throw new Error('Private key is not decrypted.');
207
- }
208
- try {
209
- await keyPacket.decrypt(privateKeyPacket);
210
- if (!algos.includes(enums.write(enums.symmetric, keyPacket.sessionKeyAlgorithm))) {
211
- throw new Error('A non-preferred symmetric algorithm was used.');
212
- }
213
- keyPackets.push(keyPacket);
214
- } catch (err) {
215
- util.print_debug_error(err);
216
- exception = err;
217
- }
218
- }));
219
- }));
220
- stream.cancel(keyPacket.encrypted); // Don't keep copy of encrypted data in memory.
221
- keyPacket.encrypted = null;
222
- }));
223
- } else {
224
- throw new Error('No key or password specified.');
225
- }
226
-
227
- if (keyPackets.length) {
228
- // Return only unique session keys
229
- if (keyPackets.length > 1) {
230
- const seen = {};
231
- keyPackets = keyPackets.filter(function(item) {
232
- const k = item.sessionKeyAlgorithm + util.Uint8Array_to_str(item.sessionKey);
233
- if (seen.hasOwnProperty(k)) {
234
- return false;
235
- }
236
- seen[k] = true;
237
- return true;
238
- });
239
- }
240
-
241
- return keyPackets.map(packet => ({ data: packet.sessionKey, algorithm: packet.sessionKeyAlgorithm }));
242
- }
243
- throw exception || new Error('Session key decryption failed.');
244
- };
245
-
246
- /**
247
- * Get literal data that is the body of the message
248
- * @returns {(Uint8Array|null)} literal body of the message as Uint8Array
249
- */
250
- Message.prototype.getLiteralData = function() {
251
- const msg = this.unwrapCompressed();
252
- const literal = msg.packets.findPacket(enums.packet.literal);
253
- return (literal && literal.getBytes()) || null;
254
- };
255
-
256
- /**
257
- * Get filename from literal data packet
258
- * @returns {(String|null)} filename of literal data packet as string
259
- */
260
- Message.prototype.getFilename = function() {
261
- const msg = this.unwrapCompressed();
262
- const literal = msg.packets.findPacket(enums.packet.literal);
263
- return (literal && literal.getFilename()) || null;
264
- };
265
-
266
- /**
267
- * Get literal data as text
268
- * @returns {(String|null)} literal body of the message interpreted as text
269
- */
270
- Message.prototype.getText = function() {
271
- const msg = this.unwrapCompressed();
272
- const literal = msg.packets.findPacket(enums.packet.literal);
273
- if (literal) {
274
- return literal.getText();
275
- }
276
- return null;
277
- };
278
-
279
- /**
280
- * Encrypt the message either with public keys, passwords, or both at once.
281
- * @param {Array<Key>} keys (optional) public key(s) for message encryption
282
- * @param {Array<String>} passwords (optional) password(s) for message encryption
283
- * @param {Object} sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
284
- * @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs
285
- * @param {Date} date (optional) override the creation date of the literal package
286
- * @param {Array} userIds (optional) user IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
287
- * @param {Boolean} streaming (optional) whether to process data as a stream
288
- * @returns {Promise<Message>} new message with encrypted content
289
- * @async
290
- */
291
- Message.prototype.encrypt = async function(keys, passwords, sessionKey, wildcard = false, date = new Date(), userIds = [], streaming) {
292
- let symAlgo;
293
- let aeadAlgo;
294
- let symEncryptedPacket;
295
-
296
- if (sessionKey) {
297
- if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) {
298
- throw new Error('Invalid session key for encryption.');
299
- }
300
- symAlgo = sessionKey.algorithm;
301
- aeadAlgo = sessionKey.aeadAlgorithm;
302
- sessionKey = sessionKey.data;
303
- } else if (keys && keys.length) {
304
- symAlgo = enums.read(enums.symmetric, await getPreferredAlgo('symmetric', keys, date, userIds));
305
- if (config.aead_protect && await isAeadSupported(keys, date, userIds)) {
306
- aeadAlgo = enums.read(enums.aead, await getPreferredAlgo('aead', keys, date, userIds));
307
- }
308
- } else if (passwords && passwords.length) {
309
- symAlgo = enums.read(enums.symmetric, config.encryption_cipher);
310
- aeadAlgo = enums.read(enums.aead, config.aead_mode);
311
- } else {
312
- throw new Error('No keys, passwords, or session key provided.');
313
- }
314
-
315
- if (!sessionKey) {
316
- sessionKey = await crypto.generateSessionKey(symAlgo);
317
- }
318
-
319
- const msg = await encryptSessionKey(sessionKey, symAlgo, aeadAlgo, keys, passwords, wildcard, date, userIds);
320
-
321
- if (config.aead_protect && aeadAlgo) {
322
- symEncryptedPacket = new packet.SymEncryptedAEADProtected();
323
- symEncryptedPacket.aeadAlgorithm = aeadAlgo;
324
- } else if (config.integrity_protect) {
325
- symEncryptedPacket = new packet.SymEncryptedIntegrityProtected();
326
- } else {
327
- symEncryptedPacket = new packet.SymmetricallyEncrypted();
328
- }
329
- symEncryptedPacket.packets = this.packets;
330
-
331
- await symEncryptedPacket.encrypt(symAlgo, sessionKey, streaming);
332
-
333
- msg.packets.push(symEncryptedPacket);
334
- symEncryptedPacket.packets = new packet.List(); // remove packets after encryption
335
- return {
336
- message: msg,
337
- sessionKey: {
338
- data: sessionKey,
339
- algorithm: symAlgo,
340
- aeadAlgorithm: aeadAlgo
341
- }
342
- };
343
- };
344
-
345
- /**
346
- * Encrypt a session key either with public keys, passwords, or both at once.
347
- * @param {Uint8Array} sessionKey session key for encryption
348
- * @param {String} symAlgo session key algorithm
349
- * @param {String} aeadAlgo (optional) aead algorithm, e.g. 'eax' or 'ocb'
350
- * @param {Array<Key>} publicKeys (optional) public key(s) for message encryption
351
- * @param {Array<String>} passwords (optional) for message encryption
352
- * @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs
353
- * @param {Date} date (optional) override the date
354
- * @param {Array} userIds (optional) user IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
355
- * @returns {Promise<Message>} new message with encrypted content
356
- * @async
357
- */
358
- export async function encryptSessionKey(sessionKey, symAlgo, aeadAlgo, publicKeys, passwords, wildcard = false, date = new Date(), userIds = []) {
359
- const packetlist = new packet.List();
360
-
361
- if (publicKeys) {
362
- const results = await Promise.all(publicKeys.map(async function(publicKey) {
363
- const encryptionKey = await publicKey.getEncryptionKey(undefined, date, userIds);
364
- const pkESKeyPacket = new packet.PublicKeyEncryptedSessionKey();
365
- pkESKeyPacket.publicKeyId = wildcard ? type_keyid.wildcard() : encryptionKey.getKeyId();
366
- pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm;
367
- pkESKeyPacket.sessionKey = sessionKey;
368
- pkESKeyPacket.sessionKeyAlgorithm = symAlgo;
369
- await pkESKeyPacket.encrypt(encryptionKey.keyPacket);
370
- delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption
371
- return pkESKeyPacket;
372
- }));
373
- packetlist.concat(results);
374
- }
375
- if (passwords) {
376
- const testDecrypt = async function(keyPacket, password) {
377
- try {
378
- await keyPacket.decrypt(password);
379
- return 1;
380
- } catch (e) {
381
- return 0;
382
- }
383
- };
384
-
385
- const sum = (accumulator, currentValue) => accumulator + currentValue;
386
-
387
- const encryptPassword = async function(sessionKey, symAlgo, aeadAlgo, password) {
388
- const symEncryptedSessionKeyPacket = new packet.SymEncryptedSessionKey();
389
- symEncryptedSessionKeyPacket.sessionKey = sessionKey;
390
- symEncryptedSessionKeyPacket.sessionKeyAlgorithm = symAlgo;
391
- if (aeadAlgo) {
392
- symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgo;
393
- }
394
- await symEncryptedSessionKeyPacket.encrypt(password);
395
-
396
- if (config.password_collision_check) {
397
- const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));
398
- if (results.reduce(sum) !== 1) {
399
- return encryptPassword(sessionKey, symAlgo, password);
400
- }
401
- }
402
-
403
- delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption
404
- return symEncryptedSessionKeyPacket;
405
- };
406
-
407
- const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, symAlgo, aeadAlgo, pwd)));
408
- packetlist.concat(results);
409
- }
410
-
411
- return new Message(packetlist);
412
- }
413
-
414
- /**
415
- * Sign the message (the literal data packet of the message)
416
- * @param {Array<module:key.Key>} privateKeys private keys with decrypted secret key data for signing
417
- * @param {Signature} signature (optional) any existing detached signature to add to the message
418
- * @param {Date} date (optional) override the creation time of the signature
419
- * @param {Array} userIds (optional) user IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
420
- * @param {Boolean} streaming (optional) whether to process data as a stream
421
- * @returns {Promise<Message>} new message with signed content
422
- * @async
423
- */
424
- Message.prototype.sign = async function(privateKeys = [], signature = null, date = new Date(), userIds = [], streaming = false) {
425
- const packetlist = new packet.List();
426
-
427
- const literalDataPacket = this.packets.findPacket(enums.packet.literal);
428
- if (!literalDataPacket) {
429
- throw new Error('No literal data packet to sign.');
430
- }
431
-
432
- let i;
433
- let existingSigPacketlist;
434
- // If data packet was created from Uint8Array, use binary, otherwise use text
435
- const signatureType = literalDataPacket.text === null ?
436
- enums.signature.binary : enums.signature.text;
437
-
438
- if (signature) {
439
- existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);
440
- for (i = existingSigPacketlist.length - 1; i >= 0; i--) {
441
- const signaturePacket = existingSigPacketlist[i];
442
- const onePassSig = new packet.OnePassSignature();
443
- onePassSig.signatureType = signaturePacket.signatureType;
444
- onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;
445
- onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;
446
- onePassSig.issuerKeyId = signaturePacket.issuerKeyId;
447
- if (!privateKeys.length && i === 0) {
448
- onePassSig.flags = 1;
449
- }
450
- packetlist.push(onePassSig);
451
- }
452
- }
453
-
454
- await Promise.all(Array.from(privateKeys).reverse().map(async function (privateKey, i) {
455
- if (privateKey.isPublic()) {
456
- throw new Error('Need private key for signing');
457
- }
458
- const signingKey = await privateKey.getSigningKey(undefined, date, userIds);
459
- const onePassSig = new packet.OnePassSignature();
460
- onePassSig.signatureType = signatureType;
461
- onePassSig.hashAlgorithm = await getPreferredHashAlgo(privateKey, signingKey.keyPacket, date, userIds);
462
- onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm;
463
- onePassSig.issuerKeyId = signingKey.getKeyId();
464
- if (i === privateKeys.length - 1) {
465
- onePassSig.flags = 1;
466
- }
467
- return onePassSig;
468
- })).then(onePassSignatureList => {
469
- onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig));
470
- });
471
-
472
- packetlist.push(literalDataPacket);
473
- packetlist.concat(await createSignaturePackets(literalDataPacket, privateKeys, signature, date, userIds, false, streaming));
474
-
475
- return new Message(packetlist);
476
- };
477
-
478
- /**
479
- * Compresses the message (the literal and -if signed- signature data packets of the message)
480
- * @param {module:enums.compression} compression compression algorithm to be used
481
- * @returns {module:message.Message} new message with compressed content
482
- */
483
- Message.prototype.compress = function(compression) {
484
- if (compression === enums.compression.uncompressed) {
485
- return this;
486
- }
487
-
488
- const compressed = new packet.Compressed();
489
- compressed.packets = this.packets;
490
- compressed.algorithm = enums.read(enums.compression, compression);
491
-
492
- const packetList = new packet.List();
493
- packetList.push(compressed);
494
-
495
- return new Message(packetList);
496
- };
497
-
498
- /**
499
- * Create a detached signature for the message (the literal data packet of the message)
500
- * @param {Array<module:key.Key>} privateKeys private keys with decrypted secret key data for signing
501
- * @param {Signature} signature (optional) any existing detached signature
502
- * @param {Date} date (optional) override the creation time of the signature
503
- * @param {Array} userIds (optional) user IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
504
- * @param {Boolean} streaming (optional) whether to process data as a stream
505
- * @returns {Promise<module:signature.Signature>} new detached signature of message content
506
- * @async
507
- */
508
- Message.prototype.signDetached = async function(privateKeys = [], signature = null, date = new Date(), userIds = [], streaming = false) {
509
- const literalDataPacket = this.packets.findPacket(enums.packet.literal);
510
- if (!literalDataPacket) {
511
- throw new Error('No literal data packet to sign.');
512
- }
513
- return new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, date, userIds, true, streaming));
514
- };
515
-
516
- /**
517
- * Create signature packets for the message
518
- * @param {module:packet.Literal} literalDataPacket the literal data packet to sign
519
- * @param {Array<module:key.Key>} privateKeys private keys with decrypted secret key data for signing
520
- * @param {Signature} signature (optional) any existing detached signature to append
521
- * @param {Date} date (optional) override the creationtime of the signature
522
- * @param {Array} userIds (optional) user IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
523
- * @param {Boolean} detached (optional) whether to create detached signature packets
524
- * @param {Boolean} streaming (optional) whether to process data as a stream
525
- * @returns {Promise<module:packet.List>} list of signature packets
526
- * @async
527
- */
528
- export async function createSignaturePackets(literalDataPacket, privateKeys, signature = null, date = new Date(), userIds = [], detached = false, streaming = false) {
529
- const packetlist = new packet.List();
530
-
531
- // If data packet was created from Uint8Array, use binary, otherwise use text
532
- const signatureType = literalDataPacket.text === null ?
533
- enums.signature.binary : enums.signature.text;
534
-
535
- await Promise.all(privateKeys.map(async (privateKey, i) => {
536
- const userId = userIds[i];
537
- if (privateKey.isPublic()) {
538
- throw new Error('Need private key for signing');
539
- }
540
- const signingKey = await privateKey.getSigningKey(undefined, date, userId);
541
- return createSignaturePacket(literalDataPacket, privateKey, signingKey.keyPacket, { signatureType }, date, userId, detached, streaming);
542
- })).then(signatureList => {
543
- signatureList.forEach(signaturePacket => packetlist.push(signaturePacket));
544
- });
545
-
546
- if (signature) {
547
- const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);
548
- packetlist.concat(existingSigPacketlist);
549
- }
550
- return packetlist;
551
- }
552
-
553
- /**
554
- * Verify message signatures
555
- * @param {Array<module:key.Key>} keys array of keys to verify signatures
556
- * @param {Date} date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time
557
- * @param {Boolean} streaming (optional) whether to process data as a stream
558
- * @returns {Promise<Array<({keyid: module:type/keyid, valid: Boolean})>>} list of signer's keyid and validity of signature
559
- * @async
560
- */
561
- Message.prototype.verify = async function(keys, date = new Date(), streaming) {
562
- const msg = this.unwrapCompressed();
563
- const literalDataList = msg.packets.filterByTag(enums.packet.literal);
564
- if (literalDataList.length !== 1) {
565
- throw new Error('Can only verify message with one literal data packet.');
566
- }
567
- if (!streaming) {
568
- msg.packets.concat(await stream.readToEnd(msg.packets.stream, _ => _));
569
- }
570
- const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse();
571
- const signatureList = msg.packets.filterByTag(enums.packet.signature);
572
- if (streaming && onePassSigList.length && !signatureList.length && msg.packets.stream) {
573
- await Promise.all(onePassSigList.map(async onePassSig => {
574
- onePassSig.correspondingSig = new Promise((resolve, reject) => {
575
- onePassSig.correspondingSigResolve = resolve;
576
- onePassSig.correspondingSigReject = reject;
577
- });
578
- onePassSig.signatureData = stream.fromAsync(async () => (await onePassSig.correspondingSig).signatureData);
579
- onePassSig.hashed = stream.readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false, streaming));
580
- onePassSig.hashed.catch(() => {});
581
- }));
582
- msg.packets.stream = stream.transformPair(msg.packets.stream, async (readable, writable) => {
583
- const reader = stream.getReader(readable);
584
- const writer = stream.getWriter(writable);
585
- try {
586
- for (let i = 0; i < onePassSigList.length; i++) {
587
- const { value: signature } = await reader.read();
588
- onePassSigList[i].correspondingSigResolve(signature);
589
- }
590
- await reader.readToEnd();
591
- await writer.ready;
592
- await writer.close();
593
- } catch (e) {
594
- onePassSigList.forEach(onePassSig => {
595
- onePassSig.correspondingSigReject(e);
596
- });
597
- await writer.abort(e);
598
- }
599
- });
600
- return createVerificationObjects(onePassSigList, literalDataList, keys, date, false, streaming);
601
- }
602
- return createVerificationObjects(signatureList, literalDataList, keys, date, false, streaming);
603
- };
604
-
605
- /**
606
- * Verify detached message signature
607
- * @param {Array<module:key.Key>} keys array of keys to verify signatures
608
- * @param {Signature} signature
609
- * @param {Date} date Verify the signature against the given date, i.e. check signature creation time < date < expiration time
610
- * @returns {Promise<Array<({keyid: module:type/keyid, valid: Boolean})>>} list of signer's keyid and validity of signature
611
- * @async
612
- */
613
- Message.prototype.verifyDetached = function(signature, keys, date = new Date()) {
614
- const msg = this.unwrapCompressed();
615
- const literalDataList = msg.packets.filterByTag(enums.packet.literal);
616
- if (literalDataList.length !== 1) {
617
- throw new Error('Can only verify message with one literal data packet.');
618
- }
619
- const signatureList = signature.packets;
620
- return createVerificationObjects(signatureList, literalDataList, keys, date, true);
621
- };
622
-
623
- /**
624
- * Create object containing signer's keyid and validity of signature
625
- * @param {module:packet.Signature} signature signature packets
626
- * @param {Array<module:packet.Literal>} literalDataList array of literal data packets
627
- * @param {Array<module:key.Key>} keys array of keys to verify signatures
628
- * @param {Date} date Verify the signature against the given date,
629
- * i.e. check signature creation time < date < expiration time
630
- * @param {Boolean} detached (optional) whether to verify detached signature packets
631
- * @returns {Promise<Array<{keyid: module:type/keyid,
632
- * valid: Boolean}>>} list of signer's keyid and validity of signature
633
- * @async
634
- */
635
- async function createVerificationObject(signature, literalDataList, keys, date = new Date(), detached = false, streaming = false) {
636
- let primaryKey = null;
637
- let signingKey = null;
638
- await Promise.all(keys.map(async function(key) {
639
- // Look for the unique key that matches issuerKeyId of signature
640
- try {
641
- signingKey = await key.getSigningKey(signature.issuerKeyId, null);
642
- primaryKey = key;
643
- } catch (e) {}
644
- }));
645
-
646
- const signaturePacket = signature.correspondingSig || signature;
647
- const verifiedSig = {
648
- keyid: signature.issuerKeyId,
649
- verified: (async () => {
650
- if (!signingKey) {
651
- return null;
652
- }
653
- const verified = await signature.verify(signingKey.keyPacket, signature.signatureType, literalDataList[0], detached, streaming);
654
- const sig = await signaturePacket;
655
- if (sig.isExpired(date) || !(
656
- sig.created >= signingKey.getCreationTime() &&
657
- sig.created < await (signingKey === primaryKey ?
658
- signingKey.getExpirationTime() :
659
- signingKey.getExpirationTime(primaryKey, date)
660
- )
661
- )) {
662
- throw new Error('Signature is expired');
663
- }
664
- return verified;
665
- })(),
666
- signature: (async () => {
667
- const sig = await signaturePacket;
668
- const packetlist = new packet.List();
669
- packetlist.push(sig);
670
- return new Signature(packetlist);
671
- })()
672
- };
673
-
674
- // Mark potential promise rejections as "handled". This is needed because in
675
- // some cases, we reject them before the user has a reasonable chance to
676
- // handle them (e.g. `await readToEnd(result.data); await result.verified` and
677
- // the data stream errors).
678
- verifiedSig.signature.catch(() => {});
679
- verifiedSig.verified.catch(() => {});
680
-
681
- return verifiedSig;
682
- }
683
-
684
- /**
685
- * Create list of objects containing signer's keyid and validity of signature
686
- * @param {Array<module:packet.Signature>} signatureList array of signature packets
687
- * @param {Array<module:packet.Literal>} literalDataList array of literal data packets
688
- * @param {Array<module:key.Key>} keys array of keys to verify signatures
689
- * @param {Date} date Verify the signature against the given date,
690
- * i.e. check signature creation time < date < expiration time
691
- * @param {Boolean} detached (optional) whether to verify detached signature packets
692
- * @returns {Promise<Array<{keyid: module:type/keyid,
693
- * valid: Boolean}>>} list of signer's keyid and validity of signature
694
- * @async
695
- */
696
- export async function createVerificationObjects(signatureList, literalDataList, keys, date = new Date(), detached = false, streaming = false) {
697
- return Promise.all(signatureList.filter(function(signature) {
698
- return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType));
699
- }).map(async function(signature) {
700
- return createVerificationObject(signature, literalDataList, keys, date, detached, streaming);
701
- }));
702
- }
703
-
704
- /**
705
- * Unwrap compressed message
706
- * @returns {module:message.Message} message Content of compressed message
707
- */
708
- Message.prototype.unwrapCompressed = function() {
709
- const compressed = this.packets.filterByTag(enums.packet.compressed);
710
- if (compressed.length) {
711
- return new Message(compressed[0].packets);
712
- }
713
- return this;
714
- };
715
-
716
- /**
717
- * Append signature to unencrypted message object
718
- * @param {String|Uint8Array} detachedSignature The detached ASCII-armored or Uint8Array PGP signature
719
- */
720
- Message.prototype.appendSignature = async function(detachedSignature) {
721
- await this.packets.read(util.isUint8Array(detachedSignature) ? detachedSignature : (await armor.decode(detachedSignature)).data);
722
- };
723
-
724
- /**
725
- * Returns ASCII armored text of message
726
- * @returns {ReadableStream<String>} ASCII armor
727
- */
728
- Message.prototype.armor = function() {
729
- return armor.encode(enums.armor.message, this.packets.write());
730
- };
731
-
732
- /**
733
- * reads an OpenPGP armored message and returns a message object
734
- * @param {String | ReadableStream<String>} armoredText text to be parsed
735
- * @returns {Promise<module:message.Message>} new message object
736
- * @async
737
- * @static
738
- */
739
- export async function readArmored(armoredText) {
740
- //TODO how do we want to handle bad text? Exception throwing
741
- //TODO don't accept non-message armored texts
742
- const streamType = util.isStream(armoredText);
743
- if (streamType === 'node') {
744
- armoredText = stream.nodeToWeb(armoredText);
745
- }
746
- const input = await armor.decode(armoredText);
747
- return read(input.data, streamType);
748
- }
749
-
750
- /**
751
- * reads an OpenPGP message as byte array and returns a message object
752
- * @param {Uint8Array | ReadableStream<Uint8Array>} input binary message
753
- * @param {Boolean} fromStream whether the message was created from a Stream
754
- * @returns {Promise<module:message.Message>} new message object
755
- * @async
756
- * @static
757
- */
758
- export async function read(input, fromStream = util.isStream(input)) {
759
- const streamType = util.isStream(input);
760
- if (streamType === 'node') {
761
- input = stream.nodeToWeb(input);
762
- }
763
- const packetlist = new packet.List();
764
- await packetlist.read(input, fromStream);
765
- const message = new Message(packetlist);
766
- message.fromStream = fromStream;
767
- return message;
768
- }
769
-
770
- /**
771
- * creates new message object from text
772
- * @param {String | ReadableStream<String>} text
773
- * @param {String} filename (optional)
774
- * @param {Date} date (optional)
775
- * @param {utf8|binary|text|mime} type (optional) data packet type
776
- * @returns {module:message.Message} new message object
777
- * @static
778
- */
779
- export function fromText(text, filename, date = new Date(), type = 'utf8') {
780
- const streamType = util.isStream(text);
781
- if (streamType === 'node') {
782
- text = stream.nodeToWeb(text);
783
- }
784
- const literalDataPacket = new packet.Literal(date);
785
- // text will be converted to UTF8
786
- literalDataPacket.setText(text, type);
787
- if (filename !== undefined) {
788
- literalDataPacket.setFilename(filename);
789
- }
790
- const literalDataPacketlist = new packet.List();
791
- literalDataPacketlist.push(literalDataPacket);
792
- const message = new Message(literalDataPacketlist);
793
- message.fromStream = streamType;
794
- return message;
795
- }
796
-
797
- /**
798
- * creates new message object from binary data
799
- * @param {Uint8Array | ReadableStream<Uint8Array>} bytes
800
- * @param {String} filename (optional)
801
- * @param {Date} date (optional)
802
- * @param {utf8|binary|text|mime} type (optional) data packet type
803
- * @returns {module:message.Message} new message object
804
- * @static
805
- */
806
- export function fromBinary(bytes, filename, date = new Date(), type = 'binary') {
807
- const streamType = util.isStream(bytes);
808
- if (!util.isUint8Array(bytes) && !streamType) {
809
- throw new Error('Data must be in the form of a Uint8Array or Stream');
810
- }
811
- if (streamType === 'node') {
812
- bytes = stream.nodeToWeb(bytes);
813
- }
814
-
815
- const literalDataPacket = new packet.Literal(date);
816
- literalDataPacket.setBytes(bytes, type);
817
- if (filename !== undefined) {
818
- literalDataPacket.setFilename(filename);
819
- }
820
- const literalDataPacketlist = new packet.List();
821
- literalDataPacketlist.push(literalDataPacket);
822
- const message = new Message(literalDataPacketlist);
823
- message.fromStream = streamType;
824
- return message;
825
- }