* Enforce the maxMemory limit passed to KDF.Scrypt
* Reject out-of-range scrypt parameters instead of trapping
* Reject a maxMemory that no derivation could satisfy
### Motivation:
We recently broke downstream builds for some narrow compilation modes
(broken in 5.1.0, fixed in 5.1.1). We would have caught this in our
CMake pipelines, but these only ran on 6.2. Had they run on 6.3 or 6.4,
they would have gated the break. There's no good reason not to run this
CMake CI build in a matrix with all current supported Swift versions.
### Modifications:
Run CMake CI job in a matrix by supported Swift version
### Result:
Two more CI jobs.
### Motivation:
`Package.swift` uses tools version 6.2 and declares no
`swiftLanguageModes`, so SwiftPM builds Swift Crypto in the Swift 6
language mode. The CMake build passes no `-swift-version`, so the
compiler falls back to the Swift 5 language mode. The two build systems
compile the same sources in different language modes.
### Modifications:
- Set `CMAKE_Swift_LANGUAGE_VERSION` to 6 after the swift-asn1
`FetchContent` block, so swift-asn1 keeps its own language mode when
CMake fetches it.
- Raise the minimum CMake version to 3.16, the release that added
`Swift_LANGUAGE_VERSION`.
- Remove the branch that set Windows output directories for CMake
versions before 3.16.
### Result:
CMake builds Swift Crypto in the Swift 6 language mode, as SwiftPM does.
### Motivation:
The comment we have in our package manifest was a bit ambiguous about
Foundation linking and caused some confusion (reported in #496). As
discussed on that issue, I don't think there's anything we want to do
differently here, but we can try and improve the comment so other
adopters don't waste time on a misunderstanding.
### Modifications:
Clarify the privacy manifest comment in the package manifest.
### Result:
Fixes#496.
### Motivation:
We're using `#if swift(...)` in some places, which breaks builds using
Swift 5 language mode with Swift 6.3+ compilers.
### Modifications:
- Check `compiler(<6.4)` instead of `swift(<6.4)`.
- Use `@_lifetime(self: copy self)` on the setter, which 6.2, 6.3, and
6.4 all accept.
### Result:
Build succeeds when compiled with `-Xswiftc -swift-version -Xswiftc 5`
on 6.2, 6.3, and 6.4.
Add `Sendable` conformance to `_RSA.Encryption.PublicKey` and
`_RSA.Encryption.PrivateKey`.
### Motivation:
The `_RSA.Signing` keys became `Sendable` in #211, but the encryption
keys lack the same conformance.
Fixes#494.
### Modifications:
Declare both conformances and add `testKeysAreSendable` to check them at
compile time.
### Result:
RSA encryption keys can be passed across concurrency domains.
Co-authored-by: Si Beaumont <beaumont@apple.com>
### Motivation:
We have some helper functions to zero out memory after use. One of these
helper functions provides a `zeroize()` method on
`UnsafeMutablePointer`, which has a subtle bug. It zeros out
`MemoryLayout.size(ofValue: Pointee.self)` instead of
`MemoryLayout<Pointee>.size`, so only the first 8 bytes get zeroed. This
bug is duplicated in CryptoExtras too in a fileprivate helper.
### Modifications:
- Zero the entire pointee in UnsafeMutablePointer.zeroize
- Copy Zeroization helpers from Crypto to CryptoExtras (without the `#if
canImport(CryptoKit)` guard)
### Result:
All the memory that should be zeroed by this helper is actually zeroed.
### Motivation:
Tending the garden. This repo only supports Swift 6.2+ these days, but
we have some code that conditionally compiles based on compiler versions
that are either always false or always true.
### Modifications:
- Remove any pre-6.2 compiler check.
### Result:
Removing dead code.
Rejects NIST PKCS#8 private keys labelled with the wrong curve.
### Checklist
- [x] I've run tests to see all new and existing tests pass
- [x] I've followed the code style of the rest of the project
- [x] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [x] I've updated the documentation if necessary
### Motivation:
NIST `PrivateKey(derRepresentation:)` and
`PrivateKey(pemRepresentation:)` never compare the PKCS#8
`privateKeyAlgorithm` to the curve. A PKCS#8 labelled secp384r1 that
holds a 32-byte SEC1 key with no `[0]` parameters loads as a P256 key
### Modifications:
- Throw `invalidASN1Object` when the PKCS#8 OID doesn't match the curve,
for P256, P384 and P521 `Signing` and `KeyAgreement`, DER and PEM
- Add a test that loads each curve's key under another curve's OID
### Result:
Keys labelled with the wrong curve now throw. No public API change.
The new test fails on `main` and passes with this change. The full suite
passes on Linux.
Fixes#485
Co-authored-by: Si Beaumont <beaumont@apple.com>
### Motivation:
`extractPrimeFactors` squares `t` times per attempt, where `t` is the
number of trailing zero bits of `e * d - 1`. Nothing bounds `e`, `d` or
`n`, so the caller picks the cost. A 2.5 KB `d` takes about 45 s before
throwing.
### Modifications:
- Reject `e >= n`, `d >= n`, and moduli over 8192 bits before factoring
- Throw once `g^(e * d - 1) != 1`, since then the numbers cannot form a
key
- Add tests for oversized and inconsistent numbers
- Keep the #482 attempt-limit test reaching the limit now that `e >= n`
is rejected
### Result:
These inputs now throw immediately. No public API change.
Valid keys aren't affected: they always have `e < n` and `d < n`, and
BoringSSL already rejects moduli over 8192 bits.
The oversized-number test fails on `main` and passes with this change.
The RSA tests pass on macOS.
Fixes#483
### Motivation:
`_createFromNumbers(n:e:d:)` can hang forever on some inputs. `e = 1, d
= 1` is enough to trigger it
`extractPrimeFactors` is meant to stop after 100 tries, but the
`continue` for a trivial base (`y` is `1` or `n - 1`) skipped the
counter. If every base is trivial, the loop never ends
### Modifications:
- Use `for _ in 0..<100` so every try counts
- Throw early when `e * d == 1`
- Add tests for both failing inputs
### Result:
These inputs now throw instead of hanging. No public API change.
The new tests hang on `main` and pass with this change. The full suite
passes on macOS and Linux.
Valid keys arent affected. Each try works at least half the time, so 100
failed tries wont happen in practice.
Fixes a hang in `_createFromNumbers(n:e:d:)`.
Fixes#481
### Motivation:
`P384._VOPRF.BlindedElement(oprfRepresentation:)` accepts uncompressed
x9.63 encoded inputs, but RFC 9497 states
only inputs using compressed encoding should be accepted:
```
SerializeElement(A): Implemented using the compressed Elliptic-Curve-Point-to-Octet-String method...
DeserializeElement(buf): Implemented by attempting to deserialize a 49-byte array to a public key
using the compressed Octet-String-to-Elliptic-Curve-Point method...
```
### Modifications:
- Add input guard to only accept points using compressed representation.
- Extend the tests.
### Result:
- OPRF element deserialization accepts only the compressed encoding.
- Uncompressed encodings now throw
`CryptoKitError.incorrectParameterSize`.
### Motivation:
ARC presentation verification derives the tag using a loop that scales
with the client-provided nonce, but it has everything it needs to
recompute it with a scalar multiplication.
### Modifications:
- Add a failing test.
- Recompute `m1Tag` as `T - nonceScalar * self.tag`, the same way the
prover does.
### Result:
ARC presentation verification computation independent of magnitude of
nonce.
### Motivation:
An EC point has a compact representation if a condition holds based on
the field prime, but `_isCompactReprestable` mistakenly uses the group
order, which is not the same. This is an issue in our BoringSSL backend
only.
### Modifications:
- Subtract `y` from the field prime rather than `group.order` in
`_isCompactRepresentable`.
- Add tests.
### Result:
`compactRepresentation` now aligns with `init(compactRepresentation:)`,
the draft, and CryptoKit for all curve points.
## Motivation
Xcode 27 is now available[^1] so it's time to merge in our 5.x branch to
main and release 5.0.
## Modifications
See "Release Notes" section below for overview of changes and links to
the PRs that landed on the 5.x branch during the beta period.
## Result
The main branch will be ready to tag a 5.0 release.
[^1]: https://developer.apple.com/download/all/?q=Xcode%2027
---
## Release Notes
Swift Crypto 5.0 aligns the cross-platform API surface with CryptoKit as
shipped in Xcode 27 (CryptoKit-383.2.1), and takes the opportunity to
streamline the package for both adopters and maintainers.
Most users will be able to depend on the 1.0.0, 2.0.0, 3.0.0, 4.0.0, or
5.0.0 series of releases.
To do so, please use the following dependency in your `Package.swift`:
```swift
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "6.0.0"),
```
### Requires Swift 6.2
The package now declares 6.2 as the minimum Swift version in its package
manifest.
### New span-based API
CryptoKit's new non-allocating, span-based entry points are now
available cross-platform:
- `SymmetricKey` gains `bytes: RawSpan`, `init(copying: RawSpan)`,
`init(copyingWithZeroing: inout MutableRawSpan)`, and
`init(size:initializingWith:)` which initializes the key through an
`inout OutputRawSpan`.
- `HashFunction` gains `update(bytes: RawSpan)` and `hash(bytes:
RawSpan)`, and `Digest` gains `init?(copying: RawSpan)`.
- `HMAC` gains `authenticationCode(for: RawSpan, using:)`.
- `HKDF` gains `deriveKey(inputKeyMaterial:salt:info:output:)` writing
into an `inout OutputRawSpan`, along with span-based `extract` and
`expand`. The existing `DataProtocol` overload now has a fast path for
contiguous salt and info.
- `AES.GCM` and `ChaChaPoly` gain in-place
`seal(inPlace:using:nonce:authenticating:tag:)` and
`open(inPlace:using:nonce:authenticating:tag:)` over `MutableRawSpan`,
and their `Nonce` types gain `bytes: RawSpan` and `init(copying:
RawSpan)`.
### Single-use KEM keys
A new `KEMOneTimePrivateKey` protocol, refining `~Copyable` and
`Sendable`, provides a `consuming func decapsulate(_:)` so a
decapsulation key cannot be reused. Conforming types are
`MLKEM768.OneTimePrivateKey`, `MLKEM1024.OneTimePrivateKey`, and
`XWingMLKEM768X25519.OneTimePrivateKey`.
### Extensible enums
Historically Swift Crypto needed a new major version each time CryptoKit
added a case to a non-frozen enum, because Swift Crypto is not built
with library evolution. All public non-frozen enums are now marked
`@nonexhaustive` (SE-0487), which should remove that reason for future
major bumps. Adopters who do not switch over these enums should not need
to widen their version constraints again.
### Other changes
- Symbols that were previously marked `@_spi(...) public` have been made
internal; they were never intended to be available.
- `@available` annotations have been removed from `Crypto`; they are
unused in all supported compilation modes.
- Some internal reference types are now marked `final`
- Some unused code, e.g. `ECDSASignature.derBytes`, is removed.
### Build and packaging
- The `CCryptoBoringSSLShims` target is removed, along with all
`bindMemory(to:)` calls.
- The `.gyb` templates for nonces, digests, ECDH, ECDSA, MLDSA, and
MLKEM are removed and the generated Swift is checked in. The BoringSSL
backend templates for MLDSA and MLKEM remain.
- Conditional compilation is simplified to `#if canImport(CryptoKit)`;
branches that could never be taken are gone.
- Developing the BoringSSL backend on macOS is no longer supported. Use
the Dev Container configuration now shipped in the repository, or build
on the target platform.
- Warnings are silenced for vendored C sources: `-Wshorten-64-to-32` for
BoringSSL and `macro-redefined` for XKCP. CI builds with
`-warnings-as-errors`.
### Commits
The changes in this release were reviewed and merged to the 5.x branch
during the beta period:
- 0a26a9e3 [5.x] Align with CryptoKit APIs from Xcode 27 beta 1 (#442)
- 8ee9962f [5.x] Align with CryptoKit APIs from Xcode 27 beta 2 (#444)
- ce8db476 [5.x] Align with CryptoKit APIs from Xcode 27 beta 4 (#453)
- 15b0fb5b [5.x] Adopt CheckImplementationOnly and CI with
-warnings-as-errors (#454)
- b3746b14 [5.x] Remove bindMemory(to:) calls and the
CCryptoBoringSSLShims target (#455)
- 57782dc6 [5.x] Remove duplicate imports from gyb-generated MLDSA
backend code (#458)
- 2c45ca2f [5.x] Remove unused internal code path:
ECDSASignature.derBytes (#457)
- 33785f67 [5.x] Mark some class types as final (#456)
- 2e074efb [5.x] Remove native SwiftPM build-system workaround in CI
(#461)
- 20f90497 [5.x] Align with CryptoKit from Xcode 27 beta 6 (#462)
---------
Co-authored-by: Dmitry <45711841+darkdi@users.noreply.github.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation:
The RSA initializers that take raw numbers, e.g. `init(n:e:)` and
friends, do not enforce a minimum key size.
Our other public API has two lower bounds: the "safe" APIs, e.g.
`init(pemRepresentation:)`, which has a 2048-bit lower bound, and the
"unsafe" variants, e.g. `init(unsfafePEMRepresentation:)`, which has a
1024-bit minimum.
Given the raw number initializers do not state they are unsafe, they
should probably have a 2048-bit minimum too.
### Modifications:
- Add a 2048-bit minimum key length check to the raw number
initializers.
- Update the documentation to match the wording on the PEM and DER
initializers.
- Extend the tests.
### Result:
The RSA initializers that take raw numbers, e.g. `init(n:e:)` and
friends, now enforce a 2048-bit minimum key length.
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation:
The BoringSSL RSA backing computes `keySizeInBits` using `RSA_size(key)
* 8`, which is incorrect. `RSA_size` returns the number of bytes
required to represent the modulus, so is rounding up to the nearest
byte.
Because of this, the minimum key strength checks are slightly off. For
example, 1017-bit keys are accepted by initializers that document a 1024
minimum, and similar for the initializers guarding for a 2048-bit
minimum.
### Modifications:
- Compute `keySizeInBits` using `RSA_bits` instead of `RSA_size`, which
returns the modulus bit length.
- Add a `modulusByteCount` property, which does still use `RSA_size`,
and use it for the block-size checks.
- Document the byte-alignment requirement of
`_RSA.Encryption.init(pemRepresentation:)` and friends.
- Update and add more tests.
### Result:
- RSA `keySizeInBits` correctly reports the modulus bit length.
- The documented minimum key length requirements are now correctly
enforced, closing a 7-bit gap.
### Motivation:
Not entirely sure how (maybe a merge in from a GHSA fork), but right now
we have failing CI on PRs for a formatting
drift.
### Modifications:
Rerun swift-format.
### Result:
Get pull request CI passing cleanly.
* Fix double-free when RSA key init from bytes fails
Motivation:
When initializing an RSA public key from DER or PEM bytes throws an error,
we double-free of the `EVP_PKEY*`: first in the catch block, then in the
backing `deinit`. The first of these should be removed.
Modifications:
Remove the duplicative call to `EVP_PKEY_free`.
Result:
Fixed double-free of `EVP_PKEY*` when failing to initialize RSA public
key from bytes.
Testing:
Tests have been added that reliably fail under ASan:
```console
% swift --version
Swift version 6.3.2 (swift-6.3.2-RELEASE)
Target: aarch64-unknown-linux-gnu
% env ASAN_OPTIONS=detect_leaks=0 swift test -c release --sanitize=address \
--filter test_invalidPEMPublicKeyThrowsWithoutDoubleFree \
--filter test_invalidDERPublicKeyThrowsWithoutDoubleFree
Test Suite 'Selected tests' started at 2026-07-06 09:36:58.468
Test Suite 'TestRSASigning' started at 2026-07-06 09:36:58.469
Test Case 'TestRSASigning.test_invalidDERPublicKeyThrowsWithoutDoubleFree' started at 2026-07-06 09:36:58.469
Test Case 'TestRSASigning.test_invalidDERPublicKeyThrowsWithoutDoubleFree' passed (0.001 seconds)
Test Case 'TestRSASigning.test_invalidPEMPublicKeyThrowsWithoutDoubleFree' started at 2026-07-06 09:36:58.470
Test Case 'TestRSASigning.test_invalidPEMPublicKeyThrowsWithoutDoubleFree' passed (0.001 seconds)
Test Suite 'TestRSASigning' passed at 2026-07-06 09:36:58.471
Executed 2 tests, with 0 failures (0 unexpected) in 0.002 (0.002) seconds
Test Suite 'Selected tests' passed at 2026-07-06 09:36:58.471
Executed 2 tests, with 0 failures (0 unexpected) in 0.002 (0.002) seconds
◇ Test run started.
↳ Testing Library Version: 6.3.2 (70eff261d7f462c)
↳ Target Platform: aarch64-unknown-linux-gnu
✔ Test run with 0 tests in 0 suites passed after 0.001 seconds.
```
* Have only one designated init for BoringSSLRSAPublicKey.Backing
### Motivation:
Our AES-CBC padding check is a padding-oracle timing side channel.
Validation short-circuits on the first mismatching byte, so the time
taken leaks padding validity; an attacker with a decryption oracle could
recover plaintext without the key. The AES core is already
BoringSSL-backed, so the remaining fix is to move the CBC mode onto
BoringSSL and update padding removal to be constant-time.
Aside: padding removal cannot be delegated to BoringSSL, whose generic
unpad is itself a documented padding oracle absent authentication.
### Modifications:
- Replace the Swift CBC block loop in `AES._CBC` with BoringSSL's
`AES_cbc_encrypt`.
- Add padding on encrypt in Swift, since `AES_cbc_encrypt` does not pad.
- Replace `trimPadding` with `removingPKCS7PaddingConstantTime`
- Add regression tests rejecting over-long pad lengths.
- Add unpad tests for every valid length.
- Add unpad tests for every corruption position.
### Result:
AES-CBC is BoringSSL-backed and padding validation runs in constant
time, removing a timing side channel.
### Motivation:
Swift Crypto 4.0 included SHA3 APIs, which required a backing
implementation on non-Apple platforms. We brought in libXCKP for this
purpose, similar to how we use BoringSSL for the implementation of the
rest of CryptoKit API on non-Apple platforms. The README includes
details of how the code is organised but was not updated to reflect this
change.
### Modifications:
- Update the backend implementation section to include XCKP alongside
BoringSSL
- Add an acknowledgments section to the README
### Result:
The README now includes details of both our backing dependencies, not
just BoringSSL.
Fixes#439.
## Summary
Fixes#435.
On Apple platforms every source file in the `Crypto` target compiles to
just `@_exported import CryptoKit` (because `CRYPTO_IN_SWIFTPM` is
defined but `CRYPTO_IN_SWIFTPM_FORCE_BUILD_API` is not), producing
**zero exported symbols**.
Xcode 26 changed how SPM packages are built for test-target
dependencies: each package product is built as a separate dynamic
framework. A module with no symbols generates a `.framework` directory
but no Mach-O binary, causing a linker error:
```
clang: error: no such file or directory:
'.../PackageFrameworks/Crypto_17A3B1FFC41E47_PackageProduct.framework/Crypto_17A3B1FFC41E47_PackageProduct'
```
## Fix
Added a minimal `_CryptoModuleAnchor` public enum (outside the
conditional compilation guard) so the module always produces at least
one exported symbol, regardless of how it is linked. The type is
prefixed with `_` to signal it is not intended for public use.
## Test plan
- [ ] Build a project with a test target that has `swift-crypto` (or a
transitive dependency like `swift-certificates`) as a
`packageProductDependency` on Xcode 26 targeting iOS Simulator — should
now succeed
- [ ] Verify existing tests still pass (`swift test`)
---------
Co-authored-by: Niccolò Calamai <niccolo.calamai@esselunga.it>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Use `FoundationEssentials` if available.
<!-- Thanks for contributing to Swift Crypto! Before you submit your
issue, please make sure you followed our checklist and check the
appropriate boxes by putting an x in the [ ]: [x] -->
### Checklist
- [x] I've run tests to see all new and existing tests pass (macOS and
linux)
- [x] I've followed the code style of the rest of the project
- [x] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [x] I've updated the documentation if necessary
#### If you've made changes to `gyb` files
- [ ] I've run `.script/generate_boilerplate_files_with_gyb` and
included updated generated files in a commit of this pull request
```
bash .script/generate_boilerplate_files_with_gyb
bash: .script/generate_boilerplate_files_with_gyb: No such file or directory
```
### Motivation:
Would be great that packages that depend on `swift-crypto` can be built
without linking full `Foundation`.
### Modifications:
This patch simply replaces `import Foundation` with a conditional
`import FoundationEssentials`.
In some files this also required to explicitly import the C standard
lib.
Maybe we could follow the same approach as in
https://github.com/swiftlang/swift-tools-support-core/blob/main/Sources/TSCLibc/libc.swift
and add an internal module that abstracts this import dance in a single
place.
### Result:
After this change the package should only depend on
`FoundationEssentials`.
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Add SHA-512/256 digest implementation via BoringSSL
### Checklist
- [x] I've run tests to see all new and existing tests pass
- [x] I've followed the code style of the rest of the project
- [x] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [x] I've updated the documentation if necessary
#### If you've made changes to `gyb` files
- [N/A] I've run `.script/generate_boilerplate_files_with_gyb` and
included updated generated files in a commit of this pull request
### Motivation:
Neither CryptoKit nor swift-crypto currently explore the SHA-512/256
hashing function. SHA-512/256 provides the same 256-bit security level
as SHA-256 but can be significantly faster on 64-bit platforms because
it uses the SHA-512 internal structure, which operates on 64-bit words.
### Modifications:
We modified CryptoExtras to include support using the BoringSSL
implementation.
### Result:
Swift ecosystem supports SHA-512/256.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Swift 6.0 is no longer supported, we should bump the tools version and
remove it from our CI.
Modifications:
* Bump the Swift tools version to Swift 6.1
* Remove Swift 6.0 jobs where appropriate in main.yml, pull_request.yml
Result:
Code reflects our support window.
Motivation:
Swift 6.3 has been released, we should add it to our CI coverage.
Modifications:
Add additional Swift 6.3 jobs where appropriate in main.yml,
pull_request.yml
Result:
Improved test coverage.
Motivation
* Following [GitHub's
announcement](https://github.blog/changelog/2025-09-19-deprecation-of-node-20-on-github-actions-runners/),
Node 20 is being deprecated and runners will begin using Node 24 by
default starting March 4th, 2026. Node 20 will reach end-of-life in
April 2026.
Modifications
* Upgrade GitHub Actions to their latest versions to ensure
compatibility with Node 24.
* Replace `actions/checkout@v4` with `actions/checkout@v6` in all
workflow files.
Result
* Workflow files reference `actions/checkout@v6`.
Add support for creating RSA private keys from encrypted PEM files.
### Checklist
- [X] I've run tests to see all new and existing tests pass
- [X] I've followed the code style of the rest of the project
- [X] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [X] I've updated the documentation if necessary
#### If you've made changes to `gyb` files
- [ ] I've run `./scripts/generate_boilerplate_files_with_gyb.sh` and
included updated generated files in a commit of this pull request
### Motivation:
Resolves#264
### Modifications:
Adds an initializer to `_RSA.Signing.PrivateKey` that takes the
encrypted PEM representation and the encryption password and calls the
high-level BoringSSL function to parse the encrypted key format.
Tests were copied from #318 by @ptoffy.
### Result:
RSA private keys can be created from encrypted PEM files.
Motivation
* `@main` references to `swiftlang/github-workflows` are deprecated.
Modifications
* Replace `@main` with `@0.0.7` in all workflow files.
Result
* Workflow files reference a pinned version of
`swiftlang/github-workflows`.
Add RSA PKCSv1.5 padding support for legacy compat
### Checklist
- [X] I've run tests to see all new and existing tests pass
- [X] I've followed the code style of the rest of the project
- [X] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [X] I've updated the documentation if necessary
#### If you've made changes to `gyb` files
- [n/a] I've run `./scripts/generate_boilerplate_files_with_gyb.sh` and
included updated generated files in a commit of this pull request
### Motivation:
I have a scenario that requires me to be able to encrypt and decrypt
values that use RSA PKCSv1.5 padding. This is known to be a weak
algorithm, so we explicitly want to discourage its use, but there are
scenarios where you need the algorithm for legacy compatibility, so we
want to provide the capability, even if we strongly discourage its use.
### Modifications:
Added a new enum + constant + passthrough to allow users to specify RSA
PKCSv1.5. From the internal review, we thought it would be best to
explicitly name the constants in a way that discouraged use without very
intentional needs, hence the "weak" and "insecure" references in all of
the naming.
### Result:
You can now specify PKCSv1.5 padding for use in encryption and
decryption. This is only adding constants, and the enums are not public,
so there should not be any impact on compatibility (source or binary).
Co-authored-by: Mike Schrag <schrag@apple.com>
Incorrect maximum encryption size for RSA OAEP
### Checklist
- [X] I've run tests to see all new and existing tests pass
- [X] I've followed the code style of the rest of the project
- [X] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [X] I've updated the documentation if necessary
#### If you've made changes to `gyb` files
- [n/a] I've run `./scripts/generate_boilerplate_files_with_gyb.sh` and
included updated generated files in a commit of this pull request
### Motivation:
The `maximumEncryptSize` function is hardcoded to use 42 as the hash
offset, but the RFC actually says it's "2*hLen-2" so 42 is only valid
for SHA1. SHA256 should be 62 (2*32-2). This adds a hash length onto the
Digest enum, which can then be used in the length calculation.
In writing the tests for this, I also stumbled on the unsafe PEM
representation for RSA Public Keys don't allow 1024-bit keys as
documented, so this also fixes that.
### Modifications:
* Added a `hashBitLength` to the RSA Digest which is then used in the
`maximumEncryptSize` to properly compute the maximum length
* Corrected the minimum key size for RSA unsafe PEM public keys to 1024
from 2048
### Result:
* The `maximumEncryptSize` function will return the expected value for
RSA OAEP SHA256 keys. I don't believe anything calls this internally, so
this would be for external consumers.
* Unsafe construction of RSA public keys now allow 1024 bit keys. It was
documented as supporting them, but the check was still 2048 (probably
copy-paste error from the safe variant). This only expands the potential
uses, so it shouldn't introduce any new failures.
Co-authored-by: Mike Schrag <schrag@apple.com>
Add PEM/DER APIs for Curve25519
### Checklist
- [x] I've run tests to see all new and existing tests pass
- [x] I've followed the code style of the rest of the project
- [x] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [x] I've updated the documentation if necessary
#### If you've made changes to `gyb` files
- [ ] I've run `./scripts/generate_boilerplate_files_with_gyb.sh` and
included updated generated files in a commit of this pull request
### Motivation:
Closes#82
Creating Ed25519/X25519 keys using PEM/DER and also generating their
PEM/DER representations can be handy
### Modifications:
Added
- `init(pemRepresentation:)` and the `pemRepresentation` computed
property
- `init(derRepresentation:)` and the `derRepresentation` computed
property
to `Curve25519.{Signing,KeyAgreement}.{Private,Public}Key`
### Result:
Curve25519 can now be created with and can produce PEM/DER
representations
Motivation:
Swift 6.2 has been released, we should add it to our CI coverage.
Modifications:
Add additional Swift 6.2 jobs where appropriate in main.yml,
pull_request.yml
Result:
Improved test coverage.
`getKeyPrimitives` is marked as throws but is not actually throwing
errors and this is yielding warnings. This fixes the warnings.
### Checklist
- [x] I've run tests to see all new and existing tests pass
- [x] I've followed the code style of the rest of the project
- [x] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [x] I've updated the documentation if necessary
#### If you've made changes to `gyb` files
- [N/A] I've run `./scripts/generate_boilerplate_files_with_gyb.sh` and
included updated generated files in a commit of this pull request
### Motivation:
Currently there's a warning
```
/swift-crypto/Sources/_CryptoExtras/RSA/RSA_boring.swift:67:9: warning: no calls to throwing functions occur within 'try' expression
```
because we're using `try` on a non throwing function. This escalates to
all of the functions that use it.
I'm not sure if removing `throws` from a non-actually-throwing public
function is breaking, as using `try` on a non throwing function only
yields a warning (if not in warnings-as-errors mode) but it actively is
a signature change so it might still be breaking. In case we don't want
to merge this as is, the warning can be removed by simply removing
useless `try`s and we can wait for the next major version to remove the
false-throwers.
### Modifications:
Remove the useless `try` and `throws` where they're not needed.
### Result:
The warning is gone.
The threading changes missed an `os(OpenBSD)`, causing the Swift
toolchain build to fail.
### Checklist
- [ ] I've run tests to see all new and existing tests pass
- [X] I've followed the code style of the rest of the project
- [X] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [ ] I've updated the documentation if necessary
#### If you've made changes to `gyb` files
- [ ] I've run `./scripts/generate_boilerplate_files_with_gyb.sh` and
included updated generated files in a commit of this pull request
### Motivation:
Buildfix the upstream Swift toolchain on OpenBSD.
### Modifications:
Added an `os(OpenBSD)` conditional, much like FreeBSD.
### Result:
The Swift toolchain will build successfully again.
Fix multiple issues in the BoringSSL vendoring script and update
BoringSSL to 0226f30467f540a3f62ef48d453f93927da199b6
### Checklist
- [x] I've run tests to see all new and existing tests pass
- [x] I've followed the code style of the rest of the project
- [x] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [x] I've updated the documentation if necessary
### Motivation:
The `vendor-boringssl.sh` script is currently broken in a number of
ways, both in general and relative to the latest BoringSSL version:
- `--enable-test-discovery` is still in use
- The Linux Swift SDKs being generated are out of date (5.10-jammy)
- The script does not prefix exported C++ symbols
- Invoking the script without a `BORINGSSL_REVISION` results in an
unconditional error
- The `PATTERNS` list is out of date for the latest BoringSSL
- The latest BoringSSL contains a bug which fails to apply `extern "C"`
to two exported symbols, allowing for collisions.
In addition, the latest BoringSSL has made `BN_MONT_CTX` opaque,
necessitating that it be referenced with `OpaquePointer` rather than
`UnsafePointer<>`.
### Modifications:
The following changes are included:
- `--enable-test-discovery` has been removed
- `vendor-boringssl.sh` and `generate-linux-sdks.sh` have been updated
to use Swift 6.1.2 SDKs built for Ubuntu Noble
- The `mangle_cpp_structures` function from `swift-nio-ssl`'s version
of `vendor-boringssl.sh` has been copied over (thanks @Lukasa!)
- `BORINGSSL_REVISION` is now allowed to be an empty string
- The `PATTERNS` array has been updated
- A patch has been added which applies `extern "C"` to the functions
which should have it
- `s/UnsafePointer<BN_MONT_CTX>/OpaquePointer/g`
- Updated `CMakeLists.txt` per `update-cmake-lists.sh`
- Update BoringSSL to
`0226f30467f540a3f62ef48d453f93927da199b6`
### Result:
Vendoring the latest BoringSSL will work again.
The latest BoringSSL is vendored.