* 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.
### 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.
### 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.
## 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
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
When developing code that uses the BoringSSL backend on macOS,
developers set a `development` boolean flag in the Package.swift. We
recently switched from declaring minimum platform versions to annotating
symbols with availability annotations. However, when `development =
true`, it flushes out some annotations that were missing in the first
pass. The result is that `main` currently doesn't build on macOS with
this flag set.
### Modifications
- Add missing availability guards required when development mode
enabled.
### Result:
Code builds macOS with `development = true` in Package.swift.
### Motivation
The use of `Data.subdata(in:)` results in needless copies when decoding
fields from bytes. Additionally, the use of a long chain of
`Data.append(_:)` without a call to `Data.init(capacity:)` or
`Data.reserveCapacity(_:)` can result in needless reallocations.
### Modifications
- Remove unused `EncodeInt` and `DecodeInt` functions. They were unused
before this PR but are there from when ARC credential serialization
included the presentation limit. `DecodeInt` also happened to be
incorrect and would crash when called with a slice.
- Add some useful utility methods for popping bytes from a view without
copying.
- Add some generic functions for encoding and decoding
`FixedWidthInteger` types along with tests for concrete types over
`Data` and slices.
- In ARC decoding, replace the use of `Data.subdata(in:)` with code that
uses the `Data.Subsequence` slice (which happens to be `Data` since the
type is self-slicing).
- In ARC encoding, reserve enough capacity in the resulting `Data` when
the sizes are known to reduce allocations.
## Results
More performant serialization and deserialization for ARC types.
### Motivation
The ARC API surface had no Sendable conformance.
### Modifications
Add Sendable conformance to ARC API types, which are all value types.
### Result
Easier to use ARC API types in concurrent contexts.
### Motivation
The latest draft of the ARC spec[0] includes moving where the
presentation limit is used. Before it was baked in when a client
constructed a credential request, but now it has moved to when a client
makes a presentation from a finalized credential. This PR updates the
internals and API surface to reflect this change.
### Modifications
- Defer passing the presentation limit until a presentation is made.
### Result
Align more closely with the published draft.
### API breakage
It's expected that this will result in the following _breaking_ API
changes:
```diff
- P384._ARCV1.PublicKey.prepareCredentialRequest(requestContext:presentationLimit:)
+ P384._ARCV1.PublicKey.prepareCredentialRequest(requestContext:)
```
```diff
- P384._ARCV1.Credential.makePresentation(context:)
+ P384._ARCV1.Credential.makePresentation(context:presentationLimit:)
```
As this is behind an underscored namespace, we deem this an acceptable
break.
[0]: https://datatracker.ietf.org/doc/draft-yun-cfrg-arc/
## Motivation
We would like to provide support for ARCV1(P-384), as defined in [IETF
Internet Draft: Anonymous Rate-Limited
Credentials](https://datatracker.ietf.org/doc/draft-yun-cfrg-arc/).
## Modifications
- Add internal implementation, generic over the NIST curves.
- Add public API for ARC(P-384), under `P384._ARCV1`.
## Result
New API for current draft of ARC.
## Tests
- End to end tests of internal implementation and API surface.
- Test vector tests of internal implementation and API surface, from the
spec draft.
## Motivation
As part of the Github Actions CI migration we held off enabling the
format check and moving to the same formatting rules as Swift NIO, but
we'd like to do that now.
## Modifications
- Add a script to generate (and update) the `.swiftformatignore` file
since this repo only wants to format a specific set of files matching a
pattern.
- Generate and commit the `.swiftformatignore` file.
- Run the fomatter and commit the results.
- Additional commits to satisfy the remaining linter rules that weren't
auto-fixed by swift-format.
- Enable the format check in CI.
## Result
- Code that's not shared is formatted with a style consistent with the
other repos this team maintain.
- CI is now checking code format again.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
## Motivation
We would like to provide support for the P384-SHA384 Verifiable Oblivious Pseudorandom Function (VOPRF) as defined in [RFC 9497: VOPRF Protocol](https://www.rfc-editor.org/rfc/rfc9497.html#name-voprf-protocol).
## Modifications
- Add protocols for some "ECToolbox" abstractions: `Group`, `GroupElement`, `GroupScalar`, `HashToGroup`.
- Add implementations backed by BoringSSL.
- Duplicate some utilities from Crypto into _CryptoExtras: hexadecimal bytes and I2OSP.
- Add VOPRF API, rooted at `enum P384._VOPRF`.
## Results
- New internal abstractions that make it easier to bring up new implementations.
- New API for `OPRF(P-384, SHA-384)` in VOPRF mode.
## Tests
- Test vectors for internal `HashToField` implementation.
- Test vectors for internal VOPRF implementation.
- Tests of the VOPRF public API.
* wrapper: Remove _boring suffix from files in CryptoBoringWrapper
* wrapper: Move EC types and random bytes into CryptoBoringWrapper
* tests: Remove unused conditional compilation conditions in wrapper tests
* API for RSA blind signing and verification from RFC 9474
* Add blind signing backend for Security framework
* Hide PSSZERO variants from public API for now
* Update CMakeLists.txt
* Verify signature produced within SecurityRSAPrivateKey.blindSignature(_:)
* Update API: bake params into key, use wrappers for intermidiate values
* Throw specific error when message too large for key modulus
* Drop Security framework backend and support all variants
* Factor out withNewBignumContext helper
* Align parameter names and labels in internal functions with public API
* Fix typo in doc comments: public -> private
* Implement client operations for RSA Blind Signatures
* Remove the BlindedMessage type
* Move prepare function to public key method
* Throw (internal) errors defined in the RFC
* Fix test function names for Linux test discovery
* Factor saltLength into a computed property on Parameters
* Improve allocations for temporary bytes
* Fixup documentation typos
* Parameters are Sendable, regardless of H type parameter
* PublicKey and PrivateKey are also Sendable, regardless of H
* Wrap internal errors in most appropriate CryptoKitError
* Factor code differently
* Tweak API to return BlindingResult nominal type instead of tuple
* Prefer withUnsafeTemporaryAllocation(of:capacity:_:) to Array.init(unsafeUnitializedCapacity:_:)
* Move unsafe temporary allocations into BlindSigningHelpers methods
* Replace hand-rolled BN ops with ArbitraryPrecisionInteger and FFAC
* Fixup placement of paren in guards with closures
* Replace closure invocation let binding with looped var
* Use ERR_peek_last_error, not ERR_get_error
* Move ArbitraryPrecisionInteger_boring.swift to CryptoBoringWrapper
* Remove conditional compilation guards for ArbitraryPrecisionInteger
* Throw CryptoBoringWrapperError.internalBoringSSLError instead of CryptoKitError.internalBoringSSLError
* Make most operations public and add raw pointer APIs
* Move ArbitraryPrecisionIntegerTests to new CryptoBoringWrapperTests target
* rename some files
* Remove @_implementationOnly from imports and raw pointer APIs
* Also move over FiniteFieldArithmeticContext to CryptoBoringWrapper
* Add FiniteFieldArithmeticContext.inverse
* Remove conditional compilation guards for FFAC
* Update CMakeLists.txt for moved files
* Revert "Add FiniteFieldArithmeticContext.inverse"
This reverts commit e02700e07c.
* Fix CMakeLists.txt
* Make most public symbols @inlinable
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>