Compare commits

...
21 Commits
Author SHA1 Message Date
Si Beaumont e15b6234fe empty: CI check 2026-11-19 14:47:20 +00:00
Si Beaumont 3280a5f728 Merge commit from fork 2026-11-19 14:46:02 +00:00
Si Beaumont 1fa43495bc Merge commit from fork
* 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
2026-11-19 14:45:16 +00:00
Si Beaumont 9f96b82711 Run CMake CI job in a matrix by supported Swift version (#500)
### 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.
2026-11-06 16:56:34 +00:00
Si Beaumont 281a92df6c Build the CMake targets in the Swift 6 language mode (#501)
### 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.
2026-11-04 11:55:03 +00:00
Si Beaumont 32adcc5038 Update conditional compilation blocks to use compiler version instead of language mode (#499) 2026-11-03 18:08:15 +00:00
Si Beaumont 1586608eee Clarify the privacy manifest comment in the package manifest (#498)
### 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.
2026-11-03 17:17:39 +00:00
Si Beaumont f8fad2f95a Fix builds using Swift 5 language mode with newer compilers (#497)
### 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.
2026-11-03 13:15:54 +00:00
Peter KrassayandSi Beaumont 6ff0a3b147 Make _RSA.Encryption keys Sendable (#495)
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>
2026-11-02 09:16:43 +00:00
Si Beaumont ab0beab369 Zero temporary buffers that hold key material and reduce more allocations (#493)
### Motivation:

AES-KeyWrap unwrap, ML-KEM decapsulation, PBKDF2, and scrypt each write
the key they return into a temporary buffer, copy it into a
`SymmetricKey`, and free the buffer without zeroing it. The
`SymmetricKey` stores its copy in `SecureBytes`, which zeroes the copy
before freeing it. Nothing zeroes the original.

AES-KeyWrap and ML-KEM can write the key directly into the
`SymmetricKey`, as X-Wing already does. That removes both the buffer and
the copy. PBKDF2 and scrypt can't, because they are in CryptoExtras and
`SymmetricKey(unsafeUninitializedCapacity:initializingWith:)` is
internal to Crypto. They keep their buffer and zero it after the copy.
Moving that buffer onto the stack made them twice as slow.

### Modifications:

- Add benchmarks for AES-KeyWrap, ML-KEM, PBKDF2, and scrypt
- Unwrap AES-KeyWrap keys straight into the `SymmetricKey`
- Decapsulate ML-KEM shared secrets straight into the `SymmetricKey`.
Regenerating `MLKEM_boring.swift` from its `.gyb` also drops five
`@available` attributes that were only ever in the generated file.
- Zero the PBKDF2 and scrypt derived key buffers

### Result:

- After the call returns, no temporary buffer still contains the key.
- `AES.KeyWrap.unwrap` makes 2 allocations instead of 3 and is about 6%
faster.
- `MLKEM768.PrivateKey.decapsulate` makes 2 allocations instead of 4.
- `KDF.Insecure.PBKDF2.deriveKey` and `KDF.Scrypt.deriveKey` make the
same number of allocations and take the same time as before.

### Benchmarks:

The tables come from `swift package benchmark --metric mallocCountTotal
--metric wallClock`.

```
aes-keywrap-unwrap (before)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *         │         3 │         3 │         3 │         3 │         3 │         3 │         3 │         5 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ns) * │       597 │       601 │       614 │       621 │       630 │       630 │       630 │         5 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

aes-keywrap-unwrap (after)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *         │         2 │         2 │         2 │         2 │         2 │         2 │         2 │         5 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ns) * │       563 │       564 │       578 │       578 │       581 │       581 │       581 │         5 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

mlkem768-decapsulate (before)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *         │         4 │         4 │         4 │         4 │         4 │         4 │         4 │        10 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (μs) * │        48 │        49 │        50 │        51 │        51 │        51 │        51 │        10 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

mlkem768-decapsulate (after)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *         │         2 │         2 │         2 │         2 │         2 │         2 │         2 │        10 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (μs) * │        46 │        48 │        49 │        51 │        51 │        51 │        51 │        10 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛
```
2026-11-02 08:31:17 +00:00
Si Beaumont 57de8e7cb8 Zero the entire pointee in UnsafeMutablePointer.zeroize (#491)
### 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.
2026-10-23 11:46:45 +00:00
Si Beaumont 6a032cf17d Remove pre-6.2 compiler checks (#492)
### 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.
2026-10-23 10:58:54 +00:00
deadcaf3andSi Beaumont 404c818e35 Check the PKCS#8 curve OID when loading NIST private keys (#486)
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>
2026-10-23 08:30:30 +01:00
Si BeaumontandPaul Toffoloni 47df2f1f6d Use a scoped zeroing allocation for the HMAC pad (#490)
### Motivation:

Currently HMAC heap allocates twice per construction for temporary
storage. `HMAC.init(key:)` builds the inner and outer pads using two
`SecureBytes` allocations. This is a bottleneck for both HMAC and HKDF,
which constructs an HMAC per output block. Both pads never escape the
initializer, so neither needs to be on the heap at all. A scoped
temporary allocation that zeroes after use does the same job with no
allocations.

### Modifications:

- Fix the Benchmarks package build (missing `Sendable` annotation)
- Add benchmarks for HMAC and HKDF
- Add scoped zeroing temporary allocation helpers
- Use a scoped zeroing allocation for the HMAC pad

### Result:

- `HMAC<SHA256>.authenticationCode`: was 5 allocations, now 3, ~20%
faster.
- `HKDF<SHA256>.deriveKey`, 1 KiB output: was 170 allocations, now 104,
~30% faster.

### Benchmarks:

```
hmac-sha256-authenticate (before)
╒═════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                  │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞═════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *        │         5 │         5 │         5 │         5 │         5 │         5 │         5 │         5 │
├─────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ns) * │      1170 │      1251 │      1251 │      1271 │      1340 │      1340 │      1340 │         5 │
╘═════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

hmac-sha256-authenticate (after)
╒═════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                  │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞═════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *        │         3 │         3 │         3 │         3 │         3 │         3 │         3 │         5 │
├─────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ns) * │       870 │       910 │       970 │      1030 │      1030 │      1030 │      1030 │         5 │
╘═════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

hkdf-sha256-derive (before)
╒═════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                  │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞═════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *        │       170 │       170 │       170 │       170 │       170 │       170 │       170 │        10 │
├─────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (μs) * │        20 │        20 │        30 │        30 │        30 │        30 │        30 │        10 │
╘═════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

hkdf-sha256-derive (after)
╒═════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                  │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞═════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *        │       104 │       104 │       104 │       104 │       104 │       104 │       104 │        10 │
├─────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (μs) * │        10 │        20 │        20 │        20 │        20 │        20 │        20 │        10 │
╘═════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛
```

### Credits:

This PR is a re-work of the original contribution by @ptoffy. The
merge-commit will show him as a co-author.

---------

Co-authored-by: Paul Toffoloni <69189821+ptoffy@users.noreply.github.com>
2026-10-22 09:36:54 +01:00
Si Beaumont c2cbadd726 Merge commit from fork 2026-10-20 10:55:16 +02:00
deadcaf3 deb49b961e Bound the cost of RSA prime factor recovery (#484)
### 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
2026-10-20 09:38:39 +01:00
deadcaf3 0f6f68df04 Bound prime factor recovery in RSA _createFromNumbers (#482)
### 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
2026-10-16 13:53:27 +00:00
Si Beaumont 1c80d3aff5 Require compressed encoding when deserializing OPRF elements (#479)
### 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`.
2026-10-09 11:38:27 +00:00
Si Beaumont 25847ff705 Make ARC presentation verification cost independent of the nonce (#478)
### 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.
2026-10-09 11:17:31 +00:00
Si Beaumont 8c018d0882 Fix compact representability for points above the field midpoint (#477)
### 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.
2026-10-09 11:57:20 +01:00
apple-ospo[bot] a629920495 Housekeeping: replace repo-level CODE_OF_CONDUCT (#476) 2026-09-25 22:47:28 +01:00
51 changed files with 840 additions and 310 deletions

No files matched your search

+6 -1
View File
@@ -14,6 +14,7 @@ jobs:
with:
license_header_check_project_name: "SwiftCrypto"
docs_check_enabled: false
format_check_container_image: "swift:latest"
unit-tests:
name: Unit tests
@@ -47,6 +48,10 @@ jobs:
cmake-checks:
name: CMake checks
strategy:
fail-fast: false
matrix:
swift_version: ["6.2", "6.3", "6.4"]
uses: apple/swift-nio/.github/workflows/cmake_tests.yml@main
with:
update_cmake_lists_config: >-
@@ -61,7 +66,7 @@ jobs:
{ "name": "CCryptoBoringSSL", "type": "assembly", "exceptions": [ "*/AES/*.swift" ] }
]
}
image: swift:6.2
image: "swift:${{ matrix.swift_version }}"
macos-tests:
name: macOS tests
+142 -1
View File
@@ -21,7 +21,7 @@ import FoundationEssentials
import Foundation
#endif
let benchmarks = {
let benchmarks: @Sendable () -> Void = {
let defaultMetrics: [BenchmarkMetric] = [.mallocCountTotal, .cpuTotal]
Benchmark(
@@ -208,4 +208,145 @@ let benchmarks = {
blackHole(try key1.sharedSecretFromKeyAgreement(with: key2.publicKey))
}
}
Benchmark(
"hmac-sha256-authenticate",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .mega,
maxDuration: .seconds(10_000_000),
maxIterations: 5
)
) { benchmark in
let key = SymmetricKey(size: .bits256)
let message = Data(repeating: 0x41, count: 1024)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(HMAC<SHA256>.authenticationCode(for: message, using: key))
}
}
Benchmark(
"hkdf-sha256-derive",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .kilo,
maxDuration: .seconds(10_000_000),
maxIterations: 10
)
) { benchmark in
let inputKeyMaterial = SymmetricKey(size: .bits256)
let salt = Data("benchmark salt".utf8)
let info = Data("benchmark info".utf8)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(
HKDF<SHA256>.deriveKey(
inputKeyMaterial: inputKeyMaterial,
salt: salt,
info: info,
outputByteCount: 1024
)
)
}
}
Benchmark(
"aes-keywrap-unwrap",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .mega,
maxDuration: .seconds(10_000_000),
maxIterations: 5
)
) { benchmark in
let kek = SymmetricKey(size: .bits256)
let wrapped = try AES.KeyWrap.wrap(SymmetricKey(size: .bits256), using: kek)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(try AES.KeyWrap.unwrap(wrapped, using: kek))
}
}
if #available(macOS 26.0, *) {
Benchmark(
"mlkem768-decapsulate",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .kilo,
maxDuration: .seconds(10_000_000),
maxIterations: 10
)
) { benchmark in
let privateKey = try MLKEM768.PrivateKey()
let encapsulated = try privateKey.publicKey.encapsulate().encapsulated
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(try privateKey.decapsulate(encapsulated))
}
}
}
Benchmark(
"pbkdf2-sha256-derive",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .kilo,
maxDuration: .seconds(10_000_000),
maxIterations: 10
)
) { benchmark in
let password = Data("benchmark password".utf8)
let salt = Data("benchmark salt".utf8)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(
try KDF.Insecure.PBKDF2.deriveKey(
from: password,
salt: salt,
using: .sha256,
outputByteCount: 32,
unsafeUncheckedRounds: 1_000
)
)
}
}
Benchmark(
"scrypt-derive",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .kilo,
maxDuration: .seconds(10_000_000),
maxIterations: 3
)
) { benchmark in
let password = Data("benchmark password".utf8)
let salt = Data("benchmark salt".utf8)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(
try KDF.Scrypt.deriveKey(
from: password,
salt: salt,
outputByteCount: 32,
rounds: 1 << 10,
blockSize: 8,
parallelism: 1
)
)
}
}
}
+6 -8
View File
@@ -12,7 +12,7 @@
##
##===----------------------------------------------------------------------===##
cmake_minimum_required(VERSION 3.15.1)
cmake_minimum_required(VERSION 3.16)
if(POLICY CMP0157)
cmake_policy(SET CMP0157 NEW)
@@ -25,13 +25,8 @@ list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules)
include(SwiftSupport)
if(CMAKE_VERSION VERSION_LESS 3.16 AND CMAKE_SYSTEM_NAME STREQUAL Windows)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
else()
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
endif()
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift)
@@ -79,5 +74,8 @@ if(NOT SwiftASN1_FOUND)
FetchContent_MakeAvailable(ASN1)
endif()
# Set after vending swift-asn1 so its targets keep their own language mode.
set(CMAKE_Swift_LANGUAGE_VERSION 6)
add_subdirectory(Sources)
add_subdirectory(cmake/modules)
-3
View File
@@ -1,3 +0,0 @@
# Code of Conduct
The code of conduct for this project can be found at https://swift.org/code-of-conduct.
+2 -3
View File
@@ -49,9 +49,8 @@ var swiftSettings: [SwiftSetting] = [
swiftSettings.append(.enableExperimentalFeature("CheckImplementationOnly"))
#endif
// This doesn't work when cross-compiling: the privacy manifest will be included in the Bundle and
// Foundation will be linked. This is, however, strictly better than unconditionally adding the
// resource.
// A resource makes SwiftPM generate a `Bundle.module` accessor that imports Foundation, not just FoundationEssentials.
// `canImport(Darwin)` checks the host, not the target, so cross-compiling from Darwin still adds the resource.
#if canImport(Darwin)
let privacyManifestExclude: [String] = []
let privacyManifestResource: [PackageDescription.Resource] = [.copy("PrivacyInfo.xcprivacy")]
+2 -2
View File
@@ -72,7 +72,7 @@ extension AES {
/// - nonce: The nonce the sealing process requires.
/// - authenticatedData: Additional data to be authenticated, if provided.
/// - tag: receives the 16-byte authentication tag
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(message: copy message)
#endif
public static func seal(
@@ -127,7 +127,7 @@ extension AES {
/// - authenticatedData: Additional data that was authenticated.
///
/// The call throws an error if decryption or authentication fail.
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(message: copy message)
#endif
public static func open(
@@ -59,7 +59,7 @@ enum OpenSSLAESGCMImpl {
return AES.GCM.SealedBox(combined: combined, nonceByteCount: nonce.count)
}
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(message: copy message)
#endif
@inlinable
@@ -119,7 +119,7 @@ enum OpenSSLAESGCMImpl {
}
/// Open a given message in place.
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(message: copy message)
#endif
@inlinable
@@ -48,7 +48,7 @@ extension BoringSSLAEAD {
}
/// Seal a given message in place
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(message: copy message)
#endif
func seal(
@@ -93,7 +93,7 @@ extension BoringSSLAEAD {
}
/// Open a given message in place.
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(message: copy message)
#endif
public func open(
@@ -150,7 +150,7 @@ enum OpenSSLChaChaPolyImpl {
return ChaChaPoly.SealedBox(combined: combined, nonceByteCount: nonce.count)
}
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(message: copy message)
#endif
static func encrypt(
@@ -211,7 +211,7 @@ enum OpenSSLChaChaPolyImpl {
}
}
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(message: copy message)
#endif
static func decrypt(
@@ -70,7 +70,7 @@ public enum ChaChaPoly: Cipher, Sendable {
/// - nonce: The nonce the sealing process requires.
/// - authenticatedData: Additional data to be authenticated.
/// - tag: Will be updated with the 16-byte authentication tag.
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(message: copy message)
#endif
public static func seal(
@@ -124,7 +124,7 @@ public enum ChaChaPoly: Cipher, Sendable {
/// - authenticatedData: Additional data that was authenticated.
///
/// The call throws an error if decryption or authentication fail.
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(message: copy message)
#endif
public static func open(
+1
View File
@@ -98,6 +98,7 @@ add_library(Crypto
"Signatures/MLDSA.swift"
"Signatures/Signature.swift"
"Util/ArraySpanHelpers.swift"
"Util/Backports.swift"
"Util/BoringSSL/CryptoKitErrors_boring.swift"
"Util/BoringSSL/InlineArray+withBytes_boring.swift"
"Util/BoringSSL/Optional+withUnsafeBytes_boring.swift"
+18 -23
View File
@@ -33,7 +33,6 @@ import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension MLKEM768 {
/// A ML-KEM-768 private key.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
struct InternalPrivateKey: @unchecked Sendable, KEMPrivateKey {
private var backing: Backing
@@ -150,14 +149,14 @@ extension MLKEM768 {
throw CryptoKitError.incorrectParameterSize
}
var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount)
let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in
return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) {
symmetricKeyDataPtr,
count in
let bytes: ContiguousBytes =
encapsulated.regions.count == 1
? encapsulated.regions.first!
: Array(encapsulated)
return bytes.withUnsafeBytes { encapsulatedPtr in
let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in
CCryptoBoringSSL_MLKEM768_decap(
symmetricKeyDataPtr.baseAddress,
encapsulatedPtr.baseAddress,
@@ -165,13 +164,13 @@ extension MLKEM768 {
&self.key
)
}
}
guard rc == 1 else {
throw CryptoKitError.internalBoringSSLError()
}
guard rc == 1 else {
throw CryptoKitError.internalBoringSSLError()
}
return SymmetricKey(data: symmetricKeyData)
count = MLKEM.sharedSecretByteCount
}
}
}
}
@@ -180,7 +179,6 @@ extension MLKEM768 {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension MLKEM768 {
/// A ML-KEM-768 public key.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
struct InternalPublicKey: @unchecked Sendable, KEMPublicKey {
private var backing: Backing
@@ -302,7 +300,6 @@ extension MLKEM768 {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension MLKEM1024 {
/// A ML-KEM-1024 private key.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
struct InternalPrivateKey: @unchecked Sendable, KEMPrivateKey {
private var backing: Backing
@@ -419,14 +416,14 @@ extension MLKEM1024 {
throw CryptoKitError.incorrectParameterSize
}
var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount)
let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in
return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) {
symmetricKeyDataPtr,
count in
let bytes: ContiguousBytes =
encapsulated.regions.count == 1
? encapsulated.regions.first!
: Array(encapsulated)
return bytes.withUnsafeBytes { encapsulatedPtr in
let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in
CCryptoBoringSSL_MLKEM1024_decap(
symmetricKeyDataPtr.baseAddress,
encapsulatedPtr.baseAddress,
@@ -434,13 +431,13 @@ extension MLKEM1024 {
&self.key
)
}
}
guard rc == 1 else {
throw CryptoKitError.internalBoringSSLError()
}
guard rc == 1 else {
throw CryptoKitError.internalBoringSSLError()
}
return SymmetricKey(data: symmetricKeyData)
count = MLKEM.sharedSecretByteCount
}
}
}
}
@@ -449,7 +446,6 @@ extension MLKEM1024 {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension MLKEM1024 {
/// A ML-KEM-1024 public key.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
struct InternalPublicKey: @unchecked Sendable, KEMPublicKey {
private var backing: Backing
@@ -568,7 +564,6 @@ extension MLKEM1024 {
private static let ciphertextByteCount = Int(MLKEM1024_CIPHERTEXT_BYTES)
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
enum MLKEM {
/// The size of the seed in bytes.
static let seedByteCount = 64
@@ -153,14 +153,14 @@ extension MLKEM${parameter_set} {
throw CryptoKitError.incorrectParameterSize
}
var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount)
let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in
return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) {
symmetricKeyDataPtr,
count in
let bytes: ContiguousBytes =
encapsulated.regions.count == 1
? encapsulated.regions.first!
: Array(encapsulated)
return bytes.withUnsafeBytes { encapsulatedPtr in
let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in
CCryptoBoringSSL_MLKEM${parameter_set}_decap(
symmetricKeyDataPtr.baseAddress,
encapsulatedPtr.baseAddress,
@@ -168,13 +168,13 @@ extension MLKEM${parameter_set} {
&self.key
)
}
}
guard rc == 1 else {
throw CryptoKitError.internalBoringSSLError()
}
guard rc == 1 else {
throw CryptoKitError.internalBoringSSLError()
}
return SymmetricKey(data: symmetricKeyData)
count = MLKEM.sharedSecretByteCount
}
}
}
}
+36
View File
@@ -189,6 +189,9 @@ extension P256 {
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
guard parsed.algorithm == .ecdsaP256 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
@@ -209,6 +212,9 @@ extension P256 {
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
guard key.algorithm == .ecdsaP256 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
@@ -413,6 +419,9 @@ extension P256 {
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
guard parsed.algorithm == .ecdsaP256 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
@@ -433,6 +442,9 @@ extension P256 {
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
guard key.algorithm == .ecdsaP256 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
@@ -636,6 +648,9 @@ extension P384 {
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
guard parsed.algorithm == .ecdsaP384 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
@@ -656,6 +671,9 @@ extension P384 {
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
guard key.algorithm == .ecdsaP384 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
@@ -860,6 +878,9 @@ extension P384 {
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
guard parsed.algorithm == .ecdsaP384 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
@@ -880,6 +901,9 @@ extension P384 {
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
guard key.algorithm == .ecdsaP384 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
@@ -1083,6 +1107,9 @@ extension P521 {
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
guard parsed.algorithm == .ecdsaP521 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
@@ -1103,6 +1130,9 @@ extension P521 {
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
guard key.algorithm == .ecdsaP521 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
@@ -1307,6 +1337,9 @@ extension P521 {
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
guard parsed.algorithm == .ecdsaP521 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
@@ -1327,6 +1360,9 @@ extension P521 {
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
guard key.algorithm == .ecdsaP521 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
+2 -2
View File
@@ -48,7 +48,7 @@ public struct HKDF<H: HashFunction>: Sendable {
/// - info: The shared information to use for key derivation.
/// - outputKey: An output span that will be populated with the derived
/// symmetric key.
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(outputKey: copy outputKey)
#endif
public static func deriveKey(inputKeyMaterial: SymmetricKey,
@@ -258,7 +258,7 @@ public struct HKDF<H: HashFunction>: Sendable {
/// - outputByteCount: The length in bytes of the resulting symmetric key.
///
/// - Returns: The derived symmetric key.
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(output: copy output)
#endif
public static func expand(pseudoRandomKey prk: RawSpan, info: RawSpan?, into output: inout OutputRawSpan) {
@@ -72,8 +72,8 @@ enum BoringSSLAESWRAPImpl {
key: SymmetricKey,
contiguousWrappedKey: WrappedKey
) throws -> SymmetricKey {
let unwrapped = try contiguousWrappedKey.withUnsafeBytes { inPtr in
try [UInt8](unsafeUninitializedCapacity: inPtr.count) { outputPtr, count in
try contiguousWrappedKey.withUnsafeBytes { inPtr in
try SymmetricKey(unsafeUninitializedCapacity: inPtr.count) { outputPtr, count in
let rc = try key.withUnsafeAESKEY(mode: .decrypting) { aesKey in
CCryptoBoringSSL_AES_unwrap_key(
aesKey,
@@ -93,8 +93,6 @@ enum BoringSSLAESWRAPImpl {
count = Int(rc)
}
}
return SymmetricKey(data: unwrapped)
}
}
@@ -684,7 +684,7 @@ func readRawPublicNumbers(
/// In a number of places we need to know if an EC key is compact representable. This function implements that check.
///
/// The check is defined in https://tools.ietf.org/id/draft-jivsov-ecc-compact-05.html#rfc.section.4.2.1. Specifically, a
/// point is compact representable if its y coordinate is the smaller of min(y, p-y) where p is the order of the prime field.
/// point is compact representable if its y coordinate is the smaller of min(y, p-y) where p is the prime of the base field.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
func _isCompactRepresentable(
@@ -699,7 +699,7 @@ func _isCompactRepresentable(
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
let context = try! FiniteFieldArithmeticContext(fieldSize: p)
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
let newY = try! context.subtract(y, from: group.order)
let newY = try! context.subtract(y, from: p)
// The point is compact representable if y is less than or equal to newY.
return y <= newY
@@ -121,10 +121,10 @@ extension Curve25519.KeyAgreement {
) throws
-> SharedSecret
{
let sharedSecret = SecureBytes(
let sharedSecret = try SecureBytes(
unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes
) { secretPointer, secretSize in
self.key.withUnsafeBytes { privateKeyPointer in
try self.key.withUnsafeBytes { privateKeyPointer in
// We precondition on all of these sizes because bounds checking is cool.
// These are fatal instead of guards because we allocated the secret (so it must be right),
// we either allocated the private key or validated it on construction (so it must be right),
@@ -133,16 +133,17 @@ extension Curve25519.KeyAgreement {
precondition(privateKeyPointer.count == Curve25519.KeyAgreement.keySizeBytes)
precondition(publicKeyShare.keyBytes.count == Curve25519.KeyAgreement.keySizeBytes)
// We don't check the return code here. This return code only validates that the generated secret is not the weak all-zero
// secret (it is not possible for BoringSSL's X25519 implementation to fail, which is nice). There is currently what I would
// politely describe as a "lack of consensus" as to whether crypto libraries should reject this secret. CryptoKit on Apple
// platforms currently does not, so for the sake of conformance with our peer implementation I will also refuse to check it.
// We may elect to revisit this decision if the security best-practice thinking changes.
CCryptoBoringSSL_X25519(
secretPointer.baseAddress,
privateKeyPointer.baseAddress,
publicKeyShare.keyBytes
)
// BoringSSL returns 0 when the peer's public key has low order, which makes the shared secret
// the weak all-zero value. CryptoKit rejects that key agreement, so we do too.
guard
CCryptoBoringSSL_X25519(
secretPointer.baseAddress,
privateKeyPointer.baseAddress,
publicKeyShare.keyBytes
) == 1
else {
throw CryptoKitError.internalBoringSSLError()
}
}
secretSize = Curve25519.KeyAgreement.keySizeBytes // We always use all of it.
@@ -65,34 +65,24 @@ public struct HMAC<H: HashFunction>: MACAlgorithm, Sendable {
#if os(iOS) && (arch(arm) || arch(i386))
fatalError("Unsupported architecture")
#else
var innerKey = SecureBytes(capacity: H.blockByteCount) { keyOutput in
if key.byteCount <= keyOutput.freeCapacity {
keyOutput.append(contentsOf: key.bytes)
} else if key.byteCount > H.blockByteCount {
let hash = H.hash(bytes: key.bytes)
hash.withUnsafeBytes {
keyOutput.append(contentsOf: $0.bytes)
}
}
keyOutput.append(repeating: 0, count: keyOutput.freeCapacity, as: UInt8.self)
}
var outerKey = innerKey
// HMAC(K, m) = H((K0 ^ opad) || H((K0 ^ ipad) || m)), where K0 is the
// key normalized to the hash block size (RFC 2104).
self.innerHasher = H()
innerKey.withUnsafeMutableBytes {
for i in 0 ..< $0.count {
$0[i] ^= 0x36
}
}
innerHasher.update(bytes: innerKey.bytes)
self.outerHasher = H()
outerKey.withUnsafeMutableBytes {
for i in 0 ..< $0.count {
$0[i] ^= 0x5c
withTemporaryZeroingAllocation(byteCount: H.blockByteCount, alignment: 1) { keyBlock in
if key.byteCount <= keyBlock.freeCapacity {
keyBlock.append(contentsOf: key.bytes)
} else if key.byteCount > H.blockByteCount {
H.hash(bytes: key.bytes).withBytes { keyBlock.append(contentsOf: $0) }
}
keyBlock.append(repeating: 0, count: keyBlock.freeCapacity, as: UInt8.self)
var k0 = keyBlock.mutableBytes
for i in 0 ..< k0.byteCount { k0[i] ^= 0x36 } // apply ipad
self.innerHasher.update(bytes: k0.bytes)
for i in 0 ..< k0.byteCount { k0[i] ^= 0x36 ^ 0x5c } // undo ipad, apply opad
self.outerHasher.update(bytes: k0.bytes)
}
outerHasher.update(data: outerKey)
#endif
}
+2 -2
View File
@@ -57,7 +57,7 @@ extension ContiguousArray where Element == UInt8 {
extension OutputRawSpan {
/// Append the contents of the given raw span to this output span.
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(self: copy self)
#endif
mutating func append(contentsOf bytes: RawSpan) {
@@ -69,7 +69,7 @@ extension OutputRawSpan {
extension OutputSpan<UInt8> {
/// Append the contents of the given raw span to this output span.
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(self: copy self)
#endif
mutating func append(contentsOf bytes: RawSpan) {
+37
View File
@@ -0,0 +1,37 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#if compiler(<6.4)
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1.0, *)
extension ContiguousBytes {
func withBytes<R>(_ body: (RawSpan) throws -> R) rethrows -> R {
try withUnsafeBytes { try body(RawSpan(_unsafeBytes: $0)) }
}
}
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1.0, *)
extension MutableRawSpan {
subscript(_ byteOffset: Int) -> UInt8 {
get { unsafeLoad(fromByteOffset: byteOffset, as: UInt8.self) }
@_lifetime(self: copy self)
set { storeBytes(of: newValue, toByteOffset: byteOffset, as: UInt8.self) }
}
}
#endif
@@ -45,7 +45,7 @@ extension UnsafeMutableRawBufferPointer {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension MutableRawSpan {
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(self: copy self)
#endif
mutating func initializeWithRandomBytes(count: Int) {
@@ -55,7 +55,7 @@ extension MutableRawSpan {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension OutputRawSpan {
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(self: copy self)
#endif
mutating func appendingRandomBytes(count: Int) {
+23 -1
View File
@@ -28,7 +28,7 @@ protocol Zeroization {
extension UnsafeMutablePointer: Zeroization {
/// Zeroizes the pointee
func zeroize() {
let size = MemoryLayout.size(ofValue: Pointee.self)
let size = MemoryLayout<Pointee>.size
memset_s(self, size, 0, size)
}
}
@@ -54,4 +54,26 @@ extension Data: Zeroization {
}
}
func withUnsafeTemporaryZeroingAllocation<R>(
byteCount: Int,
alignment: Int,
_ body: (UnsafeMutableRawBufferPointer) throws -> R
) rethrows -> R {
try withUnsafeTemporaryAllocation(byteCount: byteCount, alignment: alignment) { buffer in
defer { buffer.zeroize() }
return try body(buffer)
}
}
func withTemporaryZeroingAllocation<R>(
byteCount: Int,
alignment: Int,
_ body: (inout OutputRawSpan) throws -> R
) rethrows -> R {
try withUnsafeTemporaryZeroingAllocation(byteCount: byteCount, alignment: alignment) { buffer in
var output = OutputRawSpan(buffer: buffer, initializedCount: 0)
return try body(&output)
}
}
#endif // canImport(CryptoKit)
@@ -153,7 +153,7 @@ extension BoringSSLAEAD.AEADContext {
/// Lowest level seal operation that calls into BoringSSL directly and
/// operates on already-allocated memory.
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(tag: copy tag)
#endif
public func seal(
@@ -303,7 +303,7 @@ extension BoringSSLAEAD.AEADContext {
}
/// Lowest level call into BoringSSL that decrypts in place.
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(message: copy message)
#endif
public func open(
@@ -77,10 +77,6 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.multiply(by: rhs, on: group, context: context)
}
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package consuming func multiplying(
by rhs: ArbitraryPrecisionInteger,
@@ -90,18 +86,6 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.multiply(by: rhs, on: group, context: context)
return self
}
#else
@usableFromInline
package func multiplying(
by rhs: ArbitraryPrecisionInteger,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var `self` = self
try self.multiply(by: rhs, on: group, context: context)
return self
}
#endif
@usableFromInline
package static func multiplying(
@@ -134,10 +118,6 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.add(rhs, on: group, context: context)
}
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package consuming func adding(
_ rhs: consuming EllipticCurvePoint,
@@ -147,23 +127,7 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.add(rhs, on: group, context: context)
return self
}
#else
@usableFromInline
package func adding(
_ rhs: consuming EllipticCurvePoint,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var `self` = self
try self.add(rhs, on: group, context: context)
return self
}
#endif
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package static func adding(
_ lhs: consuming EllipticCurvePoint,
@@ -174,19 +138,6 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try lhs.add(rhs, on: group, context: context)
return lhs
}
#else
@usableFromInline
package static func adding(
_ lhs: EllipticCurvePoint,
_ rhs: EllipticCurvePoint,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var lhs = lhs
try lhs.add(rhs, on: group, context: context)
return lhs
}
#endif
@usableFromInline
package mutating func invert(
@@ -207,10 +158,6 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.invert(on: group, context: context)
}
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package consuming func inverting(
on group: BoringSSLEllipticCurveGroup,
@@ -219,22 +166,7 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.invert(on: group, context: context)
return self
}
#else
@usableFromInline
package func inverting(
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var `self` = self
try self.invert(on: group, context: context)
return self
}
#endif
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package static func inverting(
_ point: consuming EllipticCurvePoint,
@@ -244,18 +176,6 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try point.invert(on: group, context: context)
return point
}
#else
@usableFromInline
package static func inverting(
_ point: EllipticCurvePoint,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var point = point
try point.invert(on: group, context: context)
return point
}
#endif
@usableFromInline
package mutating func subtract(
@@ -278,10 +198,6 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.subtract(rhs, on: group, context: context)
}
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package consuming func subtracting(
_ rhs: consuming EllipticCurvePoint,
@@ -291,23 +207,7 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.subtract(rhs, on: group, context: context)
return self
}
#else
@usableFromInline
package func subtracting(
_ rhs: EllipticCurvePoint,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var `self` = self
try self.subtract(rhs, on: group, context: context)
return self
}
#endif
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package static func subtracting(
_ rhs: consuming EllipticCurvePoint,
@@ -318,19 +218,6 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try lhs.subtract(rhs, on: group, context: context)
return lhs
}
#else
@usableFromInline
package static func subtracting(
_ rhs: EllipticCurvePoint,
from lhs: EllipticCurvePoint,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var lhs = lhs
try lhs.subtract(rhs, on: group, context: context)
return lhs
}
#endif
@usableFromInline
package init<MessageBytes: ContiguousBytes, DSTBytes: ContiguousBytes>(
@@ -47,7 +47,7 @@ extension UnsafeMutableRawBufferPointer {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension OutputRawSpan {
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(self: copy self)
#endif
package mutating func appendingRandomBytes(count: Int) {
-14
View File
@@ -71,10 +71,6 @@ extension AES {
self.backing.update(bufferPointer)
}
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
/// Finalizes the message authentication computation and returns the
/// computed code.
///
@@ -87,16 +83,6 @@ extension AES {
self.cowIfNeeded()
return self.backing.finalize()
}
#else
/// Finalizes the message authentication computation and returns the
/// computed code.
///
/// - Returns: The message authentication code.
public func finalize() -> AES.CMAC.MAC {
var `self` = self
return self.backing.finalize()
}
#endif
/// Updates the MAC with data.
///
@@ -108,8 +108,8 @@ extension ARC {
let T = H2G.hashToGroup(presentationContext, domainSeparationString: Data(("HashToGroup-" + ciphersuite.domain + "Tag").utf8))
// Recompute m1Tag = H2G(presentationContext) - nonce * tag
var m1Tag = T
for _ in 0..<nonce { m1Tag = m1Tag - self.tag }
let nonceScalar = try Group.Scalar(bytes: I2OSP(value: nonce, outputByteCount: ciphersuite.scalarByteCount), reductionIsModOrder: true)
let m1Tag = T - nonceScalar * self.tag
// Create a verifier, and allocate variables for the constrained scalars.
var verifier = Verifier<H2G>(label: ciphersuite.domain + ciphersuite.domain + "CredentialPresentation")
+1
View File
@@ -78,6 +78,7 @@ add_library(CryptoExtras
"Util/ThreadSpecific/ThreadPosix.swift"
"Util/ThreadSpecific/ThreadSpecific.swift"
"Util/ThreadSpecific/ThreadWindows.swift"
"Util/Zeroization.swift"
"ZKPs/DLEQ.swift"
"ZKPs/Prover.swift"
"ZKPs/Verifier.swift"
@@ -72,16 +72,3 @@ final class BoringSSLSHA512256Context {
}
}
}
extension UnsafeMutablePointer {
fileprivate func zeroize() {
let size = MemoryLayout.size(ofValue: Pointee.self)
memset_s(self, size, 0, size)
}
}
extension UnsafeMutableRawBufferPointer {
fileprivate func zeroize() {
memset_s(self.baseAddress!, self.count, 0, self.count)
}
}
@@ -276,6 +276,9 @@ extension OpenSSLCurvePoint {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension OpenSSLCurvePoint: OPRFGroupElement {
init(oprfRepresentation data: Data) throws {
guard data.count == C.compressedx962PointByteCount else {
throw CryptoKitError.incorrectParameterSize
}
let point = try EllipticCurvePoint(x962Representation: data, on: C.group, context: C.__ffac)
self.init(ecPoint: point)
}
@@ -43,8 +43,9 @@ internal struct BoringSSLPBKDF2 {
outputByteCount: Int,
rounds: Int
) throws -> SymmetricKey {
// This should be SecureBytes, but we can't use that here.
// SecureBytes is internal to Crypto, so zero the buffer by hand once the key has been copied out.
var derivedKeyData = Data(count: outputByteCount)
defer { derivedKeyData.withUnsafeMutableBytes { $0.zeroize() } }
let rc = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes -> Int32 in
let saltBytes: ContiguousBytes = salt.regions.count == 1 ? salt.regions.first! : Array(salt)
@@ -39,8 +39,9 @@ internal struct CommonCryptoPBKDF2 {
outputByteCount: Int,
rounds: Int
) throws -> SymmetricKey {
// This should be SecureBytes, but we can't use that here.
// SecureBytes is internal to Crypto, so zero the buffer by hand once the key has been copied out.
var derivedKeyData = Data(count: outputByteCount)
defer { derivedKeyData.withUnsafeMutableBytes { $0.zeroize() } }
let derivationStatus = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes -> Int32 in
let saltBytes: ContiguousBytes = salt.regions.count == 1 ? salt.regions.first! : Array(salt)
@@ -81,12 +81,25 @@ internal struct BoringSSLScrypt {
parallelism: Int,
maxMemory: Int? = nil
) throws -> SymmetricKey {
// This should be SecureBytes, but we can't use that here.
// SecureBytes is internal to Crypto, so zero the buffer by hand once the key has been copied out.
var derivedKeyData = Data(count: outputByteCount)
defer { derivedKeyData.withUnsafeMutableBytes { $0.zeroize() } }
// This computes the maximum amount of memory that will be used by the scrypt algorithm with an additional memory page to spare. This value will be used by the BoringSSL as the memory limit for the algorithm.
// An additional memory page is added to the computed value (using POSIX specification) to ensure that the memory limit is not too tight.
let maxMemory = maxMemory ?? (128 * rounds * blockSize * parallelism + getPageSize())
let memoryLimit: Int
if let maxMemory {
memoryLimit = maxMemory
} else {
// This computes the maximum amount of memory that will be used by the scrypt algorithm with an additional memory page to spare. This value will be used by the BoringSSL as the memory limit for the algorithm.
// An additional memory page is added to the computed value (using POSIX specification) to ensure that the memory limit is not too tight.
let (blockBytes, blockBytesOverflowed) = 128.multipliedReportingOverflow(by: blockSize)
let (laneBytes, laneBytesOverflowed) = blockBytes.multipliedReportingOverflow(by: rounds)
let (stateBytes, stateBytesOverflowed) = laneBytes.multipliedReportingOverflow(by: parallelism)
let (computedLimit, computedLimitOverflowed) = stateBytes.addingReportingOverflow(getPageSize())
guard !blockBytesOverflowed, !laneBytesOverflowed, !stateBytesOverflowed, !computedLimitOverflowed else {
throw CryptoKitError.incorrectParameterSize
}
memoryLimit = computedLimit
}
let result = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes -> Int32 in
let saltBytes: ContiguousBytes = salt.regions.count == 1 ? salt.regions.first! : Array(salt)
@@ -102,7 +115,7 @@ internal struct BoringSSLScrypt {
UInt64(rounds),
UInt64(blockSize),
UInt64(parallelism),
maxMemory,
memoryLimit,
derivedKeyBytes.baseAddress!,
derivedKeyBytes.count
)
@@ -35,10 +35,16 @@ extension KDF {
/// - rounds: The number of rounds which should be used to perform key derivation. Must be a power of 2 less than `2^(128 * blockSize / 8)`.
/// - blockSize: The block size to use for key derivation.
/// - parallelism: The parallelism factor to use for key derivation. Must be a positive integer less than or equal to `((2^32 - 1) * 32) / (128 * blockSize)`.
/// - maxMemory: The maximum amount of memory allowed to use for key derivation. If not provided, the default value is computed for the provided parameters.
/// - maxMemory: The maximum amount of memory allowed to use for key derivation. Must be positive. If not provided, the default value is computed for the provided parameters.
/// - Returns: The derived symmetric key.
public static func deriveKey<Passphrase: DataProtocol, Salt: DataProtocol>(from password: Passphrase, salt: Salt, outputByteCount: Int, rounds: Int, blockSize: Int, parallelism: Int, maxMemory: Int? = nil) throws -> SymmetricKey {
return try BackingScrypt.deriveKey(from: password, salt: salt, outputByteCount: outputByteCount, rounds: rounds, blockSize: blockSize, parallelism: parallelism)
guard rounds > 0, blockSize > 0, parallelism > 0, outputByteCount >= 0 else {
throw CryptoKitError.incorrectParameterSize
}
if let maxMemory, maxMemory <= 0 {
throw CryptoKitError.incorrectParameterSize
}
return try BackingScrypt.deriveKey(from: password, salt: salt, outputByteCount: outputByteCount, rounds: rounds, blockSize: blockSize, parallelism: parallelism, maxMemory: maxMemory)
}
}
}
@@ -35,6 +35,9 @@ extension P384 {
static var ciphersuite: Ciphersuite { Ciphersuite(H2G.self) }
/// The maximum length, in bytes, of an input, imposed by the two-byte length prefix in the RFC 9497 framing.
static let maximumInputByteCount = 0xFFFF
/// A P-384 public key used to blind inputs and finalize blinded elements.
public struct PublicKey {
fileprivate typealias BackingPublicKey = P384.Signing.PublicKey
@@ -367,6 +370,9 @@ extension P384._VOPRF {
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P384._VOPRF.PublicKey {
internal func blind<D: DataProtocol>(_ input: D, with fixedBlind: P384._VOPRF.H2G.G.Scalar) throws -> P384._VOPRF.BlindedInput {
guard input.count <= P384._VOPRF.maximumInputByteCount else {
throw CryptoKitError.incorrectParameterSize
}
let input = Data(input)
let (blind, blindedElement) = Self.client.blindMessage(input, blind: fixedBlind)
return P384._VOPRF.BlindedInput(
@@ -436,6 +442,9 @@ extension P384._VOPRF.PrivateKey {
///
/// - Seealso: [RFC 9497: VOPRF Protocol - Evaluate]( https://cfrg.github.io/draft-irtf-cfrg-voprf/draft-irtf-cfrg-voprf.html#section-3.3.2-7).
public func evaluate<D: DataProtocol>(_ input: D) throws -> Data {
guard input.count <= P384._VOPRF.maximumInputByteCount else {
throw CryptoKitError.incorrectParameterSize
}
let inputElement = P384._VOPRF.H2G.hashToGroup(
Data(input),
domainSeparationString: Self.hashToGroupDST
+29 -9
View File
@@ -530,7 +530,7 @@ extension _RSA.Signing {
extension _RSA.Encryption {
/// Identical to ``_RSA/Signing/PublicKey``.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
public struct PublicKey {
public struct PublicKey: Sendable {
public struct Primitives: Sendable, Hashable {
public var modulus: Data
public var publicExponent: Data
@@ -612,7 +612,7 @@ extension _RSA.Encryption {
/// Identical to ``_RSA/Signing/PrivateKey``.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
public struct PrivateKey {
public struct PrivateKey: Sendable {
private var backing: BackingPrivateKey
/// Construct an RSA private key from a PEM representation.
@@ -834,21 +834,37 @@ extension _RSA {
d: ArbitraryPrecisionInteger
) throws -> (p: ArbitraryPrecisionInteger, q: ArbitraryPrecisionInteger) {
// This is based on the proof of fact 1 in https://www.ams.org/notices/199902/boneh.pdf
let k = (d * e) - 1
let t = k.trailingZeroBitCount
let r = k >> t
guard k.isEven else {
// Valid keys have e < n, and BoringSSL rejects d >= n and moduli over its maximum. Larger
// values let the caller pick the cost of the exponentiations and squaring loop below.
guard n.byteCount <= _RSA.maximumModulusBitCount / 8, e < n, d < n else {
throw CryptoKitError.incorrectParameterSize
}
let k = (d * e) - 1
// k == 0 (that is, e * d == 1) gives r == 0 below, for which every base is trivial.
guard k > 0, k.isEven else {
throw CryptoKitError.incorrectParameterSize
}
let t = k.trailingZeroBitCount
let r = k >> t
var y: ArbitraryPrecisionInteger = 0
var i = 1
let context = try FiniteFieldArithmeticContext(fieldSize: n)
while i <= 100 {
// Every attempt must count towards the limit, including those where g^r is trivially
// 1 or n - 1. Inputs for which that holds for every base would otherwise never return.
for _ in 0..<100 {
let g = try ArbitraryPrecisionInteger.random(inclusiveMin: 2, exclusiveMax: n)
// The check at the end of this attempt only holds for bases coprime to n.
guard try ArbitraryPrecisionInteger.gcd(g, n) == 1 else {
continue
}
y = try context.pow(g, r)
guard y != 1, y != n - 1 else {
@@ -877,7 +893,11 @@ extension _RSA {
return (p, q)
}
i &+= 1
// Here x is g^k unless the loop stopped at n - 1. For a valid key g^k == 1 for every
// base coprime to n, so any other value means the numbers do not form a key.
guard x == n - 1 else {
throw CryptoKitError.incorrectParameterSize
}
}
throw CryptoKitError.incorrectParameterSize
@@ -1131,3 +1131,8 @@ enum BlindSigningHelpers {
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension _RSA {
static let maximumModulusBitCount = Int(OPENSSL_RSA_MAX_MODULUS_BITS)
}
@@ -19,14 +19,9 @@ import Foundation
#endif
extension Data {
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
// This overload reduces allocations when used in a chain of infix operations.
static func + (lhs: consuming Data, rhs: consuming Data) -> Data {
lhs.append(contentsOf: rhs)
return lhs
}
#endif
}
@@ -0,0 +1,75 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
protocol Zeroization {
mutating func zeroize()
}
extension UnsafeMutablePointer: Zeroization {
/// Zeroizes the pointee
func zeroize() {
let size = MemoryLayout<Pointee>.size
memset_s(self, size, 0, size)
}
}
extension UnsafeMutableRawBufferPointer: Zeroization {
func zeroize() {
memset_s(self.baseAddress!, self.count, 0, self.count)
}
}
extension Array: Zeroization where Element == UInt8 {
/// Zeroizes the array
mutating func zeroize() {
memset_s(&self, self.count, 0, self.count)
}
}
extension Data: Zeroization {
internal mutating func zeroize() {
_ = self.withUnsafeMutableBytes {
memset_s($0.baseAddress!, $0.count, 0, $0.count)
}
}
}
func withUnsafeTemporaryZeroingAllocation<R>(
byteCount: Int,
alignment: Int,
_ body: (UnsafeMutableRawBufferPointer) throws -> R
) rethrows -> R {
try withUnsafeTemporaryAllocation(byteCount: byteCount, alignment: alignment) { buffer in
defer { buffer.zeroize() }
return try body(buffer)
}
}
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1.0, *)
func withTemporaryZeroingAllocation<R>(
byteCount: Int,
alignment: Int,
_ body: (inout OutputRawSpan) throws -> R
) rethrows -> R {
try withUnsafeTemporaryZeroingAllocation(byteCount: byteCount, alignment: alignment) { buffer in
var output = OutputRawSpan(buffer: buffer, initializedCount: 0)
return try body(&output)
}
}
@@ -325,28 +325,3 @@ extension P384._ARCV1: ARCV1 {}
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P384: ARCCurve {}
// Swift 5.10 compiler needs a little more help to infer the conformances.
#if swift(<6.0)
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
fileprivate extension P256._ARCV1.PrivateKey {
typealias H2G = P256._ARCV1.H2G
typealias Credential = P256._ARCV1.Credential
typealias PublicKey = P256._ARCV1.PublicKey
typealias CredentialRequest = P256._ARCV1.CredentialRequest
typealias CredentialResponse = P256._ARCV1.CredentialResponse
typealias Presentation = P256._ARCV1.Presentation
}
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
fileprivate extension P384._ARCV1.PrivateKey {
typealias H2G = P384._ARCV1.H2G
typealias Credential = P384._ARCV1.Credential
typealias PublicKey = P384._ARCV1.PublicKey
typealias CredentialRequest = P384._ARCV1.CredentialRequest
typealias CredentialResponse = P384._ARCV1.CredentialResponse
typealias Presentation = P384._ARCV1.Presentation
}
#endif
@@ -158,6 +158,61 @@ class ARCTests: XCTestCase {
// try endToEndWorkflow(CurveType: P521.self)
}
func testVerifyCostIsIndependentOfTheNonce() async throws {
let ciphersuite = ARC.Ciphersuite(HashToCurveImpl<P256>.self)
let (generatorG, generatorH) = ARC.getGenerators(suite: ciphersuite)
let x0 = GroupImpl<P256>.Scalar.random
let x1 = GroupImpl<P256>.Scalar.random
let x2 = GroupImpl<P256>.Scalar.random
let x0Blinding = GroupImpl<P256>.Scalar.random
let serverPrivateKey = ARC.ServerPrivateKey(x0: x0, x1: x1, x2: x2, x0Blinding: x0Blinding)
let server = ARC.Server(ciphersuite: ciphersuite, x0: x0, x1: x1, x2: x2, x0Blinding: x0Blinding)
let requestContext = Data("test request context".utf8)
let precredential = try ARC.Precredential(
ciphersuite: ciphersuite,
m1: GroupImpl<P256>.Scalar.random,
requestContext: requestContext,
r1: GroupImpl<P256>.Scalar.random,
r2: GroupImpl<P256>.Scalar.random,
serverPublicKey: server.serverPublicKey
)
let credential = try precredential.makeCredential(
credentialResponse: try server.respond(credentialRequest: precredential.credentialRequest)
)
// The nonce comes from the client, so presentation verification cost must not scale with nonce.
// This test uses such a large nonce that the test would hit the timeout if verification was correlated.
let nonce = 1 << 62
let presentationContext = Data("0123456789".utf8)
let presentation = try ARC.Presentation(
credential: credential,
presentationContext: presentationContext,
nonce: nonce,
generatorG: generatorG,
generatorH: generatorH
)
let verificationResult: LockedBox<Bool?> = .init(initialValue: nil)
let finished = expectation(description: "verification finished")
let thread = Thread {
let result = try? presentation.verify(
serverPrivateKey: serverPrivateKey,
X1: x1 * generatorH,
m2: precredential.clientSecrets.m2,
presentationContext: presentationContext,
presentationLimit: Int.max,
nonce: nonce,
generatorG: generatorG,
generatorH: generatorH,
ciphersuite: ciphersuite)
verificationResult.withLockedValue { $0 = result }
finished.fulfill()
}
thread.start()
await fulfillment(of: [finished], timeout: 10)
XCTAssertEqual(verificationResult.withLockedValue { $0 }, true)
}
func testPresentationState() throws {
let context1 = Data("context1".utf8)
let context2 = Data("context2".utf8)
@@ -79,4 +79,38 @@ final class VOPRFPublicAPITests: XCTestCase {
// [Server] Compute the PRF for the input, without blinding or proof generation.
let _: Data = try privateKey.evaluate(input)
}
func testBlindedElementRejectsUncompressedOPRFRepresentation() throws {
/// Check we only accept compressed encoded elements, as per RFC 9497:
///
/// > 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...
///
/// - See: https://www.rfc-editor.org/rfc/rfc9497.html#name-oprfp-384-sha-384
let publicKey = P384._VOPRF.PrivateKey().publicKey
let blindedElement = try publicKey.blind(Data("This is some input data".utf8)).blindedElement
let compressed = blindedElement.oprfRepresentation
let uncompressed = try P384.Signing.PublicKey(compressedRepresentation: compressed).x963Representation
XCTAssertThrowsError(try P384._VOPRF.BlindedElement(oprfRepresentation: uncompressed))
}
func testInputLongerThanRFC9497LimitThrows() throws {
let privateKey = P384._VOPRF.PrivateKey()
let publicKey = privateKey.publicKey
// RFC 9497 caps inputs at 2^16 - 1 bytes, the most the two-byte length prefix in the framing can encode.
let maximumInput = Data(repeating: 0x41, count: 0xFFFF)
let blindedInput = try publicKey.blind(maximumInput)
let blindEvaluation = try privateKey.evaluate(blindedInput.blindedElement)
XCTAssertNoThrow(try publicKey.finalize(blindedInput, using: blindEvaluation))
XCTAssertNoThrow(try privateKey.evaluate(maximumInput))
// Oversized inputs are rejected where they enter, so finalize can never be given one.
let oversizedInput = Data(repeating: 0x41, count: 0x1_0000)
XCTAssertThrowsError(try publicKey.blind(oversizedInput))
XCTAssertThrowsError(try privateKey.evaluate(oversizedInput))
}
}
+66
View File
@@ -84,4 +84,70 @@ class ScryptTests: XCTestCase {
try orFail { try self.testRFCVector(vector) }
}
}
func testDeriveKeyWithMaxMemoryBelowRequirementThrows() throws {
let password = Array("password".utf8)
let salt = Array("salt".utf8)
// These parameters need 128 * blockSize * (rounds + parallelism + 1) bytes, just over 1 MiB.
// BoringSSL reads a limit of zero as "use the default limit", and a negative limit as a huge size_t.
for maxMemory in [1024, 0, -1] {
XCTAssertThrowsError(
try KDF.Scrypt.deriveKey(
from: password,
salt: salt,
outputByteCount: 32,
rounds: 1024,
blockSize: 8,
parallelism: 1,
maxMemory: maxMemory
)
)
}
let bounded = try KDF.Scrypt.deriveKey(
from: password,
salt: salt,
outputByteCount: 32,
rounds: 1024,
blockSize: 8,
parallelism: 1,
maxMemory: 2 << 20
)
let unbounded = try KDF.Scrypt.deriveKey(
from: password,
salt: salt,
outputByteCount: 32,
rounds: 1024,
blockSize: 8,
parallelism: 1
)
XCTAssertEqual(bounded, unbounded)
}
func testDeriveKeyWithOutOfRangeParametersThrows() throws {
let password = Array("password".utf8)
let salt = Array("salt".utf8)
for (rounds, blockSize, parallelism, outputByteCount) in [
// Negative values reach UInt64 conversions and Data(count:), both of which trap.
(-1, 8, 1, 32),
(1024, -1, 1, 32),
(1024, 8, -1, 32),
(1024, 8, 1, -1),
// 128 * blockSize * rounds * parallelism overflows Int.
(1 << 32, 1 << 30, 1, 32),
] {
XCTAssertThrowsError(
try KDF.Scrypt.deriveKey(
from: password,
salt: salt,
outputByteCount: outputByteCount,
rounds: rounds,
blockSize: blockSize,
parallelism: parallelism
)
)
}
}
}
@@ -248,6 +248,13 @@ final class TestRSAEncryption: XCTestCase {
XCTAssertEqual(191, publicKey.maximumEncryptSize(with: .PKCS1_OAEP_SHA256))
}
func testKeysAreSendable() {
func assertSendable<T: Sendable>(_: T.Type) {}
assertSendable(_RSA.Encryption.PublicKey.self)
assertSendable(_RSA.Encryption.PrivateKey.self)
}
func testPKCS1() throws {
let pubKeyPEM = """
-----BEGIN RSA PUBLIC KEY-----
@@ -1062,6 +1062,70 @@ final class TestRSASigning: XCTestCase {
}
}
func testConstructKeyFromRSANumbersWithDegenerateExponentsThrows() throws {
// e * d == 1 makes g^(e * d - 1) == 1 for every base, so prime recovery can never
// make progress. This must throw rather than retry forever.
var n = [UInt8](repeating: 0xA7, count: 256)
n[255] = 0x01
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey._createFromNumbers(n: n, e: [1] as [UInt8], d: [1] as [UInt8])
)
XCTAssertThrowsError(
try _RSA.Encryption.PrivateKey._createFromNumbers(n: n, e: [1] as [UInt8], d: [1] as [UInt8])
)
XCTAssertThrowsError(
try _RSA.BlindSigning.PrivateKey<SHA384>._createFromNumbers(
n: n, e: [1] as [UInt8], d: [1] as [UInt8], parameters: .RSABSSA_SHA384_PSS_Randomized
)
)
}
func testExtractPrimeFactorsGivesUpWhenEveryBaseIsTrivial() throws {
// n = 7 is prime and e * d - 1 == 24 == 2^3 * 3, so g^3 is 1 or n - 1 for every base g
// (the only cubic residues mod 7). The attempt limit must still apply.
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 7, e: 5, d: 5))
// e * d == 1 gives an exponent of 0, so g^0 == 1 for every base.
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 3233, e: 1, d: 1))
}
func testExtractPrimeFactorsRejectsOversizedNumbers() throws {
// d == 2753 is valid for n == 3233, e == 17. Adding lambda(n) == 780 keeps the numbers
// consistent, so only the range check rejects d >= n.
XCTAssertNoThrow(try _RSA.extractPrimeFactors(n: 3233, e: 17, d: 2753))
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 3233, e: 17, d: 2753 + 780))
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 3233, e: 17 + 780 * 5, d: 2753))
// e * d - 1 == 2^9992, so without the range check the squaring loop runs 9991 times
// per attempt.
var n = [UInt8](repeating: 0xA7, count: 256)
n[255] = 0x01
var d = [UInt8](repeating: 0, count: 1250)
d[0] = 0x01
d[1249] = 0x01
XCTAssertThrowsError(try _RSA.Signing.PrivateKey._createFromNumbers(n: n, e: [1] as [UInt8], d: d))
// A modulus over 8192 bits with d < n would otherwise make each attempt arbitrarily slow.
var bigN = [UInt8](repeating: 0xA7, count: 1025)
bigN[1024] = 0x01
var bigD = [UInt8](repeating: 0, count: 1025)
bigD[1] = 0x01
bigD[1024] = 0x01
XCTAssertThrowsError(try _RSA.Signing.PrivateKey._createFromNumbers(n: bigN, e: [1] as [UInt8], d: bigD))
}
func testExtractPrimeFactorsRejectsInconsistentNumbers() throws {
for testVector in RFC9474TestVector.allValues {
let n = try ArbitraryPrecisionInteger(bytes: Data(hexString: testVector.n))
let e = try ArbitraryPrecisionInteger(bytes: Data(hexString: testVector.e))
let d = try ArbitraryPrecisionInteger(bytes: Data(hexString: testVector.d))
// Using d = d + 2 means d is still even but no longer a multiple of lambda(n).
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: n, e: e, d: d + 2))
}
}
func testGetKeyPrimitives() throws {
for testVector in RFC9474TestVector.allValues {
let n = try Data(hexString: testVector.n)
+37
View File
@@ -219,6 +219,43 @@ class ASN1Tests: XCTestCase {
XCTAssertEqual(serializer.serializedBytes, decodedPrivateKey)
}
func testPKCS8PrivateKeyWithMismatchedCurveIsRejected() throws {
func pkcs8(_ algorithm: ASN1.RFC5480AlgorithmIdentifier, _ privateKey: Data, _ publicKey: Data) throws -> (der: Data, pem: String) {
let pkey = ASN1.PKCS8PrivateKey(algorithm: algorithm, privateKey: Array(privateKey), publicKey: Array(publicKey))
var serializer = ASN1.Serializer()
try serializer.serialize(pkey)
let der = Data(serializer.serializedBytes)
return (der, ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: der).pemString)
}
let p256 = P256.Signing.PrivateKey()
let p384 = P384.Signing.PrivateKey()
let p521 = P521.Signing.PrivateKey()
let p256InP384 = try pkcs8(.ecdsaP384, p256.rawRepresentation, p256.publicKey.x963Representation)
XCTAssertThrowsError(try P256.Signing.PrivateKey(derRepresentation: p256InP384.der))
XCTAssertThrowsError(try P256.Signing.PrivateKey(pemRepresentation: p256InP384.pem))
XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(derRepresentation: p256InP384.der))
XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(pemRepresentation: p256InP384.pem))
let p384InP521 = try pkcs8(.ecdsaP521, p384.rawRepresentation, p384.publicKey.x963Representation)
XCTAssertThrowsError(try P384.Signing.PrivateKey(derRepresentation: p384InP521.der))
XCTAssertThrowsError(try P384.Signing.PrivateKey(pemRepresentation: p384InP521.pem))
XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(derRepresentation: p384InP521.der))
XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(pemRepresentation: p384InP521.pem))
let p521InP256 = try pkcs8(.ecdsaP256, p521.rawRepresentation, p521.publicKey.x963Representation)
XCTAssertThrowsError(try P521.Signing.PrivateKey(derRepresentation: p521InP256.der))
XCTAssertThrowsError(try P521.Signing.PrivateKey(pemRepresentation: p521InP256.pem))
XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(derRepresentation: p521InP256.der))
XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(pemRepresentation: p521InP256.pem))
// The correctly labelled encodings still load.
let p256InP256 = try pkcs8(.ecdsaP256, p256.rawRepresentation, p256.publicKey.x963Representation)
XCTAssertEqual(try P256.Signing.PrivateKey(derRepresentation: p256InP256.der).rawRepresentation, p256.rawRepresentation)
XCTAssertEqual(try P256.KeyAgreement.PrivateKey(pemRepresentation: p256InP256.pem).rawRepresentation, p256.rawRepresentation)
}
func testRejectDripFedASN1SPKIP256() throws {
// This test drip-feeds an ASN.1 P256 SPKI block. It should never parse correctly until we feed the entire block.
let encodedSPKI = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2adMrdG7aUfZH57aeKFFM01dPnkxC18ScRb4Z6poMBgJtYlVtd9ly63URv57ZW0Ncs1LiZB7WATb3svu+1c7HQ=="
@@ -0,0 +1,50 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
#if canImport(CryptoKit)
// Skip tests that require @testable imports of CryptoKit.
#else
@testable import Crypto
extension X25519Tests {
func testKeyAgreementWithLowOrderPublicKeyThrows() throws {
// The vectors whose shared secret is all-zero: the seven low-order u-coordinates, which are
// 0, 1, both points of order 8, p-1, p and p+1, plus a non-canonical spelling of each.
try wycheproofTest(
bundleType: self,
jsonName: "x25519_test",
testFunction: { (group: ECDHTestGroup) in
let zeroSharedSecretTests = group.tests.filter { $0.flags.contains("ZeroSharedSecret") }
XCTAssert(!zeroSharedSecretTests.isEmpty)
for testVector in zeroSharedSecretTests {
// The public key itself is accepted, as it is by CryptoKit; only the agreement fails.
let publicKey = try Curve25519.KeyAgreement.PublicKey(
rawRepresentation: Array(hexString: testVector.publicKey)
)
let privateKey = try Curve25519.KeyAgreement.PrivateKey(
rawRepresentation: Array(hexString: testVector.privateKey)
)
XCTAssertThrowsError(
try privateKey.sharedSecretFromKeyAgreement(with: publicKey),
"tcId \(testVector.tcId)"
)
}
}
)
}
}
#endif // canImport(CryptoKit)
@@ -0,0 +1,37 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
#if canImport(CryptoKit)
// Skip tests that require @testable imports of CryptoKit.
#else
@testable import Crypto
extension ECKeyEncodingsTests {
func testCompactRepresentabilityIsDecidedByTheFieldPrime() throws {
// y = n + 1, the larger of the two square roots, so not compact representable.
let aboveMidpointX = try Data(hexString: "d1db3668128866847e66864aa97c37a04f65f6ff201a7d02345dffd738908975")
let aboveMidpointY = try Data(hexString: "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632552")
let aboveMidpoint = try P256.Signing.PublicKey(rawRepresentation: aboveMidpointX + aboveMidpointY)
XCTAssertNil(aboveMidpoint.compactRepresentation)
// n/2 < y <= (p-1)/2, the smaller of the two square roots, so compact representable.
let belowMidpointX = try Data(hexString: "ce2afeafa686293c6c93f644b3f6d796c659a9277ca4af6c15ef3bfdc6e00f89")
let belowMidpointY = try Data(hexString: "7fffffff800000007fffffffffffffffde737d56d38bcf4279dce5617e3192aa")
let belowMidpoint = try P256.Signing.PublicKey(rawRepresentation: belowMidpointX + belowMidpointY)
XCTAssertEqual(belowMidpoint.compactRepresentation, belowMidpointX)
}
}
#endif // canImport(CryptoKit)
@@ -217,6 +217,12 @@ final class SecureBytesTests: XCTestCase {
XCTAssertEqual(base.count, 22)
XCTAssertEqual(Array(copy), [0, 1, 2, 3, 4])
}
func testZeroizePointerToMultiWordValueClearsAllBytes() {
var value: (UInt64, UInt64, UInt64, UInt64) = (1, 2, 3, 4)
withUnsafeMutablePointer(to: &value) { $0.zeroize() }
XCTAssertEqual(withUnsafeBytes(of: value) { Array($0) }, Array(repeating: UInt8(0), count: 32))
}
}
#endif // canImport(CryptoKit)
-5
View File
@@ -34,7 +34,6 @@ struct RFCVectorDecoder {
for _ in 0..<3 {
fileURL!.deleteLastPathComponent()
}
#if compiler(>=6.0)
if #available(macOS 13, iOS 16, watchOS 9, tvOS 16, visionOS 1, macCatalyst 16, *) {
fileURL!.append(path: "Test Vectors", directoryHint: .isDirectory)
fileURL!.append(path: "\(fileName).txt", directoryHint: .notDirectory)
@@ -42,10 +41,6 @@ struct RFCVectorDecoder {
fileURL! = fileURL!.appendingPathComponent("Test Vectors", isDirectory: true)
fileURL! = fileURL!.appendingPathComponent("\(fileName).txt", isDirectory: false)
}
#else
fileURL! = fileURL!.appendingPathComponent("Test Vectors", isDirectory: true)
fileURL! = fileURL!.appendingPathComponent("\(fileName).txt", isDirectory: false)
#endif
let rfcVectorData = try Data(contentsOf: fileURL!)
self.rfcVectorData = String(decoding: rfcVectorData, as: Unicode.UTF8.self)
-5
View File
@@ -26,7 +26,6 @@ extension XCTestCase {
for _ in 0..<3 {
fileURL.deleteLastPathComponent()
}
#if compiler(>=6.0)
if #available(macOS 13, iOS 16, watchOS 9, tvOS 16, visionOS 1, macCatalyst 16, *) {
fileURL.append(path: "Test Vectors", directoryHint: .isDirectory)
fileURL.append(path: "\(jsonName).json", directoryHint: .notDirectory)
@@ -34,10 +33,6 @@ extension XCTestCase {
fileURL = fileURL.appendingPathComponent("Test Vectors", isDirectory: true)
fileURL = fileURL.appendingPathComponent("\(jsonName).json", isDirectory: false)
}
#else
fileURL = fileURL.appendingPathComponent("Test Vectors", isDirectory: true)
fileURL = fileURL.appendingPathComponent("\(jsonName).json", isDirectory: false)
#endif
let data = try orFail(file: file, line: line) { try Data(contentsOf: unwrap(fileURL, file: file, line: line)) }