Compare commits

..
29 Commits
Author SHA1 Message Date
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
a9d1d5ab89 Merge the 5.x branch for the Swift Crypto 5.0 release (#470)
## 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>
2026-09-16 14:47:34 +01:00
Si BeaumontandCory Benfield da9d28d69e Enforce a 2048-bit minimum on RSA raw number initializers (#467)
### 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>
2026-09-01 18:48:04 +01:00
Si Beaumont f79a3ffbc0 Compute RSA key size from the modulus bit length (#466)
### 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.
2026-09-01 18:12:06 +01:00
Si Beaumont fa2832e44b Reapply swift-format to fixup PR CI (#465)
### Motivation:

Not entirely sure how (maybe a merge in from a GHSA fork), but right now
we have failing CI on PRs for a formatting
drift.

### Modifications:

Rerun swift-format.

### Result:

Get pull request CI passing cleanly.
2026-09-01 11:06:49 +00:00
Dmitry 315a799ccc Match the documented parameter names to the signatures (#463) 2026-08-31 21:00:33 +00:00
Si Beaumont 3ed653865a Update contributing guidelines (#464) 2026-08-28 15:36:47 +01:00
Si Beaumont 47d3869a72 Merge commit from fork
* 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
2026-07-16 13:29:36 +01:00
Si Beaumont c3d9fc8938 Back AES-CBC with BoringSSL and constant-time PKCS#7 unpadding (#448)
### 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.
2026-07-16 12:28:36 +00:00
Si Beaumont 1ca42a1885 Update cross-platform dependencies in README (#446)
### Motivation:

Swift Crypto 4.0 included SHA3 APIs, which required a backing
implementation on non-Apple platforms. We brought in libXCKP for this
purpose, similar to how we use BoringSSL for the implementation of the
rest of CryptoKit API on non-Apple platforms. The README includes
details of how the code is organised but was not updated to reflect this
change.

### Modifications:

- Update the backend implementation section to include XCKP alongside
BoringSSL
- Add an acknowledgments section to the README

### Result:

The README now includes details of both our backing dependencies, not
just BoringSSL.

Fixes #439.
2026-07-01 10:08:47 +00:00
83 changed files with 1756 additions and 1207 deletions

No files matched your search

+10 -6
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
@@ -21,16 +22,16 @@ jobs:
with:
linux_6_2_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
linux_6_3_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
linux_nightly_next_arguments_override: "--build-system native -Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
linux_nightly_main_arguments_override: "--build-system native --explicit-target-dependency-import-check error"
linux_nightly_next_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
windows_6_2_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
windows_6_3_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
windows_nightly_next_arguments_override: "--build-system native -Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
windows_nightly_main_arguments_override: "--build-system native --explicit-target-dependency-import-check error"
windows_nightly_next_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
release-builds:
name: Release builds
@@ -47,13 +48,16 @@ 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: >-
{
"targets": [
{ "name": "CCryptoBoringSSL", "type": "source", "exceptions": [] },
{ "name": "CCryptoBoringSSLShims", "type": "source", "exceptions": [] },
{ "name": "CryptoBoringWrapper", "type": "source", "exceptions": [] },
{ "name": "CXKCP", "type": "source", "exceptions": [] },
{ "name": "CXKCPShims", "type": "source", "exceptions": [] },
@@ -62,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.
+30 -10
View File
@@ -5,6 +5,18 @@ your contribution to Apple and the community, and agree by submitting the patch
that your contributions are licensed under the Apache 2.0 license (see
`LICENSE.txt`).
## AI tools
Human discourse is an essential part of open source development. To encourage
productive collaboration between contributors and maintainers, please refrain
from using AI tools for the following:
- Issues: titles, bodies, and comments.
- Pull requests: titles, descriptions, and comments.
Contributors who feel more comfortable writing in another language may use
automated translation tools, but must include their original content in their
preferred language.
## How to submit a bug report
@@ -44,19 +56,27 @@ $ uname -a
Linux beefy.machine 4.4.0-101-generic #124-Ubuntu SMP Fri Nov 10 18:29:59 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
```
## Writing a Patch
## Contributing a pull request
A good swift-crypto patch is:
> [!IMPORTANT]
> To ensure productive use of contributor and maintainer time and resources,
> contributors must first agree their proposed change with a maintainer in an
> issue. Pull requests opened without prior discussion may be closed without
> review.
1. Concise, and contains as few changes as needed to achieve the end result.
2. Tested, ensuring that any tests provided failed before the patch and pass after it.
3. Documented, adding API documentation as needed to cover new functions and properties.
4. Accompanied by a great commit message, using our commit message template.
If there is no issue already tracking the problem or feature request, please
file a new one using your own voice (see "AI tools" usage above).
Once an issue is assigned to you, follow these steps:
## How to contribute your work
Please open a pull request at https://github.com/apple/swift-crypto. Make sure the CI passes, and then wait for code review.
- Prepare your change, keeping in mind that a good patch is:
- Concise, and contains as few changes as needed to achieve the end result.
- Tested, ensuring that any tests provided failed before the patch and pass
after it.
- Documented, adding API documentation as needed to cover new functions and
properties.
- Accompanied by a great commit message.
- Open a pull request and wait for code review by the maintainers.
### How to update CMakeLists files
@@ -69,7 +89,7 @@ act --container-architecture linux/amd64 pull_request -j cmake-lists -W ./.githu
You can find the underlying script at https://github.com/apple/swift-nio/blob/main/scripts/update-cmake-lists.sh . Using the script directly is less straightforwards because it requires you to pass the JSON config from the `pull_request.yml` file into the script, such as:
```
curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/update-cmake-lists.sh | CONFIG_JSON='{"targets":[{"name":"CCryptoBoringSSL","type":"source","exceptions":[]},{"name":"CCryptoBoringSSLShims","type":"source","exceptions":[]},{"name":"CryptoBoringWrapper","type":"source","exceptions":[]},{"name":"Crypto","type":"source","exceptions":[]},{"name":"CryptoExtras","type":"source","exceptions":[]},{"name":"CCryptoBoringSSL","type":"assembly","exceptions":["*/AES/*.swift"]}]}' bash
curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/update-cmake-lists.sh | CONFIG_JSON='{"targets":[{"name":"CCryptoBoringSSL","type":"source","exceptions":[]},{"name":"CryptoBoringWrapper","type":"source","exceptions":[]},{"name":"Crypto","type":"source","exceptions":[]},{"name":"CryptoExtras","type":"source","exceptions":[]},{"name":"CCryptoBoringSSL","type":"assembly","exceptions":["*/AES/*.swift"]}]}' bash
```
## API Evolution
+2 -14
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")]
@@ -126,14 +125,6 @@ let package = Package(
.disableWarning("macro-redefined"),
]
),
.target(
name: "CCryptoBoringSSLShims",
dependencies: ["CCryptoBoringSSL"],
exclude: privacyManifestExclude + [
"CMakeLists.txt"
],
resources: privacyManifestResource
),
.target(
name: "CXKCPShims",
dependencies: ["CXKCP"],
@@ -146,7 +137,6 @@ let package = Package(
name: "Crypto",
dependencies: [
.target(name: "CCryptoBoringSSL", condition: .when(platforms: nonDarwinPlatforms)),
.target(name: "CCryptoBoringSSLShims", condition: .when(platforms: nonDarwinPlatforms)),
.target(name: "CryptoBoringWrapper", condition: .when(platforms: nonDarwinPlatforms)),
.target(name: "CXKCP", condition: .when(platforms: nonDarwinPlatforms)),
.target(name: "CXKCPShims", condition: .when(platforms: nonDarwinPlatforms)),
@@ -164,7 +154,6 @@ let package = Package(
name: "CryptoExtras",
dependencies: [
"CCryptoBoringSSL",
"CCryptoBoringSSLShims",
"CryptoBoringWrapper",
"Crypto",
.product(name: "SwiftASN1", package: "swift-asn1"),
@@ -186,7 +175,6 @@ let package = Package(
name: "CryptoBoringWrapper",
dependencies: [
"CCryptoBoringSSL",
"CCryptoBoringSSLShims",
],
exclude: privacyManifestExclude + [
"CMakeLists.txt"
+11 -6
View File
@@ -31,10 +31,11 @@ When building Swift Crypto for use on an Apple platform where CryptoKit is alrea
When building Swift Crypto for use on other platforms, Swift Crypto builds substantially more code. In particular, we build:
1. A vendored copy of BoringSSL's libcrypto.
2. The common API of Swift Crypto and CryptoKit.
3. The backing implementation of this common API, which calls into BoringSSL.
2. A vendored copy of XKCP's libXKCP.
3. The common API of Swift Crypto and CryptoKit.
4. The backing implementation of this common API, which calls into BoringSSL or XKCP.
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The backing BoringSSL-based implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIS predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL implementation of the library in your application, no matter the platform.
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The BoringSSL/XKCP backing implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIs predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL/XKCP implementation of the library in your application, no matter the platform.
## Evolution
@@ -48,11 +49,11 @@ Note that Swift Crypto does not intend to support all possible cryptographic pri
### Code Organisation
Files in this repository are divided into two groups, based on whether they have a name that ends in `_boring` or are in a `BoringSSL` directory, or if they are not.
Files in this repository are divided into two groups, based on whether they have a name that ends in `_boring`/`_xkcp` or are in a `BoringSSL`/`XKCP` directory, or if they are not.
Files that meet the above criteria are specific to the Swift Crypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or access a BoringSSL API, it needs to be marked this way.
Files that meet the above criteria are specific to the Swift Crypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or `import CXKCP` or access a BoringSSL or XKCP API, it needs to be marked this way.
Files that do not have the `_boring` suffix are part of the public API of CryptoKit. Changing these requires passing a higher bar, as any change in these files must be accompanied by a change in CryptoKit itself.
Files that do not have the `_boring` or `_xkcp` suffix are part of the public API of CryptoKit. Changing these requires passing a higher bar, as any change in these files must be accompanied by a change in CryptoKit itself.
## Contributing
@@ -150,3 +151,7 @@ To do so, please use the following dependency in your `Package.swift`:
Swift Crypto normally defers to the OS implementation of CryptoKit on macOS. Naturally, this makes developing Swift Crypto on macOS tricky. To get Swift Crypto to build the open source implementation on macOS, in `Package.swift`, use a Linux container. A Dev Container config is provided in the repo to make this easier.
## Acknowledgements
This project contains source code from the BoringSSL and XKCP projects.
@@ -1,29 +0,0 @@
##===----------------------------------------------------------------------===##
##
## This source file is part of the SwiftCrypto open source project
##
## Copyright (c) 2021 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
##
##===----------------------------------------------------------------------===##
add_library(CCryptoBoringSSLShims STATIC
"shims.c"
)
target_include_directories(CCryptoBoringSSLShims PUBLIC
include
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>)
target_link_libraries(CCryptoBoringSSLShims PUBLIC
CCryptoBoringSSL)
set_target_properties(CCryptoBoringSSLShims PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
set_property(GLOBAL APPEND PROPERTY SWIFT_CRYPTO_EXPORTS CCryptoBoringSSLShims)
@@ -1,15 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyTracking</key>
<false/>
<key>NSPrivacyAccessedAPITypes</key>
<array/>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyTrackingDomains</key>
<array/>
</dict>
</plist>
@@ -1,155 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 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
//
//===----------------------------------------------------------------------===//
#ifndef C_CRYPTO_BORINGSSL_SHIMS_H
#define C_CRYPTO_BORINGSSL_SHIMS_H
// This is for instances when `swift package generate-xcodeproj` is used as CCryptoBoringSSL
// is treated as a framework and requires the framework's name as a prefix.
#if __has_include(<CCryptoBoringSSL/CCryptoBoringSSL.h>)
#include <CCryptoBoringSSL/CCryptoBoringSSL.h>
#else
#include <CCryptoBoringSSL.h>
#endif
#if defined(__cplusplus)
extern "C" {
#endif
// MARK:- Pointer type shims
// This section of the code handles shims that change uint8_t* pointers to
// void *s. This is done because Swift does not have the rule that C does, that
// pointers to uint8_t can safely alias any other pointer. That means that Swift
// Unsafe[Mutable]RawPointer cannot be passed to uint8_t * APIs, which is very
// awkward, so we shim these to avoid the need to call bindMemory in Swift (which is
// wrong).
//
// Our relevant citation is: https://github.com/apple/swift-nio-extras/pull/56#discussion_r329330295.
// We want this to land: https://bugs.swift.org/browse/SR-11087. Once that lands we can remove these
// shims.
int CCryptoBoringSSLShims_EVP_AEAD_CTX_init(EVP_AEAD_CTX *ctx, const EVP_AEAD *aead,
const void *key, size_t key_len, size_t tag_len,
ENGINE *impl);
int CCryptoBoringSSLShims_EVP_AEAD_CTX_seal_scatter(
const EVP_AEAD_CTX *ctx,
void *out,
void *out_tag,
size_t *out_tag_len,
size_t max_out_tag_len,
const void *nonce,
size_t nonce_len,
const void *in,
size_t in_len,
const void *extra_in,
size_t extra_in_len,
const void *ad,
size_t ad_len);
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(const EVP_AEAD_CTX *ctx, void *out,
const void *nonce, size_t nonce_len,
const void *in, size_t in_len,
const void *in_tag, size_t in_tag_len,
const void *ad, size_t ad_len);
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open(const EVP_AEAD_CTX *ctx, void *out, size_t *out_len, size_t max_out_len,
const void *nonce, size_t nonce_len,
const void *in, size_t in_len,
const void *ad, size_t ad_len);
void CCryptoBoringSSLShims_ED25519_keypair(void *out_public_key, void *out_private_key);
void CCryptoBoringSSLShims_ED25519_keypair_from_seed(void *out_public_key,
void *out_private_key,
const void *seed);
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_do_sign(const void *digest, size_t digest_len,
const EC_KEY *eckey);
int CCryptoBoringSSLShims_ECDSA_do_verify(const void *digest, size_t digest_len,
const ECDSA_SIG *sig, const EC_KEY *eckey);
void CCryptoBoringSSLShims_X25519_keypair(void *out_public_value, void *out_private_key);
void CCryptoBoringSSLShims_X25519_public_from_private(void *out_public_value,
const void *private_key);
int CCryptoBoringSSLShims_X25519(void *out_shared_key, const void *private_key,
const void *peer_public_value);
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(const void *in, size_t in_len);
int CCryptoBoringSSLShims_ED25519_verify(const void *message, size_t message_len,
const void *signature, const void *public_key);
int CCryptoBoringSSLShims_ED25519_sign(void *out_sig, const void *message,
size_t message_len, const void *private_key);
BIGNUM *CCryptoBoringSSLShims_BN_bin2bn(const void *in, size_t len, BIGNUM *ret);
size_t CCryptoBoringSSLShims_BN_bn2bin(const BIGNUM *in, void *out);
int CCryptoBoringSSLShims_BN_mod(BIGNUM *rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
int CCryptoBoringSSLShims_RSA_verify(int hash_nid, const void *msg, size_t msg_len,
const void *sig, size_t sig_len, RSA *rsa);
int CCryptoBoringSSLShims_RSA_verify_pss_mgf1(RSA *rsa, const void *msg,
size_t msg_len, const EVP_MD *md,
const EVP_MD *mgf1_md, int salt_len,
const void *sig, size_t sig_len);
int CCryptoBoringSSLShims_RSA_sign(int hash_nid, const void *in,
unsigned int in_len, void *out,
unsigned int *out_len, RSA *rsa);
int CCryptoBoringSSLShims_RSA_sign_pss_mgf1(RSA *rsa, size_t *out_len, void *out,
size_t max_out, const void *in,
size_t in_len, const EVP_MD *md,
const EVP_MD *mgf1_md, int salt_len);
int CCryptoBoringSSLShims_RSA_public_encrypt(int flen, const void *from, void *to,
RSA *rsa, int padding);
int CCryptoBoringSSLShims_RSA_private_decrypt(int flen, const void *from, void *to,
RSA *rsa, int padding);
int CCryptoBoringSSLShims_EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, void *out,
size_t *out_len, const void *in,
size_t in_len);
int CCryptoBoringSSLShims_EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, void *out,
size_t *out_len, const void *in,
size_t in_len);
int CCryptoBoringSSLShims_EC_hash_to_curve_p256_xmd_sha256_sswu(const EC_GROUP *group, EC_POINT *out,
const void *dst, size_t dst_len,
const void *msg, size_t msg_len);
int CCryptoBoringSSLShims_EC_hash_to_curve_p384_xmd_sha384_sswu(const EC_GROUP *group, EC_POINT *out,
const void *dst, size_t dst_len,
const void *msg, size_t msg_len);
size_t CCryptoBoringSSLShims_EC_POINT_point2oct(const EC_GROUP *group,
const EC_POINT *point,
point_conversion_form_t form,
void *buf, size_t max_out,
BN_CTX *ctx);
#if defined(__cplusplus)
}
#endif // defined(__cplusplus)
#endif // C_CRYPTO_BORINGSSL_SHIMS_H
@@ -1,4 +0,0 @@
module CCryptoBoringSSLShims {
header "CCryptoBoringSSLShims.h"
export *
}
-190
View File
@@ -1,190 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 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
//
//===----------------------------------------------------------------------===//
#include <CCryptoBoringSSLShims.h>
// MARK:- Pointer type shims
// This section of the code handles shims that change uint8_t* pointers to
// void *s. This is done because Swift does not have the rule that C does, that
// pointers to uint8_t can safely alias any other pointer. That means that Swift
// Unsafe[Mutable]RawPointer cannot be passed to uint8_t * APIs, which is very
// awkward, so we shim these to avoid the need to call bindMemory in Swift (which is
// wrong).
//
// Our relevant citation is: https://github.com/apple/swift-nio-extras/pull/56#discussion_r329330295.
// We want this to land: https://bugs.swift.org/browse/SR-11087. Once that lands we can remove these
// shims.
int CCryptoBoringSSLShims_EVP_AEAD_CTX_init(EVP_AEAD_CTX *ctx, const EVP_AEAD *aead,
const void *key, size_t key_len, size_t tag_len,
ENGINE *impl) {
return CCryptoBoringSSL_EVP_AEAD_CTX_init(ctx, aead, key, key_len, tag_len, impl);
}
int CCryptoBoringSSLShims_EVP_AEAD_CTX_seal_scatter(
const EVP_AEAD_CTX *ctx,
void *out,
void *out_tag,
size_t *out_tag_len,
size_t max_out_tag_len,
const void *nonce,
size_t nonce_len,
const void *in,
size_t in_len,
const void *extra_in,
size_t extra_in_len,
const void *ad,
size_t ad_len) {
return CCryptoBoringSSL_EVP_AEAD_CTX_seal_scatter(ctx, out, out_tag, out_tag_len, max_out_tag_len, nonce, nonce_len, in, in_len, extra_in, extra_in_len, ad, ad_len);
}
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(const EVP_AEAD_CTX *ctx, void *out,
const void *nonce, size_t nonce_len,
const void *in, size_t in_len,
const void *in_tag, size_t in_tag_len,
const void *ad, size_t ad_len) {
return CCryptoBoringSSL_EVP_AEAD_CTX_open_gather(ctx, out, nonce, nonce_len, in, in_len, in_tag, in_tag_len, ad, ad_len);
}
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open(const EVP_AEAD_CTX *ctx, void *out, size_t *out_len, size_t max_out_len,
const void *nonce, size_t nonce_len,
const void *in, size_t in_len,
const void *ad, size_t ad_len) {
return CCryptoBoringSSL_EVP_AEAD_CTX_open(ctx, out, out_len, max_out_len, nonce, nonce_len, in, in_len, ad, ad_len);
}
void CCryptoBoringSSLShims_ED25519_keypair(void *out_public_key, void *out_private_key) {
CCryptoBoringSSL_ED25519_keypair(out_public_key, out_private_key);
}
void CCryptoBoringSSLShims_ED25519_keypair_from_seed(void *out_public_key,
void *out_private_key,
const void *seed) {
CCryptoBoringSSL_ED25519_keypair_from_seed(out_public_key, out_private_key, seed);
}
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_do_sign(const void *digest, size_t digest_len,
const EC_KEY *eckey) {
return CCryptoBoringSSL_ECDSA_do_sign(digest, digest_len, eckey);
}
int CCryptoBoringSSLShims_ECDSA_do_verify(const void *digest, size_t digest_len,
const ECDSA_SIG *sig, const EC_KEY *eckey) {
return CCryptoBoringSSL_ECDSA_do_verify(digest, digest_len, sig, eckey);
}
void CCryptoBoringSSLShims_X25519_keypair(void *out_public_value, void *out_private_key) {
CCryptoBoringSSL_X25519_keypair(out_public_value, out_private_key);
}
void CCryptoBoringSSLShims_X25519_public_from_private(void *out_public_value,
const void *private_key) {
CCryptoBoringSSL_X25519_public_from_private(out_public_value, private_key);
}
int CCryptoBoringSSLShims_X25519(void *out_shared_key, const void *private_key,
const void *peer_public_value) {
return CCryptoBoringSSL_X25519(out_shared_key, private_key, peer_public_value);
}
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(const void *in, size_t in_len) {
return CCryptoBoringSSL_ECDSA_SIG_from_bytes(in, in_len);
}
int CCryptoBoringSSLShims_ED25519_verify(const void *message, size_t message_len,
const void *signature, const void *public_key) {
return CCryptoBoringSSL_ED25519_verify(message, message_len, signature, public_key);
}
int CCryptoBoringSSLShims_ED25519_sign(void *out_sig, const void *message,
size_t message_len, const void *private_key) {
return CCryptoBoringSSL_ED25519_sign(out_sig, message, message_len, private_key);
}
BIGNUM *CCryptoBoringSSLShims_BN_bin2bn(const void *in, size_t len, BIGNUM *ret) {
return CCryptoBoringSSL_BN_bin2bn(in, len, ret);
}
size_t CCryptoBoringSSLShims_BN_bn2bin(const BIGNUM *in, void *out) {
return CCryptoBoringSSL_BN_bn2bin(in, out);
}
int CCryptoBoringSSLShims_BN_mod(BIGNUM *rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) {
return BN_mod(rem, a, m, ctx);
}
int CCryptoBoringSSLShims_RSA_verify(int hash_nid, const void *msg, size_t msg_len,
const void *sig, size_t sig_len, RSA *rsa) {
return CCryptoBoringSSL_RSA_verify(hash_nid, msg, msg_len, sig, sig_len, rsa);
}
int CCryptoBoringSSLShims_RSA_verify_pss_mgf1(RSA *rsa, const void *msg,
size_t msg_len, const EVP_MD *md,
const EVP_MD *mgf1_md, int salt_len,
const void *sig, size_t sig_len) {
return CCryptoBoringSSL_RSA_verify_pss_mgf1(rsa, msg, msg_len, md, mgf1_md, salt_len, sig, sig_len);
}
int CCryptoBoringSSLShims_RSA_sign(int hash_nid, const void *in,
unsigned int in_len, void *out,
unsigned int *out_len, RSA *rsa) {
return CCryptoBoringSSL_RSA_sign(hash_nid, in, in_len, out, out_len, rsa);
}
int CCryptoBoringSSLShims_RSA_sign_pss_mgf1(RSA *rsa, size_t *out_len, void *out,
size_t max_out, const void *in,
size_t in_len, const EVP_MD *md,
const EVP_MD *mgf1_md, int salt_len) {
return CCryptoBoringSSL_RSA_sign_pss_mgf1(rsa, out_len, out, max_out, in, in_len, md, mgf1_md, salt_len);
}
int CCryptoBoringSSLShims_RSA_public_encrypt(int flen, const void *from, void *to,
RSA *rsa, int padding) {
return CCryptoBoringSSL_RSA_public_encrypt(flen, from, to, rsa, padding);
}
int CCryptoBoringSSLShims_RSA_private_decrypt(int flen, const void *from, void *to,
RSA *rsa, int padding) {
return CCryptoBoringSSL_RSA_private_decrypt(flen, from, to, rsa, padding);
}
int CCryptoBoringSSLShims_EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, void *out,
size_t *out_len, const void *in,
size_t in_len) {
return CCryptoBoringSSL_EVP_PKEY_encrypt(ctx, out, out_len, in, in_len);
}
int CCryptoBoringSSLShims_EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, void *out,
size_t *out_len, const void *in,
size_t in_len) {
return CCryptoBoringSSL_EVP_PKEY_decrypt(ctx, out, out_len, in, in_len);
}
int CCryptoBoringSSLShims_EC_hash_to_curve_p256_xmd_sha256_sswu(const EC_GROUP *group, EC_POINT *out,
const void *dst, size_t dst_len,
const void *msg, size_t msg_len) {
return CCryptoBoringSSL_EC_hash_to_curve_p256_xmd_sha256_sswu(group, out, dst, dst_len, msg, msg_len);
}
int CCryptoBoringSSLShims_EC_hash_to_curve_p384_xmd_sha384_sswu(const EC_GROUP *group, EC_POINT *out,
const void *dst, size_t dst_len,
const void *msg, size_t msg_len) {
return CCryptoBoringSSL_EC_hash_to_curve_p384_xmd_sha384_sswu(group, out, dst, dst_len, msg, msg_len);
}
size_t CCryptoBoringSSLShims_EC_POINT_point2oct(const EC_GROUP *group,
const EC_POINT *point,
point_conversion_form_t form,
void *buf, size_t max_out,
BN_CTX *ctx) {
return CCryptoBoringSSL_EC_POINT_point2oct(group, point, form, buf, max_out, ctx);
}
-1
View File
@@ -13,7 +13,6 @@
##===----------------------------------------------------------------------===##
add_subdirectory(CCryptoBoringSSL)
add_subdirectory(CCryptoBoringSSLShims)
add_subdirectory(CXKCP)
add_subdirectory(CXKCPShims)
add_subdirectory(CryptoBoringWrapper)
+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
@@ -16,10 +16,8 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
@@ -50,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(
@@ -95,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(
@@ -152,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(
@@ -213,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 -2
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"
@@ -117,7 +118,6 @@ target_compile_definitions(Crypto PRIVATE
target_include_directories(Crypto PRIVATE
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CCryptoBoringSSLShims,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CryptoBoringWrapper,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CXKCP,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CXKCPShims,INCLUDE_DIRECTORIES>)
@@ -125,7 +125,6 @@ target_link_libraries(Crypto PUBLIC
$<$<NOT:$<PLATFORM_ID:Darwin>>:dispatch>
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
CCryptoBoringSSL
CCryptoBoringSSLShims
CryptoBoringWrapper
CXKCP
CXKCPShims)
+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) {
@@ -33,12 +33,8 @@ enum BoringSSLAESWRAPImpl {
let rc = try key.withUnsafeAESKEY(mode: .encrypting) { aesKey in
output.withUnsafeMutableBytes { outputPtr -> CInt in
// Memory bind is safe: we cannot alias the pointer here.
let outputPtr = outputPtr.bindMemory(to: UInt8.self)
return keyToWrap.withUnsafeBytes { keyToWrapPtr -> CInt in
// Memory bind is safe: we cannot alias the pointer here.
let keyToWrapPtr = keyToWrapPtr.bindMemory(to: UInt8.self)
return CCryptoBoringSSL_AES_wrap_key(
keyToWrap.withUnsafeBytes { keyToWrapPtr -> CInt in
CCryptoBoringSSL_AES_wrap_key(
aesKey,
nil,
outputPtr.baseAddress,
@@ -76,10 +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
// Bind is safe: we cannot violate the aliasing rules here as we never call to arbitrary code.
let inPtr = inPtr.bindMemory(to: UInt8.self)
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,
@@ -99,8 +93,6 @@ enum BoringSSLAESWRAPImpl {
count = Int(rc)
}
}
return SymmetricKey(data: unwrapped)
}
}
@@ -117,8 +109,6 @@ extension SymmetricKey {
_ body: (UnsafePointer<AES_KEY>) throws -> ResultType
) throws -> ResultType {
try self.withUnsafeBytes { bytesPointer in
// Bind is safe: cannot alias the pointer here.
let bytesPointer = bytesPointer.bindMemory(to: UInt8.self)
var aesKey = AES_KEY()
let bitsInKey = UInt32(bytesPointer.count * 8)
@@ -16,10 +16,8 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
@@ -46,7 +44,7 @@ extension Curve25519.Signing {
privateKeyBytes in
privateKeyBytes = 64
publicKey.withUnsafeMutableBytes { publicKeyPtr in
CCryptoBoringSSLShims_ED25519_keypair(
CCryptoBoringSSL_ED25519_keypair(
publicKeyPtr.baseAddress,
privateKeyPtr.baseAddress
)
@@ -80,7 +78,7 @@ extension Curve25519.Signing {
privateKeyBytes in
privateKeyBytes = 64
publicKey.withUnsafeMutableBytes { publicKeyPtr in
CCryptoBoringSSLShims_ED25519_keypair_from_seed(
CCryptoBoringSSL_ED25519_keypair_from_seed(
publicKeyPtr.baseAddress,
privateKeyPtr.baseAddress,
seedPtr.baseAddress
@@ -16,10 +16,8 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
@@ -148,7 +146,7 @@ struct OpenSSLNISTCurvePublicKeyImpl<Curve: OpenSSLSupportedNISTCurve>: Sendable
/// allows some helper operations.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
final class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
@usableFromInline
let key: OpaquePointer
@@ -335,7 +333,7 @@ class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked
func sign<D: Digest>(digest: D) throws -> ECDSASignature {
let optionalRawSignature: UnsafeMutablePointer<ECDSA_SIG>? = digest.withUnsafeBytes {
digestPtr in
CCryptoBoringSSLShims_ECDSA_do_sign(digestPtr.baseAddress, digestPtr.count, self.key)
CCryptoBoringSSL_ECDSA_do_sign(digestPtr.baseAddress, digestPtr.count, self.key)
}
guard let rawSignature = optionalRawSignature else {
throw CryptoKitError.internalBoringSSLError()
@@ -353,7 +351,7 @@ class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked
/// allows some helper operations.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
final class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
@usableFromInline
let key: OpaquePointer
@@ -575,7 +573,7 @@ class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked
func isValidSignature<D: Digest>(_ signature: ECDSASignature, for digest: D) -> Bool {
let rc: CInt = signature.withUnsafeSignaturePointer { signaturePointer in
digest.withUnsafeBytes { digestPointer in
CCryptoBoringSSLShims_ECDSA_do_verify(
CCryptoBoringSSL_ECDSA_do_verify(
digestPointer.baseAddress,
digestPointer.count,
signaturePointer,
@@ -686,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(
@@ -701,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
@@ -16,10 +16,8 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
@@ -77,7 +75,7 @@ extension Curve25519.KeyAgreement {
publicKey.withUnsafeMutableBytes { publicKeyBytes in
precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
precondition(privateKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
CCryptoBoringSSLShims_X25519_keypair(
CCryptoBoringSSL_X25519_keypair(
publicKeyBytes.baseAddress,
privateKeyBytes.baseAddress
)
@@ -105,7 +103,7 @@ extension Curve25519.KeyAgreement {
publicKeyBytes,
publicKeySize in
precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
CCryptoBoringSSLShims_X25519_public_from_private(
CCryptoBoringSSL_X25519_public_from_private(
publicKeyBytes.baseAddress,
privatePointer.baseAddress
)
@@ -123,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),
@@ -135,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.
CCryptoBoringSSLShims_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
}
@@ -71,7 +71,7 @@ extension MessageAuthenticationCode {
public func makeIterator() -> Array<UInt8>.Iterator {
self.withUnsafeBytes({ (buffPtr) in
return Array(buffPtr.bindMemory(to: UInt8.self)).makeIterator()
return Array(buffPtr).makeIterator()
})
}
@@ -16,10 +16,8 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
@@ -30,13 +28,13 @@ import Foundation
/// A wrapper around BoringSSL's ECDSA_SIG with some lifetime management.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
class ECDSASignature {
final class ECDSASignature {
private var _baseSig: UnsafeMutablePointer<ECDSA_SIG>
init<ContiguousBuffer: ContiguousBytes>(contiguousDERBytes derBytes: ContiguousBuffer) throws {
self._baseSig = try derBytes.withUnsafeBytes { bytesPtr in
guard
let sig = CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(bytesPtr.baseAddress, bytesPtr.count)
let sig = CCryptoBoringSSL_ECDSA_SIG_from_bytes(bytesPtr.baseAddress, bytesPtr.count)
else {
throw CryptoKitError.internalBoringSSLError()
}
@@ -101,21 +99,6 @@ class ECDSASignature {
)
}
@usableFromInline
var derBytes: Data {
var dataPtr: UnsafeMutablePointer<UInt8>?
var length = 0
guard CCryptoBoringSSL_ECDSA_SIG_to_bytes(&dataPtr, &length, self._baseSig) == 1 else {
fatalError("Unable to marshal signature to DER")
}
defer {
// We must free this pointer.
CCryptoBoringSSL_OPENSSL_free(dataPtr)
}
return Data(UnsafeBufferPointer(start: dataPtr, count: length))
}
func withUnsafeSignaturePointer<T>(
_ body: (UnsafeMutablePointer<ECDSA_SIG>) throws -> T
)
@@ -67,17 +67,6 @@ extension Data {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P256.Signing.ECDSASignature {
init<D: DataProtocol>(openSSLDERSignature derRepresentation: D) throws {
self.rawRepresentation = try Data(derSignature: derRepresentation, over: P256.self)
}
var openSSLDERRepresentation: Data {
try! ECDSASignature(rawRepresentation: self.rawRepresentation).derBytes
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P256.Signing.PrivateKey {
func openSSLSignature<D: Digest>(for digest: D) throws -> P256.Signing.ECDSASignature {
@@ -104,17 +93,6 @@ extension P256.Signing.PublicKey {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P384.Signing.ECDSASignature {
init<D: DataProtocol>(openSSLDERSignature derRepresentation: D) throws {
self.rawRepresentation = try Data(derSignature: derRepresentation, over: P384.self)
}
var openSSLDERRepresentation: Data {
try! ECDSASignature(rawRepresentation: self.rawRepresentation).derBytes
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P384.Signing.PrivateKey {
func openSSLSignature<D: Digest>(for digest: D) throws -> P384.Signing.ECDSASignature {
@@ -141,17 +119,6 @@ extension P384.Signing.PublicKey {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P521.Signing.ECDSASignature {
init<D: DataProtocol>(openSSLDERSignature derRepresentation: D) throws {
self.rawRepresentation = try Data(derSignature: derRepresentation, over: P521.self)
}
var openSSLDERRepresentation: Data {
try! ECDSASignature(rawRepresentation: self.rawRepresentation).derBytes
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P521.Signing.PrivateKey {
func openSSLSignature<D: Digest>(for digest: D) throws -> P521.Signing.ECDSASignature {
@@ -16,10 +16,8 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
@@ -94,7 +92,7 @@ extension Curve25519.Signing.PublicKey {
precondition(signaturePointer.count == Curve25519.Signing.PublicKey.signatureByteCount)
precondition(self.keyBytes.count == 32)
let rc: CInt = self.keyBytes.withUnsafeBytes { keyBytesPtr in
CCryptoBoringSSLShims_ED25519_verify(
CCryptoBoringSSL_ED25519_verify(
dataPointer.baseAddress,
dataPointer.count,
signaturePointer.baseAddress,
@@ -133,7 +131,7 @@ extension Curve25519.Signing.PrivateKey {
precondition(signaturePointer.count == Curve25519.Signing.PublicKey.signatureByteCount)
precondition(keyPointer.count == ED25519_PRIVATE_KEY_LEN)
return CCryptoBoringSSLShims_ED25519_sign(
return CCryptoBoringSSL_ED25519_sign(
signaturePointer.baseAddress,
dataPointer.baseAddress,
dataPointer.count,
@@ -12,24 +12,13 @@
//
//===----------------------------------------------------------------------===//
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
// MARK: - Generated file, do NOT edit
// any edits of this file WILL be overwritten and thus discarded
// see section `gyb` in `README` for details.
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@@ -12,24 +12,13 @@
//
//===----------------------------------------------------------------------===//
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
// MARK: - Generated file, do NOT edit
// any edits of this file WILL be overwritten and thus discarded
// see section `gyb` in `README` for details.
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
+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)
@@ -14,10 +14,8 @@
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
@@ -43,7 +41,7 @@ extension BoringSSLAEAD {
// Arguably this class is excessive, but it's probably better for this API to be as safe as possible
// rather than rely on defer statements for our cleanup.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
public class AEADContext {
public final class AEADContext {
private var context: EVP_AEAD_CTX
public init<Key: ContiguousBytes>(cipher: BoringSSLAEAD, key: Key) throws {
@@ -52,7 +50,7 @@ extension BoringSSLAEAD {
let rc: CInt = key.withUnsafeBytes { keyPointer in
withUnsafeMutablePointer(to: &self.context) { contextPointer in
// Create the AEAD context with a default tag length using the given key.
CCryptoBoringSSLShims_EVP_AEAD_CTX_init(
CCryptoBoringSSL_EVP_AEAD_CTX_init(
contextPointer,
cipher.boringSSLCipher,
keyPointer.baseAddress,
@@ -155,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(
@@ -177,7 +175,7 @@ extension BoringSSLAEAD.AEADContext {
return authenticatedData.withUnsafeBytes { authenticatedDataBuffer in
nonce.withUnsafeBytes { nonceBuffer in
CCryptoBoringSSLShims_EVP_AEAD_CTX_seal_scatter(
CCryptoBoringSSL_EVP_AEAD_CTX_seal_scatter(
contextPointer,
messageBuffer.baseAddress,
tagBuffer.baseAddress! + tagInitializedCount,
@@ -305,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(
@@ -319,7 +317,7 @@ extension BoringSSLAEAD.AEADContext {
nonce.withUnsafeBytes { nonceBuffer in
tag.withUnsafeBytes { tagBuffer in
authenticatedData.withUnsafeBytes { adBuffer in
CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(
CCryptoBoringSSL_EVP_AEAD_CTX_open_gather(
contextPointer,
messageBuffer.baseAddress,
nonceBuffer.baseAddress,
@@ -430,7 +428,7 @@ extension BoringSSLAEAD.AEADContext {
var writtenBytes = 0
let rc = withUnsafePointer(to: &self.context) { contextPointer in
CCryptoBoringSSLShims_EVP_AEAD_CTX_open(
CCryptoBoringSSL_EVP_AEAD_CTX_open(
contextPointer,
outputBuffer.baseAddress,
&writtenBytes,
+2 -4
View File
@@ -24,13 +24,11 @@ add_library(CryptoBoringWrapper STATIC
)
target_include_directories(CryptoBoringWrapper PUBLIC
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CCryptoBoringSSLShims,INCLUDE_DIRECTORIES>)
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>)
target_link_libraries(CryptoBoringWrapper PUBLIC
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
CCryptoBoringSSL
CCryptoBoringSSLShims)
CCryptoBoringSSL)
target_compile_options(CryptoBoringWrapper PRIVATE ${SWIFT_CRYPTO_COMPILE_OPTIONS})
@@ -13,10 +13,8 @@
//===----------------------------------------------------------------------===//
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
@@ -79,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,
@@ -92,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(
@@ -136,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,
@@ -149,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,
@@ -176,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(
@@ -209,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,
@@ -221,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,
@@ -246,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(
@@ -280,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,
@@ -293,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,
@@ -320,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>(
@@ -494,29 +379,35 @@ extension EllipticCurvePoint {
to group: BoringSSLEllipticCurveGroup,
domainSeparationTag: DSTBytes
) throws {
let hashToCurveFunction =
switch group.curveName {
case .p256: CCryptoBoringSSLShims_EC_hash_to_curve_p256_xmd_sha256_sswu
case .p384: CCryptoBoringSSLShims_EC_hash_to_curve_p384_xmd_sha384_sswu
// BoringSSL has no P521 hash_to_curve API.
case .p521: throw CryptoBoringWrapperError.invalidParameter
case .none: throw CryptoBoringWrapperError.internalBoringSSLError()
}
try self.init(_pointAtInfinityOn: group)
try msg.withUnsafeBytes { msgPtr in
try group.withUnsafeGroupPointer { groupPtr in
try domainSeparationTag.withUnsafeBytes { dstPtr in
guard
hashToCurveFunction(
let rc: CInt
switch group.curveName {
case .p256:
rc = CCryptoBoringSSL_EC_hash_to_curve_p256_xmd_sha256_sswu(
groupPtr,
self._basePoint,
dstPtr.baseAddress,
dstPtr.count,
msgPtr.baseAddress,
msgPtr.count
) == 1
else { throw CryptoBoringWrapperError.internalBoringSSLError() }
)
case .p384:
rc = CCryptoBoringSSL_EC_hash_to_curve_p384_xmd_sha384_sswu(
groupPtr,
self._basePoint,
dstPtr.baseAddress,
dstPtr.count,
msgPtr.baseAddress,
msgPtr.count
)
// BoringSSL has no P521 hash_to_curve API.
case .p521: throw CryptoBoringWrapperError.invalidParameter
case .none: throw CryptoBoringWrapperError.internalBoringSSLError()
}
guard rc == 1 else { throw CryptoBoringWrapperError.internalBoringSSLError() }
}
}
}
@@ -603,7 +494,7 @@ extension EllipticCurvePoint {
let numBytesWritten = group.withUnsafeGroupPointer { groupPtr in
buf.withUnsafeMutableBytes { bufPtr in
CCryptoBoringSSLShims_EC_POINT_point2oct(
CCryptoBoringSSL_EC_POINT_point2oct(
groupPtr,
self._basePoint,
compressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED,
@@ -14,10 +14,8 @@
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
@@ -123,7 +121,7 @@ extension ArbitraryPrecisionInteger.BackingStorage {
self.init()
let rc: UnsafeMutablePointer<BIGNUM>? = bytes.withUnsafeBytes { bytesPointer in
CCryptoBoringSSLShims_BN_bin2bn(
CCryptoBoringSSL_BN_bin2bn(
bytesPointer.baseAddress,
bytesPointer.count,
&self._backing
@@ -459,7 +457,8 @@ extension ArbitraryPrecisionInteger {
if nonNegative {
CCryptoBoringSSL_BN_nnmod(resultPtr, selfPtr, modPtr, bnCtx)
} else {
CCryptoBoringSSLShims_BN_mod(resultPtr, selfPtr, modPtr, bnCtx)
// BN_mod is a C macro for BN_div with a nil quotient; call that directly.
CCryptoBoringSSL_BN_div(nil, resultPtr, selfPtr, modPtr, bnCtx)
}
}
}
@@ -718,7 +717,7 @@ extension Data {
assert(bytesPtr.count == byteCount)
return integer.withUnsafeBignumPointer { bnPtr in
CCryptoBoringSSLShims_BN_bn2bin(bnPtr, bytesPtr.baseAddress!)
CCryptoBoringSSL_BN_bn2bin(bnPtr, bytesPtr.baseAddress!)
}
}
@@ -37,7 +37,7 @@ import Foundation
/// ourselves.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
package class FiniteFieldArithmeticContext: @unchecked Sendable {
package final class FiniteFieldArithmeticContext: @unchecked Sendable {
private let fieldSize: ArbitraryPrecisionInteger
package let bnCtx: OpaquePointer
@@ -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) {
+5 -91
View File
@@ -25,19 +25,6 @@ extension AES {
/// suite.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
public enum _CBC {
private static var blockSize: Int { 16 }
private static func encryptBlockInPlace(
_ plaintext: inout Block,
priorCiphertextBlock: Block,
using key: SymmetricKey
) throws {
assert([128, 192, 256].contains(key.bitCount))
plaintext ^= priorCiphertextBlock
try AES.permute(&plaintext, key: key)
}
/// Encrypts data using AES-CBC.
///
/// - Parameters:
@@ -60,44 +47,7 @@ extension AES {
///
/// - Note: If `noPadding` is set to `true`, `plainText` has to be a multiple of the blockSize (16 bytes). Otherwise an error will be thrown.
public static func encrypt<Plaintext: DataProtocol>(_ plaintext: Plaintext, using key: SymmetricKey, iv: AES._CBC.IV, noPadding: Bool) throws -> Data {
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
let requiresFullPaddingBlock = (plaintext.count % AES._CBC.blockSize) == 0
if noPadding && !requiresFullPaddingBlock {
throw CryptoKitError.incorrectParameterSize
}
var ciphertext = Data()
ciphertext.reserveCapacity(plaintext.count + Self.blockSize) // Room for padding.
var previousBlock = Block(iv)
var plaintext = plaintext[...]
while plaintext.count > 0 {
var block = Block(blockBytes: plaintext.prefix(Self.blockSize))
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
ciphertext.append(contentsOf: block)
previousBlock = block
plaintext = plaintext.dropFirst(Self.blockSize)
}
if requiresFullPaddingBlock && !noPadding {
var block = Block.paddingBlock
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
ciphertext.append(contentsOf: block)
}
return ciphertext
}
private static func decryptBlockInPlace(_ ciphertext: inout Block, priorCiphertextBlock: Block, using key: SymmetricKey) throws {
assert([128, 192, 256].contains(key.bitCount))
try AES.inversePermute(&ciphertext, key: key)
ciphertext ^= priorCiphertextBlock
try OpenSSLAESCBCImpl.encrypt(plaintext, using: key, iv: iv, noPadding: noPadding)
}
/// Decrypts data using AES-CBC.
@@ -120,29 +70,7 @@ extension AES {
/// - noPadding: If this is set to `true`, padding won't be removed.
/// - Returns: The decrypted message.
public static func decrypt<Ciphertext: DataProtocol>(_ ciphertext: Ciphertext, using key: SymmetricKey, iv: AES._CBC.IV, noPadding: Bool) throws -> Data {
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
var plaintext = Data()
plaintext.reserveCapacity(ciphertext.count)
var previousBlock = Block(iv)
var ciphertext = ciphertext[...]
while ciphertext.count > 0 {
let ctBlock = Block(blockBytes: ciphertext.prefix(Self.blockSize))
var block = ctBlock
try Self.decryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
plaintext.append(contentsOf: block)
previousBlock = ctBlock
ciphertext = ciphertext.dropFirst(Self.blockSize)
}
if !noPadding {
try plaintext.trimPadding()
}
return plaintext
try OpenSSLAESCBCImpl.decrypt(ciphertext, using: key, iv: iv, noPadding: noPadding)
}
}
}
@@ -194,7 +122,7 @@ extension AES._CBC {
0, 0, 0, 0, 0, 0, 0, 0
)
withUnsafeMutableBytes(of: &self.ivBytes) { bytesPtr in
Swift.withUnsafeMutableBytes(of: &self.ivBytes) { bytesPtr in
bytesPtr.copyBytes(from: ivBytes)
}
}
@@ -205,24 +133,10 @@ extension AES._CBC {
Array(unsafeRawBufferPointer).makeIterator()
}
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension Data {
fileprivate mutating func trimPadding() throws {
guard let paddingBytes = self.last else {
// Degenerate case, empty string. This is forbidden:
// we must always pad.
throw CryptoKitError.incorrectParameterSize
mutating func withUnsafeMutableBytes<ReturnType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
return try Swift.withUnsafeMutableBytes(of: &self.ivBytes, body)
}
guard paddingBytes > 0 &&
self.count >= paddingBytes &&
self.suffix(Int(paddingBytes)).allSatisfy({ $0 == paddingBytes }) else {
throw CryptoKitError.incorrectParameterSize
}
self = self.dropLast(Int(paddingBytes))
}
}
@@ -15,10 +15,8 @@
import Crypto
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
@@ -68,7 +66,6 @@ extension AES.GCM {
/// - Parameters:
/// - sealedBox: The sealed box to authenticate and decrypt
/// - key: An encryption key of 128 or 256 bits
/// - nonce: An Nonce for AES-GCM-SIV encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with AES.GCM.Nonce().
/// - authenticatedData: Data that was authenticated as part of the seal
/// - Returns: The ciphertext if opening was successful
/// - Throws: CipherError errors. If the authentication of the sealed box failed, incorrectTag is thrown.
@@ -82,7 +79,6 @@ extension AES.GCM {
/// - Parameters:
/// - sealedBox: The sealed box to authenticate and decrypt
/// - key: An encryption key of 128 or 256 bits
/// - nonce: An Nonce for AES-GCM-SIV encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with AES.GCM.Nonce().
/// - Returns: The ciphertext if opening was successful
/// - Throws: CipherError errors. If the authentication of the sealed box failed, incorrectTag is thrown.
public static func open(_ sealedBox: SealedBox, using key: SymmetricKey) throws -> Data {
+4 -124
View File
@@ -15,10 +15,8 @@
import Crypto
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
@@ -99,32 +97,24 @@ extension AES {
precondition(payload.count == Int(Self.blockSize))
key.withUnsafeBytes { keyPtr in
// We bind both pointers here. These binds are not technically safe, but because we
// know the pointers don't persist they can't violate the aliasing rules. We really
// want a "with memory rebound" function but we don't have it yet.
let keyBytes = keyPtr.bindMemory(to: UInt8.self)
let blockBytes = payload.bindMemory(to: UInt8.self)
var key = AES_KEY()
if permutation == .forward {
let rc = CCryptoBoringSSL_AES_set_encrypt_key(keyBytes.baseAddress, UInt32(keyBytes.count * 8), &key)
let rc = CCryptoBoringSSL_AES_set_encrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key)
precondition(rc == 0)
CCryptoBoringSSL_AES_encrypt(blockBytes.baseAddress, blockBytes.baseAddress, &key)
CCryptoBoringSSL_AES_encrypt(payload.baseAddress, payload.baseAddress, &key)
} else {
let rc = CCryptoBoringSSL_AES_set_decrypt_key(keyBytes.baseAddress, UInt32(keyBytes.count * 8), &key)
let rc = CCryptoBoringSSL_AES_set_decrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key)
precondition(rc == 0)
CCryptoBoringSSL_AES_decrypt(blockBytes.baseAddress, blockBytes.baseAddress, &key)
CCryptoBoringSSL_AES_decrypt(payload.baseAddress, payload.baseAddress, &key)
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
struct Block {
private static var blockSize: Int { 16 }
typealias BlockBytes = (
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8
@@ -140,70 +130,9 @@ extension AES {
)
}
init(_ blockBytes: BlockBytes) {
self.blockBytes = blockBytes
}
init(_ iv: AES._CBC.IV) {
self.blockBytes = iv.ivBytes
}
init<BlockBytes: Collection>(blockBytes: BlockBytes) where BlockBytes.Element == UInt8 {
// The block size is always 16. Pad out past there.
precondition(blockBytes.count <= Self.blockSize)
self.blockBytes = (
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
)
Swift.withUnsafeMutableBytes(of: &self.blockBytes) { bytesPtr in
bytesPtr.copyBytes(from: blockBytes)
// Early exit here.
if blockBytes.count == Self.blockSize {
return
}
var remainingBytes = bytesPtr.dropFirst(blockBytes.count)
let padByte = UInt8(remainingBytes.count)
for index in remainingBytes.indices {
remainingBytes[index] = padByte
}
}
}
static var paddingBlock: Block {
// The padding block is a full block of value blocksize.
let value = UInt8(truncatingIfNeeded: Self.blockSize)
return Block((
value, value, value, value, value, value, value, value,
value, value, value, value, value, value, value, value
))
}
func withUnsafeBytes<ReturnType>(_ body: (UnsafeRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
return try Swift.withUnsafeBytes(of: self.blockBytes, body)
}
mutating func withUnsafeMutableBytes<ReturnType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
return try Swift.withUnsafeMutableBytes(of: &self.blockBytes, body)
}
static func ^= (lhs: inout Block, rhs: Block) {
// Ideally we'd not use raw pointers for this.
lhs.withUnsafeMutableBytes { lhsPtr in
rhs.withUnsafeBytes { rhsPtr in
assert(lhsPtr.count == Self.blockSize)
assert(rhsPtr.count == Self.blockSize)
for index in 0..<Self.blockSize {
lhsPtr[index] ^= rhsPtr[index]
}
}
}
}
}
private static func isValidKey(_ key: SymmetricKey) -> Bool {
@@ -215,52 +144,3 @@ extension AES {
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension AES.Block: RandomAccessCollection, MutableCollection {
var startIndex: Int {
0
}
var endIndex: Int {
Self.blockSize
}
subscript(position: Int) -> UInt8 {
get {
precondition(position >= 0)
precondition(position < Self.blockSize)
return self.withUnsafeBytes { $0[position] }
}
set {
precondition(position >= 0)
precondition(position < Self.blockSize)
self.withUnsafeMutableBytes { $0[position] = newValue }
}
}
func withContiguousStorageIfAvailable<ReturnValue>(
_ body: (UnsafeBufferPointer<UInt8>) throws -> ReturnValue)
rethrows -> ReturnValue? {
return try withUnsafePointer(to: self.blockBytes) { tuplePtr in
// Homogeneous tuples are always bound to the element type as well as to their own type.
let retyped = UnsafeRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
let bufferised = UnsafeBufferPointer(start: retyped, count: Self.blockSize)
return try body(bufferised)
}
}
mutating func withContiguousMutableStorageIfAvailable<ReturnValue>(
_ body: (inout UnsafeMutableBufferPointer<UInt8>) throws -> ReturnValue)
rethrows -> ReturnValue? {
return try withUnsafeMutablePointer(to: &self.blockBytes) { tuplePtr in
// Homogeneous tuples are always bound to the element type as well as to their own type.
let retyped = UnsafeMutableRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
var bufferised = UnsafeMutableBufferPointer(start: retyped, count: Self.blockSize)
return try body(&bufferised)
}
}
}
@@ -0,0 +1,194 @@
//===----------------------------------------------------------------------===//
//
// 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 Crypto
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
@usableFromInline
enum OpenSSLAESCBCImpl {
private static let blockSize = 16
@usableFromInline
enum Direction {
case encrypt
case decrypt
@usableFromInline
var _boringSSLParameter: Int32 {
switch self {
case .encrypt: AES_ENCRYPT
case .decrypt: AES_DECRYPT
}
}
}
/// Encrypts plaintext using AES-CBC.
///
/// PKCS#7 padding is added unless `noPadding` is set, in which case the plaintext must
/// already be a whole number of blocks.
static func encrypt<Plaintext: DataProtocol>(
_ plaintext: Plaintext,
using key: SymmetricKey,
iv: AES._CBC.IV,
noPadding: Bool
) throws -> Data {
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
// With padding disabled the input must be a whole number of blocks.
if noPadding && (plaintext.count % Self.blockSize != 0) {
throw CryptoKitError.incorrectParameterSize
}
// AES_cbc_encrypt performs no padding, so PKCS#7 is applied here.
var padded = Data(plaintext)
if !noPadding {
// PKCS#7 always appends 1...blockSize bytes (a full block when already aligned).
let padLength = Self.blockSize - (plaintext.count % Self.blockSize)
let padding = repeatElement(UInt8(padLength), count: padLength)
padded.append(contentsOf: padding)
}
return padded.withUnsafeBytes { plaintextPtr in
Self._cipher(.encrypt, plaintextPtr, using: key, iv: iv)
}
}
/// Decrypts ciphertext using AES-CBC.
///
/// BoringSSL runs with padding disabled and, unless `noPadding` is set, PKCS#7 padding is
/// removed here in constant time. BoringSSL's own PKCS#7 removal is not constant-time (it is a
/// documented padding oracle absent authentication), so it must not be delegated.
static func decrypt<Ciphertext: DataProtocol>(
_ ciphertext: Ciphertext,
using key: SymmetricKey,
iv: AES._CBC.IV,
noPadding: Bool
) throws -> Data {
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
// CBC ciphertext is always a whole number of non-empty blocks.
guard ciphertext.count > 0, ciphertext.count % Self.blockSize == 0 else {
throw CryptoKitError.incorrectParameterSize
}
let contiguousCiphertext = Data(ciphertext)
let plaintext = contiguousCiphertext.withUnsafeBytes { ciphertextPtr in
Self._cipher(.decrypt, ciphertextPtr, using: key, iv: iv)
}
return noPadding ? plaintext : try plaintext.removingPKCS7PaddingConstantTime(blockSize: Self.blockSize)
}
/// Runs raw AES-CBC in the given direction over a single contiguous buffer.
///
/// `AES_cbc_encrypt` performs no padding, so `input` must be a whole number of blocks and the
/// output has the same length. PKCS#7 is applied and removed by the callers.
@usableFromInline
static func _cipher(
_ direction: Direction,
_ input: UnsafeRawBufferPointer,
using key: SymmetricKey,
iv: AES._CBC.IV
) -> Data {
precondition(input.count % Self.blockSize == 0)
var output = Data(count: input.count)
var iv = iv
key.withUnsafeBytes { keyPtr in
// AES_cbc_encrypt advances the IV in place, so operate on our own copy.
iv.withUnsafeMutableBytes { ivPtr in
var key = AES_KEY()
switch direction {
case .encrypt:
precondition(
CCryptoBoringSSL_AES_set_encrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key) == 0
)
case .decrypt:
precondition(
CCryptoBoringSSL_AES_set_decrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key) == 0
)
}
output.withUnsafeMutableBytes { outputPtr in
CCryptoBoringSSL_AES_cbc_encrypt(
input.baseAddress,
outputPtr.baseAddress,
input.count,
&key,
ivPtr.baseAddress,
direction._boringSSLParameter
)
}
}
}
return output
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension Data {
/// Removes PKCS#7 padding in constant time with respect to the padding bytes.
fileprivate func removingPKCS7PaddingConstantTime(blockSize: Int = 16) throws -> Data {
// The total length is not secret, so branching on it is safe.
guard self.count >= blockSize, self.count % blockSize == 0 else {
throw CryptoKitError.incorrectParameterSize
}
let padLength = self.last!
let lastBlock = self.suffix(blockSize)
// Validate padding in constant time.
var bad: UInt32 = 0
// A valid PKCS#7 pad length is 1...blockSize.
bad |= constantTimeLessThanOrEqual(padLength, 0)
bad |= constantTimeLessThanOrEqual(UInt8(blockSize + 1), padLength)
// We MUST operate on every byte in the block, and each byte in the padding region MUST equal `padLength`.
for index in lastBlock.indices {
let byte = UInt32(lastBlock[index])
let distanceFromEnd = self.endIndex - index
let inPadding = constantTimeLessThanOrEqual(UInt8(distanceFromEnd), padLength)
bad |= inPadding & (byte ^ UInt32(padLength))
}
// Throw if padding was invalid.
guard bad == 0 else {
throw CryptoKitError.incorrectParameterSize
}
// Drop the padding.
return self.dropLast(Int(padLength))
}
}
/// Returns `0xFFFFFFFF` if `lhs <= rhs`, otherwise `0`, without a data-dependent branch.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
private func constantTimeLessThanOrEqual(_ lhs: UInt8, _ rhs: UInt8) -> UInt32 {
// `lhs - rhs - 1` is negative iff `lhs <= rhs`; propagate its sign bit across the word.
let difference = Int32(lhs) - Int32(rhs) - 1
return UInt32(bitPattern: difference >> 31)
}
@@ -19,10 +19,8 @@ import CryptoBoringWrapper
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
-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")
+4 -4
View File
@@ -18,6 +18,7 @@ add_library(CryptoExtras
"AES/AES_CTR.swift"
"AES/AES_GCM_SIV.swift"
"AES/Block Function.swift"
"AES/BoringSSL/AES_CBC_boring.swift"
"AES/BoringSSL/AES_CFB_boring.swift"
"AES/BoringSSL/AES_CTR_boring.swift"
"AES/BoringSSL/AES_GCM_SIV_boring.swift"
@@ -77,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"
@@ -86,15 +88,13 @@ add_library(CryptoExtras
target_compile_options(CryptoExtras PRIVATE -DCRYPTO_IN_SWIFTPM)
target_include_directories(CryptoExtras PRIVATE
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CCryptoBoringSSLShims,INCLUDE_DIRECTORIES>)
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>)
target_link_libraries(CryptoExtras PUBLIC
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
Crypto
CryptoBoringWrapper
CCryptoBoringSSL
CCryptoBoringSSLShims)
CCryptoBoringSSL)
target_compile_options(CryptoExtras PRIVATE ${SWIFT_CRYPTO_COMPILE_OPTIONS})
@@ -17,10 +17,8 @@ import CryptoBoringWrapper
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
@@ -72,22 +70,15 @@ enum OpenSSLChaCha20CTRImpl {
key.withUnsafeBytes { keyPtr in
nonce.withUnsafeBytes { noncePtr in
message.withUnsafeBytes { plaintextPtr in
// We bind all three pointers here. These binds are not technically safe, but because we
// know the pointers don't persist they can't violate the aliasing rules. We really
// want a "with memory rebound" function but we don't have it yet.
let keyBytes = keyPtr.bindMemory(to: UInt8.self)
let nonceBytes = noncePtr.bindMemory(to: UInt8.self)
let plaintext = plaintextPtr.bindMemory(to: UInt8.self)
var ciphertext = Data(repeating: 0, count: plaintext.count)
var ciphertext = Data(repeating: 0, count: plaintextPtr.count)
ciphertext.withUnsafeMutableBytes { ciphertext in
CCryptoBoringSSL_CRYPTO_chacha_20(
ciphertext.baseAddress,
plaintext.baseAddress,
plaintext.count,
keyBytes.baseAddress,
nonceBytes.baseAddress,
plaintextPtr.baseAddress,
plaintextPtr.count,
keyPtr.baseAddress,
noncePtr.baseAddress,
counter
)
}
@@ -14,10 +14,8 @@
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import Crypto
import CryptoBoringWrapper
@@ -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)
}
}
@@ -161,7 +161,7 @@ struct OpenSSLGroupScalar<C: OpenSSLSupportedNISTCurve>: GroupScalar, CustomStri
/// Deserializes a scalar from data.
/// - Parameters:
/// - data: The serialized scalar
/// - bytes: The serialized scalar
/// - reductionIsModOrder: Resulting number is taken "mod q" (characteristic) by default. Override by setting true if "mod p" (order) is desired.
/// - Returns: The deserialized scalar
init(bytes: Data, reductionIsModOrder: Bool = false) throws {
@@ -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)
}
@@ -22,10 +22,8 @@ import Foundation
#if !canImport(CommonCrypto)
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
@@ -45,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)
@@ -16,10 +16,8 @@ import Crypto
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
@@ -83,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)
@@ -104,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
@@ -105,9 +105,15 @@ extension _RSA.BlindSigning {
}
/// Construct a RSA public key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes, parameters: Parameters) throws {
self.backing = try BackingPublicKey(n: n, e: e)
self.parameters = parameters
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
public var pkcs1DERRepresentation: Data {
@@ -206,9 +212,15 @@ extension _RSA.BlindSigning {
}
/// Construct an RSA private key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes, parameters: Parameters) throws {
self.backing = try BackingPrivateKey(n: n, e: e, d: d, p: p, q: q)
self.parameters = parameters
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
/// Randomly generate a new RSA private key of a given size.
+68 -15
View File
@@ -117,8 +117,14 @@ extension _RSA.Signing {
}
/// Construct an RSA public key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.backing = try BackingPublicKey(n: n, e: e)
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
public var pkcs1DERRepresentation: Data {
@@ -248,8 +254,14 @@ extension _RSA.Signing {
}
/// Construct an RSA private key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes) throws {
self.backing = try BackingPrivateKey(n: n, e: e, d: d, p: p, q: q)
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
/// Randomly generate a new RSA private key of a given size.
@@ -518,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
@@ -535,6 +547,7 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
public init(pemRepresentation: String) throws {
self.backing = try BackingPublicKey(pemRepresentation: pemRepresentation)
guard self.keySizeInBits >= 2048, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
@@ -544,6 +557,7 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 1024 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
/// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons.
public init(unsafePEMRepresentation pemRepresentation: String) throws {
self.backing = try BackingPublicKey(pemRepresentation: pemRepresentation)
@@ -554,6 +568,7 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
public init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
self.backing = try BackingPublicKey(derRepresentation: derRepresentation)
guard self.keySizeInBits >= 2048, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
@@ -563,6 +578,7 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 1024 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
/// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons.
public init<Bytes: DataProtocol>(unsafeDERRepresentation derRepresentation: Bytes) throws {
self.backing = try BackingPublicKey(derRepresentation: derRepresentation)
@@ -570,8 +586,14 @@ extension _RSA.Encryption {
}
/// Construct an RSA public key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.backing = try BackingPublicKey(n: n, e: e)
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
public var pkcs1DERRepresentation: Data { self.backing.pkcs1DERRepresentation }
@@ -579,6 +601,7 @@ extension _RSA.Encryption {
public var derRepresentation: Data { self.backing.derRepresentation }
public var pemRepresentation: String { self.backing.pemRepresentation }
public var keySizeInBits: Int { self.backing.keySizeInBits }
internal var modulusByteCount: Int { self.backing.modulusByteCount }
fileprivate init(_ backing: BackingPublicKey) { self.backing = backing }
public func getKeyPrimitives() throws -> Primitives {
@@ -589,13 +612,14 @@ 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.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
public init(pemRepresentation: String) throws {
self.backing = try BackingPrivateKey(pemRepresentation: pemRepresentation)
guard self.keySizeInBits >= 2048, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
@@ -605,6 +629,7 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 1024 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
/// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons.
public init(unsafePEMRepresentation pemRepresentation: String) throws {
self.backing = try BackingPrivateKey(pemRepresentation: pemRepresentation)
@@ -615,6 +640,7 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
public init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
self.backing = try BackingPrivateKey(derRepresentation: derRepresentation)
guard self.keySizeInBits >= 2048, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
@@ -624,6 +650,7 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 1024 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
/// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons.
public init<Bytes: DataProtocol>(unsafeDERRepresentation derRepresentation: Bytes) throws {
self.backing = try BackingPrivateKey(derRepresentation: derRepresentation)
@@ -632,8 +659,14 @@ extension _RSA.Encryption {
/// Construct an RSA private key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes) throws {
self.backing = try BackingPrivateKey(n: n, e: e, d: d, p: p, q: q)
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
/// Randomly generate a new RSA private key of a given size.
@@ -741,8 +774,8 @@ extension _RSA.Encryption {
extension _RSA.Encryption.PrivateKey {
/// Decrypt a message encrypted with this key's public key and using the specified padding mode.
///
/// > Important: The size of the data to decrypt must be equal to the block size of the key (e.g.
/// `keySizeInBits / 8`). Attempting to decrypt data of the wrong size will fail.
/// > Important: The size of the data to decrypt must be equal to the block size of the key.
/// Attempting to decrypt data of the wrong size will fail.
public func decrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
return try self.backing.decrypt(data, padding: padding)
}
@@ -764,17 +797,17 @@ extension _RSA.Encryption.PublicKey {
switch padding.backing {
case ._weakAndInsecure_pkcs1v1_5:
// https://www.rfc-editor.org/rfc/rfc8017#section-7.2
return (self.keySizeInBits / 8) - 11
return self.modulusByteCount - 11
case let .pkcs1_oaep(Digest):
// https://datatracker.ietf.org/doc/html/rfc8017#section-7.1.1
return (self.keySizeInBits / 8) - (2 * Digest.hashBitLength / 8) - 2
return self.modulusByteCount - (2 * Digest.hashBitLength / 8) - 2
}
}
/// Encrypt a message with this key, using the specified padding mode.
///
/// > Important: The size of the data to encrypt _must_ not exceed the modulus of the key (e.g.
/// `keySizeInBits / 8`), minus any additional space required by the padding mode. Attempting to
/// > Important: The size of the data to encrypt _must_ not exceed the block size of the key,
/// minus any additional space required by the padding mode. Attempting to
/// encrypt data larger than this will fail. Use ``maximumEncryptSize(with:)`` to determine
/// exactly how many bytes can be encrypted by the key.
public func encrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
@@ -801,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 {
@@ -844,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
+45 -45
View File
@@ -18,10 +18,8 @@ import CryptoBoringWrapper
// NOTE: This file is unconditionally compiled because RSABSSA is implemented using BoringSSL on all platforms.
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
@@ -83,6 +81,10 @@ internal struct BoringSSLRSAPublicKey: Sendable {
self.backing.keySizeInBits
}
var modulusByteCount: Int {
self.backing.modulusByteCount
}
fileprivate init(_ backing: Backing) {
self.backing = backing
}
@@ -228,17 +230,17 @@ extension BoringSSLRSAPublicKey {
self.pointer = pointer
}
fileprivate init(copying other: Backing) {
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
fileprivate convenience init(copying other: Backing) {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
let rsaPublicKey = CCryptoBoringSSL_RSAPublicKey_dup(
CCryptoBoringSSL_EVP_PKEY_get0_RSA(other.pointer)
)
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
}
fileprivate init(pemRepresentation: String) throws {
fileprivate convenience init(pemRepresentation: String) throws {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
var pemRepresentation = pemRepresentation
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
// There are two encodings for RSA public keys: PKCS#1 and the SPKI form.
// The SPKI form is what we support for EC keys, so we try that first, then we
@@ -254,20 +256,15 @@ extension BoringSSLRSAPublicKey {
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
do {
let rsaPublicKey = try pemRepresentation.withUTF8 { utf8Ptr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPublicKey(bio, nil, nil, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
let rsaPublicKey = try pemRepresentation.withUTF8 { utf8Ptr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPublicKey(bio, nil, nil, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
CCryptoBoringSSL_EVP_PKEY_free(self.pointer)
throw error
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
}
}
@@ -280,8 +277,8 @@ extension BoringSSLRSAPublicKey {
}
}
private init<Bytes: ContiguousBytes>(contiguousDerRepresentation: Bytes) throws {
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
private convenience init<Bytes: ContiguousBytes>(contiguousDerRepresentation: Bytes) throws {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
// There are two encodings for RSA public keys: PKCS#1 and the SPKI form.
// The SPKI form is what we support for EC keys, so we try that first, then we
// fall back to the PKCS#1 form if that parse fails.
@@ -296,25 +293,20 @@ extension BoringSSLRSAPublicKey {
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
do {
let rsaPublicKey = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
guard let key = CCryptoBoringSSL_d2i_RSAPublicKey_bio(bio, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
let rsaPublicKey = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
guard let key = CCryptoBoringSSL_d2i_RSAPublicKey_bio(bio, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
CCryptoBoringSSL_EVP_PKEY_free(self.pointer)
throw error
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
}
}
fileprivate init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
fileprivate convenience init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
let n = try ArbitraryPrecisionInteger(bytes: n)
let e = try ArbitraryPrecisionInteger(bytes: e)
@@ -361,7 +353,12 @@ extension BoringSSLRSAPublicKey {
fileprivate var keySizeInBits: Int {
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
return Int(CCryptoBoringSSL_RSA_size(rsaPublicKey)) * 8
return Int(CCryptoBoringSSL_RSA_bits(rsaPublicKey))
}
fileprivate var modulusByteCount: Int {
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
return Int(CCryptoBoringSSL_RSA_size(rsaPublicKey))
}
fileprivate func isValidSignature<D: Digest>(
@@ -376,7 +373,7 @@ extension BoringSSLRSAPublicKey {
let rc: CInt = digest.withUnsafeBytes { digestPtr in
switch padding.backing {
case .pkcs1v1_5:
return CCryptoBoringSSLShims_RSA_verify(
return CCryptoBoringSSL_RSA_verify(
hashDigestType.nid,
digestPtr.baseAddress,
digestPtr.count,
@@ -385,7 +382,7 @@ extension BoringSSLRSAPublicKey {
rsaPublicKey
)
case .pss:
return CCryptoBoringSSLShims_RSA_verify_pss_mgf1(
return CCryptoBoringSSL_RSA_verify_pss_mgf1(
rsaPublicKey,
digestPtr.baseAddress,
digestPtr.count,
@@ -396,7 +393,7 @@ extension BoringSSLRSAPublicKey {
signaturePtr.count
)
case .pssZero:
return CCryptoBoringSSLShims_RSA_verify_pss_mgf1(
return CCryptoBoringSSL_RSA_verify_pss_mgf1(
rsaPublicKey,
digestPtr.baseAddress,
digestPtr.count,
@@ -448,7 +445,7 @@ extension BoringSSLRSAPublicKey {
}
var writtenLength = bufferPtr.count
let rc = CCryptoBoringSSLShims_EVP_PKEY_encrypt(
let rc = CCryptoBoringSSL_EVP_PKEY_encrypt(
ctx,
bufferPtr.baseAddress,
&writtenLength,
@@ -473,7 +470,6 @@ extension BoringSSLRSAPublicKey {
parameters: _RSA.BlindSigning.Parameters<H>
) throws -> _RSA.BlindSigning.BlindingResult {
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
let modulusByteCount = Int(CCryptoBoringSSL_RSA_size(rsaPublicKey))
let e = try ArbitraryPrecisionInteger(copying: CCryptoBoringSSL_RSA_get0_e(rsaPublicKey))
let n = try ArbitraryPrecisionInteger(copying: CCryptoBoringSSL_RSA_get0_n(rsaPublicKey))
let finiteField = try FiniteFieldArithmeticContext(fieldSize: n)
@@ -531,7 +527,6 @@ extension BoringSSLRSAPublicKey {
parameters: _RSA.BlindSigning.Parameters<H>
) throws -> _RSA.Signing.RSASignature {
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
let modulusByteCount = Int(CCryptoBoringSSL_RSA_size(rsaPublicKey))
let n = try ArbitraryPrecisionInteger(copying: CCryptoBoringSSL_RSA_get0_n(rsaPublicKey))
let finiteField = try FiniteFieldArithmeticContext(fieldSize: n)
@@ -831,7 +826,7 @@ extension BoringSSLRSAPrivateKey {
fileprivate var keySizeInBits: Int {
let rsaPrivateKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
return Int(CCryptoBoringSSL_RSA_size(rsaPrivateKey)) * 8
return Int(CCryptoBoringSSL_RSA_bits(rsaPrivateKey))
}
fileprivate var publicKey: BoringSSLRSAPublicKey {
@@ -863,10 +858,10 @@ extension BoringSSLRSAPrivateKey {
switch padding.backing {
case .pkcs1v1_5:
var writtenLength = CUnsignedInt(0)
let rc = CCryptoBoringSSLShims_RSA_sign(
let rc = CCryptoBoringSSL_RSA_sign(
hashDigestType.nid,
digestPtr.baseAddress,
CUnsignedInt(digestPtr.count),
digestPtr.count,
bufferPtr.baseAddress,
&writtenLength,
rsaPrivateKey
@@ -874,7 +869,7 @@ extension BoringSSLRSAPrivateKey {
outputLength = Int(writtenLength)
return rc
case .pss:
return CCryptoBoringSSLShims_RSA_sign_pss_mgf1(
return CCryptoBoringSSL_RSA_sign_pss_mgf1(
rsaPrivateKey,
&outputLength,
bufferPtr.baseAddress,
@@ -886,7 +881,7 @@ extension BoringSSLRSAPrivateKey {
CInt(hashDigestType.digestLength)
)
case .pssZero:
return CCryptoBoringSSLShims_RSA_sign_pss_mgf1(
return CCryptoBoringSSL_RSA_sign_pss_mgf1(
rsaPrivateKey,
&outputLength,
bufferPtr.baseAddress,
@@ -943,7 +938,7 @@ extension BoringSSLRSAPrivateKey {
var writtenLength = bufferPtr.count
let rc = CCryptoBoringSSLShims_EVP_PKEY_decrypt(
let rc = CCryptoBoringSSL_EVP_PKEY_decrypt(
ctx,
bufferPtr.baseAddress,
&writtenLength,
@@ -1136,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)
}
@@ -15,10 +15,8 @@
// NOTE: This file is unconditionally compiled because RSABSSA is implemented using BoringSSL on all platforms.
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
@@ -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
}
@@ -29,7 +29,7 @@ final class ThreadSpecificVariable<Value: AnyObject> {
// the actual type in there is `Box<(ThreadSpecificVariable<T>, T)>` but we can't use that as C functions can't capture (even types)
private typealias BoxedType = Box<(AnyObject, AnyObject)>
private class Key {
private final class Key {
private var underlyingKey: ThreadOpsSystem.ThreadSpecificKey
internal init(destructor: @escaping ThreadOpsSystem.ThreadSpecificKeyDestructor) {
@@ -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)
}
}
+6 -6
View File
@@ -24,7 +24,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 32)
let result = input.withUnsafeBytes { inputBytes in
SHA3_256(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
SHA3_256(&output, inputBytes.baseAddress, inputBytes.count)
}
// Should return 0 on success
@@ -43,7 +43,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 28)
let result = input.withUnsafeBytes { inputBytes in
SHA3_224(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
SHA3_224(&output, inputBytes.baseAddress, inputBytes.count)
}
// Should return 0 on success
@@ -62,7 +62,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 48)
let result = input.withUnsafeBytes { inputBytes in
SHA3_384(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
SHA3_384(&output, inputBytes.baseAddress, inputBytes.count)
}
// Should return 0 on success
@@ -82,7 +82,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 64)
let result = input.withUnsafeBytes { inputBytes in
SHA3_512(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
SHA3_512(&output, inputBytes.baseAddress, inputBytes.count)
}
// Should return 0 on success
@@ -102,7 +102,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 32) // 256 bits output
let result = input.withUnsafeBytes { inputBytes in
SHAKE128(&output, output.count, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
SHAKE128(&output, output.count, inputBytes.baseAddress, inputBytes.count)
}
// Should return 0 on success
@@ -121,7 +121,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 32) // 256 bits output
let result = input.withUnsafeBytes { inputBytes in
SHAKE256(&output, output.count, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
SHAKE256(&output, output.count, inputBytes.baseAddress, inputBytes.count)
}
// Should return 0 on success
@@ -163,6 +163,85 @@ final class CBCTests: XCTestCase {
}
}
func testDecryptRejectsPaddingLengthGreaterThanBlockSize() throws {
// A plaintext whose final block claims a PKCS#7 pad length of 17 (0x11)
// is invalid for a 16-byte block: the maximum valid PKCS#7 pad is one
// full block (16). Correct unpadding must reject it. Regression guard:
// the previous `trimPadding` accepted any pad length up to 255 and
// scanned across blocks, so it wrongly stripped 17 bytes here.
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// 32-byte (block-multiple) plaintext ending in 17 bytes of 0x11.
var plaintext = Data(repeating: 0xAB, count: 15)
plaintext.append(Data(repeating: 0x11, count: 17))
precondition(plaintext.count == 32)
let ciphertext = try AES._CBC.encrypt(plaintext, using: key, iv: iv, noPadding: true)
XCTAssertThrowsError(
try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false)
) { error in
guard let error = error as? CryptoKitError, case .incorrectParameterSize = error else {
XCTFail("Unexpected error: \(error)")
return
}
}
}
func testUnpadAcceptsAllValidPaddingLengths() throws {
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// For every valid PKCS#7 pad length (1...16), round-trip a message that
// pads to exactly that length and assert exact recovery.
for padLength in 1...16 {
let messageLength = 32 - padLength // pads to 32 bytes (two blocks)
let message = Data((0..<messageLength).map { UInt8(truncatingIfNeeded: $0) })
let ciphertext = try AES._CBC.encrypt(message, using: key, iv: iv, noPadding: false)
let decrypted = try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false)
XCTAssertEqual(decrypted, message, "round-trip failed for pad length \(padLength)")
}
}
func testUnpadRejectsCorruptedPaddingByte() throws {
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// Build a validly-padded block-multiple plaintext, then corrupt each
// padding byte except the last (which encodes the claimed length). The
// constant-time scan must reject a mismatch at any position.
for padLength in 2...16 {
var padded = Data((0..<(32 - padLength)).map { UInt8(truncatingIfNeeded: $0) })
padded.append(Data(repeating: UInt8(padLength), count: padLength))
precondition(padded.count == 32)
for position in (32 - padLength)..<31 {
var corrupted = padded
corrupted[position] = UInt8(padLength) ^ 0xFF // guaranteed != padLength
let ciphertext = try AES._CBC.encrypt(corrupted, using: key, iv: iv, noPadding: true)
XCTAssertThrowsError(
try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false),
"corruption at pad length \(padLength), position \(position) was not rejected"
)
}
}
}
func testUnpadRejectsZeroPaddingLength() throws {
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// A final byte of 0x00 claims a pad length of zero, which is invalid PKCS#7.
var padded = Data((0..<31).map { UInt8(truncatingIfNeeded: $0) })
padded.append(0x00)
let ciphertext = try AES._CBC.encrypt(padded, using: key, iv: iv, noPadding: true)
XCTAssertThrowsError(try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false))
}
func testToDataConversion() throws {
let randomBytes = (0..<16).map { _ in UInt8.random(in: UInt8.min...UInt8.max) }
let dataIn = Data(randomBytes)
@@ -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
)
)
}
}
}
@@ -201,6 +201,17 @@ final class TestRSABlindSigning: XCTestCase {
e: bytesValues.randomElement()!,
parameters: .RSABSSA_SHA384_PSS_Randomized
)
// Modulus of a 512-bit key: `openssl rsa -in key.pem -noout -modulus`.
let _512BitModulus =
"e24c4c2c70e673315c2420b0e211542bbccf5b79f2ce6bdaa4aac29650bd064b"
+ "955ae1613a449c7143e906d7f251e49356771d9d6f8f15bcf4044f87de1c1bed"
XCTAssertThrowsError(
try _RSA.BlindSigning.PublicKey(
n: Data(hexString: _512BitModulus),
e: Data(hexString: "010001"),
parameters: .RSABSSA_SHA384_PSS_Randomized
)
)
}
func testConstructAndUseKeyFromRSANumbersWhileRecoveringPrimes() throws {
@@ -111,6 +111,13 @@ final class TestRSAEncryption: XCTestCase {
n: bytesValues.randomElement()!,
e: bytesValues.randomElement()!
)
// Modulus of a 512-bit key: `openssl rsa -in key.pem -noout -modulus`.
let _512BitModulus =
"e24c4c2c70e673315c2420b0e211542bbccf5b79f2ce6bdaa4aac29650bd064b"
+ "955ae1613a449c7143e906d7f251e49356771d9d6f8f15bcf4044f87de1c1bed"
XCTAssertThrowsError(
try _RSA.Encryption.PublicKey(n: Data(hexString: _512BitModulus), e: Data(hexString: "010001"))
)
}
func testConstructAndUseKeyFromRSANumbersWhileRecoveringPrimes() throws {
@@ -170,6 +177,84 @@ final class TestRSAEncryption: XCTestCase {
XCTAssertEqual(190, pubKey2048.maximumEncryptSize(with: .PKCS1_OAEP_SHA256))
}
// The encryption key initializers require the modulus bit length to be a multiple of 8.
func testRejectKeysWithNonByteAlignedModulus() throws {
// Equivalent key: `openssl genrsa -traditional 2050`, converted to the encodings below.
let _2050BitRSAPrivateKeyPEM = """
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQECxVSlteS7/eN5dXzn+RdyApV8JJILQaXaZOgxl/FELWhXq4lY
Uk6+0keFtdLvSsdsBAZlq7VT8vHyfxqhcpb0RkjThWfVhR2BjzO8TNLA+mlKGKZJ
foTE3r7o99Ev4X+H4QxCyAC8oyAKy1lyDA4wT7OFBBXtXJmeQ/PbYCuMMyqrCWUg
VL48rK150QxHQ0U9XsGCnF70X/PMPebKY60OS36pTYhmi77h0maiY4yW2kHNfgeG
Mbc3XQ19Sr42f5zKe0AIQfzK91v6M5PaEIpJAfm+JPDNWf2+RKEVa93gNiuTZ2+p
gUjf7ut8mY5MEn7fZhCeZeNBjNTuKXj3JqdP3wIDAQABAoIBAQC252vPakq7XeOc
0vdx+ISye99GAs6aP+z/pgvbtR+yYbxxg/ndR2bXDBBDYT/I1YFZzFh9HUWnWJIC
CljlFl2onfDE7pBVQdV9moaMfK+8Ilgz4PUEhbHKCgpClJM3H05nTmUN83qwyXtf
EhJhX2s/sfezpP/Op+HyfbfspW4CZrrJmv1zfqIjDiV7LMaoDDU+UDHexcgwoXCa
HKC/U7RcbNYE3hOg/Fjx+nevprXthhf8mpnkAzTcpXsMcATuvh7sSqdFnHkF9egw
CBnlx+iH9J/6Q3VwoZgwggi9S6qT5yrS0/JVWVic4KaiE81dDr+KLmXIpOFRNuYf
8sP79cfRAoGBAcwBZ+XfX5H8Ii7tSjCJWJ+sw6cevH4YQhYWDEgodsmzj2hDRoRj
EaGdATP5dry7RWePTuhN0KlvMYX/xI2kvoRrK6sR4bad0V2J8lKBFxAil55w531L
wZUAhxzAChWZ6uRMR694yati/8wIG+BMdwBPA+00+pMH2Kd9HGN8xoBHAoGBAYrA
0sfOCNqvkf7OsoiShjSdeTYkTqjHrVR7m6DJg2FUL6E9VnaSLG0esnAYGAozKfFl
rQz7gEGckMG2dILOAY9z3wv4ltX12RxmAJMHoO/ENDVxiqSKC7utiKzcii9qy626
RIuAvOwSOeU25VVTOzOm35wabuLAThMYBqdYl9epAoGAYsWKgZlM9BOnY1wgKfvT
w7Vc7W10G78psYRabsQBfZ3IlSKc6aA8EO+daoOOM0gixvHGh6rtuvPdNmCM270c
C2LXpYvZY1TPt73/Aiglw5kp5SNpEUZK8quCV3IEuE6sWQjn+418AAjp0+2Jzsec
ZbyRo0VU6G0u4AfFKLeKB9ECgYAURk8NIBHoWXggJDGbPhtSfHwLQdYgaREH88lM
es0apJ5Fo8bbFCrf9+GmTDZ/35zZ3yUCM7CkrgvpRxu41CfUXFkqXjwxBQ1/neWN
p6imZ+dej1RVmxl7LDCG4FTglpWbeKOonpYVceIzWZxxw3KY9ospk1n6n3HjHSrK
UYyK8QKBgQDWsxq+0VhPgMRDUKg2p1gdnluX9I5lmZVwy1No6QfChJUo/RCRYcIe
jLXlpoAW9UUR5JCx3/hKyKvbl34J/LV3Tc/63vHxOGnh8eAySyCcpFJFmyciIZdY
iRLB6wzq+zLIZkK7+5TdHCZ9jIi5oKyk2YDT6LSTUnuG9DlGpcSmqA==
-----END RSA PRIVATE KEY-----
"""
let _2050BitRSAPublicKeyPEM = """
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQECxVSlteS7/eN5dXzn+Rdy
ApV8JJILQaXaZOgxl/FELWhXq4lYUk6+0keFtdLvSsdsBAZlq7VT8vHyfxqhcpb0
RkjThWfVhR2BjzO8TNLA+mlKGKZJfoTE3r7o99Ev4X+H4QxCyAC8oyAKy1lyDA4w
T7OFBBXtXJmeQ/PbYCuMMyqrCWUgVL48rK150QxHQ0U9XsGCnF70X/PMPebKY60O
S36pTYhmi77h0maiY4yW2kHNfgeGMbc3XQ19Sr42f5zKe0AIQfzK91v6M5PaEIpJ
Afm+JPDNWf2+RKEVa93gNiuTZ2+pgUjf7ut8mY5MEn7fZhCeZeNBjNTuKXj3JqdP
3wIDAQAB
-----END PUBLIC KEY-----
"""
XCTAssertThrowsError(try _RSA.Encryption.PrivateKey(pemRepresentation: _2050BitRSAPrivateKeyPEM))
XCTAssertThrowsError(try _RSA.Encryption.PrivateKey(unsafePEMRepresentation: _2050BitRSAPrivateKeyPEM))
XCTAssertThrowsError(try _RSA.Encryption.PublicKey(pemRepresentation: _2050BitRSAPublicKeyPEM))
XCTAssertThrowsError(try _RSA.Encryption.PublicKey(unsafePEMRepresentation: _2050BitRSAPublicKeyPEM))
}
// The raw number encryption key initializers do not require the key modulus bit length to be a multiple of 8.
func testMaximumEncryptSizeWithNonByteAlignedModulus() throws {
// Modulus of a 2050-bit key: `openssl rsa -in key.pem -noout -modulus`.
let _2050BitModulus = Data(
base64Encoded:
"AsVUpbXku/3jeXV85/kXcgKVfCSSC0Gl2mToMZfxRC1oV6uJWFJOvtJHhbX" +
"S70rHbAQGZau1U/Lx8n8aoXKW9EZI04Vn1YUdgY8zvEzSwPppShimSX6ExN" +
"6+6PfRL+F/h+EMQsgAvKMgCstZcgwOME+zhQQV7VyZnkPz22ArjDMqqwllI" +
"FS+PKytedEMR0NFPV7Bgpxe9F/zzD3mymOtDkt+qU2IZou+4dJmomOMltpB" +
"zX4HhjG3N10NfUq+Nn+cyntACEH8yvdb+jOT2hCKSQH5viTwzVn9vkShFWv" +
"d4DYrk2dvqYFI3+7rfJmOTBJ+32YQnmXjQYzU7il49yanT98="
)!
let publicExponent = Data(base64Encoded: "AQAB")!
let publicKey = try _RSA.Encryption.PublicKey(n: _2050BitModulus, e: publicExponent)
XCTAssertEqual(2050, publicKey.keySizeInBits)
XCTAssertEqual(215, publicKey.maximumEncryptSize(with: .PKCS1_OAEP))
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-----
+373 -19
View File
@@ -361,8 +361,10 @@ final class TestRSASigning: XCTestCase {
try XCTAssertThrowsError((_RSA.Signing.PrivateKey(keySize: .init(bitCount: 1024)), 1024))
}
func testRejectSmallKeys() throws {
let smallRSAPrivateKeyPEM = """
// The default initializers require a modulus of at least 2048 bits.
func testRejectKeysBelow2048BitMinimum() throws {
// Equivalent key: `openssl genrsa -traditional 512`, converted to the encodings below.
let _512BitRSAPrivateKeyPEM = """
-----BEGIN RSA PRIVATE KEY-----
MIIBPAIBAAJBAOJMTCxw5nMxXCQgsOIRVCu8z1t58s5r2qSqwpZQvQZLlVrhYTpE
nHFD6QbX8lHkk1Z3HZ1vjxW89ARPh94cG+0CAwEAAQJBAMdmOVyTYswvuyPuVk3s
@@ -374,14 +376,14 @@ final class TestRSASigning: XCTestCase {
-----END RSA PRIVATE KEY-----
"""
let smallRSAPublicKeyPEM = """
let _512BitRSAPublicKeyPEM = """
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOJMTCxw5nMxXCQgsOIRVCu8z1t58s5r
2qSqwpZQvQZLlVrhYTpEnHFD6QbX8lHkk1Z3HZ1vjxW89ARPh94cG+0CAwEAAQ==
-----END PUBLIC KEY-----
"""
let smallRSAPrivateKeyPKCS8PEM = """
let _512BitRSAPrivateKeyPKCS8PEM = """
-----BEGIN PRIVATE KEY-----
MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA4kxMLHDmczFcJCCw
4hFUK7zPW3nyzmvapKrCllC9BkuVWuFhOkSccUPpBtfyUeSTVncdnW+PFbz0BE+H
@@ -394,7 +396,7 @@ final class TestRSASigning: XCTestCase {
-----END PRIVATE KEY-----
"""
let smallRSAPrivateKeyDER = Data(base64Encoded:
let _512BitRSAPrivateKeyDER = Data(base64Encoded:
"MIIBPAIBAAJBAOJMTCxw5nMxXCQgsOIRVCu8z1t58s5r2qSqwpZQvQZLlVr" +
"hYTpEnHFD6QbX8lHkk1Z3HZ1vjxW89ARPh94cG+0CAwEAAQJBAMdmOVyTYs" +
"wvuyPuVk3svQEJDqFpFATFTlP4TxuKKvTmbdQuVCorMmLLKThDI3pDNWKuA" +
@@ -405,7 +407,7 @@ final class TestRSASigning: XCTestCase {
"7MWbrFpUouirbQ="
)!
let smallRSAPrivateKeyPKCS8DER = Data(base64Encoded:
let _512BitRSAPrivateKeyPKCS8DER = Data(base64Encoded:
"MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA4kxMLHDmczF" +
"cJCCw4hFUK7zPW3nyzmvapKrCllC9BkuVWuFhOkSccUPpBtfyUeSTVncdnW" +
"+PFbz0BE+H3hwb7QIDAQABAkEAx2Y5XJNizC+7I+5WTey9AQkOoWkUBMVOU" +
@@ -416,18 +418,282 @@ final class TestRSASigning: XCTestCase {
"w8CIQCNHhOCOnp3lmwZQr0gcaw1Y/XJKtqDsxZusWlSi6KttA=="
)!
let smallRSAPublicKeyDER = Data(base64Encoded:
let _512BitRSAPublicKeyDER = Data(base64Encoded:
"MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOJMTCxw5nMxXCQgsOIRVCu8z1t" +
"58s5r2qSqwpZQvQZLlVrhYTpEnHFD6QbX8lHkk1Z3HZ1vjxW89ARPh94cG+" +
"0CAwEAAQ=="
)!
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: smallRSAPrivateKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: smallRSAPrivateKeyPKCS8PEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: smallRSAPrivateKeyDER))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: smallRSAPrivateKeyPKCS8DER))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(pemRepresentation: smallRSAPublicKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(derRepresentation: smallRSAPublicKeyDER))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: _512BitRSAPrivateKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: _512BitRSAPrivateKeyPKCS8PEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: _512BitRSAPrivateKeyDER))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: _512BitRSAPrivateKeyPKCS8DER))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(pemRepresentation: _512BitRSAPublicKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(derRepresentation: _512BitRSAPublicKeyDER))
// Generated via `openssl genrsa -traditional 2047`, then converted to the encodings below.
let _2047BitRSAPrivateKeyPEM = """
-----BEGIN RSA PRIVATE KEY-----
MIIEoAIBAAKCAQBXog86uwpuCobeXXokHAePMu15O2Cwfvwx7/EzZl6jY70ConNX
mzR5U39kQQpFa0dxRQdgUA8YpU5/8aILp3Yv0S2BssiuqdL5IkzdBzLNRhSQabuM
+vyCQjImHF/bA28+5DKJ9uzIhywA9JS2o/4TtE6mLqWbFAY+dM716llarKJgzLh/
Vg0mH6H5vDoo4D6z+M2jQRiUbV+yIiiaY8/SMyLltsZeEl/hx/NyACPSUAClVlsj
vRRZzQl8oDybMVvUAbrIwR+ZVQltdqVgx5zVf8G3BHi7lUdyqxIt0QWQRBTTd1tY
sSOKmVhYB+DvPv2IJKGXqKo+XKQBLmm9UIuxAgMBAAECggEAN/6hZJGnNHEdhHCO
XwxZ+DI+czxxp9U8KFx87q72wcg1Ob27nbraaLvlppW4jmriF4pYED6XptPZuP8Y
4AF9D0jFnx4yBQkWeYJlQsYau/ePpEcrRAYL2t+ZU6jFxxgGuVTuxiE1Y1ybzXB6
pclbzBNmPeGIh/LfmoDgzVmVBs6FhBrl8z+eWciISgskTaESkboiV+HAzDBJ23gP
LD0fjk69Dw75MS7QHBYm5jDIpXFvh+nPJOfwIAuaEQ9ZaF3Uh8zjBOyhtOSO9cdV
wXME4sIvA7IqlGoacxUtjyoWarPqk/V4UWl7/Q8gZlRagqjaJ+DqpqrD6UFCxwvw
KCyJ0QKBgQDTV7joBHuuw/RuDe8VwxUuRJTIcdrn6g2Kn3CxV9YLJhxr1doEmw3Y
DASY7zddkgJjssbkub5FhySAlqOIz5ok62erHMsyC90VXqWDC1uFHW6EQh/N/S/A
vgEuyIJ/dtxXYLFyozm0Az98A37nGGTSt9tphKsTPiHS1jOB3f9DbwKBgGomcW7T
Slq0+VSGniD+ciB71UMrW9FcF9qsnTPXQGZV4JqpLvE/tEq7uyr/Dp6l3mstVmtL
tBjkPef32oz3JXo32IWS37VZlu+3I2v7VQThFLnc3F0KUcZmH1Uy1my8itjP6jIf
wNwiUObilCubgiGEVxfMb0G7juMETZYyuRLfAoGAVwIFcRfvZ4rrBagc5yOyg6Le
cgtVqSbVvl1Xwts7lslw6ABZyo2fTHPeLKxHafFjpHIEqkPCDtPNdlcOKpP1jP+R
ZYPsL8VslpCpqWKyogH07uReParfzwUqbX1FJH7lxd9cDqseZXr01vSFeVS0pX/m
B/IDkF+DA08GU4/2uGcCgYAV1CP9e1vN/WtMc4ZvGIQVpAF+F5uBGSQapuaI85nd
sYlHpMTvfX8w4xwhQmQaQdfUSHV+CQpXGBCW9EQwOt6tHHDdPw/b9jlwwEN7gCrC
nxqpAf8a7vVUDEojNhocMEWJQnBRsG/zlOb4I93+fbMr+1ABp9u1M8G1c3wVCAdB
FwKBgF8sJlG58EKSfdvhVNDRq4hC/yjcI6987rg2fmeX9QUYiwReniaesEoBdeHz
OYWR3DtC5SNiDKuj7QmnRvNcbFwBz5dGOdiXytRtLkpwDArY/hV/hqeSH1nHU0fp
LUScnTZr95HkLFIle1JCFXw0viGHKEBkdFvcuXIFON9KNTA/
-----END RSA PRIVATE KEY-----
"""
let _2047BitRSAPublicKeyPEM = """
-----BEGIN PUBLIC KEY-----
MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBXog86uwpuCobeXXokHAeP
Mu15O2Cwfvwx7/EzZl6jY70ConNXmzR5U39kQQpFa0dxRQdgUA8YpU5/8aILp3Yv
0S2BssiuqdL5IkzdBzLNRhSQabuM+vyCQjImHF/bA28+5DKJ9uzIhywA9JS2o/4T
tE6mLqWbFAY+dM716llarKJgzLh/Vg0mH6H5vDoo4D6z+M2jQRiUbV+yIiiaY8/S
MyLltsZeEl/hx/NyACPSUAClVlsjvRRZzQl8oDybMVvUAbrIwR+ZVQltdqVgx5zV
f8G3BHi7lUdyqxIt0QWQRBTTd1tYsSOKmVhYB+DvPv2IJKGXqKo+XKQBLmm9UIux
AgMBAAE=
-----END PUBLIC KEY-----
"""
let _2047BitRSAPrivateKeyPKCS8PEM = """
-----BEGIN PRIVATE KEY-----
MIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAFeiDzq7Cm4Kht5d
eiQcB48y7Xk7YLB+/DHv8TNmXqNjvQKic1ebNHlTf2RBCkVrR3FFB2BQDxilTn/x
ogundi/RLYGyyK6p0vkiTN0HMs1GFJBpu4z6/IJCMiYcX9sDbz7kMon27MiHLAD0
lLaj/hO0TqYupZsUBj50zvXqWVqsomDMuH9WDSYfofm8OijgPrP4zaNBGJRtX7Ii
KJpjz9IzIuW2xl4SX+HH83IAI9JQAKVWWyO9FFnNCXygPJsxW9QBusjBH5lVCW12
pWDHnNV/wbcEeLuVR3KrEi3RBZBEFNN3W1ixI4qZWFgH4O8+/YgkoZeoqj5cpAEu
ab1Qi7ECAwEAAQKCAQA3/qFkkac0cR2EcI5fDFn4Mj5zPHGn1TwoXHzurvbByDU5
vbudutpou+WmlbiOauIXilgQPpem09m4/xjgAX0PSMWfHjIFCRZ5gmVCxhq794+k
RytEBgva35lTqMXHGAa5VO7GITVjXJvNcHqlyVvME2Y94YiH8t+agODNWZUGzoWE
GuXzP55ZyIhKCyRNoRKRuiJX4cDMMEnbeA8sPR+OTr0PDvkxLtAcFibmMMilcW+H
6c8k5/AgC5oRD1loXdSHzOME7KG05I71x1XBcwTiwi8DsiqUahpzFS2PKhZqs+qT
9XhRaXv9DyBmVFqCqNon4OqmqsPpQULHC/AoLInRAoGBANNXuOgEe67D9G4N7xXD
FS5ElMhx2ufqDYqfcLFX1gsmHGvV2gSbDdgMBJjvN12SAmOyxuS5vkWHJICWo4jP
miTrZ6scyzIL3RVepYMLW4UdboRCH839L8C+AS7Ign923FdgsXKjObQDP3wDfucY
ZNK322mEqxM+IdLWM4Hd/0NvAoGAaiZxbtNKWrT5VIaeIP5yIHvVQytb0VwX2qyd
M9dAZlXgmqku8T+0Sru7Kv8OnqXeay1Wa0u0GOQ95/fajPclejfYhZLftVmW77cj
a/tVBOEUudzcXQpRxmYfVTLWbLyK2M/qMh/A3CJQ5uKUK5uCIYRXF8xvQbuO4wRN
ljK5Et8CgYBXAgVxF+9niusFqBznI7KDot5yC1WpJtW+XVfC2zuWyXDoAFnKjZ9M
c94srEdp8WOkcgSqQ8IO0812Vw4qk/WM/5Flg+wvxWyWkKmpYrKiAfTu5F49qt/P
BSptfUUkfuXF31wOqx5levTW9IV5VLSlf+YH8gOQX4MDTwZTj/a4ZwKBgBXUI/17
W839a0xzhm8YhBWkAX4Xm4EZJBqm5ojzmd2xiUekxO99fzDjHCFCZBpB19RIdX4J
ClcYEJb0RDA63q0ccN0/D9v2OXDAQ3uAKsKfGqkB/xru9VQMSiM2GhwwRYlCcFGw
b/OU5vgj3f59syv7UAGn27UzwbVzfBUIB0EXAoGAXywmUbnwQpJ92+FU0NGriEL/
KNwjr3zuuDZ+Z5f1BRiLBF6eJp6wSgF14fM5hZHcO0LlI2IMq6PtCadG81xsXAHP
l0Y52JfK1G0uSnAMCtj+FX+Gp5IfWcdTR+ktRJydNmv3keQsUiV7UkIVfDS+IYco
QGR0W9y5cgU430o1MD8=
-----END PRIVATE KEY-----
"""
let _2047BitRSAPrivateKeyDER = Data(base64Encoded:
"MIIEoAIBAAKCAQBXog86uwpuCobeXXokHAePMu15O2Cwfvwx7/EzZl6jY70" +
"ConNXmzR5U39kQQpFa0dxRQdgUA8YpU5/8aILp3Yv0S2BssiuqdL5IkzdBz" +
"LNRhSQabuM+vyCQjImHF/bA28+5DKJ9uzIhywA9JS2o/4TtE6mLqWbFAY+d" +
"M716llarKJgzLh/Vg0mH6H5vDoo4D6z+M2jQRiUbV+yIiiaY8/SMyLltsZe" +
"El/hx/NyACPSUAClVlsjvRRZzQl8oDybMVvUAbrIwR+ZVQltdqVgx5zVf8G" +
"3BHi7lUdyqxIt0QWQRBTTd1tYsSOKmVhYB+DvPv2IJKGXqKo+XKQBLmm9UI" +
"uxAgMBAAECggEAN/6hZJGnNHEdhHCOXwxZ+DI+czxxp9U8KFx87q72wcg1O" +
"b27nbraaLvlppW4jmriF4pYED6XptPZuP8Y4AF9D0jFnx4yBQkWeYJlQsYa" +
"u/ePpEcrRAYL2t+ZU6jFxxgGuVTuxiE1Y1ybzXB6pclbzBNmPeGIh/LfmoD" +
"gzVmVBs6FhBrl8z+eWciISgskTaESkboiV+HAzDBJ23gPLD0fjk69Dw75MS" +
"7QHBYm5jDIpXFvh+nPJOfwIAuaEQ9ZaF3Uh8zjBOyhtOSO9cdVwXME4sIvA" +
"7IqlGoacxUtjyoWarPqk/V4UWl7/Q8gZlRagqjaJ+DqpqrD6UFCxwvwKCyJ" +
"0QKBgQDTV7joBHuuw/RuDe8VwxUuRJTIcdrn6g2Kn3CxV9YLJhxr1doEmw3" +
"YDASY7zddkgJjssbkub5FhySAlqOIz5ok62erHMsyC90VXqWDC1uFHW6EQh" +
"/N/S/AvgEuyIJ/dtxXYLFyozm0Az98A37nGGTSt9tphKsTPiHS1jOB3f9Db" +
"wKBgGomcW7TSlq0+VSGniD+ciB71UMrW9FcF9qsnTPXQGZV4JqpLvE/tEq7" +
"uyr/Dp6l3mstVmtLtBjkPef32oz3JXo32IWS37VZlu+3I2v7VQThFLnc3F0" +
"KUcZmH1Uy1my8itjP6jIfwNwiUObilCubgiGEVxfMb0G7juMETZYyuRLfAo" +
"GAVwIFcRfvZ4rrBagc5yOyg6LecgtVqSbVvl1Xwts7lslw6ABZyo2fTHPeL" +
"KxHafFjpHIEqkPCDtPNdlcOKpP1jP+RZYPsL8VslpCpqWKyogH07uReParf" +
"zwUqbX1FJH7lxd9cDqseZXr01vSFeVS0pX/mB/IDkF+DA08GU4/2uGcCgYA" +
"V1CP9e1vN/WtMc4ZvGIQVpAF+F5uBGSQapuaI85ndsYlHpMTvfX8w4xwhQm" +
"QaQdfUSHV+CQpXGBCW9EQwOt6tHHDdPw/b9jlwwEN7gCrCnxqpAf8a7vVUD" +
"EojNhocMEWJQnBRsG/zlOb4I93+fbMr+1ABp9u1M8G1c3wVCAdBFwKBgF8s" +
"JlG58EKSfdvhVNDRq4hC/yjcI6987rg2fmeX9QUYiwReniaesEoBdeHzOYW" +
"R3DtC5SNiDKuj7QmnRvNcbFwBz5dGOdiXytRtLkpwDArY/hV/hqeSH1nHU0" +
"fpLUScnTZr95HkLFIle1JCFXw0viGHKEBkdFvcuXIFON9KNTA/"
)!
let _2047BitRSAPrivateKeyPKCS8DER = Data(base64Encoded:
"MIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAFeiDzq7Cm4" +
"Kht5deiQcB48y7Xk7YLB+/DHv8TNmXqNjvQKic1ebNHlTf2RBCkVrR3FFB2" +
"BQDxilTn/xogundi/RLYGyyK6p0vkiTN0HMs1GFJBpu4z6/IJCMiYcX9sDb" +
"z7kMon27MiHLAD0lLaj/hO0TqYupZsUBj50zvXqWVqsomDMuH9WDSYfofm8" +
"OijgPrP4zaNBGJRtX7IiKJpjz9IzIuW2xl4SX+HH83IAI9JQAKVWWyO9FFn" +
"NCXygPJsxW9QBusjBH5lVCW12pWDHnNV/wbcEeLuVR3KrEi3RBZBEFNN3W1" +
"ixI4qZWFgH4O8+/YgkoZeoqj5cpAEuab1Qi7ECAwEAAQKCAQA3/qFkkac0c" +
"R2EcI5fDFn4Mj5zPHGn1TwoXHzurvbByDU5vbudutpou+WmlbiOauIXilgQ" +
"Ppem09m4/xjgAX0PSMWfHjIFCRZ5gmVCxhq794+kRytEBgva35lTqMXHGAa" +
"5VO7GITVjXJvNcHqlyVvME2Y94YiH8t+agODNWZUGzoWEGuXzP55ZyIhKCy" +
"RNoRKRuiJX4cDMMEnbeA8sPR+OTr0PDvkxLtAcFibmMMilcW+H6c8k5/AgC" +
"5oRD1loXdSHzOME7KG05I71x1XBcwTiwi8DsiqUahpzFS2PKhZqs+qT9XhR" +
"aXv9DyBmVFqCqNon4OqmqsPpQULHC/AoLInRAoGBANNXuOgEe67D9G4N7xX" +
"DFS5ElMhx2ufqDYqfcLFX1gsmHGvV2gSbDdgMBJjvN12SAmOyxuS5vkWHJI" +
"CWo4jPmiTrZ6scyzIL3RVepYMLW4UdboRCH839L8C+AS7Ign923FdgsXKjO" +
"bQDP3wDfucYZNK322mEqxM+IdLWM4Hd/0NvAoGAaiZxbtNKWrT5VIaeIP5y" +
"IHvVQytb0VwX2qydM9dAZlXgmqku8T+0Sru7Kv8OnqXeay1Wa0u0GOQ95/f" +
"ajPclejfYhZLftVmW77cja/tVBOEUudzcXQpRxmYfVTLWbLyK2M/qMh/A3C" +
"JQ5uKUK5uCIYRXF8xvQbuO4wRNljK5Et8CgYBXAgVxF+9niusFqBznI7KDo" +
"t5yC1WpJtW+XVfC2zuWyXDoAFnKjZ9Mc94srEdp8WOkcgSqQ8IO0812Vw4q" +
"k/WM/5Flg+wvxWyWkKmpYrKiAfTu5F49qt/PBSptfUUkfuXF31wOqx5levT" +
"W9IV5VLSlf+YH8gOQX4MDTwZTj/a4ZwKBgBXUI/17W839a0xzhm8YhBWkAX" +
"4Xm4EZJBqm5ojzmd2xiUekxO99fzDjHCFCZBpB19RIdX4JClcYEJb0RDA63" +
"q0ccN0/D9v2OXDAQ3uAKsKfGqkB/xru9VQMSiM2GhwwRYlCcFGwb/OU5vgj" +
"3f59syv7UAGn27UzwbVzfBUIB0EXAoGAXywmUbnwQpJ92+FU0NGriEL/KNw" +
"jr3zuuDZ+Z5f1BRiLBF6eJp6wSgF14fM5hZHcO0LlI2IMq6PtCadG81xsXA" +
"HPl0Y52JfK1G0uSnAMCtj+FX+Gp5IfWcdTR+ktRJydNmv3keQsUiV7UkIVf" +
"DS+IYcoQGR0W9y5cgU430o1MD8="
)!
let _2047BitRSAPublicKeyDER = Data(base64Encoded:
"MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBXog86uwpuCobeXXo" +
"kHAePMu15O2Cwfvwx7/EzZl6jY70ConNXmzR5U39kQQpFa0dxRQdgUA8YpU" +
"5/8aILp3Yv0S2BssiuqdL5IkzdBzLNRhSQabuM+vyCQjImHF/bA28+5DKJ9" +
"uzIhywA9JS2o/4TtE6mLqWbFAY+dM716llarKJgzLh/Vg0mH6H5vDoo4D6z" +
"+M2jQRiUbV+yIiiaY8/SMyLltsZeEl/hx/NyACPSUAClVlsjvRRZzQl8oDy" +
"bMVvUAbrIwR+ZVQltdqVgx5zVf8G3BHi7lUdyqxIt0QWQRBTTd1tYsSOKmV" +
"hYB+DvPv2IJKGXqKo+XKQBLmm9UIuxAgMBAAE="
)!
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: _2047BitRSAPrivateKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: _2047BitRSAPrivateKeyPKCS8PEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: _2047BitRSAPrivateKeyDER))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: _2047BitRSAPrivateKeyPKCS8DER))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(pemRepresentation: _2047BitRSAPublicKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(derRepresentation: _2047BitRSAPublicKeyDER))
}
// The unsafe initializers require a modulus of at least 1024 bits. 1017 bits occupies 128 bytes,
// the same as 1024.
func testRejectKeysBelow1024BitMinimum() throws {
// Generated via `openssl genrsa -traditional 1017`, then converted to the encodings below.
let _1017BitRSAPrivateKeyPEM = """
-----BEGIN RSA PRIVATE KEY-----
MIICWAIBAAKBgAFVByFodT87fB0oWSEkwybEeqayqUavihFHLu3Ss/XuUxVosi5z
lnzxbta17k8WXJYXa7OZC4jicxQer5xrZr9Op1k99zlJUbMtznl+BiSRKoAOjmsQ
mLPU5er1hF1MnHUJsS1SgoTbR0CLPFNh4ai7WtOY6bWv/k9B03xNPeRVAgMBAAEC
gYAAhvHcYWZL0DELpKSoPdDPLV5PSlE7fEjJD37dcsvtXBIaXaRsRybcZ/jxE2qq
dvHKHphqp/vtfZYF9yKMZd9xcsxceGTRWR9kxQdKe6r9y1gzF1piRAyU4UcyjzFc
h4w4psX3AqqN4qpQJgYUZamSRnnoJ3Vq7u/oR3W0P+PL3QJAGTnDt6UAHahmdryj
KMFyQan+GU/eo6KDD84blk1L8axsEHtKUvtVBOWPRaR2WJI+q26adZbVvp707brW
8sa+9wJADYTjZOw5A2C+mXlbBwV78cLrXwsZ/+5zrlGH5dMuDYbuJH3InXK/SguL
f/OqQmrtUwSmL5QfQ//QPbUpsioIEwJABg1h8/HWsUbyLpLb4q9nJnIO0SvkkwYu
w+ADpnAtRHLGCr5J+tbqcx5Q3biz3FRaTO9gh84EwpOI2HD3mZAtyQJABk3sRQor
5DlfaO7A1ltmW23MmXvx2fn3FFmNCE4c8c30jCvkPBhgwET1/utAgMygc9B9Nz7Z
/bn0AHLVSPJ05QJAFJqFaLd6j9v/WK7noJk0f7lWTZnfeRkZPxJh4AobfnGKV1yO
+mB6mLJo/StOBrM82IdCBXTHRYYS2zUCCoJG1Q==
-----END RSA PRIVATE KEY-----
"""
let _1017BitRSAPublicKeyPEM = """
-----BEGIN PUBLIC KEY-----
MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgAFVByFodT87fB0oWSEkwybEeqay
qUavihFHLu3Ss/XuUxVosi5zlnzxbta17k8WXJYXa7OZC4jicxQer5xrZr9Op1k9
9zlJUbMtznl+BiSRKoAOjmsQmLPU5er1hF1MnHUJsS1SgoTbR0CLPFNh4ai7WtOY
6bWv/k9B03xNPeRVAgMBAAE=
-----END PUBLIC KEY-----
"""
let _1017BitRSAPrivateKeyPKCS8PEM = """
-----BEGIN PRIVATE KEY-----
MIICcgIBADANBgkqhkiG9w0BAQEFAASCAlwwggJYAgEAAoGAAVUHIWh1Pzt8HShZ
ISTDJsR6prKpRq+KEUcu7dKz9e5TFWiyLnOWfPFu1rXuTxZclhdrs5kLiOJzFB6v
nGtmv06nWT33OUlRsy3OeX4GJJEqgA6OaxCYs9Tl6vWEXUycdQmxLVKChNtHQIs8
U2HhqLta05jpta/+T0HTfE095FUCAwEAAQKBgACG8dxhZkvQMQukpKg90M8tXk9K
UTt8SMkPft1yy+1cEhpdpGxHJtxn+PETaqp28coemGqn++19lgX3Ioxl33FyzFx4
ZNFZH2TFB0p7qv3LWDMXWmJEDJThRzKPMVyHjDimxfcCqo3iqlAmBhRlqZJGeegn
dWru7+hHdbQ/48vdAkAZOcO3pQAdqGZ2vKMowXJBqf4ZT96jooMPzhuWTUvxrGwQ
e0pS+1UE5Y9FpHZYkj6rbpp1ltW+nvTtutbyxr73AkANhONk7DkDYL6ZeVsHBXvx
wutfCxn/7nOuUYfl0y4Nhu4kfcidcr9KC4t/86pCau1TBKYvlB9D/9A9tSmyKggT
AkAGDWHz8daxRvIuktvir2cmcg7RK+STBi7D4AOmcC1EcsYKvkn61upzHlDduLPc
VFpM72CHzgTCk4jYcPeZkC3JAkAGTexFCivkOV9o7sDWW2ZbbcyZe/HZ+fcUWY0I
ThzxzfSMK+Q8GGDARPX+60CAzKBz0H03Ptn9ufQActVI8nTlAkAUmoVot3qP2/9Y
ruegmTR/uVZNmd95GRk/EmHgCht+cYpXXI76YHqYsmj9K04GszzYh0IFdMdFhhLb
NQIKgkbV
-----END PRIVATE KEY-----
"""
let _1017BitRSAPrivateKeyDER = Data(base64Encoded:
"MIICWAIBAAKBgAFVByFodT87fB0oWSEkwybEeqayqUavihFHLu3Ss/XuUxV" +
"osi5zlnzxbta17k8WXJYXa7OZC4jicxQer5xrZr9Op1k99zlJUbMtznl+Bi" +
"SRKoAOjmsQmLPU5er1hF1MnHUJsS1SgoTbR0CLPFNh4ai7WtOY6bWv/k9B0" +
"3xNPeRVAgMBAAECgYAAhvHcYWZL0DELpKSoPdDPLV5PSlE7fEjJD37dcsvt" +
"XBIaXaRsRybcZ/jxE2qqdvHKHphqp/vtfZYF9yKMZd9xcsxceGTRWR9kxQd" +
"Ke6r9y1gzF1piRAyU4UcyjzFch4w4psX3AqqN4qpQJgYUZamSRnnoJ3Vq7u" +
"/oR3W0P+PL3QJAGTnDt6UAHahmdryjKMFyQan+GU/eo6KDD84blk1L8axsE" +
"HtKUvtVBOWPRaR2WJI+q26adZbVvp707brW8sa+9wJADYTjZOw5A2C+mXlb" +
"BwV78cLrXwsZ/+5zrlGH5dMuDYbuJH3InXK/SguLf/OqQmrtUwSmL5QfQ//" +
"QPbUpsioIEwJABg1h8/HWsUbyLpLb4q9nJnIO0SvkkwYuw+ADpnAtRHLGCr" +
"5J+tbqcx5Q3biz3FRaTO9gh84EwpOI2HD3mZAtyQJABk3sRQor5DlfaO7A1" +
"ltmW23MmXvx2fn3FFmNCE4c8c30jCvkPBhgwET1/utAgMygc9B9Nz7Z/bn0" +
"AHLVSPJ05QJAFJqFaLd6j9v/WK7noJk0f7lWTZnfeRkZPxJh4AobfnGKV1y" +
"O+mB6mLJo/StOBrM82IdCBXTHRYYS2zUCCoJG1Q=="
)!
let _1017BitRSAPrivateKeyPKCS8DER = Data(base64Encoded:
"MIICcgIBADANBgkqhkiG9w0BAQEFAASCAlwwggJYAgEAAoGAAVUHIWh1Pzt" +
"8HShZISTDJsR6prKpRq+KEUcu7dKz9e5TFWiyLnOWfPFu1rXuTxZclhdrs5" +
"kLiOJzFB6vnGtmv06nWT33OUlRsy3OeX4GJJEqgA6OaxCYs9Tl6vWEXUycd" +
"QmxLVKChNtHQIs8U2HhqLta05jpta/+T0HTfE095FUCAwEAAQKBgACG8dxh" +
"ZkvQMQukpKg90M8tXk9KUTt8SMkPft1yy+1cEhpdpGxHJtxn+PETaqp28co" +
"emGqn++19lgX3Ioxl33FyzFx4ZNFZH2TFB0p7qv3LWDMXWmJEDJThRzKPMV" +
"yHjDimxfcCqo3iqlAmBhRlqZJGeegndWru7+hHdbQ/48vdAkAZOcO3pQAdq" +
"GZ2vKMowXJBqf4ZT96jooMPzhuWTUvxrGwQe0pS+1UE5Y9FpHZYkj6rbpp1" +
"ltW+nvTtutbyxr73AkANhONk7DkDYL6ZeVsHBXvxwutfCxn/7nOuUYfl0y4" +
"Nhu4kfcidcr9KC4t/86pCau1TBKYvlB9D/9A9tSmyKggTAkAGDWHz8daxRv" +
"Iuktvir2cmcg7RK+STBi7D4AOmcC1EcsYKvkn61upzHlDduLPcVFpM72CHz" +
"gTCk4jYcPeZkC3JAkAGTexFCivkOV9o7sDWW2ZbbcyZe/HZ+fcUWY0IThzx" +
"zfSMK+Q8GGDARPX+60CAzKBz0H03Ptn9ufQActVI8nTlAkAUmoVot3qP2/9" +
"YruegmTR/uVZNmd95GRk/EmHgCht+cYpXXI76YHqYsmj9K04GszzYh0IFdM" +
"dFhhLbNQIKgkbV"
)!
let _1017BitRSAPublicKeyDER = Data(base64Encoded:
"MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgAFVByFodT87fB0oWSEkwyb" +
"EeqayqUavihFHLu3Ss/XuUxVosi5zlnzxbta17k8WXJYXa7OZC4jicxQer5" +
"xrZr9Op1k99zlJUbMtznl+BiSRKoAOjmsQmLPU5er1hF1MnHUJsS1SgoTbR" +
"0CLPFNh4ai7WtOY6bWv/k9B03xNPeRVAgMBAAE="
)!
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey(unsafePEMRepresentation: _1017BitRSAPrivateKeyPEM)
)
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey(unsafePEMRepresentation: _1017BitRSAPrivateKeyPKCS8PEM)
)
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey(unsafeDERRepresentation: _1017BitRSAPrivateKeyDER)
)
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey(unsafeDERRepresentation: _1017BitRSAPrivateKeyPKCS8DER)
)
XCTAssertThrowsError(
try _RSA.Signing.PublicKey(unsafePEMRepresentation: _1017BitRSAPublicKeyPEM)
)
XCTAssertThrowsError(
try _RSA.Signing.PublicKey(unsafeDERRepresentation: _1017BitRSAPublicKeyDER)
)
}
func testHandlingNonStandardKeys() throws {
@@ -575,12 +841,12 @@ final class TestRSASigning: XCTestCase {
"En7fZhCeZeNBjNTuKXj3JqdP3wIDAQAB"
)!
XCTAssertEqual(try _RSA.Signing.PrivateKey(pemRepresentation: awkwardRSAPrivateKeyPEM).keySizeInBits, 2056)
XCTAssertEqual(try _RSA.Signing.PrivateKey(pemRepresentation: awkwardRSAPrivateKeyPKCS8PEM).keySizeInBits, 2056)
XCTAssertEqual(try _RSA.Signing.PrivateKey(derRepresentation: awkwardRSAPrivateKeyDER).keySizeInBits, 2056)
XCTAssertEqual(try _RSA.Signing.PrivateKey(derRepresentation: awkwardRSAPrivateKeyPKCS8DER).keySizeInBits, 2056)
XCTAssertEqual(try _RSA.Signing.PublicKey(pemRepresentation: awkwardRSAPublicKeyPEM).keySizeInBits, 2056)
XCTAssertEqual(try _RSA.Signing.PublicKey(derRepresentation: awkwardRSAPublicKeyDER).keySizeInBits, 2056)
XCTAssertEqual(try _RSA.Signing.PrivateKey(pemRepresentation: awkwardRSAPrivateKeyPEM).keySizeInBits, 2050)
XCTAssertEqual(try _RSA.Signing.PrivateKey(pemRepresentation: awkwardRSAPrivateKeyPKCS8PEM).keySizeInBits, 2050)
XCTAssertEqual(try _RSA.Signing.PrivateKey(derRepresentation: awkwardRSAPrivateKeyDER).keySizeInBits, 2050)
XCTAssertEqual(try _RSA.Signing.PrivateKey(derRepresentation: awkwardRSAPrivateKeyPKCS8DER).keySizeInBits, 2050)
XCTAssertEqual(try _RSA.Signing.PublicKey(pemRepresentation: awkwardRSAPublicKeyPEM).keySizeInBits, 2050)
XCTAssertEqual(try _RSA.Signing.PublicKey(derRepresentation: awkwardRSAPublicKeyDER).keySizeInBits, 2050)
}
func testMangledPKCS8DERKey() throws {
@@ -770,6 +1036,13 @@ final class TestRSASigning: XCTestCase {
n: bytesValues.randomElement()!,
e: bytesValues.randomElement()!
)
// Modulus of the 512-bit key above: `openssl rsa -in key.pem -noout -modulus`.
let _512BitModulus =
"e24c4c2c70e673315c2420b0e211542bbccf5b79f2ce6bdaa4aac29650bd064b"
+ "955ae1613a449c7143e906d7f251e49356771d9d6f8f15bcf4044f87de1c1bed"
XCTAssertThrowsError(
try _RSA.Signing.PublicKey(n: Data(hexString: _512BitModulus), e: Data(hexString: "010001"))
)
}
func testConstructAndUseKeyFromRSANumbersWhileRecoveringPrimes() throws {
@@ -789,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)
@@ -910,6 +1247,23 @@ final class TestRSASigning: XCTestCase {
return pemLines.joined(separator: "\n")
}
func test_invalidDERPublicKeyThrowsWithoutDoubleFree() throws {
// SEQUENCE { INTEGER 0, INTEGER 0 }
let badBase64 = "MAYCAQACAQ=="
let badDER = Array(Data(base64Encoded: badBase64)!)
XCTAssertThrowsError(try BoringSSLRSAPublicKey(derRepresentation: badDER))
}
func test_invalidPEMPublicKeyThrowsWithoutDoubleFree() throws {
// SEQUENCE { INTEGER 0, INTEGER 0 }
let badPEM = """
-----BEGIN PUBLIC KEY-----
MAYCAQACAQ==
-----END PUBLIC KEY-----
"""
XCTAssertThrowsError(try BoringSSLRSAPublicKey(pemRepresentation: badPEM))
}
}
+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)
+31
View File
@@ -93,6 +93,37 @@ final class XWingTests: XCTestCase {
let importedKey = try XWingMLKEM768X25519.PrivateKey.init(integrityCheckedRepresentation: exportedFormat)
XCTAssertEqual(importedKey.seedRepresentation, privateKey.seedRepresentation)
}
func testDecapsulateInputValidation() throws {
let ciphersuite = HPKE.Ciphersuite.XWingMLKEM768X25519_SHA256_AES_GCM_256
let skR = try XWingMLKEM768X25519.PrivateKey.generate()
// Dummy key with the correct size fails with an error from the underlying implementation.
let corretlySizedKey = Data(repeating: 0x00, count: 1120)
XCTAssertThrowsError(
try HPKE.Recipient(
privateKey: skR,
ciphersuite: ciphersuite,
info: Data(),
encapsulatedKey: corretlySizedKey
)
)
// Keys with the wrong size fail input validation.
let keySizesToTest = [0, 1, 1119, 1221, 2000]
for keySize in keySizesToTest {
let wronglySizedKey = Data(repeating: 0x00, count: keySize)
XCTAssertThrowsError(
try HPKE.Recipient(
privateKey: skR,
ciphersuite: ciphersuite,
info: Data(),
encapsulatedKey: wronglySizedKey
),
"Unexpectedly returned from malformed decapsulation path for keySize \(keySize)"
)
}
}
}
// Struct to parse KAT file
@@ -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)) }