Compare commits

...

172 Commits

Author SHA1 Message Date
dependabot[bot]
88310fe69d
Bump playwright from 1.51.0 to 1.51.1 (#1834)
Bumps [playwright](https://github.com/microsoft/playwright) from 1.51.0 to 1.51.1.
- [Release notes](https://github.com/microsoft/playwright/releases)
- [Commits](https://github.com/microsoft/playwright/compare/v1.51.0...v1.51.1)

---
updated-dependencies:
- dependency-name: playwright
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-18 13:56:54 +01:00
dependabot[bot]
c2526c8a88
Tests: bump playwright from 1.50.1 to 1.51.0 (#1831)
Bumps [playwright](https://github.com/microsoft/playwright) from 1.50.1 to 1.51.0.
- [Release notes](https://github.com/microsoft/playwright/releases)
- [Commits](https://github.com/microsoft/playwright/compare/v1.50.1...v1.51.0)

---
updated-dependencies:
- dependency-name: playwright
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-07 15:53:39 +01:00
larabr
1848f51a4c
Merge pull request #1829
Re-enable using WebCrypto for X25519 when available.
2025-03-05 11:51:40 +01:00
larabr
4762d2c762 CI: do not test Webkit on Linux
The tests work correctly in Epiphany, but not in the WebKit build,
where the native X25519 implementation throws non-standard errors on
importKey (DataError) and generateKey (OperationError).
Patching this would be simply a matter of catching such errors and falling back
to the JS implementation, but since only the CI WebKit build seems to be
affected, we prefer not to relax fallback checks in the context of crypto
operations without issues reported in the wild.
2025-02-26 13:00:14 +01:00
larabr
d5689894f6 Re-enable using WebCrypto for X25519 when available
Reverting commit ccb040ae96acd127a29161ffaf3b82b5b18c062f .
Firefox has fixed support in v132 (https://bugzilla.mozilla.org/show_bug.cgi?id=1918354)
usage of v130 and 131, which have a broken implementation, is now below 1%.

Also, Chrome has released support in v133.
2025-02-26 12:15:17 +01:00
Carlos Alexandro Becker
6d4a86295e
Make Issuer Key ID signature subpacket non-critical (#1828)
RPM <=4.16 does not support it.

See also:
- https://github.com/ProtonMail/go-crypto/pull/175
- https://github.com/ProtonMail/go-crypto/issues/263
2025-02-26 10:19:25 +01:00
dependabot[bot]
8a2062d342
Bump the noble group with 3 updates (#1825)
Bumps the noble group with 3 updates: [@noble/ciphers](https://github.com/paulmillr/noble-ciphers), [@noble/curves](https://github.com/paulmillr/noble-curves) and [@noble/hashes](https://github.com/paulmillr/noble-hashes).

Also:
* Internal: OCB: do not reuse AES-CBC instance (Noble is now preventing instance reuse).
* Tests: update error message following noble-curve change


Updates `@noble/ciphers` from 1.0.0 to 1.2.1
- [Release notes](https://github.com/paulmillr/noble-ciphers/releases)
- [Commits](https://github.com/paulmillr/noble-ciphers/compare/1.0.0...1.2.1)

Updates `@noble/curves` from 1.6.0 to 1.8.1
- [Release notes](https://github.com/paulmillr/noble-curves/releases)
- [Commits](https://github.com/paulmillr/noble-curves/compare/1.6.0...1.8.1)

Updates `@noble/hashes` from 1.5.0 to 1.7.1
- [Release notes](https://github.com/paulmillr/noble-hashes/releases)
- [Commits](https://github.com/paulmillr/noble-hashes/compare/1.5.0...1.7.1)

---

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: larabr <7375870+larabr@users.noreply.github.com>
2025-02-12 13:20:20 +01:00
dependabot[bot]
e9fe979649
Bump fflate from 0.7.4 to 0.8.2 (#1826)
Bumps [fflate](https://github.com/101arrowz/fflate) from 0.7.4 to 0.8.2.
- [Release notes](https://github.com/101arrowz/fflate/releases)
- [Changelog](https://github.com/101arrowz/fflate/blob/master/CHANGELOG.md)
- [Commits](https://github.com/101arrowz/fflate/compare/v0.7.4...v0.8.2)

---
updated-dependencies:
- dependency-name: fflate
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-02-11 13:59:09 +01:00
dependabot[bot]
1ab6f27fc9
Bump playwright from 1.48.2 to 1.50.1 (#1824)
Bumps [playwright](https://github.com/microsoft/playwright) from 1.48.2 to 1.50.1.
- [Release notes](https://github.com/microsoft/playwright/releases)
- [Commits](https://github.com/microsoft/playwright/compare/v1.48.2...v1.50.1)

---
updated-dependencies:
- dependency-name: playwright
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-02-11 13:27:41 +01:00
larabr
a7660cc43b CI: fix (again) Dependabot setup: add workaround to set different schedules for npm updates 2025-02-11 11:38:06 +01:00
larabr
b583bcad23
CI: fix Dependabot setup (#1823)
Typo in filename resulting in bot not actually working.
2025-02-10 19:20:03 +01:00
larabr
a3a9e06802
CI: add reconnection mechanism for Browserstack on testsStartTimeout (#1822)
iOS tests sometimes fail to start due to some "server disconnect" issue on BS side.
This seems more prominent on certain devices (e.g. iPhone 16 with iOS 18).
So, we also change the 'iOS latest' target to a more stable one.
2025-02-10 19:15:43 +01:00
Daniel Huigens
965e63b672
Only push new tags when running npm version (#1821) 2025-02-03 14:27:39 +01:00
Daniel Huigens
96b13a468b
6.1.0 2025-01-30 14:15:35 +01:00
Daniel Huigens
432856ff0e
Fix signing using keys without preferred hash algorithms (#1820) 2025-01-29 16:45:32 +01:00
larabr
b2bd8a0fdd
Merge pull request #1812
Improve internal tree-shaking and lazy load md5
2024-11-25 11:13:15 +01:00
larabr
6db98f1e47 Internal: improve tree-shaking in armor module 2024-11-22 14:34:18 +01:00
larabr
8e5da78971 Internal: improve tree-shaking of web-stream-tools
Import single functions instead of entire lib.
2024-11-22 14:34:18 +01:00
larabr
a5d894f514 Internal: avoid importing enums in legacy_cipher chunk
To avoid issues with the lightweight build:
for now it works fine, but it could mess up chunking in the future,
and it already results in a circular import.
2024-11-22 14:34:18 +01:00
larabr
a16160fc66 Use noble-hashes for md5
The existing md5 module brought in the util module,
which messed up the chunking structure in the lightweight build;
inlining those functions is an option, but the noble-hashes code
is also more modern and readable.
2024-11-22 14:32:42 +01:00
larabr
abe750cf7c Lightweight build: lazy load md5 hashing module
Used by old, legacy messages only
2024-11-22 14:32:42 +01:00
larabr
2a8969b437 Internal: improve tree-shaking for crypto modules
Every submodule under the 'crypto' directory was exported-imported
even if a handful of functions where actually needed.
We now only export entire modules behind default exports if it makes
sense for readability and if the different submodules would be
imported together anyway (e.g. `cipherMode` exports are all needed
by the SEIPD class).

We've also dropped exports that are not used outside of the crypto modules,
e.g. pkcs5 helpers.
2024-11-22 14:32:39 +01:00
larabr
bf85deedb8
Merge pull request #1811 2024-11-22 14:30:41 +01:00
larabr
6c3b02872d Throw on encryption using non-standard experimentalGCM AEAD algo
The `enums.aead.gcm` ID standardized by RFC9580 should be used instead.
2024-11-22 14:29:14 +01:00
larabr
4d2d8740dc Fix decryption support for non-standard, legacy AEAD messages and keys that used experimentalGCM
This adds back support for decrypting password-protected messages which
were encrypted in OpenPGP.js v5 with custom config settings
`config.aeadProtect = true` together with
`config.preferredAEADAlgorithm = openpgp.enums.aead.experimentalGCM`.

Public-key-encrypted messages are affected if they were encrypted using the same config, while also providing `encryptionKeys` that declared `experimentalGCM` in their AEAD prefs.
Such keys could be generated in OpenPGP.js v5 by setting the aforementioned config values.
2024-11-22 10:15:20 +01:00
larabr
bbdaad0cba TS: add gcm to enums.aead, mark non-standard experimentalGCM as deprecated
`experimentalGCM` should not be used anymore,
as a different a different algorithm ID was standardized
for GCM, and using the experimental value could give
interoperability issues with e.g. SEIPDv2 and AEAD-encrypted keys.
2024-11-22 10:15:20 +01:00
larabr
daeaf6b1da CI: disable Browserstack concurrency to improve reliability 2024-11-21 18:11:10 +01:00
larabr
67faffafff 6.0.1 2024-11-21 17:16:29 +01:00
larabr
f75447afaa Fix ES imports for webpack: declare exports.browser entrypoint as higher priority than import
We could also drop the browser's directive `"./dist/node/openpgp.min.cjs": "./dist/openpgp.min.js"`,
since that build cannot be used with `require()`, and it's instead meant
to be the target of <script> tags.
But we keep it around for now to avoid potentially breaking changes, in case it's
used in some setups.
2024-11-21 16:43:15 +01:00
larabr
121b478312 Tests: drop unused, unnecessary error assertion
The `expect().to.not.throw` check as written is a no-op.
In fact, `throw` should have been called as a function.

We drop the relevant check altogether since if the wrapped
operation throws, the test will naturally fail due to the
unexpected error.
2024-11-13 19:44:06 +01:00
larabr
088d5f3638
Merge pull request #1807 2024-11-11 20:46:51 +01:00
Daniel Huigens
ac1bfc0d60
Fix openpgp.verify/decrypt with expectSigned: true and format: 'binary' (#1805) 2024-11-11 15:42:33 +01:00
larabr
287104aafb TS: fix PrivateKey.getDecryptionKeys() return type 2024-11-11 14:20:18 +01:00
larabr
2d65d1d553 TS: generateKey: fix options.type definitions to accept 'curve25519' and 'curve448' 2024-11-11 13:28:05 +01:00
Daniel Huigens
3f060660c2
Update hash algorithm preferences order (#1804)
Prefer SHA3_512 over SHA3_256 for consistency.
2024-11-07 15:19:20 +01:00
larabr
01b62399af Revert "CI: temporarily enable for PRs to v6 branch" [skip ci] 2024-11-05 12:56:39 +01:00
larabr
dd01ee00cb 6.0.0 2024-11-04 17:35:18 +01:00
Daniel Huigens
a5645e1d6c Spaces after "RFC" in README 2024-11-04 17:03:36 +01:00
Daniel Huigens
09800741f0 Document required Web Crypto support in README 2024-11-04 17:02:04 +01:00
Daniel Huigens
31a7e2616b
Merge pull request #1629 from openpgpjs/v6
V6
2024-11-04 12:11:19 +01:00
larabr
42d504a69a
Switch to SHA512 as default preferred hash algo (config.preferredHashAlgorithm) (#1801)
This affects the preferences of newly generated keys, which by default will
have SHA512 as first hash algo preference.
SHA512 will also be used when signing, as long as the recipient keys declare
support for the algorithm.
2024-10-31 00:24:19 +01:00
larabr
fb72ea449a
Merge pull request #1802
Determine signature hash prefs based on recipient keys instead of signing key
2024-10-31 00:16:40 +01:00
larabr
f9a3e54364 openpgp.sign: add recipientKeys option to get the signing prefs from
If given, the signature will be generated using the preferred hash algo from the recipient keys.
Otherwise, the signing key preferences are used (this was also the existing behavior).

Note: when signing through `openpgp.encrypt`, the `encryptionKeys` are automatically used as recipient keys.
2024-10-30 19:06:44 +01:00
larabr
d3e75de23d openpgp.encrypt: use encryptionKeys to determine preferred hash algo when signing
In `openpgp.sign`, the signing key preferences are considered instead,
since no "recipient keys" are available.

The hash algo selection logic has been reworked as follows:
if `config.preferredHashAlgo` appears in the prefs of all recipients, we pick it;
otherwise, we use the strongest supported algo (note: SHA256 is always implicitly supported by all keys),
as long as it is compatible with the signing key (e.g. ECC keys require minimum digest sizes).

Previously, only the preferences of the signing key were used to determine the hash algo to use,
but this is in contrast to the RFC: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.16-2 .
Also, an algo stronger than `config.preferredHashAlgo` would be used, if the signing key
declared it as first preference.

With this change, `config.preferredHashAlgo` is picked even if it's weaker than the
preferences of the recipient keys.
2024-10-30 19:06:44 +01:00
larabr
12274a1543 Update README [skip ci] 2024-10-28 18:01:07 +01:00
larabr
0138b69356 CI: update Browserstack project id to include target branch 2024-10-28 13:38:59 +01:00
larabr
821f260ba9 Lightweight build: lazy load bzip decompression lib 2024-10-28 13:38:59 +01:00
larabr
09095ced4f Run npm update
as well as npm audit
2024-10-28 13:38:59 +01:00
larabr
d7f5736d67
Merge pull request #1794 2024-10-25 12:16:02 +02:00
larabr
693adb417e CI: run browser tests also on Linux
To test platform potential specific code of e.g. the WebCrypto API

Testing on Windows would be nice too, but all browsers fail to fetch resources
from the web-test-runner server.
2024-10-25 11:38:52 +02:00
larabr
013dffce70 CI: test latest Webkit on macOS, as a replacement for testing Safari on Browserstack
We were previously testing the webkit engine on Linux, which however relies on a
different WebCrypto API implementation compared to the macOS version (behind Safari).

Also, increase mocha timeouts, as the argon2 memory-heavy test takes longer in Firefox.
2024-10-24 20:12:11 +02:00
larabr
59c809c943 CI: Browserstack: test only iOS latest and min supported version (iOS 14)
Dropping Safari since Web Secure Sockets do not seem to work with
the 'networkLogs' capability, which is in turn required for the HTTPS
connection to work without insecure certs warnings.
2024-10-24 15:39:20 +02:00
larabr
4ddadd4f53 CI: setup HTTPS in web-test-runner for BrowserStack tests
To have tests work Browserstack Safari (also below iOS 15), as the tests are run in an iframe,
rewriting localhost as hostname, making WebCrypto not available.

We keep HTTP for the non-browserstack tests so that in local testing,
generating self-signed certs is not required.
2024-10-24 15:39:14 +02:00
larabr
ae5698c621 CI: fix playwright version parsing
Only look at direct dependency
2024-10-23 18:03:54 +02:00
larabr
4b017f6c67 Tests: drop karma (deprecated) in favor of web-test-runner 2024-10-23 18:03:51 +02:00
larabr
e924a50c31
Merge pull request #1799 2024-10-22 14:32:31 +02:00
larabr
88f20974dd Tests: add support for RNG mocking in browser tests
The affected tests were previously only run in Node.
2024-10-22 12:40:15 +02:00
larabr
05fbc63732 Use WebCrypto.getRandomValues in Node
To move towards uniform code with across platforms.
2024-10-22 12:40:15 +02:00
larabr
3cdaab7894 Check session key size on v3 SKESK and PKESK packet decryption
For v3 SKESK and PKESK packets, the session key algorithm is part of the payload,
so we can check the session key size on packet decryption.
This is helpful to catch errors early, when using e.g. `decryptSessionKeys`.

In v6 packets, the session key size check can only be done on SEIPDv2 decryption.
2024-10-22 12:40:15 +02:00
larabr
e58c02d5ee Check session key size on SEIPD decryption
This is especially important for SEIPDv2 session keys,
as a key derivation step is run where the resulting key
will always match the expected cipher size,
but we want to ensure that the input key isn't e.g. too short.
2024-10-22 12:40:15 +02:00
larabr
a57bffc84a
Fix key and signature parsing of EdDSALegacy entities with unsupported curves (e.g. Curve448Legacy) (#1798)
Signature parsing would fail in case of unexpected payload sizes, causing key parsing to always throw
when processing e.g. an (unsupported) Curve448Legacy subkey instead of ignoring it.

To address this, we now throw on signature verification instead of parsing (as done for ECDSA).

NB: the bug and this fix are not relevant for the new Ed25519/Ed448 entities as standardized by the crypto-refresh.
2024-10-14 12:15:33 +02:00
larabr
5ee854140a CI: update SOP test suite docker image to v1.1.12
Includes rsop with crypto-refresh support
2024-10-03 16:44:55 +02:00
larabr
ada794cab6 Throw on (unexpected) low order points in ECDH over Curve25519/448
These points do not pose a security threat in the context of OpenPGP ECDH,
and would simply result in an all-zero shared secret being generated.
However, they represent unexpected inputs, so we prefer to warn the user.
2024-09-12 13:32:14 +02:00
larabr
e80d71bdfc CI: setup Dependabot to update non-dev dependencies
We unfortunately need to manually list them as they are still
declared as dev dependencies in the package.json, due to the fact
that we bundle them.
2024-09-11 19:41:57 +02:00
larabr
e454faab0c CI: setup Dependabot to update playwright and test latest browser versions 2024-09-11 19:35:47 +02:00
larabr
6ac17dc71c 6.0.0-beta.3.patch.1 2024-09-11 10:57:20 +02:00
larabr
148fff91e8 Docs: fix type tag warnings 2024-09-11 10:56:08 +02:00
larabr
ccb040ae96 Revert to not using the WebCrypto for X25519 (ECDH only)
Due to missing support in WebKit and Chrome (without experimental flags),
and broken support in Firefox, for now we go back to using a JS implementation.

This change only affects encryption and decryption using X25519.
For signing and verification using Ed25519 we keep relying on
WebCrypto when available (namely in WebKit, Firefox, and Node).
2024-09-11 10:56:08 +02:00
larabr
2b9a07e840 Run npm audit 2024-09-11 10:42:37 +02:00
larabr
0255fcba86 CI: update playwright to test latest browser versions 2024-09-11 10:39:51 +02:00
larabr
f2818429db 6.0.0-beta.3.patch.0 2024-09-09 11:47:41 +02:00
larabr
8d8033383b Fix regression in x25519 (legacy) key generation: store clamped secret scalar
Fixes regression from changes in #1782, as the spec mandates that
legacy x25519 store the secret scalar already clamped.
Keys generated using v6.0.0-beta.3 are still expected to be functional,
since the scalar is to be clamped before computing the ECDH shared secret.
2024-09-09 11:20:59 +02:00
larabr
a3839f6db5 6.0.0-beta.3 2024-09-05 13:24:51 +02:00
larabr
1bcce67c68 CI: test also on Node 22 2024-09-05 13:20:56 +02:00
larabr
e7b7f6c6b1 Run npm update 2024-09-05 13:20:56 +02:00
larabr
ab8445116c CI: update SOP test suite docker image to v1.1.10
Add rsop to tested libraries.
2024-09-05 13:20:56 +02:00
larabr
f36be640cc Fallback to js implementation on WebCrypto EdDSA key generation failure
Workaround random failures in WebKit (Linux).
2024-09-04 17:47:55 +02:00
larabr
2f185481a7
PrivateKey.getDecryptionKeys: throw if no decryption key is found (#1789)
To avoid returning dummy key packets, and improving error reporting.
This new behavior is also better aligned with that of `Key.getSigningKey()`.

This is a breaking change for apps that call `getDecryptionKeys()` directly.
The related error messages returned by `openpgp.decrypt` have also changed,
becoming more specific.

This change is also made in preparation of supporting private keys with
public key packets.
2024-09-03 14:40:06 +02:00
larabr
5fd7ef370f
Drop asmcrypto.js for AES fallbacks in favor of noble-ciphers (#1785)
Asm.js has now been deprecated for many years, and no performance gain is
recorded for AES compared to vanilla JS.
The relevant AES fallback code is primarily used if the WebCrypto (resp.
NodeCrypto) implementation is not available.
2024-08-21 12:59:23 +02:00
larabr
79014f00f0
Merge pull request #1782 2024-08-21 12:53:13 +02:00
larabr
5c583341d7 Update README 2024-08-14 16:28:56 +02:00
larabr
db82968b48 Tests: do not test RFC8032 test vectors on Safari
As it implements a different RFC for non-deterministic signature generation
2024-08-14 16:22:01 +02:00
larabr
7698790d1c Use WebCrypto for x25519 when available 2024-08-14 16:22:01 +02:00
larabr
bcaaa7e2d2 Use WebCrypto for ed25519 when available 2024-08-14 16:22:00 +02:00
Daniel Huigens
fca699373a
Try more AEAD ciphersuites for SEIPDv2 (#1781)
Stick more closely to the algorithm preferences when creating an SEIPDv2
message, by trying additional combinations of the preferred symmetric algorithm
and the preferred AEAD algorithm. If one of them is supported but not the
other, we still use it (with the mandatory-to-implement algorithm for the other
one).
2024-08-12 11:52:52 +02:00
larabr
efb0324330 TS: add definition for config.enableParsingV5Entities [skip ci] 2024-07-15 15:14:27 +02:00
larabr
c0b35306cb 6.0.0-beta.2 2024-07-05 15:12:14 +02:00
larabr
35a1e1f23b Run npm audit 2024-07-05 15:10:29 +02:00
larabr
b9c5c8df59
Allow parsing legacy AEAD messages regardless of config.enableParsingV5Entities (#1779)
As legacy AEAD messages have been in circulation for longer.
2024-07-05 14:38:16 +02:00
Daniel Huigens
857b794e13
Disallow using forbidden S2K modes (#1777)
RFC9580 says that:

    Argon2 is only used with AEAD (S2K usage octet 253).  An
    implementation MUST NOT create and MUST reject as malformed any
    secret key packet where the S2K usage octet is not AEAD (253) and
    the S2K specifier type is Argon2.

Therefore, we disallow reading and writing Argon2 keys without AEAD.

And:

    [The Simple and Salted S2K methods] are used only for reading in
    backwards compatibility mode.
    
Since v6 keys don't need backwards compatibility, we also disallow
reading Simple S2K there. We still allow reading Salted S2K since the
spec says it may be used "when [the password] is high entropy".
2024-07-05 13:52:45 +02:00
Daniel Huigens
00e147f5c1
Use preferred AEAD mode for secret key encryption (#1776)
When config.aeadProtect is enabled, use config.preferredAEADAlgorithm
to decide the AEAD mode when encrypting secret keys.
2024-07-05 13:50:11 +02:00
Daniel Huigens
42938c871a
Fix legacy AEAD secret key encryption of v5 keys (#1775) 2024-07-04 19:41:39 +02:00
larabr
40b6427658 Tests: fix stream polyfilling in legacy browsers
web-streams-polyfill v4 has a different entrypoint for the polyfills.
2024-07-04 14:51:59 +02:00
larabr
f729d2bfa7
Fix ECDH fingerprint size of v6 keys (#1771)
Fingerprint should not be truncated, unlike for v5 keys.
2024-07-04 14:28:43 +02:00
larabr
5268c484e9
Disable support for parsing v5 entities by default (add config.enableParsingV5Entities) (#1774)
Parsing of v5 keys, v5 signatures and AEAD-encrypted data packets now requires turning on
the corresponding config flag.
The affected entities are non-standard, and in the crypto-refresh RFC they have been superseded by
v6 keys, v6 signatures and SEIPDv2 encrypted data, respectively.
However, generation of v5 entities was supported behind config flag in OpenPGP.js v5, and some other libraries,
hence parsing them might be necessary in some cases.
2024-07-04 13:59:40 +02:00
Daniel Huigens
9efdaf14b1 Let hard revocations apply at any time (#1773)
"Hard" revocations (i.e. key compromise, and unknown reasons) apply
at any time, even before the revocation was created.

Co-authored-by: larabr <larabr+github@protonmail.com>
2024-07-04 13:51:35 +02:00
larabr
8d11c5fd0f Drop support for Node 16 and 17 2024-06-26 12:01:10 +02:00
larabr
7af16be62b
Use positive cert for self-signatures (#1769)
To uniform behaviour with other openpgp libs.
2024-06-25 12:50:26 +02:00
larabr
4026e24585 Merge branch 'main' into v6 2024-06-18 19:21:16 +02:00
larabr
a0337780b7 5.11.2 2024-06-18 17:53:56 +02:00
larabr
3eba29dba8
Merge pull request #1762
`openpgp.verify`: fix bug preventing verification of detached signatures over streamed data
2024-06-18 17:39:21 +02:00
larabr
12fb916360 Pass curve object instead of oid to checkPublicPointEnconding 2024-06-18 17:09:23 +02:00
larabr
cf94380e26 Read wireFormatLeadingByte value from curve object 2024-06-18 17:09:23 +02:00
larabr
52611e7f26 Detect unexpected eddsaLegacy OID on parsing 2024-06-18 17:09:23 +02:00
larabr
f8d0e6052f Detect invalid ECDSA, EdDSA and ECDH public key point encodings on usage
We now throw on unexpected leading byte.
This change is primarily intended to help with debugging, in case of malformed params.
In fact, in case of wrong point size, the operations would already fail anyway,
just in lower-level functions.
2024-06-18 17:09:23 +02:00
larabr
08b71487c5 Detect invalid PKESK public point encoding on decryption
We got a report of a message including a PKESK packet where
the ECDH x25519Legacy point was missing the leading byte (0x40).
While decryption naturally would naturally fail afterwards, this
change ensures we fail at a higher level, and do not blindly pass
down invalid data to the low-level crypto functions.
2024-06-18 17:09:23 +02:00
larabr
75f10955e6 Tests: move away from global streamed data
To improve readability
2024-06-18 17:07:41 +02:00
larabr
1ce2df1119 Avoid using stream.clone over polyfilled steam in test
Gives issues in Node and Safari < 14.1
2024-06-18 16:36:31 +02:00
larabr
6ace4a00f5 Update web-stream-tools to fix passiveClone cancellation race condition in tests
Affecting tests over streamed detached verification
2024-06-18 10:16:33 +02:00
Daniel Huigens
9f5ff66c3d
Store unhashed subpackets in a more structured format (#1767)
To match the new `unknownSubpackets` property.
2024-06-17 16:52:28 +02:00
Daniel Huigens
b1e27a1430
Delay checking unknown critical signature subpackets (#1766)
Throw when verifying signatures with unknown critical subpackets,
instead of when parsing them.
2024-06-17 12:31:31 +02:00
larabr
a315c46583 openpgp.verify: fix bug preventing verification of detached signature over streamed data
When given a streamed `message` and a detached `signature` in input,
the function would return an empty array as `data` instead of
the input stream, meaning it was not possible to pull it, causing
the `verified` promise to hang indefinitely.

The above issue was introduced v5.0.0-2, and thus affects all v5 releases
up to v5.11.1.
2024-05-31 15:58:42 +02:00
larabr
d138b5290b 6.0.0-beta.1 2024-05-17 14:13:46 +02:00
larabr
1d732c34ff Run npm update 2024-05-17 13:04:47 +02:00
larabr
6a306a1797 Lint: add support for dep imports that use exports declarations 2024-05-17 13:00:37 +02:00
larabr
676c31b748 CI: update SOP actions to Node 20 2024-05-16 17:21:36 +02:00
larabr
727c7cad37 read[Private]Key: support parsing key blocks (return first parsable key)
Previously, `readKey` and `readPrivateKey` would throw when given a block
of keys as input.
With this change, the first parsable key is returned by both functions:
the behaviour is equivalent to calling `readKeys` (resp. `readPrivateKeys`)
and taking the first array entry.
2024-05-16 14:07:39 +02:00
larabr
ad7165dfd0 readPrivateKeys: support parsing key block with mix of private and public keys
Previously, parsing a key block where a public key followed a private one would fail.
2024-05-16 14:07:39 +02:00
larabr
cf0285add5 Drop BigInteger class, use standalone helpers 2024-05-16 13:59:11 +02:00
larabr
90495522f7 CI: update Browserstack legacy targets (drop Safari 13) 2024-05-16 13:59:11 +02:00
larabr
2985b0f470 Lint: add support for TS files, fix errors 2024-05-16 13:59:11 +02:00
larabr
5bfff907b4 Move Brainpool curves implementation from noble-curves fork
The main repo doesn't implement them
2024-05-16 13:59:11 +02:00
larabr
ec52bdea83 Point to official noble-hashes and noble-curve libs 2024-05-16 13:59:11 +02:00
larabr
d1a24d1758 Drop support for platforms without native BigInt (e.g. Safari <14)
Remove BN.js fallback, and only keep native BigInteger interface
(for algorithmic constant-time functions).
Also, add support for TS modules, to move some over from the forked
noble repos.
2024-05-16 13:59:11 +02:00
larabr
7e2ea3f871 CI: update cache actions to Node 20 2024-05-02 21:45:58 +02:00
larabr
f3f1ab931b Tests: update SEIPD version check to no longer depend on config.aeadProtect
The logic was updated in github.com/openpgpjs/openpgpjs/pull/1678 .
The tests worked anyway thanks to the config option matching the (monkey patched)
keys' feature flags, which are the deciding factor for whether to use AEAD.
2024-05-02 21:45:58 +02:00
larabr
2bf7c92469 6.0.0-beta.0 2024-04-12 14:28:06 +02:00
larabr
5464caa6f7
Fix email address validity check to still allow unicode values, and further relax constraints (#1739)
We relaxed constraints in a previous commit, but excluded unicode chars, which are however allowed in v5.

We now drop almost all email address constraints, by primarily rejecting
control and spaces char classes.
Library users are strongly encouraged to implement additional checks as needed,
based on their supported email address format.

NB: the validity checks in question affect the userID inputs accepted by e.g.
`generateKey` and `reformatKey`, not the values parsed from existing entities,
e.g. using `readKey` (where almost no validation is performed).
2024-04-12 13:47:52 +02:00
larabr
231fbbe8ca Run npm update 2024-04-09 19:07:58 +02:00
larabr
9a53ac15df Tests: bump Sinon to v17 2024-04-09 18:57:53 +02:00
larabr
a05c23b507 Key.getRevocationCertificate(): apply config settings when armoring
The `config` input was not passed down to the armor function due to an oversight.
2024-04-09 18:40:51 +02:00
larabr
90c8fbbf00
Add back armor checksum for non-v6 artifacts (#1741)
We need to include the checksum to work around a GnuPG bug where data fails to
be decoded if the base64 ends with no padding chars (=) (see https://dev.gnupg.org/T7071).
Pure v6 artifacts are unaffected and won't include the checksum, as mandated by
the spec.

Breaking change:
`openpgp.armor` takes an additional `emitChecksum` argument (defaults to
false).
NB: some types of data must not include the checksum, but compliance is left as
responsibility of the caller: this function does not carry out any checks.
Refer to the crypto-refresh RFC for more details.

---------

Co-authored-by: Daniel Huigens <d.huigens@protonmail.com>
2024-04-09 17:12:44 +02:00
larabr
e9e843280b CI: update to sop-openpgp-v2 to test different v6 profiles
The implemented profiles do not work on v5, hence for now they need to be manually
disabled in the config of 'sop-openpgpjs-main'.
2024-04-05 17:25:54 +02:00
larabr
c68bd960ce
Randomise v4 and v5 signatures via custom notation, add config.nonDeterministicSignaturesViaNotation to disable feature (#1737)
EdDSA is known to be vulnerable to fault attacks which can lead to secret key
extraction if two signatures over the same data can be collected. Randomly
occurring bitflips in specific parts of the computation might in principle
result in vulnerable faulty signatures being generated.
To protect signatures generated using v4 and v5 keys from this possibility, we
randomise each signature by adding a custom notation with a random value,
functioning as a salt. 
For simplicity, we add the salt to all algos, not just EdDSA, as it may also
serve as protection in case of weaknesses in the hash algo, potentially
hindering e.g. some chosen-prefix attacks.
v6 signatures do not need to rely on this, as they are non-deterministic by
design.

While this notation solution is interoperable, it will reveal that the
signature has been generated using OpenPGP.js, which may not be desirable in
some cases.
For this reason, the option `config.nonDeterministicSignaturesViaNotation`
(defaulting to true) has been added to turn off the feature.
2024-04-02 17:37:57 +02:00
larabr
aa222fecb2
Drop config.revocationsExpire, always honour revocation expiration instead (#1736)
Unclear motivation for adding the original config option; if an expiration is there, it should
be honoured.

Breaking change:
the option used to default to `false`, and ignore revocation expirations. We now honour
those expirations, namely match the behaviour resulting from setting the option to `true`.
2024-03-28 14:24:23 +01:00
larabr
6ebd179ed5 Fix encrypting to a key with no declared features 2024-03-22 17:12:45 +01:00
larabr
2574795d37
Fix wrong serialization of PKESK v6 for x25519/x448 (#1734)
The cleartext session key symmetric algorithm was accidentally included in the packet.
As a result, the generated messages may fail to parse and/or decrypt in other implementations.
The messages would still decrypt successfully in OpenPGP.js, due to an overly permissive parsing procedure,
which simply discarded the unused additional byte.

We know also throw on unexpected cleartext symmetric algo in PKESK v6.
2024-03-22 17:10:27 +01:00
larabr
b41298a3f6 Add back armor checksum to detached signatures for GPG compatibility
GPG v2 fails to parse detached signatures without the checksum
2024-03-22 16:21:55 +01:00
larabr
cb97c8fcb9 CI: fix sop test result comparison 2024-03-22 16:14:18 +01:00
larabr
aba61efa70 CI: update interop test suite: fix sop-openpgpjs, include crypto-refresh tests, and compare with gopenpgp v3
sop-openpgpjs did not correctly apply the `OPENPGPJS_PATH` env variable; as a result,
it did not actually test the code from either the PR and base branch, but always from
the hardcoded version bundled with it.
2024-03-22 16:14:18 +01:00
larabr
147d043a32 6.0.0-alpha.1 2024-02-28 13:22:22 +01:00
larabr
df59dec319 Update README 2024-02-28 13:22:22 +01:00
larabr
f5cebfe6fd CI: update Playwright browser installation 2024-02-28 13:06:22 +01:00
larabr
15adf84a7d Run npm update 2024-02-28 12:44:05 +01:00
larabr
d4fd9c8d43 Merge branch 'main' into v6 2024-02-28 12:00:01 +01:00
larabr
151f15e282
Node: drop asn1.js dependency (#1722)
asn1.js is a fairly large lib and was simply needed to handle DER encodings in
some NodeCrypto operations.
This change replaces the dependency by moving to:

- JWT encoding for RSA (support added in Node v15)
- a much lighter dependency (eckey-utils) for ECDSA, where JWT cannot be used
for now, as Node has yet to add decoding support for Brainpool curves.

The change also allows us to drop BN.js as a direct dependency, optimising the
BigInteger-related chunking in the lightweight build.
2024-02-27 14:56:07 +01:00
larabr
a6283e64cc Drop internal cipher/aes module
The module was barely used, and its presence confusing, since
WebCrypto or asmcrypto are often directly used and usable instead.
Also, use AES_CBC instead of AES_ECB for single-block encryption,
so that we can drop support for the latter in the asmcrypto lib.
2024-02-27 14:43:24 +01:00
larabr
9c75845944 Use WebCrypto for AES-KW
Fallback needed for AES192, due to missing Chromium support.
2024-02-27 14:43:24 +01:00
larabr
db15f6d6a1
Import legacy ciphers (CAST5, TwoFish, BlowFish, DES) only on demand (#1723)
This primarily affects the lightweight build, which will not include these
(fairly large) modules in the main bundle file.
2024-02-26 15:37:50 +01:00
larabr
026b348cf8 5.11.1 2024-02-19 17:23:54 +01:00
larabr
711c41826a Run npm audit 2024-02-19 17:22:15 +01:00
larabr
a4e2c56c49
Use JS fallback code for RSA message decryption in Node if PKCS#1 is not supported (#1728)
Necessary as Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption.
2024-02-19 17:14:55 +01:00
Mingye Wang
7a6b41fbd4
README: replace "IETF proposal" with "RFC4880bis proposal" (#1726) 2024-02-19 15:17:40 +01:00
larabr
17bbab44c9 README: clarify web-stream-tools version to install for TypeScript projects [skip ci] 2024-02-19 13:52:30 +01:00
larabr
b413a113f9 CI: update actions to Node 20 2024-02-12 13:53:46 +01:00
larabr
280828dae6 Throw if WebCrypto API is not available
It was already required, this simply makes errors more clear.
2024-02-06 16:00:35 +01:00
larabr
3320eaccb2
Relax constraints for UserID email address validity (#1641)
New checks align with the HTML5 W3C spec and should be more lax than the
existing ones (meaning, addresses which passed validation before should
continue to be valid).
Addresses such as `@localhost` are now allowed too, since presence of "." is no
longer enforced.

These checks should not be considered exhaustive: library users are encouraged
to implement separate checks for email validity if needed.

Co-authored-by: Daniel Huigens <d.huigens@protonmail.com>
2024-02-02 15:04:34 +01:00
larabr
22c2682574
Ensure primary key meets strength and algo requirements when encrypting/verifying/signing using subkeys (#1719)
Breaking change: the requirements of `config.minRSABits`, `rejectPublicKeyAlgorithms` and `rejectCurves`
are now applied to the primary key, aside from the selected subkey.

The motivation is that the subkeys are certified by the primary key, but if the latter is
weak, arbitrary subkeys could potentially be added.

Note that the change does not affect decryption, to allow decrypting older messages.
2024-02-02 14:50:32 +01:00
larabr
f64dc3f35f
enums.curve: rename NIST curves (p256,p384,p521`) and clean up unused internal values (#1721)
This is a breaking change, as NIST curves identifiers and values in
`enums.curves` have been renamed:
- the identifiers `enums.curve.p256`, `.p384`, `.p521` are now marked as
`@deprecated`
- the new identifiers are, respectively: `enums.curve.nistP256`, `.nistP384`,
`.nistP521`.
- the corresponding values have been changed from `'p256'`,`'p384'`,`'p521'` to
`'nistP256'`, `'nistP384'`, `'nistP521'`.

Affected high-level API functions:
- in `generateKey`, the `options.curve` argument will expect the updated string
values
- `Key.getAlgorithmInfo()` will return the updated `curve` values
2024-02-02 12:54:24 +01:00
larabr
6370e0b2d3 CI: fix typescript test runner issues by switching to tsx from ts-node
ts-node is still needed for mocha to work with the different versions of Node
(passing --import in NODE_OPTIONS is not supported in older versions).
2024-02-01 10:38:01 +01:00
larabr
6bfb557ca6 Update Rollup to v4 2024-02-01 10:23:50 +01:00
larabr
959956cfc9
Use Compression Stream API when available, drop config.deflateLevel (#1717)
Breaking change: the `config.deflateLevel` is removed as the API does not accept a deflate level
in input, and the setting is of limited importance. Plus, using compression
is discouraged on security grounds.
2024-02-01 09:42:16 +01:00
larabr
99899d1d5c
Drop support for native Node Readable stream: require passing Node Web Streams (#1716)
Breaking change: all functions taking streams as inputs will now require passing Web Streams in Node.js . If given a native `stream.Readable` input, they will throw. The browser build is unaffected by this change.

Utils to convert from and to Web Streams in Node are available from v17,
see https://nodejs.org/api/stream.html#streamreadabletowebstreamreadable-options .
Previously, we automatically converted between Node native streams and custom, Web-like Readable streams.
This led to occasional issues.
2024-01-26 17:52:29 +01:00
larabr
591b9399a8
Skip key validation for keys encrypted with non-legacy AEAD mechanism (#1713)
The public key material integrity is guaranteed by the new encryption mechanism,
hence `.validate()` does not need to run further checks.
2024-01-15 15:07:09 +01:00
larabr
f77da9cdb0
Add config.parseAEADEncryptedV4KeysAsLegacy to support AEAD-encrypted v4 keys from OpenPGP.js v5 or older (#1672)
The config option must be set when reading v4 private keys (e.g. those
generated in OpenPGP.js by default, without setting `config.v5Keys = true`)
which were encrypted by OpenPGP.js v5 (or older) using `config.aeadProtect = true`.
Otherwise, key parsing and/or key decryption will fail.

Additional context: OpenPGP.js up to v5 used to support encrypting v4 keys
using AEAD as specified by draft RFC4880bis
(https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-5.5.3-3.5).
Said AEAD mechanism was not standardized as-is, and it's been replaced in the
crypto-refresh with a new version that guarantees full key integrity on decryption.
The legacy AEAD format is incompatible, but fundamentally indistinguishable,
from that of the crypto-refresh for v4 keys. Thus, we rely on the caller to
instruct us to process the key as legacy, via the new config flag.

Co-authored-by: Daniel Huigens <d.huigens@protonmail.com>
2024-01-12 16:29:56 +01:00
larabr
19cb6ee521 Lint: make 'space-before-function-paren' rule stricter to reflect enforced style 2023-12-18 15:52:19 +01:00
larabr
e92b44bc84 CI (temp): fix typescript test runner failure due to ts-node bug
This fix triggers some warnings about experimental features,
and it's meant to be temporary until ts-node shares a long-term solutio .

See https://github.com/TypeStrong/ts-node/issues/2094.
2023-12-08 15:10:27 +01:00
larabr
c754fac10f CI: replace nyc with c8 as coverage tool
Unclear if nyc is still actively maintained, and it does not seem
to work with ESM out of the box.
2023-12-08 14:53:19 +01:00
larabr
90a2af9fe2 Tests: fix flaky elliptic curve test in Node
`genKeyPair()` does not pad the returned values. This caused random test failures in Node
as some secret keys are 1 byte short.
2023-12-08 14:46:41 +01:00
larabr
ff4181ad5a Add back zlib and zip to preferred compression algos on key generation
To signal support, despite "no compression" being preferred by default,
for security reasons.
2023-12-08 14:00:22 +01:00
larabr
e93702bb8d Fix types path for lightweight build [skip ci] 2023-11-21 17:34:59 +01:00
Ryan
54fc2c8fbd
Add SHA3-256 and SHA3-512 to preferred hash algos on key generation (#1696)
This is to signal support to senders who wish to use these algos.
Note  that SHA256 remains as first default preference, followed by SHA512,
as in the context of OpenPGP signatures they provide
better performance/security ratio than their SHA3 counterparts.
2023-11-02 14:16:40 +01:00
199 changed files with 17162 additions and 18816 deletions

View File

@ -1,8 +1,15 @@
module.exports = {
'extends': 'airbnb-base',
'extends': [
'airbnb-base',
'airbnb-typescript/base'
],
'parser': '@typescript-eslint/parser',
'parserOptions': {
'ecmaVersion': 11,
'sourceType': 'module'
'sourceType': 'module',
'project': 'tsconfig.json'
},
'env': {
@ -12,11 +19,18 @@ module.exports = {
},
'plugins': [
'@typescript-eslint',
'chai-friendly',
'import',
'unicorn'
],
'settings': {
'import/resolver': {
'typescript': {}
}
},
'globals': { // TODO are all these necessary?
'globalThis': true,
'console': true,
@ -43,11 +57,11 @@ module.exports = {
'arrow-body-style': 'off',
'arrow-parens': ['error','as-needed'],
'class-methods-use-this': 'off',
'comma-dangle': ['error', 'never'],
'comma-spacing': 'off',
'@typescript-eslint/comma-dangle': ['error', 'never'],
'@typescript-eslint/comma-spacing': 'off',
'consistent-return': 'off',
'default-case': 'off',
'default-param-last': 'off',
'@typescript-eslint/default-param-last': 'off',
'eol-last': ['error', 'always'],
'function-call-argument-newline': 'off',
'func-names': ['error', 'never'],
@ -68,7 +82,7 @@ module.exports = {
'no-plusplus': 'off',
'no-restricted-syntax': ['error', 'ForInStatement', 'LabeledStatement', 'WithStatement'],
'object-curly-newline': 'off',
'no-shadow': 'off', // TODO get rid of this
'@typescript-eslint/no-shadow': 'off', // TODO get rid of this
'object-property-newline': [
'error',
{
@ -89,10 +103,12 @@ module.exports = {
'prefer-template': 'off',
'quote-props': 'off',
'quotes': ['error', 'single', { 'avoidEscape': true }],
'space-before-function-paren': 'off',
'@typescript-eslint/space-before-function-paren': ['error', { 'anonymous': 'ignore', 'named': 'never', 'asyncArrow': 'always' }],
'spaced-comment': 'off',
'indent': ['error', 2, { 'SwitchCase': 1 }],
'no-unused-vars': 'error',
'indent': 'off',
'@typescript-eslint/indent': ['error', 2, { 'SwitchCase': 1 }],
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': 'error',
// eslint-plugin-import rules:
'import/named': 'error',
@ -100,24 +116,23 @@ module.exports = {
'import/first': 'off',
'import/no-extraneous-dependencies': ['error', { 'devDependencies': true, 'optionalDependencies': false, 'peerDependencies': false }],
'import/no-unassigned-import': 'error',
'import/no-unresolved': ['error', {
// esm exports not supported: https://github.com/import-js/eslint-plugin-import/issues/1810
ignore: ['openpgp', '@openpgp/noble-hashes', '@openpgp/web-stream-tools', '@openpgp/asmcrypto.js']
}],
'import/no-unresolved': 'error',
'import/prefer-default-export': 'off',
// Custom silencers:
'camelcase': 'off', // used in tests, need to fix separately
'no-multi-assign': 'off',
'no-underscore-dangle': 'off',
'no-await-in-loop': 'off',
'camelcase': 'off', // snake_case used in tests, need to fix separately
'@typescript-eslint/naming-convention': 'off', // supersedes 'camelcase' rule
'@typescript-eslint/lines-between-class-members': 'off',
// Custom errors:
'no-use-before-define': [2, { 'functions': false, 'classes': true, 'variables': false }],
'@typescript-eslint/no-use-before-define': ['error', { 'functions': false, 'classes': true, 'variables': false, 'allowNamedExports': true }],
'no-constant-condition': [2, { 'checkLoops': false }],
'new-cap': [2, { 'properties': false, 'capIsNewExceptionPattern': 'EAX|OCB|GCM|CMAC|CBC|OMAC|CTR', 'newIsCapExceptionPattern': 'type|hash*' }],
'max-lines': [2, { 'max': 620, 'skipBlankLines': true, 'skipComments': true }],
'no-unused-expressions': 0,
'@typescript-eslint/no-unused-expressions': 0,
'chai-friendly/no-unused-expressions': [2, { 'allowShortCircuit': true }],
'unicorn/switch-case-braces': ['error', 'avoid'],

33
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,33 @@
version: 2
updates:
- package-ecosystem: "npm"
# The redundant target-branch directive is needed to set two different update schedules for npm,
# working around a dependabot limitation:
# see https://github.com/dependabot/dependabot-core/issues/1778#issuecomment-1988140219 .
target-branch: main
directory: "/"
schedule:
interval: "daily"
allow:
- dependency-name: "playwright"
versioning-strategy: increase
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
allow:
- dependency-name: "@noble*"
- dependency-name: "fflate"
versioning-strategy: increase
groups:
# Any packages matching the pattern @noble* where the highest resolvable
# version is minor or patch will be grouped together.
# Grouping rules apply to version updates only.
noble:
applies-to: version-updates
patterns:
- "@noble*"
update-types:
- "minor"
- "patch"

View File

@ -11,7 +11,8 @@
"id": "sop-openpgpjs-main",
"path": "__SOP_OPENPGPJS__",
"env": {
"OPENPGPJS_PATH": "__OPENPGPJS_MAIN__"
"OPENPGPJS_PATH": "__OPENPGPJS_MAIN__",
"DISABLE_PROFILES": "true"
}
},
{
@ -21,10 +22,14 @@
"path": "__GPGME_SOP__"
},
{
"path": "__GOSOP__"
"id": "gosop-v2",
"path": "__GOSOP_V2__"
},
{
"path": "__RNP_SOP__"
},
{
"path": "__RSOP__"
}
],
"rlimits": {

View File

@ -7,7 +7,8 @@ cat $CONFIG_TEMPLATE \
| sed "s@__OPENPGPJS_MAIN__@${OPENPGPJS_MAIN}@g" \
| sed "s@__SQOP__@${SQOP}@g" \
| sed "s@__GPGME_SOP__@${GPGME_SOP}@g" \
| sed "s@__GOSOP__@${GOSOP}@g" \
| sed "s@__SOP_OPENPGPJS__@${SOP_OPENPGPJS}@g" \
| sed "s@__GOSOP_V2__@${GOSOP_V2}@g" \
| sed "s@__SOP_OPENPGPJS__@${SOP_OPENPGPJS_V2}@g" \
| sed "s@__RNP_SOP__@${RNP_SOP}@g" \
| sed "s@__RSOP__@${RSOP}@g" \
> $CONFIG_OUTPUT

View File

@ -2,7 +2,7 @@ name: Performance Regression Test
on:
pull_request:
branches: [main, v6]
branches: [main]
jobs:
benchmark:
@ -11,15 +11,17 @@ jobs:
steps:
# check out pull request branch
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
path: pr
# check out main branch (to compare performance)
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
ref: main
path: main
- uses: actions/setup-node@v3
- uses: actions/setup-node@v4
with:
node-version: '>=20.6.0'
- name: Run pull request time benchmark
run: cd pr && npm install && npm run --silent benchmark-time > benchmarks.txt && cat benchmarks.txt

View File

@ -4,7 +4,7 @@ on:
push:
branches: [main]
pull_request:
branches: [main, v6]
branches: [main]
jobs:
lint:
@ -13,7 +13,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- run: npm ci --ignore-scripts
- run: npm run docs

View File

@ -2,7 +2,7 @@ name: SOP interoperability test suite
on:
pull_request:
branches: [ main, v6 ]
branches: [ main ]
jobs:
@ -10,34 +10,34 @@ jobs:
name: Run interoperability test suite
runs-on: ubuntu-latest
container:
image: ghcr.io/protonmail/openpgp-interop-test-docker:v1.1.1
image: ghcr.io/protonmail/openpgp-interop-test-docker:v1.1.12
credentials:
username: ${{ github.actor }}
password: ${{ secrets.github_token }}
steps:
# check out repo for scripts
- uses: actions/checkout@v3
- uses: actions/checkout@v4
# check out pull request branch
- name: Checkout openpgpjs-branch
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
path: openpgpjs-branch
- name: Install openpgpjs-branch
run: cd openpgpjs-branch && npm install
- name: Print openpgpjs-branch version
run: $SOP_OPENPGPJS version --extended
run: $SOP_OPENPGPJS_V2 version --extended
env:
OPENPGPJS_PATH: ${{ github.workspace }}/openpgpjs-branch
# check out main branch
- name: Checkout openpgpjs-main
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
ref: main
path: openpgpjs-main
- name: Install openpgpjs-main
run: cd openpgpjs-main && npm install
- name: Print openpgpjs-main version
run: $SOP_OPENPGPJS version --extended
run: $SOP_OPENPGPJS_V2 version --extended
env:
OPENPGPJS_PATH: ${{ github.workspace }}/openpgpjs-main
# Run test suite
@ -56,12 +56,12 @@ jobs:
RESULTS_HTML: .github/test-suite/test-suite-results.html
# Upload results
- name: Upload test results json artifact
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: test-suite-results.json
path: .github/test-suite/test-suite-results.json
- name: Upload test results html artifact
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: test-suite-results.html
path: .github/test-suite/test-suite-results.html
@ -72,16 +72,16 @@ jobs:
needs: test-suite
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Download test results json artifact
id: download-test-results
uses: actions/download-artifact@v3
uses: actions/download-artifact@v4
with:
name: test-suite-results.json
- name: Compare with baseline
uses: ProtonMail/openpgp-interop-test-analyzer@v1
uses: ProtonMail/openpgp-interop-test-analyzer@v2
with:
results: ${{ steps.download-test-results.outputs.download-path }}/test-suite-results.json
output: baseline-comparison.json
baseline: sop-openpgpjs-main
target: sop-openpgpjs-main
target: sop-openpgpjs-branch

View File

@ -4,18 +4,18 @@ on:
push:
branches: [main]
pull_request:
branches: [main, v6]
branches: [main]
jobs:
build: # cache both dist and tests (non-lightweight only), based on commit hash
name: Build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- name: Check for cached folders
id: cache-full
uses: actions/cache@v3
uses: actions/cache@v4
with:
path: |
dist
@ -31,20 +31,20 @@ jobs:
strategy:
fail-fast: false # if tests for one version fail, continue with the rest
matrix:
node-version: [16.x, 18.x, '20.x']
node-version: [18.x, 20.x, 22.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
name: Node ${{ matrix.node-version }}
runs-on: ubuntu-latest
needs: build
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- run: npm ci --ignore-scripts # for mocha
- name: Retrieve cached folders
uses: actions/cache/restore@v3
uses: actions/cache/restore@v4
id: cache-full
with:
# test/lib is not needed, but the path must be specified fully for a cache-hit
@ -57,15 +57,22 @@ jobs:
test-browsers-latest:
name: Browsers (latest)
runs-on: ubuntu-latest
needs: build
strategy:
fail-fast: false # if tests for one version fail, continue with the rest
matrix:
# run on all main platforms to test platform-specific code, if present
# (e.g. webkit's WebCrypto API implementation is different in macOS vs Linux)
# TODO: windows-latest fails to fetch resources from the wtr server; investigate if the problem is with path declaration or permissions
runner: ['ubuntu-latest', 'macos-latest']
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- name: Retrieve cached built folders
uses: actions/cache/restore@v3
uses: actions/cache/restore@v4
id: cache-full
with:
path: |
@ -79,33 +86,36 @@ jobs:
npm pkg delete scripts.prepare
npm ci
- name: Get Playwright version
- name: Get Playwright version and cache location
id: playwright-version
run: |
PLAYWRIGHT_VERSION=$(npm ls playwright | grep playwright | sed 's/.*@//')
PLAYWRIGHT_VERSION=$(npm ls playwright --depth=0 | grep playwright | sed 's/.*@//')
echo "version=$PLAYWRIGHT_VERSION" >> $GITHUB_OUTPUT
PLAYWRIGHT_CACHE=${{ fromJSON('{"ubuntu-latest": "~/.cache/ms-playwright", "macos-latest": "~/Library/Caches/ms-playwright"}')[matrix.runner] }}
echo "playwright_cache=$PLAYWRIGHT_CACHE" >> $GITHUB_OUTPUT
- name: Check for cached browsers
id: cache-playwright-browsers
uses: actions/cache@v3
uses: actions/cache@v4
with:
path: ~/.cache/ms-playwright
key: playwright-browsers-${{ steps.playwright-version.outputs.version }}
path: ${{ steps.playwright-version.outputs.playwright_cache }}
key: playwright-browsers-${{ matrix.runner }}-${{ steps.playwright-version.outputs.version }}
- name: Install browsers
if: steps.cache-playwright-browsers.outputs.cache-hit != 'true'
run: |
npx playwright install-deps chrome
npx playwright install-deps firefox
npx playwright install --with-deps chromium
npx playwright install --with-deps firefox
- name: Install WebKit # caching not possible, external shared libraries required
run: npx playwright install-deps webkit
if: ${{ matrix.runner == 'macos-latest' }} # do not install on ubuntu, since the X25519 WebCrypto implementation has issues
run: npx playwright install --with-deps webkit
- name: Run browser tests
run: npm run test-browser
run: npm run test-browser:ci -- --static-logging
- name: Run browser tests (lightweight) # overwrite test/lib
run: |
npm run build-test --lightweight
npm run test-browser
npm run test-browser:ci -- --static-logging
test-browsers-compatibility:
name: Browsers (older, on Browserstack)
@ -116,14 +126,23 @@ jobs:
BROWSERSTACK_ACCESS_KEY: VjgBVRMxNVBj7SjJFiau
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- name: Generate self-signed HTTPS certificates for web-test-runner server
uses: kofemann/action-create-certificate@v0.0.4
with:
hostcert: '127.0.0.1.pem'
hostkey: '127.0.0.1-key.pem'
cachain: 'ca-chain.pem'
- name: Adjust HTTPS certificates permissions
run: sudo chown runner:docker *.pem
- name: Install dependencies
run: npm ci --ignore-scripts
- name: Retrieve cached dist folder
uses: actions/cache/restore@v3
uses: actions/cache/restore@v4
id: cache-full
with:
path: |
@ -139,12 +158,12 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Run browserstack tests
run: npm run test-browserstack
run: npm run test-browserstack -- --static-logging
- name: Run browserstack tests (lightweight) # overwrite test/lib
run: |
npm run build-test --lightweight
npm run test-browserstack
npm run test-browserstack -- --static-logging
env:
LIGHTWEIGHT: true
@ -154,11 +173,11 @@ jobs:
needs: build
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- run: npm ci --ignore-scripts # TS
- name: Retrieve cached folders
uses: actions/cache/restore@v3
uses: actions/cache/restore@v4
id: cache-full
with:
path: |
@ -173,11 +192,11 @@ jobs:
needs: build
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- run: npm ci --ignore-scripts # linter
- name: Retrieve cached folders
uses: actions/cache/restore@v3
uses: actions/cache/restore@v4
id: cache-full
with:
path: |

2
.gitignore vendored
View File

@ -5,4 +5,4 @@ test/lib/
test/typescript/definitions.js
dist/
openpgp.store/
.nyc_output/
coverage

View File

@ -1,7 +1,7 @@
OpenPGP.js [![BrowserStack Status](https://automate.browserstack.com/badge.svg?badge_key=N1l2eHFOanVBMU9wYWxJM3ZnWERnc1lidkt5UkRqa3BralV3SWVhOGpGTT0tLVljSjE4Z3dzVmdiQjl6RWgxb2c3T2c9PQ==--5864052cd523f751b6b907d547ac9c4c5f88c8a3)](https://automate.browserstack.com/public-build/N1l2eHFOanVBMU9wYWxJM3ZnWERnc1lidkt5UkRqa3BralV3SWVhOGpGTT0tLVljSjE4Z3dzVmdiQjl6RWgxb2c3T2c9PQ==--5864052cd523f751b6b907d547ac9c4c5f88c8a3) [![Join the chat on Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/openpgpjs/openpgpjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
OpenPGP.js [![Join the chat on Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/openpgpjs/openpgpjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
==========
[OpenPGP.js](https://openpgpjs.org/) is a JavaScript implementation of the OpenPGP protocol. It implements the [crypto-refresh](https://datatracker.ietf.org/doc/draft-ietf-openpgp-crypto-refresh) (superseding [RFC4880](https://tools.ietf.org/html/rfc4880) and [RFC4880bis](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10)).
[OpenPGP.js](https://openpgpjs.org/) is a JavaScript implementation of the OpenPGP protocol. It implements [RFC 9580](https://datatracker.ietf.org/doc/rfc9580/) (superseding [RFC 4880](https://tools.ietf.org/html/rfc4880) and [RFC 4880bis](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10)).
**Table of Contents**
@ -33,60 +33,62 @@ OpenPGP.js [![BrowserStack Status](https://automate.browserstack.com/badge.svg?b
### Platform Support
* The `dist/openpgp.min.js` (or `.mjs`) bundle works with recent versions of Chrome, Firefox, Edge and Safari 13+.
* The `dist/openpgp.min.js` (or `.mjs`) bundle works with recent versions of Chrome, Firefox, Edge and Safari 14+.
* The `dist/node/openpgp.min.mjs` (or `.cjs`) bundle works in Node.js v16+: it is used by default when you `import ... from 'openpgp'` (resp. `require('openpgp')`).
* The `dist/node/openpgp.min.mjs` (or `.cjs`) bundle works in Node.js v18+: it is used by default when you `import ... from 'openpgp'` (or `require('openpgp')`, respectively).
* Support for the [Web Cryptography API](https://w3c.github.io/webcrypto/)'s `SubtleCrypto` is required.
* In browsers, `SubtleCrypto` is only available in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).
* In supported versions of Node.js, `SubtleCrypto` is always available.
* Support for the [Web Streams API](https://streams.spec.whatwg.org/) is required.
* In browsers: the latest versions of Chrome, Firefox, Edge and Safari support Streams, including `TransformStream`s.
These are needed if you use the library with stream inputs.
In previous versions of OpenPGP.js, Web Streams were automatically polyfilled by the library,
but from v6 this task is left up to the library user, due to the more extensive browser support, and the
polyfilling side-effects. If you're working with [older browsers versions which do not implement e.g. TransformStreams](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream#browser_compatibility), you can manually
load the [Web Streams polyfill](https://github.com/MattiasBuelens/web-streams-polyfills).
Please note that when you load the polyfills, the global `ReadableStream` property (if it exists) gets overwritten with the polyfill version.
In some edge cases, you might need to use the native
`ReadableStream` (for example when using it to create a `Response`
object), in which case you should store a reference to it before loading
the polyfills. There is also the [web-streams-adapter](https://github.com/MattiasBuelens/web-streams-adapter)
library to convert back and forth between them.
* In Node.js: OpenPGP.js v6 no longer supports native Node `Readable` streams in inputs, and instead expects (and outputs) [Node's Web Streams](https://nodejs.org/api/webstreams.html#class-readablestream). [Node v17+ includes utilities to convert from and to Web Streams](https://nodejs.org/api/stream.html#streamreadabletowebstreamreadable-options).
* Streaming support: the latest versions of Chrome, Firefox, Edge and Safari implement the
[Streams specification](https://streams.spec.whatwg.org/), including `TransformStream`s.
These are needed if you use the library with streamed inputs.
In previous versions of OpenPGP.js, WebStreams were automatically polyfilled by the library,
but from v6 this task is left up to the library user, due to the more extensive browser support, and the
polyfilling side-effects. If you're working with [older browsers versions which do not implement e.g. TransformStreams](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream), you can manually
load [WebStream polyfill](https://github.com/MattiasBuelens/web-streams-polyfills).
Please note that when you load the polyfills, the global `ReadableStream` property (if it exists) gets overwritten with the polyfill version.
In some edge cases, you might need to use the native
`ReadableStream` (for example when using it to create a `Response`
object), in which case you should store a reference to it before loading
the polyfills. There is also the [web-streams-adapter](https://github.com/MattiasBuelens/web-streams-adapter)
library to convert back and forth between them.
### Performance
* Version 3.0.0 of the library introduces support for public-key cryptography using [elliptic curves](https://wiki.gnupg.org/ECC). We use native implementations on browsers and Node.js when available. Elliptic curve cryptography provides stronger security per bits of key, which allows for much faster operations. Currently the following curves are supported:
* Version 3.0.0 of the library introduced support for public-key cryptography using [elliptic curves](https://wiki.gnupg.org/ECC). We use native implementations on browsers and Node.js when available. Compared to RSA, elliptic curve cryptography provides stronger security per bits of key, which allows for much faster operations. Currently the following curves are supported:
| Curve | Encryption | Signature | NodeCrypto | WebCrypto | Constant-Time |
|:---------------:|:----------:|:---------:|:----------:|:---------:|:-----------------:|
| curve25519 | ECDH | N/A | No | No | Algorithmically** |
| ed25519 | N/A | EdDSA | No | No | Algorithmically** |
| p256 | ECDH | ECDSA | Yes* | Yes* | If native*** |
| p384 | ECDH | ECDSA | Yes* | Yes* | If native*** |
| p521 | ECDH | ECDSA | Yes* | Yes* | If native*** |
| brainpoolP256r1 | ECDH | ECDSA | Yes* | No | If native*** |
| brainpoolP384r1 | ECDH | ECDSA | Yes* | No | If native*** |
| brainpoolP512r1 | ECDH | ECDSA | Yes* | No | If native*** |
| secp256k1 | ECDH | ECDSA | Yes* | No | If native*** |
| curve25519 | ECDH | N/A | No | No | Algorithmically |
| ed25519 | N/A | EdDSA | No | Yes* | If native** |
| nistP256 | ECDH | ECDSA | Yes* | Yes* | If native** |
| nistP384 | ECDH | ECDSA | Yes* | Yes* | If native** |
| nistP521 | ECDH | ECDSA | Yes* | Yes* | If native** |
| brainpoolP256r1 | ECDH | ECDSA | Yes* | No | If native** |
| brainpoolP384r1 | ECDH | ECDSA | Yes* | No | If native** |
| brainpoolP512r1 | ECDH | ECDSA | Yes* | No | If native** |
| secp256k1 | ECDH | ECDSA | Yes* | No | If native** |
\* when available
\** the curve25519 and ed25519 implementations are algorithmically constant-time, but may not be constant-time after optimizations of the JavaScript compiler
\*** these curves are only constant-time if the underlying native implementation is available and constant-time
\** these curves are only constant-time if the underlying native implementation is available and constant-time
* 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 platform's [native Web Crypto API](https://w3c.github.io/webcrypto/) is used for performance. On Node.js the native [crypto module](https://nodejs.org/api/crypto.html#crypto_crypto) is also used, in cases where it offers additional functionality.
* The library implements authenticated encryption (AEAD) as per the ["crypto refresh" draft standard](https://datatracker.ietf.org/doc/draft-ietf-openpgp-crypto-refresh) using AES-OCB, EAX, or GCM. This makes symmetric encryption faster on platforms with native implementations. However, since the specification is very recent and other OpenPGP implementations are in the process of adopting it, the feature is currently behind a flag. **Note: activating this setting can break compatibility with other OpenPGP implementations which have yet to implement the feature.** You can enable it by setting `openpgp.config.aeadProtect = true`.
Note that this setting has a different effect from the one in OpenPGP.js v5, which implemented support for a provisional version of AEAD from [RFC4880bis](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10), which was modified in a later draft of the crypto refresh.
* The library implements authenticated encryption (AEAD) as per [RFC 9580](https://datatracker.ietf.org/doc/rfc9580/) using AES-GCM, OCB, or EAX. This makes symmetric encryption faster on platforms with native implementations. However, since the specification is very recent and other OpenPGP implementations are in the process of adopting it, the feature is currently behind a flag. **Note: activating this setting can break compatibility with other OpenPGP implementations which have yet to implement the feature.** You can enable it by setting `openpgp.config.aeadProtect = true`.
Note that this setting has a different effect from the one in OpenPGP.js v5, which implemented support for a provisional version of AEAD from [RFC 4880bis](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10), which was modified in RFC 9580.
You can change the AEAD mode by setting one of the following options:
```
openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.ocb; // Default (widest ecosystem support), non-native
openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.gcm; // Native in WebCrypto and Node.js
openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.gcm; // Default, native in WebCrypto and Node.js
openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.ocb; // Non-native, but supported across RFC 9580 implementations
openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.eax; // Native in Node.js
```
* For environments that don't provide native crypto, the library falls back to [asm.js](https://caniuse.com/#feat=asmjs) AES and AEAD implementations.
### Getting started
#### Node.js
@ -182,7 +184,7 @@ If you notice missing or incorrect type definitions, feel free to open a PR.
### Examples
Here are some examples of how to use OpenPGP.js v5. For more elaborate examples and working code, please check out the [public API unit tests](https://github.com/openpgpjs/openpgpjs/blob/main/test/general/openpgp.js). If you're upgrading from v4 it might help to check out the [changelog](https://github.com/openpgpjs/openpgpjs/wiki/V5-Changelog) and [documentation](https://github.com/openpgpjs/openpgpjs#documentation).
Here are some examples of how to use OpenPGP.js v6. For more elaborate examples and working code, please check out the [public API unit tests](https://github.com/openpgpjs/openpgpjs/blob/main/test/general/openpgp.js). If you're upgrading from v4 it might help to check out the [changelog](https://github.com/openpgpjs/openpgpjs/wiki/v6-Changelog) and [documentation](https://github.com/openpgpjs/openpgpjs#documentation).
#### Encrypt and decrypt *Uint8Array* data with a password
@ -387,14 +389,8 @@ Where the value can be any of:
})();
```
For more information on using ReadableStreams, see [the MDN Documentation on the
Streams API](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API).
You can also pass a [Node.js `Readable`
stream](https://nodejs.org/api/stream.html#stream_class_stream_readable), in
which case OpenPGP.js will return a Node.js `Readable` stream as well, which you
can `.pipe()` to a `Writable` stream, for example.
For more information on using ReadableStreams (both in browsers and Node.js), see [the MDN Documentation on the
Streams API](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) .
#### Streaming encrypt and decrypt *String* data with PGP keys
@ -451,7 +447,7 @@ can `.pipe()` to a `Writable` stream, for example.
ECC keys (smaller and faster to generate):
Possible values for `curve` are: `curve25519`, `ed25519`, `p256`, `p384`, `p521`,
Possible values for `curve` are: `curve25519`, `ed25519`, `nistP256`, `nistP384`, `nistP521`,
`brainpoolP256r1`, `brainpoolP384r1`, `brainpoolP512r1`, and `secp256k1`.
Note that both the `curve25519` and `ed25519` options generate a primary key for signing using Ed25519
and a subkey for encryption using Curve25519.
@ -668,7 +664,7 @@ To create your own build of the library, just run the following command after cl
npm install && npm test
For debugging browser errors, you can run `npm start` and open [`http://localhost:8080/test/unittests.html`](http://localhost:8080/test/unittests.html) in a browser, or run the following command:
For debugging browser errors, run the following command:
npm run browsertest

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

222
openpgp.d.ts vendored
View File

@ -1,3 +1,5 @@
/* eslint-disable max-lines, @typescript-eslint/indent */
/**
* Type definitions for OpenPGP.js http://openpgpjs.org/
*
@ -7,9 +9,19 @@
* - Errietta Kostala <https://github.com/errietta>
*/
import type { WebStream as GenericWebStream, NodeStream as GenericNodeStream } from '@openpgp/web-stream-tools';
import type { WebStream as GenericWebStream, NodeWebStream as GenericNodeWebStream } from '@openpgp/web-stream-tools';
/* ############## v5 KEY #################### */
/* ############## STREAM #################### */
type Data = Uint8Array | string;
// web-stream-tools might end up supporting additional data types, so we re-declare the types
// to enforce the type contraint that we need.
export type WebStream<T extends Data> = GenericWebStream<T>;
export type NodeWebStream<T extends Data> = GenericNodeWebStream<T>;
export type Stream<T extends Data> = WebStream<T> | NodeWebStream<T>;
export type MaybeStream<T extends Data> = T | Stream<T>;
type MaybeArray<T> = T | Array<T>;
/* ############## KEY #################### */
// The Key and PublicKey types can be used interchangably since TS cannot detect the difference, as they have the same class properties.
// The declared readKey(s) return type is Key instead of a PublicKey since it seems more obvious that a Key can be cast to a PrivateKey.
export function readKey(options: { armoredKey: string, config?: PartialConfig }): Promise<Key>;
@ -54,8 +66,8 @@ export abstract class Key {
// NB: the order of the `update` declarations matters, since PublicKey includes PrivateKey
public update(sourceKey: PrivateKey, date?: Date, config?: Config): Promise<PrivateKey>;
public update(sourceKey: PublicKey, date?: Date, config?: Config): Promise<PublicKey>;
public signPrimaryUser(privateKeys: PrivateKey[], date?: Date, userID?: UserID, config?: Config): Promise<this>
public signAllUsers(privateKeys: PrivateKey[], date?: Date, config?: Config): Promise<this>
public signPrimaryUser(privateKeys: PrivateKey[], date?: Date, userID?: UserID, config?: Config): Promise<this>;
public signAllUsers(privateKeys: PrivateKey[], date?: Date, config?: Config): Promise<this>;
public verifyPrimaryKey(date?: Date, userID?: UserID, config?: Config): Promise<void>; // throws on error
public verifyPrimaryUser(publicKeys: PublicKey[], date?: Date, userIDs?: UserID, config?: Config): Promise<{ keyID: KeyID, valid: boolean | null }[]>;
public verifyAllUsers(publicKeys?: PublicKey[], date?: Date, config?: Config): Promise<{ userID: string, keyID: KeyID, valid: boolean | null }[]>;
@ -82,7 +94,7 @@ export class PrivateKey extends PublicKey {
public revoke(reason?: ReasonForRevocation, date?: Date, config?: Config): Promise<PrivateKey>;
public isDecrypted(): boolean;
public addSubkey(options: SubkeyOptions): Promise<PrivateKey>;
public getDecryptionKeys(keyID?: KeyID, date?: Date | null, userID?: UserID, config?: Config): Promise<PrivateKey | Subkey>
public getDecryptionKeys(keyID?: KeyID, date?: Date | null, userID?: UserID, config?: Config): Promise<(PrivateKey | Subkey)[]>;
public update(sourceKey: PublicKey, date?: Date, config?: Config): Promise<PrivateKey>;
}
@ -98,9 +110,9 @@ export class Subkey {
public getCreationTime(): Date;
public getAlgorithmInfo(): AlgorithmInfo;
public getKeyID(): KeyID;
public getExpirationTime(date?: Date, config?: Config): Promise<Date | typeof Infinity | null>
public getExpirationTime(date?: Date, config?: Config): Promise<Date | typeof Infinity | null>;
public isRevoked(signature: SignaturePacket, key: AnyKeyPacket, date?: Date, config?: Config): Promise<boolean>;
public update(subKey: Subkey, date?: Date, config?: Config): Promise<void>
public update(subKey: Subkey, date?: Date, config?: Config): Promise<void>;
public revoke(primaryKey: SecretKeyPacket, reasonForRevocation?: ReasonForRevocation, date?: Date, config?: Config): Promise<Subkey>;
}
@ -118,13 +130,13 @@ export interface PrimaryUser {
selfCertification: SignaturePacket;
}
type AlgorithmInfo = {
export type AlgorithmInfo = {
algorithm: enums.publicKeyNames;
bits?: number;
curve?: EllipticCurveName;
};
/* ############## v5 SIG #################### */
/* ############## SIG #################### */
export function readSignature(options: { armoredSignature: string, config?: PartialConfig }): Promise<Signature>;
export function readSignature(options: { binarySignature: Uint8Array, config?: PartialConfig }): Promise<Signature>;
@ -143,7 +155,7 @@ interface VerificationResult {
signature: Promise<Signature>;
}
/* ############## v5 CLEARTEXT #################### */
/* ############## CLEARTEXT #################### */
export function readCleartextMessage(options: { cleartextMessage: string, config?: PartialConfig }): Promise<CleartextMessage>;
@ -176,7 +188,7 @@ export class CleartextMessage {
verify(keys: PublicKey[], date?: Date, config?: Config): Promise<VerificationResult[]>;
}
/* ############## v5 MSG #################### */
/* ############## MSG #################### */
export function generateSessionKey(options: { encryptionKeys: MaybeArray<PublicKey>, date?: Date, encryptionUserIDs?: MaybeArray<UserID>, config?: PartialConfig }): Promise<SessionKey>;
export function encryptSessionKey(options: EncryptSessionKeyOptions & { format?: 'armored' }): Promise<string>;
export function encryptSessionKey(options: EncryptSessionKeyOptions & { format: 'binary' }): Promise<Uint8Array>;
@ -190,25 +202,25 @@ export function createMessage<T extends MaybeStream<string>>(options: { text: T,
export function createMessage<T extends MaybeStream<Uint8Array>>(options: { binary: T, filename?: string, date?: Date, format?: enums.literalFormatNames }): Promise<Message<T>>;
export function encrypt<T extends MaybeStream<Data>>(options: EncryptOptions & { message: Message<T>, format?: 'armored' }): Promise<
T extends WebStream<infer X> ? WebStream<string> :
T extends NodeStream<infer X> ? NodeStream<string> :
T extends WebStream<Data> ? WebStream<string> :
T extends NodeWebStream<Data> ? NodeWebStream<string> :
string
>;
export function encrypt<T extends MaybeStream<Data>>(options: EncryptOptions & { message: Message<T>, format: 'binary' }): Promise<
T extends WebStream<infer X> ? WebStream<Uint8Array> :
T extends NodeStream<infer X> ? NodeStream<Uint8Array> :
T extends WebStream<Data> ? WebStream<Uint8Array> :
T extends NodeWebStream<Data> ? NodeWebStream<Uint8Array> :
Uint8Array
>;
export function encrypt<T extends MaybeStream<Data>>(options: EncryptOptions & { message: Message<T>, format: 'object' }): Promise<Message<T>>;
export function sign<T extends MaybeStream<Data>>(options: SignOptions & { message: Message<T>, format?: 'armored' }): Promise<
T extends WebStream<infer X> ? WebStream<string> :
T extends NodeStream<infer X> ? NodeStream<string> :
T extends WebStream<Data> ? WebStream<string> :
T extends NodeWebStream<Data> ? NodeWebStream<string> :
string
>;
export function sign<T extends MaybeStream<Data>>(options: SignOptions & { message: Message<T>, format: 'binary' }): Promise<
T extends WebStream<infer X> ? WebStream<Uint8Array> :
T extends NodeStream<infer X> ? NodeStream<Uint8Array> :
T extends WebStream<Data> ? WebStream<Uint8Array> :
T extends NodeWebStream<Data> ? NodeWebStream<Uint8Array> :
Uint8Array
>;
export function sign<T extends MaybeStream<Data>>(options: SignOptions & { message: Message<T>, format: 'object' }): Promise<Message<T>>;
@ -217,26 +229,26 @@ export function sign(options: SignOptions & { message: CleartextMessage, format:
export function decrypt<T extends MaybeStream<Data>>(options: DecryptOptions & { message: Message<T>, format: 'binary' }): Promise<DecryptMessageResult & {
data:
T extends WebStream<infer X> ? WebStream<Uint8Array> :
T extends NodeStream<infer X> ? NodeStream<Uint8Array> :
T extends WebStream<Data> ? WebStream<Uint8Array> :
T extends NodeWebStream<Data> ? NodeWebStream<Uint8Array> :
Uint8Array
}>;
export function decrypt<T extends MaybeStream<Data>>(options: DecryptOptions & { message: Message<T> }): Promise<DecryptMessageResult & {
data:
T extends WebStream<infer X> ? WebStream<string> :
T extends NodeStream<infer X> ? NodeStream<string> :
T extends WebStream<Data> ? WebStream<string> :
T extends NodeWebStream<Data> ? NodeWebStream<string> :
string
}>;
export function verify(options: VerifyOptions & { message: CleartextMessage, format?: 'utf8' }): Promise<VerifyMessageResult<string>>;
export function verify<T extends MaybeStream<Data>>(options: VerifyOptions & { message: Message<T>, format: 'binary' }): Promise<VerifyMessageResult<
T extends WebStream<infer X> ? WebStream<Uint8Array> :
T extends NodeStream<infer X> ? NodeStream<Uint8Array> :
T extends WebStream<Data> ? WebStream<Uint8Array> :
T extends NodeWebStream<Data> ? NodeWebStream<Uint8Array> :
Uint8Array
>>;
export function verify<T extends MaybeStream<Data>>(options: VerifyOptions & { message: Message<T> }): Promise<VerifyMessageResult<
T extends WebStream<infer X> ? WebStream<string> :
T extends NodeStream<infer X> ? NodeStream<string> :
T extends WebStream<Data> ? WebStream<string> :
T extends NodeWebStream<Data> ? NodeWebStream<string> :
string
>>;
@ -263,7 +275,7 @@ export class Message<T extends MaybeStream<Data>> {
/** Encrypt the message
@param encryptionKeys array of public keys, used to encrypt the message
*/
public encrypt(encryptionKeys?: PublicKey[], passwords?: string[], sessionKeys?: SessionKey[], wildcard?: boolean, encryptionKeyIDs?: KeyID[], date?: Date, userIDs?: UserID[], config?: Config): Promise<Message<MaybeStream<Data>>>;
public encrypt(encryptionKeys?: PublicKey[], passwords?: string[], sessionKeys?: SessionKey[], wildcard?: boolean, encryptionKeyIDs?: KeyID[], date?: Date, userIDs?: UserID[], config?: Config): Promise<Message<MaybeStream<Data>>>;
/** Returns the key IDs of the keys to which the session key is encrypted
*/
@ -305,7 +317,7 @@ export class Message<T extends MaybeStream<Data>> {
}
/* ############## v5 CONFIG #################### */
/* ############## CONFIG #################### */
interface Config {
preferredHashAlgorithm: enums.hash;
@ -313,13 +325,11 @@ interface Config {
preferredCompressionAlgorithm: enums.compression;
showVersion: boolean;
showComment: boolean;
deflateLevel: number;
aeadProtect: boolean;
allowUnauthenticatedMessages: boolean;
allowUnauthenticatedStream: boolean;
minRSABits: number;
passwordCollisionCheck: boolean;
revocationsExpire: boolean;
ignoreUnsupportedPackets: boolean;
ignoreMalformedPackets: boolean;
versionString: string;
@ -330,6 +340,7 @@ interface Config {
constantTimePKCS1Decryption: boolean;
constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: Set<enums.symmetric>;
v6Keys: boolean;
enableParsingV5Entities: boolean;
preferredAEADAlgorithm: enums.aead;
aeadChunkSizeByte: number;
s2kType: enums.s2k.iterated | enums.s2k.argon2;
@ -343,15 +354,15 @@ interface Config {
rejectPublicKeyAlgorithms: Set<enums.publicKey>;
rejectCurves: Set<enums.curve>;
}
export var config: Config;
export const config: Config;
// PartialConfig has the same properties as Config, but declared as optional.
// This interface is relevant for top-level functions, which accept a subset of configuration options
interface PartialConfig extends Partial<Config> {}
export interface PartialConfig extends Partial<Config> {}
/* ############## v5 PACKET #################### */
/* ############## PACKET #################### */
declare abstract class BasePacket {
export declare abstract class BasePacket {
static readonly tag: enums.packet;
public read(bytes: Uint8Array): void;
public write(): Uint8Array;
@ -424,7 +435,7 @@ export class AEADEncryptedDataPacket extends BasePacket {
static readonly tag: enums.packet.aeadEncryptedData;
private decrypt(sessionKeyAlgorithm: enums.symmetric, sessionKey: Uint8Array, config?: Config): void;
private encrypt(sessionKeyAlgorithm: enums.symmetric, sessionKey: Uint8Array, config?: Config): void;
private crypt(fn: Function, sessionKey: Uint8Array, data: MaybeStream<Uint8Array>): MaybeStream<Uint8Array>
private crypt(fn: Function, sessionKey: Uint8Array, data: MaybeStream<Uint8Array>): MaybeStream<Uint8Array>;
}
export class PublicKeyEncryptedSessionKeyPacket extends BasePacket {
@ -487,7 +498,8 @@ export class SignaturePacket extends BasePacket {
public hashAlgorithm: enums.hash | null;
public publicKeyAlgorithm: enums.publicKey | null;
public signatureData: null | Uint8Array;
public unhashedSubpackets: null | Uint8Array;
public unhashedSubpackets: RawSubpacket[];
public unknownSubpackets: RawSubpacket[];
public signedHashValue: null | Uint8Array;
public created: Date | null;
public signatureExpirationTime: null | number;
@ -531,6 +543,12 @@ export class SignaturePacket extends BasePacket {
public getExpirationTime(): Date | typeof Infinity;
}
export interface RawSubpacket {
type: number;
critical: boolean;
body: Uint8Array;
}
export interface RawNotation {
name: string;
value: Uint8Array;
@ -561,16 +579,7 @@ export class PacketList<T extends AnyPacket> extends Array<T> {
public findPacket(tag: enums.packet): T | undefined;
}
/* ############## v5 STREAM #################### */
type Data = Uint8Array | string;
export interface WebStream<T extends Data> extends GenericWebStream<T> {}
export interface NodeStream<T extends Data> extends GenericNodeStream<T> {}
export type Stream<T extends Data> = WebStream<T> | NodeStream<T>;
export type MaybeStream<T extends Data> = T | Stream<T>;
/* ############## v5 GENERAL #################### */
type MaybeArray<T> = T | Array<T>;
/* ############## GENERAL #################### */
export interface UserID { name?: string; email?: string; comment?: string; }
export interface SessionKey {
@ -586,7 +595,7 @@ export interface DecryptedSessionKey {
export interface ReasonForRevocation { flag?: enums.reasonForRevocation, string?: string }
interface EncryptOptions {
export interface EncryptOptions {
/** message to be encrypted as created by createMessage */
message: Message<MaybeStream<Data>>;
/** (optional) array of keys or single key, used to encrypt the message */
@ -618,7 +627,7 @@ interface EncryptOptions {
config?: PartialConfig;
}
interface DecryptOptions {
export interface DecryptOptions {
/** the message object with the encrypted data */
message: Message<MaybeStream<Data>>;
/** (optional) private keys with decrypted secret key data or session key */
@ -640,7 +649,7 @@ interface DecryptOptions {
config?: PartialConfig;
}
interface SignOptions {
export interface SignOptions {
message: CleartextMessage | Message<MaybeStream<Data>>;
signingKeys: MaybeArray<PrivateKey>;
format?: 'armored' | 'binary' | 'object';
@ -652,7 +661,7 @@ interface SignOptions {
config?: PartialConfig;
}
interface VerifyOptions {
export interface VerifyOptions {
/** (cleartext) message object with signatures */
message: CleartextMessage | Message<MaybeStream<Data>>;
/** array of publicKeys or single key, to verify signatures */
@ -668,7 +677,7 @@ interface VerifyOptions {
config?: PartialConfig;
}
interface EncryptSessionKeyOptions extends SessionKey {
export interface EncryptSessionKeyOptions extends SessionKey {
encryptionKeys?: MaybeArray<PublicKey>,
passwords?: MaybeArray<string>,
format?: 'armored' | 'binary' | 'object',
@ -679,7 +688,7 @@ interface EncryptSessionKeyOptions extends SessionKey {
config?: PartialConfig
}
interface SerializedKeyPair<T extends string|Uint8Array> {
interface SerializedKeyPair<T extends string | Uint8Array> {
privateKey: T;
publicKey: T;
}
@ -688,12 +697,12 @@ interface KeyPair {
publicKey: PublicKey;
}
export type EllipticCurveName = 'ed25519Legacy' | 'curve25519Legacy' | 'p256' | 'p384' | 'p521' | 'secp256k1' | 'brainpoolP256r1' | 'brainpoolP384r1' | 'brainpoolP512r1';
export type EllipticCurveName = 'ed25519Legacy' | 'curve25519Legacy' | 'nistP256' | 'nistP384' | 'nistP521' | 'secp256k1' | 'brainpoolP256r1' | 'brainpoolP384r1' | 'brainpoolP512r1';
interface GenerateKeyOptions {
userIDs: MaybeArray<UserID>;
passphrase?: string;
type?: 'ecc' | 'rsa';
type?: 'ecc' | 'rsa' | 'curve25519' | 'curve448';
curve?: EllipticCurveName;
rsaBits?: number;
keyExpirationTime?: number;
@ -704,30 +713,24 @@ interface GenerateKeyOptions {
}
export type KeyOptions = GenerateKeyOptions;
interface SubkeyOptions {
type?: 'ecc' | 'rsa';
curve?: EllipticCurveName;
rsaBits?: number;
keyExpirationTime?: number;
date?: Date;
export interface SubkeyOptions extends Pick<GenerateKeyOptions, 'type' | 'curve' | 'rsaBits' | 'keyExpirationTime' | 'date' | 'config'> {
sign?: boolean;
config?: PartialConfig;
}
declare class KeyID {
export declare class KeyID {
bytes: string;
equals(keyID: KeyID, matchWildcard?: boolean): boolean;
toHex(): string;
static fromID(hex: string): KeyID;
}
interface DecryptMessageResult {
export interface DecryptMessageResult {
data: MaybeStream<Data>;
signatures: VerificationResult[];
filename: string;
}
interface VerifyMessageResult<T extends MaybeStream<Data> = MaybeStream<Data>> {
export interface VerifyMessageResult<T extends MaybeStream<Data> = MaybeStream<Data>> {
data: T;
signatures: VerificationResult[];
}
@ -736,7 +739,7 @@ interface VerifyMessageResult<T extends MaybeStream<Data> = MaybeStream<Data>> {
/**
* Armor an OpenPGP binary packet block
*/
export function armor(messagetype: enums.armor, body: object, partindex?: number, parttotal?: number, customComment?: string, config?: Config): string;
export function armor(messagetype: enums.armor, body: object, partindex?: number, parttotal?: number, customComment?: string, emitChecksum?: boolean, config?: Config): string;
/**
* DeArmor an OpenPGP armored message; verify the checksum and return the encoded bytes
@ -746,44 +749,44 @@ export function unarmor(input: string, config?: Config): Promise<{ text: string,
/* ############## v5 ENUMS #################### */
export namespace enums {
function read(type: typeof armor, e: armor): armorNames;
function read(type: typeof compression, e: compression): compressionNames;
function read(type: typeof hash, e: hash): hashNames;
function read(type: typeof packet, e: packet): packetNames;
function read(type: typeof publicKey, e: publicKey): publicKeyNames;
function read(type: typeof symmetric, e: symmetric): symmetricNames;
function read(type: typeof keyStatus, e: keyStatus): keyStatusNames;
function read(type: typeof keyFlags, e: keyFlags): keyFlagsNames;
export function read(type: typeof armor, e: armor): armorNames;
export function read(type: typeof compression, e: compression): compressionNames;
export function read(type: typeof hash, e: hash): hashNames;
export function read(type: typeof packet, e: packet): packetNames;
export function read(type: typeof publicKey, e: publicKey): publicKeyNames;
export function read(type: typeof symmetric, e: symmetric): symmetricNames;
export function read(type: typeof keyStatus, e: keyStatus): keyStatusNames;
export function read(type: typeof keyFlags, e: keyFlags): keyFlagsNames;
export type armorNames = 'multipartSection' | 'multipartLast' | 'signed' | 'message' | 'publicKey' | 'privateKey';
enum armor {
export enum armor {
multipartSection = 0,
multipartLast = 1,
signed = 2,
message = 3,
publicKey = 4,
privateKey = 5,
signature = 6,
signature = 6
}
enum reasonForRevocation {
export enum reasonForRevocation {
noReason = 0, // No reason specified (key revocations or cert revocations)
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';
enum compression {
export enum compression {
uncompressed = 0,
zip = 1,
zlib = 2,
bzip2 = 3,
bzip2 = 3
}
export type hashNames = 'md5' | 'sha1' | 'ripemd' | 'sha256' | 'sha384' | 'sha512' | 'sha224';
enum hash {
export type hashNames = 'md5' | 'sha1' | 'ripemd' | 'sha256' | 'sha384' | 'sha512' | 'sha224' | 'sha3_256' | 'sha3_512';
export enum hash {
md5 = 1,
sha1 = 2,
ripemd = 3,
@ -791,12 +794,14 @@ export namespace enums {
sha384 = 9,
sha512 = 10,
sha224 = 11,
sha3_256 = 12,
sha3_512 = 14
}
export type packetNames = 'publicKeyEncryptedSessionKey' | 'signature' | 'symEncryptedSessionKey' | 'onePassSignature' | 'secretKey' | 'publicKey'
| 'secretSubkey' | 'compressed' | 'symmetricallyEncrypted' | 'marker' | 'literal' | 'trust' | 'userID' | 'publicSubkey' | 'userAttribute'
| 'symEncryptedIntegrityProtected' | 'modificationDetectionCode' | 'AEADEncryptedDataPacket';
enum packet {
export type packetNames = 'publicKeyEncryptedSessionKey' | 'signature' | 'symEncryptedSessionKey' | 'onePassSignature' | 'secretKey' | 'publicKey' |
'secretSubkey' | 'compressed' | 'symmetricallyEncrypted' | 'marker' | 'literal' | 'trust' | 'userID' | 'publicSubkey' | 'userAttribute' |
'symEncryptedIntegrityProtected' | 'modificationDetectionCode' | 'AEADEncryptedDataPacket';
export enum packet {
publicKeyEncryptedSessionKey = 1,
signature = 2,
symEncryptedSessionKey = 3,
@ -814,11 +819,11 @@ export namespace enums {
userAttribute = 17,
symEncryptedIntegrityProtectedData = 18,
modificationDetectionCode = 19,
aeadEncryptedData = 20,
aeadEncryptedData = 20
}
export type publicKeyNames = 'rsaEncryptSign' | 'rsaEncrypt' | 'rsaSign' | 'elgamal' | 'dsa' | 'ecdh' | 'ecdsa' | 'eddsaLegacy' | 'aedh' | 'aedsa' | 'ed25519' | 'x25519' | 'ed448' | 'x448';
enum publicKey {
export enum publicKey {
rsaEncryptSign = 1,
rsaEncrypt = 2,
rsaSign = 3,
@ -835,10 +840,16 @@ export namespace enums {
ed448 = 28
}
enum curve {
p256 = 'p256',
p384 = 'p384',
p521 = 'p521',
export enum curve {
/** @deprecated use `nistP256` instead */
p256 = 'nistP256',
nistP256 = 'nistP256',
/** @deprecated use `nistP384` instead */
p384 = 'nistP384',
nistP384 = 'nistP384',
/** @deprecated use `nistP521` instead */
p521 = 'nistP521',
nistP521 = 'nistP521',
/** @deprecated use `ed25519Legacy` instead */
ed25519 = 'ed25519Legacy',
ed25519Legacy = 'ed25519Legacy',
@ -852,7 +863,7 @@ export namespace enums {
}
export type symmetricNames = 'idea' | 'tripledes' | 'cast5' | 'blowfish' | 'aes128' | 'aes192' | 'aes256' | 'twofish';
enum symmetric {
export enum symmetric {
idea = 1,
tripledes = 2,
cast5 = 3,
@ -860,31 +871,30 @@ export namespace enums {
aes128 = 7,
aes192 = 8,
aes256 = 9,
twofish = 10,
twofish = 10
}
export type keyStatusNames = 'invalid' | 'expired' | 'revoked' | 'valid' | 'noSelfCert';
enum keyStatus {
export enum keyStatus {
invalid = 0,
expired = 1,
revoked = 2,
valid = 3,
noSelfCert = 4,
noSelfCert = 4
}
export type keyFlagsNames = 'certifyKeys' | 'signData' | 'encryptCommunication' | 'encryptStorage' | 'splitPrivateKey' | 'authentication'
| 'sharedPrivateKey';
enum keyFlags {
export type keyFlagsNames = 'certifyKeys' | 'signData' | 'encryptCommunication' | 'encryptStorage' | 'splitPrivateKey' | 'authentication' | 'sharedPrivateKey';
export enum keyFlags {
certifyKeys = 1,
signData = 2,
encryptCommunication = 4,
encryptStorage = 8,
splitPrivateKey = 16,
authentication = 32,
sharedPrivateKey = 128,
sharedPrivateKey = 128
}
enum signature {
export enum signature {
binary = 0,
text = 1,
standalone = 2,
@ -903,21 +913,23 @@ export namespace enums {
}
export type aeadNames = 'eax' | 'ocb' | 'gcm';
enum aead {
export enum aead {
eax = 1,
ocb = 2,
gcm = 3,
/** @deprecated use `gcm` instead */
experimentalGCM = 100 // Private algorithm
}
export type literalFormatNames = 'utf8' | 'binary' | 'text' | 'mime'
enum literal {
export type literalFormatNames = 'utf8' | 'binary' | 'text' | 'mime';
export enum literal {
binary = 98,
text = 116,
utf8 = 117,
mime = 109
}
enum s2k {
export enum s2k {
simple = 0,
salted = 1,
iterated = 3,

18084
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,11 +1,11 @@
{
"name": "openpgp",
"description": "OpenPGP.js is a Javascript implementation of the OpenPGP protocol. This is defined in RFC 4880.",
"version": "6.0.0-alpha.0",
"version": "6.1.0",
"license": "LGPL-3.0+",
"homepage": "https://openpgpjs.org/",
"engines": {
"node": ">= 16.0.0"
"node": ">= 18.0.0"
},
"keywords": [
"crypto",
@ -22,12 +22,12 @@
"exports": {
".": {
"types": "./openpgp.d.ts",
"browser": "./dist/openpgp.min.mjs",
"import": "./dist/node/openpgp.mjs",
"require": "./dist/node/openpgp.min.cjs",
"browser": "./dist/openpgp.min.mjs"
"require": "./dist/node/openpgp.min.cjs"
},
"./lightweight": {
"types": "../openpgp.d.ts",
"types": "./openpgp.d.ts",
"browser": "./dist/lightweight/openpgp.min.mjs"
}
},
@ -46,67 +46,72 @@
"build-test": "npm run build --build-only=test",
"prepare": "npm run build",
"test": "mocha --timeout 120000 test/unittests.js",
"test-type-definitions": "ts-node --esm test/typescript/definitions.ts",
"test-type-definitions": "tsx test/typescript/definitions.ts",
"benchmark-time": "node test/benchmarks/time.js",
"benchmark-memory-usage": "node test/benchmarks/memory_usage.js",
"start": "http-server",
"prebrowsertest": "npm run build-test",
"browsertest": "npm start -- -o test/unittests.html",
"test-browser": "karma start test/karma.conf.cjs",
"test-browserstack": "karma start test/karma.conf.cjs --browsers bs_safari_latest,bs_ios_14,bs_safari_13_1",
"coverage": "nyc npm test",
"browsertest": "web-test-runner --config test/web-test-runner.config.js --group local --manual --open",
"test-browser": "web-test-runner --config test/web-test-runner.config.js --group local --playwright --browsers chromium firefox webkit",
"test-browser:ci": "web-test-runner --config test/web-test-runner.config.js --group headless:ci",
"test-browserstack": "web-test-runner --config test/web-test-runner.browserstack.config.js",
"coverage": "c8 npm test",
"lint": "eslint .",
"docs": "jsdoc --configure .jsdocrc.cjs --destination docs --recurse README.md src && printf '%s' 'docs.openpgpjs.org' > docs/CNAME",
"preversion": "rm -rf dist docs node_modules && npm ci && npm test",
"version": "npm run docs && git add -A docs",
"postversion": "git push && git push --tags && npm publish"
"postversion": "git push --follow-tags && npm publish"
},
"devDependencies": {
"@openpgp/asmcrypto.js": "^3.0.0",
"@openpgp/noble-curves": "^1.2.1-0",
"@noble/ciphers": "^1.2.1",
"@noble/curves": "^1.8.1",
"@noble/hashes": "^1.5.0",
"@openpgp/jsdoc": "^3.6.11",
"@openpgp/noble-hashes": "^1.3.3-0",
"@openpgp/seek-bzip": "^1.0.5-git",
"@openpgp/tweetnacl": "^1.0.4-1",
"@openpgp/web-stream-tools": "^0.0.14",
"@rollup/plugin-alias": "^5.0.0",
"@rollup/plugin-commonjs": "^24.0.1",
"@rollup/plugin-node-resolve": "^15.0.1",
"@rollup/plugin-replace": "^5.0.2",
"@rollup/plugin-terser": "^0.4.0",
"@rollup/plugin-wasm": "^6.1.2",
"@types/chai": "^4.2.14",
"@openpgp/web-stream-tools": "~0.1.3",
"@rollup/plugin-alias": "^5.1.1",
"@rollup/plugin-commonjs": "^25.0.8",
"@rollup/plugin-node-resolve": "^15.3.0",
"@rollup/plugin-replace": "^5.0.7",
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^11.1.6",
"@rollup/plugin-wasm": "^6.2.2",
"@types/chai": "^4.3.19",
"@types/sinon": "^17.0.3",
"@typescript-eslint/parser": "^7.18.0",
"@web/test-runner": "^0.19.0",
"@web/test-runner-browserstack": "^0.7.2",
"@web/test-runner-mocha": "^0.9.0",
"@web/test-runner-playwright": "^0.11.0",
"argon2id": "^1.0.1",
"benchmark": "^2.1.4",
"bn.js": "^4.11.8",
"chai": "^4.3.7",
"chai-as-promised": "^7.1.1",
"eslint": "^8.34.0",
"bn.js": "^5.2.1",
"c8": "^8.0.1",
"chai": "^4.4.1",
"chai-as-promised": "^7.1.2",
"eckey-utils": "^0.7.14",
"eslint": "^8.57.1",
"eslint-config-airbnb": "^19.0.4",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-plugin-chai-friendly": "^0.7.2",
"eslint-plugin-import": "^2.27.5",
"eslint-config-airbnb-typescript": "^18.0.0",
"eslint-import-resolver-typescript": "^3.6.3",
"eslint-plugin-chai-friendly": "^0.7.4",
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-unicorn": "^48.0.1",
"fflate": "^0.7.4",
"http-server": "^14.1.1",
"karma": "^6.4.0",
"karma-browserstack-launcher": "^1.6.0",
"karma-chrome-launcher": "^3.1.1",
"karma-firefox-launcher": "^2.1.2",
"karma-mocha": "^2.0.1",
"karma-mocha-reporter": "^2.2.5",
"karma-webkit-launcher": "^2.1.0",
"mocha": "^10.2.0",
"nyc": "^14.1.1",
"playwright": "^1.30.0",
"rollup": "^3.29.4",
"sinon": "^15.1.0",
"ts-node": "^10.9.1",
"typescript": "^4.1.2",
"web-streams-polyfill": "^3.2.0"
"fflate": "^0.8.2",
"mocha": "^10.7.3",
"playwright": "^1.51.1",
"rollup": "^4.24.2",
"sinon": "^18.0.1",
"ts-node": "^10.9.2",
"tslib": "^2.8.0",
"tsx": "^4.19.2",
"typescript": "^5.6.3",
"web-streams-polyfill": "^4.0.0"
},
"dependencies": {
"asn1.js": "^5.0.0"
"overrides": {
"@web/dev-server-core": "npm:@openpgp/wtr-dev-server-core@0.7.3-patch.1",
"@web/test-runner-core": "npm:@openpgp/wtr-test-runner-core@0.13.4-patch.0"
},
"repository": {
"type": "git",

View File

@ -9,12 +9,13 @@ import commonjs from '@rollup/plugin-commonjs';
import replace from '@rollup/plugin-replace';
import terser from '@rollup/plugin-terser';
import { wasm } from '@rollup/plugin-wasm';
import typescript from '@rollup/plugin-typescript';
// ESlint does not support JSON module imports yet, see https://github.com/eslint/eslint/discussions/15305
// import pkg from './package.json' assert { type: 'json' };
const pkg = JSON.parse(readFileSync('./package.json'));
const nodeDependencies = Object.keys(pkg.dependencies);
const nodeDependencies = Object.keys(pkg.dependencies || {});
const nodeBuiltinModules = builtinModules.concat(['module']);
const wasmOptions = {
@ -22,13 +23,20 @@ const wasmOptions = {
browser: { targetEnv: 'browser', maxFileSize: undefined } // always inlline (our wasm files are small)
};
const getChunkFileName = (chunkInfo, extension) => {
// index files result in chunks named simply 'index', so we rename them to include the package name
if (chunkInfo.name === 'index') {
const packageName = chunkInfo.facadeModuleId.split('/').at(-2); // assume index file is under the root folder
return `${packageName}.${extension}`;
const getChunkFileName = (chunkInfo, extension) => `[name].${extension}`;
/**
* Dynamically imported modules which expose an index file as entrypoint end up with a chunk named `index`
* by default. We want to preserve the module name instead.
*/
const setManualChunkName = chunkId => {
if (chunkId.includes('seek-bzip')) {
return 'seek-bzip';
} else if (chunkId.includes('argon2id')) {
return 'argon2id';
} else {
return undefined;
}
return `[name].${extension}`;
};
const banner =
@ -49,98 +57,120 @@ const terserOptions = {
}
};
const nodeBuild = {
input: 'src/index.js',
external: nodeBuiltinModules.concat(nodeDependencies),
output: [
{ file: 'dist/node/openpgp.cjs', format: 'cjs', name: pkg.name, banner, intro },
{ file: 'dist/node/openpgp.min.cjs', format: 'cjs', name: pkg.name, banner, intro, plugins: [terser(terserOptions)], sourcemap: true },
{ file: 'dist/node/openpgp.mjs', format: 'es', banner, intro },
{ file: 'dist/node/openpgp.min.mjs', format: 'es', banner, intro, plugins: [terser(terserOptions)], sourcemap: true }
].map(options => ({ ...options, inlineDynamicImports: true })),
plugins: [
resolve({
exportConditions: ['node'] // needed for resolution of noble-curves import of '@noble/crypto' in Node 18
}),
typescript({
compilerOptions: { outDir: './dist/tmp-ts' }
}),
commonjs(),
replace({
'OpenPGP.js VERSION': `OpenPGP.js ${pkg.version}`
}),
wasm(wasmOptions.node)
]
};
const fullBrowserBuild = {
input: 'src/index.js',
external: nodeBuiltinModules.concat(nodeDependencies),
output: [
{ file: 'dist/openpgp.js', format: 'iife', name: pkg.name, banner, intro },
{ file: 'dist/openpgp.min.js', format: 'iife', name: pkg.name, banner, intro, plugins: [terser(terserOptions)], sourcemap: true },
{ file: 'dist/openpgp.mjs', format: 'es', banner, intro },
{ file: 'dist/openpgp.min.mjs', format: 'es', banner, intro, plugins: [terser(terserOptions)], sourcemap: true }
].map(options => ({ ...options, inlineDynamicImports: true })),
plugins: [
resolve({
browser: true
}),
typescript({
compilerOptions: { outDir: './dist/tmp-ts' } // to avoid js files being overwritten
}),
commonjs({
ignore: nodeBuiltinModules.concat(nodeDependencies)
}),
replace({
'OpenPGP.js VERSION': `OpenPGP.js ${pkg.version}`,
"import { createRequire } from 'module';": 'const createRequire = () => () => {}',
delimiters: ['', '']
}),
wasm(wasmOptions.browser)
]
};
const lightweightBrowserBuild = {
input: 'src/index.js',
external: nodeBuiltinModules.concat(nodeDependencies),
output: [
{ entryFileNames: 'openpgp.mjs', chunkFileNames: chunkInfo => getChunkFileName(chunkInfo, 'mjs') },
{ entryFileNames: 'openpgp.min.mjs', chunkFileNames: chunkInfo => getChunkFileName(chunkInfo, 'min.mjs'), plugins: [terser(terserOptions)], sourcemap: true }
].map(options => ({ ...options, dir: 'dist/lightweight', manualChunks: setManualChunkName, format: 'es', banner, intro })),
preserveEntrySignatures: 'exports-only',
plugins: [
resolve({
browser: true
}),
typescript({
compilerOptions: { outDir: './dist/lightweight/tmp-ts' }
}),
commonjs({
ignore: nodeBuiltinModules.concat(nodeDependencies)
}),
replace({
'OpenPGP.js VERSION': `OpenPGP.js ${pkg.version}`,
"import { createRequire } from 'module';": 'const createRequire = () => () => {}',
delimiters: ['', '']
}),
wasm(wasmOptions.browser)
]
};
const testBuild = {
input: 'test/unittests.js',
output: [
{ file: 'test/lib/unittests-bundle.js', format: 'es', intro, sourcemap: true, inlineDynamicImports: true }
],
external: nodeBuiltinModules.concat(nodeDependencies),
plugins: [
alias({
entries: {
openpgp: `./dist/${process.env.npm_config_lightweight ? 'lightweight/' : ''}openpgp.mjs`
}
}),
resolve({
browser: true
}),
typescript({
compilerOptions: { outDir: './test/lib/tmp-ts' }
}),
commonjs({
ignore: nodeBuiltinModules.concat(nodeDependencies),
requireReturnsDefault: 'preferred'
}),
replace({
"import { createRequire } from 'module';": 'const createRequire = () => () => {}',
delimiters: ['', '']
}),
wasm(wasmOptions.browser)
]
};
export default Object.assign([
{
input: 'src/index.js',
external: nodeBuiltinModules.concat(nodeDependencies),
output: [
{ file: 'dist/openpgp.js', format: 'iife', name: pkg.name, banner, intro },
{ file: 'dist/openpgp.min.js', format: 'iife', name: pkg.name, banner, intro, plugins: [terser(terserOptions)], sourcemap: true },
{ file: 'dist/openpgp.mjs', format: 'es', banner, intro },
{ file: 'dist/openpgp.min.mjs', format: 'es', banner, intro, plugins: [terser(terserOptions)], sourcemap: true }
].map(options => ({ ...options, inlineDynamicImports: true })),
plugins: [
resolve({
browser: true
}),
commonjs({
ignore: nodeBuiltinModules.concat(nodeDependencies)
}),
replace({
'OpenPGP.js VERSION': `OpenPGP.js ${pkg.version}`,
"import { createRequire } from 'module';": 'const createRequire = () => () => {}',
delimiters: ['', '']
}),
wasm(wasmOptions.browser)
]
},
{
input: 'src/index.js',
external: nodeBuiltinModules.concat(nodeDependencies),
output: [
{ file: 'dist/node/openpgp.cjs', format: 'cjs', name: pkg.name, banner, intro },
{ file: 'dist/node/openpgp.min.cjs', format: 'cjs', name: pkg.name, banner, intro, plugins: [terser(terserOptions)], sourcemap: true },
{ file: 'dist/node/openpgp.mjs', format: 'es', banner, intro },
{ file: 'dist/node/openpgp.min.mjs', format: 'es', banner, intro, plugins: [terser(terserOptions)], sourcemap: true }
].map(options => ({ ...options, inlineDynamicImports: true })),
plugins: [
resolve(),
commonjs(),
replace({
'OpenPGP.js VERSION': `OpenPGP.js ${pkg.version}`
}),
wasm(wasmOptions.node)
]
},
{
input: 'src/index.js',
external: nodeBuiltinModules.concat(nodeDependencies),
output: [
{ dir: 'dist/lightweight', entryFileNames: 'openpgp.mjs', chunkFileNames: chunkInfo => getChunkFileName(chunkInfo, 'mjs'), format: 'es', banner, intro },
{ dir: 'dist/lightweight', entryFileNames: 'openpgp.min.mjs', chunkFileNames: chunkInfo => getChunkFileName(chunkInfo, 'min.mjs'), format: 'es', banner, intro, plugins: [terser(terserOptions)], sourcemap: true }
],
preserveEntrySignatures: 'exports-only',
plugins: [
resolve({
browser: true
}),
commonjs({
ignore: nodeBuiltinModules.concat(nodeDependencies)
}),
replace({
'OpenPGP.js VERSION': `OpenPGP.js ${pkg.version}`,
"import { createRequire } from 'module';": 'const createRequire = () => () => {}',
delimiters: ['', '']
}),
wasm(wasmOptions.browser)
]
},
{
input: 'test/unittests.js',
output: [
{ file: 'test/lib/unittests-bundle.js', format: 'es', intro, sourcemap: true, inlineDynamicImports: true }
],
external: nodeBuiltinModules.concat(nodeDependencies),
plugins: [
alias({
entries: {
openpgp: `./dist/${process.env.npm_config_lightweight ? 'lightweight/' : ''}openpgp.mjs`
}
}),
resolve({
browser: true
}),
commonjs({
ignore: nodeBuiltinModules.concat(nodeDependencies),
requireReturnsDefault: 'preferred'
}),
replace({
"import { createRequire } from 'module';": 'const createRequire = () => () => {}',
delimiters: ['', '']
}),
wasm(wasmOptions.browser)
]
}
nodeBuild,
fullBrowserBuild,
lightweightBrowserBuild,
testBuild
].filter(config => {
config.output = config.output.filter(output => {
return (output.file || output.dir + '/' + output.entryFileNames).includes(

View File

@ -1,20 +0,0 @@
/**
* We don't use the BigIntegerInterface wrapper from noble-hashes because:
* - importing the instance results in it being shared with noble-hashes, which separately calls `setImplementation()`
* on load, causing it to throw due to duplicate initialization.
* - even duplicating the interface code here to keep a separate instance requires handing a race-conditions the first time
* `getBigInteger` is called, when the code needs to check if the implementation is set, and initialize it if not.
* Ultimately, the interface provides no advantages and it's only needed because of TS.
*/
const detectBigInt = () => typeof BigInt !== 'undefined';
export async function getBigInteger() {
if (detectBigInt()) {
// NativeBigInteger is small, so it's imported in isolation (it could also be imported at the top level)
const { default: NativeBigInteger } = await import('@openpgp/noble-hashes/esm/biginteger/native.interface');
return NativeBigInteger;
} else {
// FallbackBigInteger relies on large BN.js lib, which is also used by noble-hashes and noble-curves
const { default: FallbackBigInteger } = await import('@openpgp/noble-hashes/esm/biginteger/bn.interface');
return FallbackBigInteger;
}
}

View File

@ -59,20 +59,22 @@ export class CleartextMessage {
/**
* Sign the cleartext message
* @param {Array<Key>} privateKeys - private keys with decrypted secret key data for signing
* @param {Array<Key>} signingKeys - private keys with decrypted secret key data for signing
* @param {Array<Key>} recipientKeys - recipient keys to get the signing preferences from
* @param {Signature} [signature] - Any existing detached signature
* @param {Array<module:type/keyid~KeyID>} [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} [signingKeyIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
* @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from
* @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]
* @param {Object} [config] - Full configuration, defaults to openpgp.config
* @returns {Promise<CleartextMessage>} New cleartext message with signed content.
* @async
*/
async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {
async sign(signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config = defaultConfig) {
const literalDataPacket = new LiteralDataPacket();
literalDataPacket.setText(this.text);
const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, notations, true, config));
const newSignature = new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, true, config));
return new CleartextMessage(this.text, newSignature);
}
@ -111,9 +113,9 @@ export class CleartextMessage {
* @returns {String | ReadableStream<String>} ASCII armor.
*/
armor(config = defaultConfig) {
// emit header if one of the signatures has a version not 6
const emitHeader = this.signature.packets.some(packet => packet.version !== 6);
const hash = emitHeader ?
// emit header and checksum if one of the signatures has a version not 6
const emitHeaderAndChecksum = this.signature.packets.some(packet => packet.version !== 6);
const hash = emitHeaderAndChecksum ?
Array.from(new Set(this.signature.packets.map(
packet => enums.read(enums.hash, packet.hashAlgorithm).toUpperCase()
))).join() :
@ -124,7 +126,9 @@ export class CleartextMessage {
text: this.text,
data: this.signature.packets.write()
};
return armor(enums.armor.signed, body, undefined, undefined, undefined, config);
// An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.
return armor(enums.armor.signed, body, undefined, undefined, undefined, emitHeaderAndChecksum, config);
}
}

View File

@ -26,7 +26,7 @@ export default {
* @memberof module:config
* @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash}
*/
preferredHashAlgorithm: enums.hash.sha256,
preferredHashAlgorithm: enums.hash.sha512,
/**
* @memberof module:config
* @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric}
@ -37,11 +37,6 @@ export default {
* @property {Integer} compression Default compression algorithm {@link module:enums.compression}
*/
preferredCompressionAlgorithm: enums.compression.uncompressed,
/**
* @memberof module:config
* @property {Integer} deflateLevel Default zip/zlib compression level, between 1 and 9
*/
deflateLevel: 6,
/**
* Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.
* This option is applicable to:
@ -55,6 +50,14 @@ export default {
* @property {Boolean} aeadProtect
*/
aeadProtect: false,
/**
* When reading OpenPGP v4 private keys (e.g. those generated in OpenPGP.js when not setting `config.v5Keys = true`)
* which were encrypted by OpenPGP.js v5 (or older) using `config.aeadProtect = true`,
* this option must be set, otherwise key parsing and/or key decryption will fail.
* Note: only set this flag if you know that the keys are of the legacy type, as non-legacy keys
* will be processed incorrectly.
*/
parseAEADEncryptedV4KeysAsLegacy: false,
/**
* Default Authenticated Encryption with Additional Data (AEAD) encryption mode
* Only has an effect when aeadProtect is set to true.
@ -78,6 +81,14 @@ export default {
* @property {Boolean} v6Keys
*/
v6Keys: false,
/**
* Enable parsing v5 keys and v5 signatures (which is different from the AEAD-encrypted SEIPDv2 packet).
* These are non-standard entities, which in the crypto-refresh have been superseded
* by v6 keys and v6 signatures, respectively.
* However, generation of v5 entities was supported behind config flag in OpenPGP.js v5, and some other libraries,
* hence parsing them might be necessary in some cases.
*/
enableParsingV5Entities: false,
/**
* S2K (String to Key) type, used for key derivation in the context of secret key encryption
* and password-encrypted data. Weaker s2k options are not allowed.
@ -152,11 +163,6 @@ export default {
* @property {Boolean} passwordCollisionCheck
*/
passwordCollisionCheck: false,
/**
* @memberof module:config
* @property {Boolean} revocationsExpire If true, expired revocation signatures are ignored
*/
revocationsExpire: false,
/**
* Allow decryption using RSA keys without `encrypt` flag.
* This setting is potentially insecure, but it is needed to get around an old openpgpjs bug
@ -252,6 +258,14 @@ export default {
* @property {Array} knownNotations
*/
knownNotations: [],
/**
* If true, a salt notation is used to randomize signatures generated by v4 and v5 keys (v6 signatures are always non-deterministic, by design).
* This protects EdDSA signatures from potentially leaking the secret key in case of faults (i.e. bitflips) which, in principle, could occur
* during the signing computation. It is added to signatures of any algo for simplicity, and as it may also serve as protection in case of
* weaknesses in the hash algo, potentially hindering e.g. some chosen-prefix attacks.
* NOTE: the notation is interoperable, but will reveal that the signature has been generated using OpenPGP.js, which may not be desirable in some cases.
*/
nonDeterministicSignaturesViaNotation: true,
/**
* Whether to use the the noble-curves library for curves (other than Curve25519) that are not supported by the available native crypto API.
* When false, certain standard curves will not be supported (depending on the platform).

View File

@ -21,126 +21,77 @@
* @module crypto/aes_kw
*/
import * as cipher from './cipher';
import { aeskw as nobleAesKW } from '@noble/ciphers/aes';
import { getCipherParams } from './cipher';
import util from '../util';
const webCrypto = util.getWebCrypto();
/**
* AES key wrap
* @function
* @param {Uint8Array} key
* @param {Uint8Array} data
* @returns {Uint8Array}
* @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo
* @param {Uint8Array} key - wrapping key
* @param {Uint8Array} dataToWrap
* @returns {Uint8Array} wrapped key
*/
export function wrap(key, data) {
const aes = new cipher['aes' + (key.length * 8)](key);
const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);
const P = unpack(data);
let A = IV;
const R = P;
const n = P.length / 2;
const t = new Uint32Array([0, 0]);
let B = new Uint32Array(4);
for (let j = 0; j <= 5; ++j) {
for (let i = 0; i < n; ++i) {
t[1] = n * j + (1 + i);
// B = A
B[0] = A[0];
B[1] = A[1];
// B = A || R[i]
B[2] = R[2 * i];
B[3] = R[2 * i + 1];
// B = AES(K, B)
B = unpack(aes.encrypt(pack(B)));
// A = MSB(64, B) ^ t
A = B.subarray(0, 2);
A[0] ^= t[0];
A[1] ^= t[1];
// R[i] = LSB(64, B)
R[2 * i] = B[2];
R[2 * i + 1] = B[3];
}
export async function wrap(algo, key, dataToWrap) {
const { keySize } = getCipherParams(algo);
// sanity checks, since WebCrypto does not use the `algo` input
if (!util.isAES(algo) || key.length !== keySize) {
throw new Error('Unexpected algorithm or key size');
}
return pack(A, R);
try {
const wrappingKey = await webCrypto.importKey('raw', key, { name: 'AES-KW' }, false, ['wrapKey']);
// Import data as HMAC key, as it has no key length requirements
const keyToWrap = await webCrypto.importKey('raw', dataToWrap, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);
const wrapped = await webCrypto.wrapKey('raw', keyToWrap, wrappingKey, { name: 'AES-KW' });
return new Uint8Array(wrapped);
} catch (err) {
// no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
if (err.name !== 'NotSupportedError' &&
!(key.length === 24 && err.name === 'OperationError')) {
throw err;
}
util.printDebugError('Browser did not support operation: ' + err.message);
}
return nobleAesKW(key).encrypt(dataToWrap);
}
/**
* AES key unwrap
* @function
* @param {String} key
* @param {String} data
* @returns {Uint8Array}
* @throws {Error}
* @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo
* @param {Uint8Array} key - wrapping key
* @param {Uint8Array} wrappedData
* @returns {Uint8Array} unwrapped data
*/
export function unwrap(key, data) {
const aes = new cipher['aes' + (key.length * 8)](key);
const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);
const C = unpack(data);
let A = C.subarray(0, 2);
const R = C.subarray(2);
const n = C.length / 2 - 1;
const t = new Uint32Array([0, 0]);
let B = new Uint32Array(4);
for (let j = 5; j >= 0; --j) {
for (let i = n - 1; i >= 0; --i) {
t[1] = n * j + (i + 1);
// B = A ^ t
B[0] = A[0] ^ t[0];
B[1] = A[1] ^ t[1];
// B = (A ^ t) || R[i]
B[2] = R[2 * i];
B[3] = R[2 * i + 1];
// B = AES-1(B)
B = unpack(aes.decrypt(pack(B)));
// A = MSB(64, B)
A = B.subarray(0, 2);
// R[i] = LSB(64, B)
R[2 * i] = B[2];
R[2 * i + 1] = B[3];
}
export async function unwrap(algo, key, wrappedData) {
const { keySize } = getCipherParams(algo);
// sanity checks, since WebCrypto does not use the `algo` input
if (!util.isAES(algo) || key.length !== keySize) {
throw new Error('Unexpected algorithm or key size');
}
if (A[0] === IV[0] && A[1] === IV[1]) {
return pack(R);
}
throw new Error('Key Data Integrity failed');
}
function createArrayBuffer(data) {
if (util.isString(data)) {
const { length } = data;
const buffer = new ArrayBuffer(length);
const view = new Uint8Array(buffer);
for (let j = 0; j < length; ++j) {
view[j] = data.charCodeAt(j);
let wrappingKey;
try {
wrappingKey = await webCrypto.importKey('raw', key, { name: 'AES-KW' }, false, ['unwrapKey']);
} catch (err) {
// no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
if (err.name !== 'NotSupportedError' &&
!(key.length === 24 && err.name === 'OperationError')) {
throw err;
}
return buffer;
util.printDebugError('Browser did not support operation: ' + err.message);
return nobleAesKW(key).decrypt(wrappedData);
}
return new Uint8Array(data).buffer;
}
function unpack(data) {
const { length } = data;
const buffer = createArrayBuffer(data);
const view = new DataView(buffer);
const arr = new Uint32Array(length / 4);
for (let i = 0; i < length / 4; ++i) {
arr[i] = view.getUint32(4 * i);
}
return arr;
}
function pack() {
let length = 0;
for (let k = 0; k < arguments.length; ++k) {
length += 4 * arguments[k].length;
}
const buffer = new ArrayBuffer(length);
const view = new DataView(buffer);
let offset = 0;
for (let i = 0; i < arguments.length; ++i) {
for (let j = 0; j < arguments[i].length; ++j) {
view.setUint32(offset + 4 * j, arguments[i][j]);
try {
const unwrapped = await webCrypto.unwrapKey('raw', wrappedData, wrappingKey, { name: 'AES-KW' }, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);
return new Uint8Array(await webCrypto.exportKey('raw', unwrapped));
} catch (err) {
if (err.name === 'OperationError') {
throw new Error('Key Data Integrity failed');
}
offset += 4 * arguments[i].length;
throw err;
}
return new Uint8Array(buffer);
}

216
src/crypto/biginteger.ts Normal file
View File

@ -0,0 +1,216 @@
// Operations are not constant time, but we try and limit timing leakage where we can
const _0n = BigInt(0);
const _1n = BigInt(1);
export function uint8ArrayToBigInt(bytes: Uint8Array) {
const hexAlphabet = '0123456789ABCDEF';
let s = '';
bytes.forEach(v => {
s += hexAlphabet[v >> 4] + hexAlphabet[v & 15];
});
return BigInt('0x0' + s);
}
export function mod(a: bigint, m: bigint) {
const reduced = a % m;
return reduced < _0n ? reduced + m : reduced;
}
/**
* Compute modular exponentiation using square and multiply
* @param {BigInt} a - Base
* @param {BigInt} e - Exponent
* @param {BigInt} n - Modulo
* @returns {BigInt} b ** e mod n.
*/
export function modExp(b: bigint, e: bigint, n: bigint) {
if (n === _0n) throw Error('Modulo cannot be zero');
if (n === _1n) return BigInt(0);
if (e < _0n) throw Error('Unsopported negative exponent');
let exp = e;
let x = b;
x %= n;
let r = BigInt(1);
while (exp > _0n) {
const lsb = exp & _1n;
exp >>= _1n; // e / 2
// Always compute multiplication step, to reduce timing leakage
const rx = (r * x) % n;
// Update r only if lsb is 1 (odd exponent)
r = lsb ? rx : r;
x = (x * x) % n; // Square
}
return r;
}
function abs(x: bigint) {
return x >= _0n ? x : -x;
}
/**
* Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)
* Given a and b, compute (x, y) such that ax + by = gdc(a, b).
* Negative numbers are also supported.
* @param {BigInt} a - First operand
* @param {BigInt} b - Second operand
* @returns {{ gcd, x, y: bigint }}
*/
function _egcd(aInput: bigint, bInput: bigint) {
let x = BigInt(0);
let y = BigInt(1);
let xPrev = BigInt(1);
let yPrev = BigInt(0);
// Deal with negative numbers: run algo over absolute values,
// and "move" the sign to the returned x and/or y.
// See https://math.stackexchange.com/questions/37806/extended-euclidean-algorithm-with-negative-numbers
let a = abs(aInput);
let b = abs(bInput);
const aNegated = aInput < _0n;
const bNegated = bInput < _0n;
while (b !== _0n) {
const q = a / b;
let tmp = x;
x = xPrev - q * x;
xPrev = tmp;
tmp = y;
y = yPrev - q * y;
yPrev = tmp;
tmp = b;
b = a % b;
a = tmp;
}
return {
x: aNegated ? -xPrev : xPrev,
y: bNegated ? -yPrev : yPrev,
gcd: a
};
}
/**
* Compute the inverse of `a` modulo `n`
* Note: `a` and and `n` must be relatively prime
* @param {BigInt} a
* @param {BigInt} n - Modulo
* @returns {BigInt} x such that a*x = 1 mod n
* @throws {Error} if the inverse does not exist
*/
export function modInv(a: bigint, n: bigint) {
const { gcd, x } = _egcd(a, n);
if (gcd !== _1n) {
throw new Error('Inverse does not exist');
}
return mod(x + n, n);
}
/**
* Compute greatest common divisor between this and n
* @param {BigInt} aInput - Operand
* @param {BigInt} bInput - Operand
* @returns {BigInt} gcd
*/
export function gcd(aInput: bigint, bInput: bigint) {
let a = aInput;
let b = bInput;
while (b !== _0n) {
const tmp = b;
b = a % b;
a = tmp;
}
return a;
}
/**
* Get this value as an exact Number (max 53 bits)
* Fails if this value is too large
* @returns {Number}
*/
export function bigIntToNumber(x: bigint) {
const number = Number(x);
if (number > Number.MAX_SAFE_INTEGER) {
// We throw and error to conform with the bn.js implementation
throw new Error('Number can only safely store up to 53 bits');
}
return number;
}
/**
* Get value of i-th bit
* @param {BigInt} x
* @param {Number} i - Bit index
* @returns {Number} Bit value.
*/
export function getBit(x:bigint, i: number) {
const bit = (x >> BigInt(i)) & _1n;
return bit === _0n ? 0 : 1;
}
/**
* Compute bit length
*/
export function bitLength(x: bigint) {
// -1n >> -1n is -1n
// 1n >> 1n is 0n
const target = x < _0n ? BigInt(-1) : _0n;
let bitlen = 1;
let tmp = x;
// eslint-disable-next-line no-cond-assign
while ((tmp >>= _1n) !== target) {
bitlen++;
}
return bitlen;
}
/**
* Compute byte length
*/
export function byteLength(x: bigint) {
const target = x < _0n ? BigInt(-1) : _0n;
const _8n = BigInt(8);
let len = 1;
let tmp = x;
// eslint-disable-next-line no-cond-assign
while ((tmp >>= _8n) !== target) {
len++;
}
return len;
}
/**
* Get Uint8Array representation of this number
* @param {String} endian - Endianess of output array (defaults to 'be')
* @param {Number} length - Of output array
* @returns {Uint8Array}
*/
export function bigIntToUint8Array(x: bigint, endian = 'be', length: number) {
// we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)
// this is faster than shift+mod iterations
let hex = x.toString(16);
if (hex.length % 2 === 1) {
hex = '0' + hex;
}
const rawLength = hex.length / 2;
const bytes = new Uint8Array(length || rawLength);
// parse hex
const offset = length ? length - rawLength : 0;
let i = 0;
while (i < rawLength) {
bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);
i++;
}
if (endian !== 'be') {
bytes.reverse();
}
return bytes;
}

View File

@ -1,26 +0,0 @@
import { AES_ECB } from '@openpgp/asmcrypto.js/aes/ecb.js';
/**
* Javascript AES implementation.
* This is used as fallback if the native Crypto APIs are not available.
*/
function aes(length) {
const C = function(key) {
const aesECB = new AES_ECB(key);
this.encrypt = function(block) {
return aesECB.encrypt(block);
};
this.decrypt = function(block) {
return aesECB.decrypt(block);
};
};
C.blockSize = C.prototype.blockSize = 16;
C.keySize = C.prototype.keySize = length / 8;
return C;
}
export default aes;

View File

@ -1,13 +0,0 @@
import * as cipher from '.';
import enums from '../../enums';
/**
* Get implementation of the given cipher
* @param {enums.symmetric} algo
* @returns {Object}
* @throws {Error} on invalid algo
*/
export default function getCipher(algo) {
const algoName = enums.read(enums.symmetric, algo);
return cipher[algoName];
}

View File

@ -1,80 +1,73 @@
/**
* @fileoverview Symmetric cryptography functions
* @module crypto/cipher
*/
import enums from '../../enums';
import aes from './aes';
import { DES, TripleDES } from './des';
import CAST5 from './cast5';
import TF from './twofish';
import BF from './blowfish';
export async function getLegacyCipher(algo) {
switch (algo) {
case enums.symmetric.aes128:
case enums.symmetric.aes192:
case enums.symmetric.aes256:
throw new Error('Not a legacy cipher');
case enums.symmetric.cast5:
case enums.symmetric.blowfish:
case enums.symmetric.twofish:
case enums.symmetric.tripledes: {
const { legacyCiphers } = await import('./legacy_ciphers');
const algoName = enums.read(enums.symmetric, algo);
const cipher = legacyCiphers.get(algoName);
if (!cipher) {
throw new Error('Unsupported cipher algorithm');
}
return cipher;
}
default:
throw new Error('Unsupported cipher algorithm');
}
}
/**
* AES-128 encryption and decryption (ID 7)
* @function
* @param {String} key - 128-bit key
* @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
* @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
* @returns {Object}
* Get block size for given cipher algo
* @param {module:enums.symmetric} algo - alrogithm identifier
*/
export const aes128 = aes(128);
function getCipherBlockSize(algo) {
switch (algo) {
case enums.symmetric.aes128:
case enums.symmetric.aes192:
case enums.symmetric.aes256:
case enums.symmetric.twofish:
return 16;
case enums.symmetric.blowfish:
case enums.symmetric.cast5:
case enums.symmetric.tripledes:
return 8;
default:
throw new Error('Unsupported cipher');
}
}
/**
* AES-128 Block Cipher (ID 8)
* @function
* @param {String} key - 192-bit key
* @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
* @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
* @returns {Object}
* Get key size for given cipher algo
* @param {module:enums.symmetric} algo - alrogithm identifier
*/
export const aes192 = aes(192);
function getCipherKeySize(algo) {
switch (algo) {
case enums.symmetric.aes128:
case enums.symmetric.blowfish:
case enums.symmetric.cast5:
return 16;
case enums.symmetric.aes192:
case enums.symmetric.tripledes:
return 24;
case enums.symmetric.aes256:
case enums.symmetric.twofish:
return 32;
default:
throw new Error('Unsupported cipher');
}
}
/**
* AES-128 Block Cipher (ID 9)
* @function
* @param {String} key - 256-bit key
* @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
* @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
* @returns {Object}
* Get block and key size for given cipher algo
* @param {module:enums.symmetric} algo - alrogithm identifier
*/
export const aes256 = aes(256);
// Not in OpenPGP specifications
export const des = DES;
/**
* Triple DES Block Cipher (ID 2)
* @function
* @param {String} key - 192-bit key
* @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67}
* @returns {Object}
*/
export const tripledes = TripleDES;
/**
* CAST-128 Block Cipher (ID 3)
* @function
* @param {String} key - 128-bit key
* @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm}
* @returns {Object}
*/
export const cast5 = CAST5;
/**
* Twofish Block Cipher (ID 10)
* @function
* @param {String} key - 256-bit key
* @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH}
* @returns {Object}
*/
export const twofish = TF;
/**
* Blowfish Block Cipher (ID 4)
* @function
* @param {String} key - 128-bit key
* @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH}
* @returns {Object}
*/
export const blowfish = BF;
/**
* Not implemented
* @function
* @throws {Error}
*/
export const idea = function() {
throw new Error('IDEA symmetric-key algorithm not implemented');
};
export function getCipherParams(algo) {
return { keySize: getCipherKeySize(algo), blockSize: getCipherBlockSize(algo) };
}

View File

@ -0,0 +1,18 @@
/**
* This file is needed to dynamic import the legacy ciphers.
* Separate dynamic imports are not convenient as they result in multiple chunks.
*/
import { TripleDES as tripledes } from './des';
import cast5 from './cast5';
import twofish from './twofish';
import blowfish from './blowfish';
// We avoid importing 'enums' as this module is lazy loaded, and doing so could mess up
// chunking for the lightweight build
export const legacyCiphers = new Map(Object.entries({
tripledes,
cast5,
twofish,
blowfish
}));

View File

@ -21,11 +21,13 @@
* @module crypto/mode/cfb
*/
import { AES_CFB } from '@openpgp/asmcrypto.js/aes/cfb.js';
import * as stream from '@openpgp/web-stream-tools';
import getCipher from '../cipher/getCipher';
import { cfb as nobleAesCfb, unsafe as nobleAesHelpers } from '@noble/ciphers/aes';
import { transform as streamTransform } from '@openpgp/web-stream-tools';
import util from '../../util';
import enums from '../../enums';
import { getLegacyCipher, getCipherParams } from '../cipher';
import { getRandomBytes } from '../random';
const webCrypto = util.getWebCrypto();
const nodeCrypto = util.getNodeCrypto();
@ -42,6 +44,20 @@ const nodeAlgos = {
/* twofish is not implemented in OpenSSL */
};
/**
* Generates a random byte prefix for the specified algorithm
* See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
* @param {module:enums.symmetric} algo - Symmetric encryption algorithm
* @returns {Promise<Uint8Array>} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.
* @async
*/
export async function getPrefixRandom(algo) {
const { blockSize } = getCipherParams(algo);
const prefixrandom = await getRandomBytes(blockSize);
const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);
return util.concat([prefixrandom, repeat]);
}
/**
* CFB encryption
* @param {enums.symmetric} algo - block cipher algorithm
@ -60,8 +76,8 @@ export async function encrypt(algo, key, plaintext, iv, config) {
return aesEncrypt(algo, key, plaintext, iv, config);
}
const Cipher = getCipher(algo);
const cipherfn = new Cipher(key);
const LegacyCipher = await getLegacyCipher(algo);
const cipherfn = new LegacyCipher(key);
const block_size = cipherfn.blockSize;
const blockc = iv.slice();
@ -83,7 +99,7 @@ export async function encrypt(algo, key, plaintext, iv, config) {
}
return ciphertext.subarray(0, j);
};
return stream.transform(plaintext, process, process);
return streamTransform(plaintext, process, process);
}
/**
@ -103,8 +119,8 @@ export async function decrypt(algo, key, ciphertext, iv) {
return aesDecrypt(algo, key, ciphertext, iv);
}
const Cipher = getCipher(algo);
const cipherfn = new Cipher(key);
const LegacyCipher = await getLegacyCipher(algo);
const cipherfn = new LegacyCipher(key);
const block_size = cipherfn.blockSize;
let blockp = iv;
@ -126,12 +142,12 @@ export async function decrypt(algo, key, ciphertext, iv) {
}
return plaintext.subarray(0, j);
};
return stream.transform(ciphertext, process, process);
return streamTransform(ciphertext, process, process);
}
class WebCryptoEncryptor {
constructor(algo, key, iv) {
const { blockSize } = getCipher(algo);
const { blockSize } = getCipherParams(algo);
this.key = key;
this.prevBlock = iv;
this.nextBlock = new Uint8Array(blockSize);
@ -141,7 +157,7 @@ class WebCryptoEncryptor {
}
static async isSupported(algo) {
const { keySize } = getCipher(algo);
const { keySize } = getCipherParams(algo);
return webCrypto.importKey('raw', new Uint8Array(keySize), 'aes-cbc', false, ['encrypt'])
.then(() => true, () => false);
}
@ -174,17 +190,17 @@ class WebCryptoEncryptor {
const encryptedBlocks = await this._runCBC(toEncrypt);
xorMut(encryptedBlocks, plaintext);
this.prevBlock = encryptedBlocks.subarray(-this.blockSize).slice();
this.prevBlock = encryptedBlocks.slice(-this.blockSize);
// take care of leftover data
if (leftover > 0) this.nextBlock.set(value.subarray(-leftover).slice());
if (leftover > 0) this.nextBlock.set(value.subarray(-leftover));
this.i = leftover;
return encryptedBlocks;
}
this.i += added.length;
let encryptedBlock = new Uint8Array();
let encryptedBlock;
if (this.i === this.nextBlock.length) { // block ready to be encrypted
const curBlock = this.nextBlock;
encryptedBlock = await this._runCBC(this.prevBlock);
@ -195,6 +211,8 @@ class WebCryptoEncryptor {
const remaining = value.subarray(added.length);
this.nextBlock.set(remaining, this.i);
this.i += remaining.length;
} else {
encryptedBlock = new Uint8Array();
}
return encryptedBlock;
@ -237,22 +255,111 @@ class WebCryptoEncryptor {
}
}
async function aesEncrypt(algo, key, pt, iv) {
if (webCrypto && await WebCryptoEncryptor.isSupported(algo)) { // Chromium does not implement AES with 192-bit keys
const cfb = new WebCryptoEncryptor(algo, key, iv);
return util.isStream(pt) ? stream.transform(pt, value => cfb.encryptChunk(value), () => cfb.finish()) : cfb.encrypt(pt);
} else {
const cfb = new AES_CFB(key, iv);
return stream.transform(pt, value => cfb.aes.AES_Encrypt_process(value), () => cfb.aes.AES_Encrypt_finish());
class NobleStreamProcessor {
constructor(forEncryption, algo, key, iv) {
this.forEncryption = forEncryption;
const { blockSize } = getCipherParams(algo);
this.key = nobleAesHelpers.expandKeyLE(key);
if (iv.byteOffset % 4 !== 0) iv = iv.slice(); // aligned arrays required by noble-ciphers
this.prevBlock = getUint32Array(iv);
this.nextBlock = new Uint8Array(blockSize);
this.i = 0; // pointer inside next block
this.blockSize = blockSize;
}
_runCFB(src) {
const src32 = getUint32Array(src);
const dst = new Uint8Array(src.length);
const dst32 = getUint32Array(dst);
for (let i = 0; i + 4 <= dst32.length; i += 4) {
const { s0: e0, s1: e1, s2: e2, s3: e3 } = nobleAesHelpers.encrypt(this.key, this.prevBlock[0], this.prevBlock[1], this.prevBlock[2], this.prevBlock[3]);
dst32[i + 0] = src32[i + 0] ^ e0;
dst32[i + 1] = src32[i + 1] ^ e1;
dst32[i + 2] = src32[i + 2] ^ e2;
dst32[i + 3] = src32[i + 3] ^ e3;
this.prevBlock = (this.forEncryption ? dst32 : src32).slice(i, i + 4);
}
return dst;
}
async processChunk(value) {
const missing = this.nextBlock.length - this.i;
const added = value.subarray(0, missing);
this.nextBlock.set(added, this.i);
if ((this.i + value.length) >= (2 * this.blockSize)) {
const leftover = (value.length - missing) % this.blockSize;
const toProcess = util.concatUint8Array([
this.nextBlock,
value.subarray(missing, value.length - leftover)
]);
const processedBlocks = this._runCFB(toProcess);
// take care of leftover data
if (leftover > 0) this.nextBlock.set(value.subarray(-leftover));
this.i = leftover;
return processedBlocks;
}
this.i += added.length;
let processedBlock;
if (this.i === this.nextBlock.length) { // block ready to be encrypted
processedBlock = this._runCFB(this.nextBlock);
this.i = 0;
const remaining = value.subarray(added.length);
this.nextBlock.set(remaining, this.i);
this.i += remaining.length;
} else {
processedBlock = new Uint8Array();
}
return processedBlock;
}
async finish() {
let result;
if (this.i === 0) { // nothing more to encrypt
result = new Uint8Array();
} else {
const processedBlock = this._runCFB(this.nextBlock);
result = processedBlock.subarray(0, this.i);
}
this.clearSensitiveData();
return result;
}
clearSensitiveData() {
this.nextBlock.fill(0);
this.prevBlock.fill(0);
this.key.fill(0);
}
}
function aesDecrypt(algo, key, ct, iv) {
if (util.isStream(ct)) {
const cfb = new AES_CFB(key, iv);
return stream.transform(ct, value => cfb.aes.AES_Decrypt_process(value), () => cfb.aes.AES_Decrypt_finish());
async function aesEncrypt(algo, key, pt, iv) {
if (webCrypto && await WebCryptoEncryptor.isSupported(algo)) { // Chromium does not implement AES with 192-bit keys
const cfb = new WebCryptoEncryptor(algo, key, iv);
return util.isStream(pt) ? streamTransform(pt, value => cfb.encryptChunk(value), () => cfb.finish()) : cfb.encrypt(pt);
} else if (util.isStream(pt)) { // async callbacks are not accepted by streamTransform unless the input is a stream
const cfb = new NobleStreamProcessor(true, algo, key, iv);
return streamTransform(pt, value => cfb.processChunk(value), () => cfb.finish());
}
return AES_CFB.decrypt(ct, key, iv);
return nobleAesCfb(key, iv).encrypt(pt);
}
async function aesDecrypt(algo, key, ct, iv) {
if (util.isStream(ct)) {
const cfb = new NobleStreamProcessor(false, algo, key, iv);
return streamTransform(ct, value => cfb.processChunk(value), () => cfb.finish());
}
return nobleAesCfb(key, iv).decrypt(ct);
}
function xorMut(a, b) {
@ -262,14 +369,16 @@ function xorMut(a, b) {
}
}
const getUint32Array = arr => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
function nodeEncrypt(algo, key, pt, iv) {
const algoName = enums.read(enums.symmetric, algo);
const cipherObj = new nodeCrypto.createCipheriv(nodeAlgos[algoName], key, iv);
return stream.transform(pt, value => new Uint8Array(cipherObj.update(value)));
return streamTransform(pt, value => new Uint8Array(cipherObj.update(value)));
}
function nodeDecrypt(algo, key, ct, iv) {
const algoName = enums.read(enums.symmetric, algo);
const decipherObj = new nodeCrypto.createDecipheriv(nodeAlgos[algoName], key, iv);
return stream.transform(ct, value => new Uint8Array(decipherObj.update(value)));
return streamTransform(ct, value => new Uint8Array(decipherObj.update(value)));
}

View File

@ -21,7 +21,7 @@
* @module crypto/mode/eax
*/
import { AES_CTR } from '@openpgp/asmcrypto.js/aes/ctr.js';
import { ctr as nobleAesCtr } from '@noble/ciphers/aes';
import CMAC from '../cmac';
import util from '../../util';
import enums from '../../enums';
@ -72,9 +72,8 @@ async function CTR(key) {
}
}
// asm.js fallback
return async function(pt, iv) {
return AES_CTR.encrypt(pt, key, iv);
return nobleAesCtr(key, iv).encrypt(pt);
};
}

View File

@ -21,7 +21,7 @@
* @module crypto/mode/gcm
*/
import { AES_GCM } from '@openpgp/asmcrypto.js/aes/gcm.js';
import { gcm as nobleAesGcm } from '@noble/ciphers/aes';
import util from '../../util';
import enums from '../../enums';
@ -74,7 +74,7 @@ async function GCM(cipher, key) {
return {
encrypt: async function(pt, iv, adata = new Uint8Array()) {
if (webcryptoEmptyMessagesUnsupported && !pt.length) {
return AES_GCM.encrypt(pt, key, iv, adata);
return nobleAesGcm(key, iv, adata).encrypt(pt);
}
const ct = await webCrypto.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt);
return new Uint8Array(ct);
@ -82,7 +82,7 @@ async function GCM(cipher, key) {
decrypt: async function(ct, iv, adata = new Uint8Array()) {
if (webcryptoEmptyMessagesUnsupported && ct.length === tagLength) {
return AES_GCM.decrypt(ct, key, iv, adata);
return nobleAesGcm(key, iv, adata).decrypt(ct);
}
try {
const pt = await webCrypto.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct);
@ -106,11 +106,11 @@ async function GCM(cipher, key) {
return {
encrypt: async function(pt, iv, adata) {
return AES_GCM.encrypt(pt, key, iv, adata);
return nobleAesGcm(key, iv, adata).encrypt(pt);
},
decrypt: async function(ct, iv, adata) {
return AES_GCM.decrypt(ct, key, iv, adata);
return nobleAesGcm(key, iv, adata).decrypt(ct);
}
};
}

View File

@ -0,0 +1,35 @@
/**
* @fileoverview Cipher modes
* @module crypto/cipherMode
*/
export * as cfb from './cfb';
import eax from './eax';
import ocb from './ocb';
import gcm from './gcm';
import enums from '../../enums';
/**
* Get implementation of the given AEAD mode
* @param {enums.aead} algo
* @param {Boolean} [acceptExperimentalGCM] - whether to allow the non-standard, legacy `experimentalGCM` algo
* @returns {Object}
* @throws {Error} on invalid algo
*/
export function getAEADMode(algo, acceptExperimentalGCM = false) {
switch (algo) {
case enums.aead.eax:
return eax;
case enums.aead.ocb:
return ocb;
case enums.aead.gcm:
return gcm;
case enums.aead.experimentalGCM:
if (!acceptExperimentalGCM) {
throw new Error('Unexpected non-standard `experimentalGCM` AEAD algorithm provided in `config.preferredAEADAlgorithm`: use `gcm` instead');
}
return gcm;
default:
throw new Error('Unsupported AEAD mode');
}
}

Some files were not shown because too many files have changed in this diff Show More