### 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.
* 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.
## 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.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.
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.
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
`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.
Motivation
In preparation for adopting FoundationEssentials where available, we
need to avoid using Thread as that isn't available. To that end, let's
bring over NIO's ThreadSpecificVariable wrapper.
Modifications
Bring over NIO's ThreadSpecificVariable wrapper and supporting code.
Result
No need for Thread anymore.
### Motivation:
swift-crypto currently fails to compile with TSAN enabled in 5.10 and
6.0 due to a TSAN error stemming from the use of `consuming` in the
`finalize()` method of `_CryptoExtras/AES/CMAC`.
### Modifications:
Like #384, the `consuming finalize()` method in `_CryptoExtras/AES/CMAC`
is now wrapped inside a `#if compiler(>=6.1)` condition. A non-consuming
variant is used otherwise.
### Result:
`swift-crypto` can successfully compile with TSAN enabled in 5.10 and
6.0.
Swift SDK solution for adding armv7 symbols for swift-crypto using the
[swift-sdk-generator](https://github.com/swiftlang/swift-sdk-generator).
### Motivation:
As outlined in #223, the necessary symbols for armv7 are missing from
swift-crypto, and we'd like to add them in some way that could be
accepted by the team. It was discussed that using Swift SDKs generated
from the swift-sdk-generator could be a solution that could be easily
vetted, since the swift-sdk-generator is a component maintained by Apple
and the swiftlang organization.
### Modifications:
- Added a new `./scripts/generate-linux-sdks.sh` script to clone & build
the swift-sdk-generator, and create Swift SDKs for x86_64, aarch64, and
armv7.
- Modified the `./scripts/vendor-boringssl.sh` script to use these
installed Swift SDKs to cross-compile for Linux architectures in the
script.
- Ran the scripts against the exact revision of BoringSSL to avoid
source updates, which adds the missing symbols for armv7.
### Result:
Swift SDKs are used to generate symbols for Linux architectures instead
of Docker, and missing symbols for armv7 are added as well.
I have a few pros and cons for this solution:
- Pros
- Swift SDKs are used to cross-compile for Linux instead of Docker,
which performs better than Rosetta 2 emulation. Docker does not have to
be used at all for this solution.
- Switching to using Swift SDKs is the more "correct" way to
cross-compile for Linux targets, and much of the ecosystem for
cross-compilation of Swift packages is moving to using Swift SDKs.
- Cons
- Lots of downloads need to happen since the swift-sdk-generator needs
to download the host macOS toolchain for Swift 5.10, plus Ubuntu
packages and target toolchains for each architecture (x86_64, aarch64,
armv7). This results in ~15GB of artifacts in the /tmp directory for
just the generator artifacts. However, this only needs to be run once
before running the vendoring script.
Let me know what you think @Lukasa.
## Motivation
We were using a `@TaskLocal static var` to hold the
`FiniteFieldArithmeticContext` (FFAC) on each of the curve types. The
intention here was this would operate as a thread-local value, since
task-locals behave like thread locals when the caller is not part of a
task context. However, they still require binding, (i.e. the use of e.g.
`P256.$__ffac.withValue { ... }`[^1], otherwise they just return the
_default_ value, which is globally shared. We were not doing that, nor
do we have a sensible place where we could.
This causes crashes when using these values in a multithreaded
environment since the same value will be used across threads.
## Modifications
- Use an explicit thread-local API from Foundation to store and read the
per-curve FFAC.
- Add a test that shows each thread gets the same value on each read,
but distinct from all other threads.
## Result
Fixes crash when using ECToolbox-based APIs in multithreaded code.
[^1]:
https://developer.apple.com/documentation/swift/tasklocal#Using-task-local-values-outside-of-tasks
Motivation
AES CMAC is a standardised albeit somewhat uncommon MAC built on top of
the AES block cipher. CMAC pops up in a few places, mostly where it is
convenient to assume that you have access to AES, but not to a hash
function. For example, AES-SIV is built on CMAC.
Modifications
Add CMAC support
Add tests and test vectors
Result
CMAC is supported
Add Sequence conformance to `AES._CBC.IV` where `Element` is `UInt8`.
<!-- 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
- [ ] I've run tests to see all new and existing tests pass
> PKCS8DERRepresentationTests do not compile on master branch with Error
`'pkcs8DERRepresentation' is only available in iOS 14.0 or newer`. All
the other tests pass after my changes.
- [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
### Motivation:
No convenient API for converting `AES._CBC.IV` into `Data`.
### Modifications:
Added `Sequence` conformance to `AES._CBC.IV` similarly how it is done
for `AES.GCM._SIV.Nonce`.
### Result:
It will be possible to create `Data` instance with `AES._CBC.IV` passed
as init argument.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation
We shouldn't repeatedly reconstruct static data
Modifications
- Turn the groups into static lets instead of computed properties
Result
Fewer allocations
Motivation:
Version 3.13.0 hits a compiler assertion when compiling in release mode
on Linux with Swift 6.1. This appears to stem from missing inlinable
annotations.
Modifications:
- Add a few more `@inlinable` and `@usableFromInline` annotations
Result:
Builds on 6.1+ in release mode
Make swift-crypto build on Windows
### 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:
Currently, swift-crypto on the main branch does not build on Windows.
### Modifications:
* Add the Windows Arm64 assembly files to the CMake build.
* Add appropriate CMake options for swift-crypto to build on Windows.
### Result:
swift-crypto can be built on Windows from main
Fixes#369
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Provides a typealias for `CryptoKitError` to hide the implementation
detail of CryptoKit. Resolves#274
### Motivation:
CryptoKit is an implementation detail on Apple platforms - this makes it
clearer for users coming from other platforms
### Modifications:
Added a type alias and updated documentation
Co-authored-by: Cory Benfield <lukasa@apple.com>
## Motivation
The ARC IETF draft has been updated to now support P256 and drop support
for P384.
## Modifications
- Update the internal ARC implementation to accommodate multiple curves
- Add API surface for P256
- Deprecate API for P384
- Add tests for P256 with test vectors from the draft
- Move over the end-to-end API tests to P256
- Add benchmarks for P256
## Result
- New API `P256._ARCV1`, which provides an implementation of ARC(P-256).
- Deprecate `P384._ARCV1`, which provides an implementation of
ARC(P-256).
[^1]:
https://chris-wood.github.io/draft-arc/draft-yun-cfrg-arc.html#name-arcv1-p256
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation:
Depending on the platform Swift Crypto Extras might use an
implementation backed by `Security.framework`, specifically for RSA.
Since
BoringSSL is a necessary dependency on all platforms, we can deduplicate
the implementation and keep a single backend.
### Modifications:
Remove the `Security.framework` implementation and tie the RSA backend
to
BoringSSL.
### Result:
Swift Crypto Extras always uses the BoringSSL backend for RSA.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation
PKCS#8 is pretty widely used. Currently getting a key in PKCS#8 DER
representations requires going through a PKCS8 PEM document and then get
its DER bytes.
### Modifications
Add a computed property to RSA private keys that calls into BoringSSL or
Security.framework to get the PKCS8 DER representation of the key.
ECDH keys use the existing `derRepresentation` property to provide a
property of the same name.
A small ASN1 encoder adds the functionality to ed25519/x25519 keys.
### Result
The representation can be accessed directly.
*The identifiers for MLKEM are [still a
draft](https://datatracker.ietf.org/doc/draft-ietf-lamps-kyber-certificates/).
As such MLKEM is not included in the PR.*
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation
Both of these types should be CoW data structures that are inherently
Sendable. This will make programming with them substantially easier.
Modifications
- ArbitraryPrecisionInteger gets marked @unchecked Sendable
- Refactor EllipticCurvePoint to become a CoW value type
- Make EllipticCurvePoint @unchecked Sendable
Results
Easier to use types
Fixed the documentation comment for the constructors
* `init(unsafePEMRepresentation:)`
* `init(unsafeDERRepresentation:)`
of **`_RSA.Signing.PrivateKey`** which said "*public* key" instead of
"*private* key".
### Modifications:
No code changes.
Add ML-DSA-87
### 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
- [X] I've run `.script/generate_boilerplate_files_with_gyb` and
included updated generated files in a commit of this pull request
### Motivation:
See #355
### Modifications:
Add the "87" parameter set in MLDSA_boring.swift.gyb, add tests for
`MLDSA87` and update the test vectors for both ML-DSA 65 and 87
### Result:
`MLDSA87` is now available
This patch updates BoringSSL to
035e720641f385e82c72b7b0a9e1d89e58cb5ed5. As with all of our patch
updates to BoringSSL, this comes in multiple commits. The first contains
the changes to the vendoring script, and the last contains the tweaks to
product code. The middle commit can be ignored for review purposes.
Generalises the definition of ML-DSA algorithms with GYB to allow the
addition of other parameter sets in the future
### 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
- [X] I've run `.script/generate_boilerplate_files_with_gyb` and
included updated generated files in a commit of this pull request
### Motivation:
BoringSSL recently [made ML-DSA-87
public](https://boringssl.googlesource.com/boringssl/+/2a514a51baebd5a232fc64f7b082f7a8b28cd29d)
in its API, in addition to ML-DSA-65 which has already been [integrated
into Swift Crypto](https://github.com/apple/swift-crypto/pull/267).
By generating the code with GYB we will be able to add support for
ML-DSA-87 very easily in the future when the vendored version of
BoringSSL is updated.
### Modifications:
Generate the code for `MLDSA65` (and in future also for `MLDSA87`) with
GYB.
### Result:
Nothing changes in the public API, but adding `MLDSA87` in the future
will be instantaneous.
Motivation:
Swift 5.9 is no longer supported, we should bump the tools version and
remove it from our CI.
Modifications:
* Bump the Swift tools version to Swift 5.10
* Remove Swift 5.9 jobs where appropriate in main.yml, pull_request.yml
Result:
Code reflects our support window.
Add support for ML-KEM post-quantum key encapsulation mechanism inside
`_CryptoExtras`.
<!-- 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
- [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
- [x] I've run `.script/generate_boilerplate_files_with_gyb` and
included updated generated files in a commit of this pull request
### Motivation:
With the advent of quantum computing, the mathematical foundations on
which the cryptographic protocols in use today are based have been
questioned, as they can easily be circumvented and violated by quantum
computers.
While waiting for the creation of quantum computers that work at full
capacity, and to protect network communications from "[Harvest Now,
Decrypt
Later](https://en.wikipedia.org/wiki/Harvest_now,_decrypt_later)"
attacks, the cryptographic community is working on post-quantum
cryptography algorithms, which work on the traditional computers we use
today, but are resistant to future attacks by quantum computers.
One of these algorithms is ML-KEM (AKA Kyber), a module lattice-based
key encapsulation mechanism standardized by NIST in [FIPS
203](https://csrc.nist.gov/pubs/fips/203/final), that is available
inside BoringSSL.
By including ML-KEM inside Swift Crypto, we can get closer to
normalizing quantum secure algorithms and start implementing them into
our apps and libraries to make them quantum-proof.
### Modifications:
Added `MLKEM768` and `MLKEM1024` enums (generated with `gyb`) inside the
`_CryptoExtras` module with corresponding `PrivateKey` and `PublicKey`
structs that use BoringSSL methods to decapsulate and encapsulate
ML-KEM-768 and ML-KEM-1024 ciphertexts, with the code style of other
KEMs in the library (they also conform to `KEMPrivateKey` and
`KEMPublicKey` protocols).
### Result:
ML-KEM key agreements can be handled with Swift Crypto.
Add support for ML-DSA post-quantum digital signatures inside
`_CryptoExtras`.
### Motivation:
With the advent of quantum computing, the mathematical foundations on
which the cryptographic protocols in use today are based have been
questioned, as they can easily be circumvented and violated by quantum
computers.
While waiting for the creation of quantum computers that work at full
capacity, and to protect network communications from "[Harvest Now,
Decrypt
Later](https://en.wikipedia.org/wiki/Harvest_now,_decrypt_later)"
attacks, the cryptographic community is working on post-quantum
cryptography algorithms, which work on the traditional computers we use
today, but are resistant to future attacks by quantum computers.
One of these algorithms is ML-DSA (AKA Dilithium), a module
lattice-based signature scheme standardized by NIST in [FIPS
204](https://csrc.nist.gov/pubs/fips/204/final), that is available
inside BoringSSL.
By including ML-DSA inside Swift Crypto, we can get closer to
normalizing quantum secure algorithms and start implementing them into
our apps and libraries to make them quantum-proof.
### Modifications:
Added a `MLDSA65` enum inside the `_CryptoExtras` module with
corresponding `PrivateKey`, `PublicKey` and `Signature` structs that use
BoringSSL methods to produce and verify ML-DSA-65 digital signatures,
with the code style of other signature schemes in the library.
Added tests that cover use cases of the ML-DSA scheme, including [test
vectors taken from the BoringSSL
repo](https://boringssl.googlesource.com/boringssl/+/refs/heads/master/crypto/mldsa/mldsa_nist_keygen_tests.txt)
(extracted from a `.txt` file and encoded in JSON).
### Result:
ML-DSA-65 digital signatures can be created and verified with Swift
Crypto.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
OpenBSD support.
### 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 (_not necessary_)
#### If you've made changes to `gyb` files
- [X] I've run `.script/generate_boilerplate_files_with_gyb` and
included updated generated files in a commit of this pull request (_not
applicable_)
### Motivation:
swift-crypto is a required dependency for swift-package-manager, and
must build and run on OpenBSD.
### Modifications:
OpenBSD support for cmake/swiftpm.
* Add to patterns for CMakeLists. Also provide a helpful error so future
porters have a slightly better idea of what might need to be updated.
* Proactively reverse sense in some system name checks so they read as
"if not Darwin". This is likely safer to do here than elsewhere since
there are likely not going to be other platforms for which swift-crypto
already exists.
* Add to Package.swift
ManagedBuffer.capacity is unavailable on OpenBSD.
ManagedBuffer.capacity depends on malloc introspection (e.g.,
`malloc_size`), which is not available on this platform -- and is thus
marked as such.
Here, SecureBytes uses a ManagedBuffer in Backing. We have capacity
tracked in the BackingHeader, and most of the references to the
ManagedBuffer.capacity property can be replaced with references to the
capacity in the header. However, since capacity in the header is marked
as internal which conflicts with some of the @inline functions, so we
must change those to @usableFromInline for the platform as well.
Add conditional for RandomBytes.
Required for tests to build on OpenBSD.
### Result:
swift-crypto builds and runs on OpenBSD.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
https://github.com/apple/swift-crypto/issues/338 pointed to some
availability guard platform mismatches on `ARC` and its extensions. This
PR aims to fix these and make sure all platforms build correctly.