* 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'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.
* 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>