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
205 changed files with 2679 additions and 5232 deletions

No files matched your search

+13 -14
View File
@@ -10,37 +10,33 @@ on:
jobs:
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.7
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.13
with:
license_header_check_project_name: "SwiftCrypto"
docs_check_enabled: false
format_check_container_image: "swift:latest"
unit-tests:
name: Unit tests
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
with:
linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_1_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_2_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_3_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
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: "-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_1_enabled: true
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
windows_6_1_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_2_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_3_arguments_override: "--explicit-target-dependency-import-check error"
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
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: "-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
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
with:
windows_6_1_enabled: true
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
@@ -52,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": [] },
@@ -67,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
+34 -66
View File
@@ -26,58 +26,31 @@ import PackageDescription
import class Foundation.ProcessInfo
// To develop this on Apple platforms, set this to true
let development = false
// NOTE: To develop the the non-Darwin Crypto target on macOS, use a Dev Container.
let nonDarwinPlatforms: [Platform] = [
.linux,
.android,
.windows,
.wasi,
.openbsd,
// The SwiftPM Platform symbol is not yet public but the underlying platform name is set.
// -- https://github.com/swiftlang/swift-package-manager/blob/swift-6.2.3-RELEASE/Sources/PackageDescription/SupportedPlatforms.swift#L75
.custom("freebsd"),
]
// Ideally, we should use `.when(platforms:)` to set `swiftSettings` and
// `dependencies` like on other platforms. However, `Platform.freebsd` is not
// yet available, and therefore we guard the settings behind this boolean.
#if os(FreeBSD)
let isFreeBSD = true
#else
let isFreeBSD = false
var swiftSettings: [SwiftSetting] = [
.define("CRYPTO_IN_SWIFTPM"),
.enableExperimentalFeature("Lifetimes"),
.enableExperimentalFeature("SourceWarningControl"),
]
// Only enable CheckImplementationOnly on 6.4 -- 6.3 has the feature, but produces many false positives.
#if compiler(>=6.4)
swiftSettings.append(.enableExperimentalFeature("CheckImplementationOnly"))
#endif
let swiftSettings: [SwiftSetting]
let dependencies: [Target.Dependency]
if development || isFreeBSD {
swiftSettings = [
.define("CRYPTO_IN_SWIFTPM"),
.define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API"),
.enableExperimentalFeature("Lifetimes"),
]
dependencies = [
"CCryptoBoringSSL",
"CCryptoBoringSSLShims",
"CryptoBoringWrapper",
"CXKCP",
"CXKCPShims",
]
} else {
let platforms: [Platform] = [
Platform.linux,
Platform.android,
Platform.windows,
Platform.wasi,
Platform.openbsd,
]
swiftSettings = [
.define("CRYPTO_IN_SWIFTPM"),
.define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API", .when(platforms: platforms)),
.enableExperimentalFeature("Lifetimes"),
]
dependencies = [
.target(name: "CCryptoBoringSSL", condition: .when(platforms: platforms)),
.target(name: "CCryptoBoringSSLShims", condition: .when(platforms: platforms)),
.target(name: "CryptoBoringWrapper", condition: .when(platforms: platforms)),
.target(name: "CXKCP", condition: .when(platforms: platforms)),
.target(name: "CXKCPShims", condition: .when(platforms: platforms)),
]
}
// 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")]
@@ -130,6 +103,10 @@ let package = Package(
.when(platforms: [Platform.wasi])
),
.define("OPENSSL_NO_ASM", .when(platforms: [Platform.wasi])),
// BoringSSL is vendored verbatim; we don't fix its warnings. Xcode enables
// -Wshorten-64-to-32 by default (SwiftPM does not), which produces dozens
// of warnings. Silence that group here.
.disableWarning("shorten-64-to-32"),
]
),
.target(
@@ -145,16 +122,9 @@ let package = Package(
.headerSearchPath("low/KeccakP-1600"),
.headerSearchPath("low/common"),
.headerSearchPath("common"),
.disableWarning("macro-redefined"),
]
),
.target(
name: "CCryptoBoringSSLShims",
dependencies: ["CCryptoBoringSSL"],
exclude: privacyManifestExclude + [
"CMakeLists.txt"
],
resources: privacyManifestResource
),
.target(
name: "CXKCPShims",
dependencies: ["CXKCP"],
@@ -165,16 +135,16 @@ let package = Package(
),
.target(
name: "Crypto",
dependencies: dependencies,
dependencies: [
.target(name: "CCryptoBoringSSL", 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)),
],
exclude: privacyManifestExclude + [
"vendored-sources.txt",
"CMakeLists.txt",
"AEADs/Nonces.swift.gyb",
"Digests/Digests.swift.gyb",
"Key Agreement/ECDH.swift.gyb",
"Signatures/ECDSA.swift.gyb",
"Signatures/MLDSA.swift.gyb",
"Signatures/BoringSSL/MLDSA_boring.swift.gyb",
"KEM/MLKEM.swift.gyb",
"KEM/BoringSSL/MLKEM_boring.swift.gyb",
],
resources: privacyManifestResource,
@@ -184,7 +154,6 @@ let package = Package(
name: "CryptoExtras",
dependencies: [
"CCryptoBoringSSL",
"CCryptoBoringSSLShims",
"CryptoBoringWrapper",
"Crypto",
.product(name: "SwiftASN1", package: "swift-asn1"),
@@ -206,7 +175,6 @@ let package = Package(
name: "CryptoBoringWrapper",
dependencies: [
"CCryptoBoringSSL",
"CCryptoBoringSSLShims",
],
exclude: privacyManifestExclude + [
"CMakeLists.txt"
+22 -13
View File
@@ -7,9 +7,9 @@ Swift Crypto is an open-source implementation of a substantial portion of the AP
Swift Crypto is available as a Swift Package Manager package. To use it, add the following dependency in your `Package.swift`:
```swift
// swift-crypto 1.x, 2.x, 3.x, and 4.x are almost API compatible, so most clients
// swift-crypto 1.x, 2.x, 3.x, 4.x, and 5.x are almost API compatible, so most clients
// should allow any of them
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "5.0.0"),
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "6.0.0"),
```
and to your target, add `Crypto` to your dependencies. You can then `import Crypto` to get access to Swift Crypto's functionality.
@@ -28,13 +28,14 @@ Swift Crypto compiles in two distinct modes depending on the platform for which
When building Swift Crypto for use on an Apple platform where CryptoKit is already available, Swift Crypto compiles its entire API surface down to nothing and simply re-exports the API of CryptoKit. This means that when using Apple platforms Swift Crypto simply delegates all work to the core implementation of CryptoKit, as though Swift Crypto was not even there.
When building Swift Crypto for use on Linux or Windows, Swift Crypto builds substantially more code. In particular, we build:
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
@@ -108,7 +109,7 @@ If you believe you have identified a vulnerability in Swift Crypto, please [repo
### Swift versions
The most recent versions of Swift Crypto support Swift 6 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
The most recent versions of Swift Crypto support Swift 6.2 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
Swift Crypto | Minimum Swift Version
--------------------|----------------------
@@ -120,7 +121,9 @@ Swift Crypto | Minimum Swift Version
`3.3.0 ..< 3.8.0` | 5.8
`3.9.0 ..< 3.13.0` | 5.9
`3.13.0 ..< 4.0.0` | 5.10
`4.0.0 ...` | 6.0
`4.0.0 ..< 4.4.0` | 6.0
`4.4.0 ..< 5.0.0` | 6.1
`5.0.0 ...` | 6.2
### Compatibility
@@ -136,13 +139,19 @@ Swift Crypto 3.0.0 was released in September 2023. Again the only breaking chang
Swift Crypto 4.0.0 was released in September 2025. Again the only breaking change was the addition of new cases in the `CryptoError` enumeration, so most users can safely depend on the 1.0.0, 2.0.0, 3.0.0, or 4.0.0 series of releases. Note that in this release `_CryptoExtras` was renamed to `CryptoExtras`. The old products and targets have been kept around for compatibility reasons, but users depending only on new code should use `CryptoExtras` not `_CryptoExtras`.
Swift Crypto 5.0.0 was released in September 2026. Because this version is only supported on Swift versions that support extensible enums, this release has mechanically marked all non-frozen public enums in CryptoKit as `@nonexhaustive`, which should mitigate the need for any future major releases of Swift Crypto. 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" ..< "5.0.0"),
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "6.0.0"),
```
### Developing Swift Crypto on macOS
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`, change `let development = false` to `let development = true`, as this will force Swift Crypto to build its public API.
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)
+6 -74
View File
@@ -11,47 +11,28 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION || CRYPTOKIT_NO_IMPORT_FOUNDATION
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
typealias AESGCMImpl = CoreCryptoGCMImpl
#else
typealias AESGCMImpl = OpenSSLAESGCMImpl
#endif
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension AES {
/// The Advanced Encryption Standard (AES) Galois Counter Mode (GCM) cipher
/// suite.
@nonexhaustive
public enum GCM: Cipher, Sendable {
static let tagByteCount = 16
static let defaultNonceByteCount = 12
#if !CRYPTOKIT_STATIC_LIBRARY
/// Fixed-length array of tagByteCount bytes.
typealias TagStorage = [16 of UInt8]
#endif
/// Secures the given plaintext message with encryption and an
/// authentication tag that covers both the encrypted data and
@@ -91,8 +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
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(message: copy message)
#endif
public static func seal(
@@ -108,21 +88,6 @@ extension AES {
)
}
// Note: historical version of the above, which should be removed once
// the above is API and clients move over to it.
#if swift(<6.3)
@_lifetime(message: copy message)
#endif
internal static func seal(
inplace message: inout MutableRawSpan,
using key: SymmetricKey,
nonce: RawSpan,
authenticating authenticatedData: RawSpan? = nil,
tag: inout OutputRawSpan
) throws(CryptoKitMetaError) {
return try AESGCMImpl.seal(key: key, message: &message, nonce: nonce, authenticatedData: authenticatedData, tag: &tag)
}
/// Decrypts the message and verifies the authenticity of both the
/// encrypted message and additional data.
///
@@ -162,8 +127,7 @@ extension AES {
/// - authenticatedData: Additional data that was authenticated.
///
/// The call throws an error if decryption or authentication fail.
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(message: copy message)
#endif
public static func open(
@@ -182,36 +146,9 @@ extension AES {
tag: tag
)
}
// Note: historical version of the above, which should be removed once
// the above is API and clients move over to it.
#if swift(<6.3)
@_lifetime(message: copy message)
#endif
internal static func open(
inplace message: inout MutableRawSpan,
using key: SymmetricKey,
nonce: RawSpan,
tag: RawSpan,
authenticating authenticatedData: RawSpan? = nil
) throws(CryptoKitMetaError) {
try AESGCMImpl
.open(
key: key,
message: &message,
nonce: nonce,
authenticatedData: authenticatedData,
tag: tag
)
}
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension AES.GCM {
/// A secure container for your data that you can access using a cipher.
///
@@ -227,11 +164,6 @@ extension AES.GCM {
///
/// The receiver uses another instance of the same cipher, like the
/// ``open(_:using:)`` method, to open the box.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct SealedBox: AEADSealedBox, Sendable {
private let combinedRepresentation: Data
private let nonceByteCount: Int
@@ -326,4 +258,4 @@ extension AES.GCM {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,10 +11,14 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
import FoundationEssentials
@@ -55,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
@@ -115,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
@@ -160,4 +164,4 @@ enum OpenSSLAESGCMImpl {
}
}
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
@@ -11,11 +11,14 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
import FoundationEssentials
@@ -45,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(
@@ -90,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(
@@ -147,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(
@@ -208,7 +211,7 @@ enum OpenSSLChaChaPolyImpl {
}
}
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(message: copy message)
#endif
static func decrypt(
@@ -242,4 +245,4 @@ enum OpenSSLChaChaPolyImpl {
}
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
@@ -11,38 +11,21 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION || CRYPTOKIT_NO_IMPORT_FOUNDATION
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
typealias ChaChaPolyImpl = CoreCryptoChaChaPolyImpl
#else
typealias ChaChaPolyImpl = OpenSSLChaChaPolyImpl
#endif
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
/// An implementation of the ChaCha20-Poly1305 cipher.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
@nonexhaustive
public enum ChaChaPoly: Cipher, Sendable {
static let tagByteCount = 16
static let keyBitsCount = 256
@@ -87,8 +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.
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(message: copy message)
#endif
public static func seal(
@@ -101,21 +83,6 @@ public enum ChaChaPoly: Cipher, Sendable {
try ChaChaPolyImpl.encrypt(key: key, inPlace: &message, nonce: nonce.bytes, authenticatedData: authenticatedData, tag: &tag)
}
// Note: historical version of the above, which should be removed once
// the above is API and clients move over to it.
#if swift(<6.3)
@_lifetime(message: copy message)
#endif
internal static func seal(
inplace message: inout MutableRawSpan,
using key: SymmetricKey,
nonce: RawSpan,
authenticating authenticatedData: RawSpan? = nil,
tag: inout OutputRawSpan
) throws(CryptoKitMetaError) {
try ChaChaPolyImpl.encrypt(key: key, inPlace: &message, nonce: nonce, authenticatedData: authenticatedData, tag: &tag)
}
/// Decrypts the message and verifies the authenticity of both the encrypted
/// message and additional data.
///
@@ -157,8 +124,7 @@ public enum ChaChaPoly: Cipher, Sendable {
/// - authenticatedData: Additional data that was authenticated.
///
/// The call throws an error if decryption or authentication fail.
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(message: copy message)
#endif
public static func open(
@@ -170,28 +136,8 @@ public enum ChaChaPoly: Cipher, Sendable {
) throws(CryptoKitMetaError) {
try ChaChaPolyImpl.decrypt(key: key, inPlace: &message, nonce: nonce.bytes, tag: tag, authenticatedData: authenticatedData)
}
// Note: historical version of the above, which should be removed once
// the above is API and clients move over to it.
#if swift(<6.3)
@_lifetime(message: copy message)
#endif
public static func open(
inplace message: inout MutableRawSpan,
using key: SymmetricKey,
nonce: RawSpan,
tag: RawSpan,
authenticating authenticatedData: RawSpan? = nil
) throws(CryptoKitMetaError) {
try ChaChaPolyImpl.decrypt(key: key, inPlace: &message, nonce: nonce, tag: tag, authenticatedData: authenticatedData)
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension ChaChaPoly {
/// A secure container for your data that you access using a cipher.
///
@@ -208,11 +154,6 @@ extension ChaChaPoly {
/// The receiver uses another instance of the same cipher, like the
/// ``open(_:using:)`` method, to open the box.
@frozen
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct SealedBox: AEADSealedBox, Sendable {
/// A combined element composed of the tag, the nonce, and the
/// ciphertext.
@@ -272,4 +213,4 @@ extension ChaChaPoly {
}
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+2 -11
View File
@@ -11,20 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
protocol AEADSealedBox: Sendable {
@@ -46,11 +42,6 @@ protocol AEADSealedBox: Sendable {
}
/// A type representing authenticated encryption with associated data.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
protocol Cipher {
associatedtype Key
associatedtype SealedBox: AEADSealedBox
+3 -29
View File
@@ -11,19 +11,15 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#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.
@@ -32,22 +28,12 @@ public import Foundation
// MARK: - AES.GCM + Nonce
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension AES.GCM {
/// A value used once during a cryptographic operation and then discarded.
///
/// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical
/// that nonces are unique per call to encryption APIs in order to protect the
/// integrity of the encryption.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct Nonce: ContiguousBytes, Sequence, Sendable {
typealias Storage = ContiguousArray<UInt8>
@@ -84,7 +70,6 @@ extension AES.GCM {
/// - Parameters:
/// - bytes: The bytes that represent the nonce.
/// The initializer throws an error if the data has a length smaller than 12 bytes.
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
public init(copying bytes: RawSpan) throws(CryptoKitMetaError) {
if bytes.byteCount < AES.GCM.defaultNonceByteCount {
throw error(CryptoKitError.incorrectParameterSize)
@@ -167,22 +152,12 @@ extension AES.GCM {
}
// MARK: - ChaChaPoly + Nonce
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension ChaChaPoly {
/// A value used once during a cryptographic operation and then discarded.
///
/// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical
/// that nonces are unique per call to encryption APIs in order to protect the
/// integrity of the encryption.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct Nonce: ContiguousBytes, Sequence, Sendable {
typealias Storage = [12 of UInt8]
@@ -219,7 +194,6 @@ extension ChaChaPoly {
/// - Parameters:
/// - bytes: The bytes that represent the nonce.
/// The initializer throws an error if the data isn't 12 bytes long.
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
public init(copying bytes: RawSpan) throws(CryptoKitMetaError) {
if bytes.byteCount != ChaChaPoly.nonceByteCount {
throw error(CryptoKitError.incorrectParameterSize)
@@ -299,4 +273,4 @@ extension ChaChaPoly {
}
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
-199
View File
@@ -1,199 +0,0 @@
//===----------------------------------------------------------------------===//
//
// 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 CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#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.
%{
ciphers = [{"name": "AES.GCM", "recommendedNonceSize": "AES.GCM.defaultNonceByteCount", "nonceValidation": "< AES.GCM.defaultNonceByteCount", "dataDescription": "/// - data: A data representation of the nonce.\n/// The initializer throws an error if the data has a length smaller than 12 bytes.", "bytesDescription": "/// - bytes: The bytes that represent the nonce.\n/// The initializer throws an error if the data has a length smaller than 12 bytes.", "fixedLength": None}]
if "NO_CHACHAPOLY" in globals():
pass
else:
ciphers.append({"name": "ChaChaPoly", "recommendedNonceSize": "ChaChaPoly.nonceByteCount", "nonceValidation": "!= ChaChaPoly.nonceByteCount", "dataDescription": "/// - data: A 12-byte data representation of the nonce.\n/// The initializer throws an error if the data isn't 12 bytes long.", "bytesDescription": "/// - bytes: The bytes that represent the nonce.\n/// The initializer throws an error if the data isn't 12 bytes long.", "fixedLength" : 12})
}%
% for cipher in ciphers:
%{
name = cipher["name"]
nonceSize = cipher["recommendedNonceSize"]
nonceValidation = cipher["nonceValidation"]
dataDescription = cipher["dataDescription"]
bytesDescription = cipher["bytesDescription"]
if "NO_INLINEARRAY" in globals():
fixedLength = None
else:
fixedLength = cipher["fixedLength"]
}%
// MARK: - ${name} + Nonce
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension ${name} {
/// A value used once during a cryptographic operation and then discarded.
///
/// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical
/// that nonces are unique per call to encryption APIs in order to protect the
/// integrity of the encryption.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct Nonce: ContiguousBytes, Sequence, Sendable {
% if fixedLength is None:
typealias Storage = ContiguousArray<UInt8>
% else:
typealias Storage = [${fixedLength} of UInt8]
% end
let storage: Storage
/// Creates a new random nonce.
///
/// The default nonce is a 12-byte random nonce.
public init() {
self.storage = Self.randomNonceStorage
}
/// Creates a nonce from the given data.
///
/// Unless your use case calls for a nonce with a specific value, use the
/// ``init()`` method to instead create a random nonce.
///
/// - Parameters:
${dataDescription}
internal init(data: RawSpan) throws(CryptoKitMetaError) {
if data.byteCount ${nonceValidation} {
throw error(CryptoKitError.incorrectParameterSize)
}
self.storage = Storage(copying: data)
}
/// Creates a nonce from the given data.
///
/// Unless your use case calls for a nonce with a specific value, use the
/// ``init()`` method to instead create a random nonce.
///
/// - Parameters:
${bytesDescription}
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
public init(copying bytes: RawSpan) throws(CryptoKitMetaError) {
if bytes.byteCount ${nonceValidation} {
throw error(CryptoKitError.incorrectParameterSize)
}
self.storage = Storage(copying: bytes)
}
/// Creates a nonce from the given data.
///
/// Unless your use case calls for a nonce with a specific value, use the
/// ``init()`` method to instead create a random nonce.
///
/// - Parameters:
${dataDescription}
public init<D: DataProtocol>(data: D) throws(CryptoKitMetaError) {
if data.count ${nonceValidation} {
throw error(CryptoKitError.incorrectParameterSize)
}
% if fixedLength is None:
self.storage = Storage(data)
% else:
self.storage = Storage(copying: data)
% end
}
/// Calls the given closure with a pointer to the underlying bytes of the array’s
/// contiguous storage.
///
/// - Parameters:
/// - body: A closure with an `UnsafeRawBufferPointer` parameter that points to the
/// contiguous storage for the array. The system creates the storage if it doesn’t
/// exist. If body has a return value, that value is also used as the return value
/// for the ``withUnsafeBytes(_:)`` method. The argument is valid only for
/// the duration of the closure’s execution.
///
/// - Returns: The return value, if any, of the body closure parameter.
#if !hasFeature(Embedded)
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try self.bytes.withUnsafeBytes(body)
}
#else
public func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
return try self.bytes.withUnsafeBytes(body)
}
#endif
/// The bytes stored in the nonce.
public var bytes: RawSpan {
get {
storage.span.bytes
}
}
/// The number of bytes stored in the nonce.
public var count: Int { storage.count }
/// Returns an iterator over the elements of the nonce.
public func makeIterator() -> Array<UInt8>.Iterator {
self.withUnsafeBytes({ (buffPtr) in
return Array(buffPtr).makeIterator()
})
}
/// Storage for a new, random nonce.
static var randomNonceStorage: Storage {
% if fixedLength is None:
var data = Storage(repeating: 0, count: ${nonceSize})
assert(data.count == ${nonceSize})
% else:
var data = Storage(repeating: 0)
% end
var mutableSpan = data.mutableSpan
var mutableBytes = mutableSpan.mutableBytes
initializeRandomNonce(into: &mutableBytes)
return data
}
/// Initialize the given mutable span with random bytes.
static func initializeRandomNonce(into data: inout MutableRawSpan) {
data.initializeWithRandomBytes(count: data.byteCount)
}
}
}
% end
#endif // Linux or !SwiftPM
+3 -7
View File
@@ -11,20 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
// This module implements "just enough" ASN.1. Specifically, we implement exactly enough ASN.1 DER parsing to handle
// the following use-cases:
@@ -744,4 +740,4 @@ extension FixedWidthInteger {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,20 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
extension ASN1 {
/// An ASN1 ANY represents...well, anything.
@@ -77,4 +73,4 @@ extension ASN1ImplicitlyTaggable {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,20 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
extension ASN1 {
/// A bitstring is a representation of...well...some bits.
@@ -80,4 +76,4 @@ extension ASN1.ASN1BitString: ContiguousBytes {
#endif
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,20 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
extension Bool: ASN1ImplicitlyTaggable {
static var defaultIdentifier: ASN1.ASN1Identifier {
@@ -64,4 +60,4 @@ extension Bool: ASN1ImplicitlyTaggable {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,20 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
extension ASN1 {
/// An `ASN1Identifier` is a representation of the abstract notion of an ASN.1 identifier. Identifiers have a number of properties that relate to both the specific
@@ -155,4 +151,4 @@ extension ASN1.ASN1Identifier: CustomStringConvertible {
}
#endif
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,20 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
/// A protocol that represents any internal object that can present itself as a INTEGER, or be parsed from
/// a INTEGER.
@@ -279,4 +275,4 @@ extension UInt8 {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,20 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
extension ASN1 {
/// An ASN1 NULL represents nothing.
@@ -51,4 +47,4 @@ extension ASN1 {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,20 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
extension ASN1 {
/// An octet string is a representation of a string of octets.
@@ -73,4 +69,4 @@ extension ASN1.ASN1OctetString: ContiguousBytes {
#endif
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,20 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
private func contents(of string: StaticString) -> ArraySlice<UInt8> {
if string.hasPointerRepresentation {
@@ -291,4 +287,4 @@ extension ASN1.ASN1BMPString: ExpressibleByStringLiteral {
#endif
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,20 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
// For temporary purposes we pretend that ArraySlice is our "bigint" type. We don't really need anything else.
extension ArraySlice: ASN1Serializable where Element == UInt8 { }
@@ -48,4 +44,4 @@ extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,20 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
extension ASN1 {
struct GeneralizedTime: ASN1ImplicitlyTaggable, Hashable {
@@ -413,4 +409,4 @@ extension Int {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,20 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
extension ASN1 {
/// An Object Identifier is a representation of some kind of object: really any kind of object.
@@ -224,4 +220,4 @@ extension UInt {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+3 -11
View File
@@ -11,24 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if CRYPTOKIT_STATIC_LIBRARY
@_exported import CryptoKit_Static
#else
#if canImport(CryptoKit)
@_exported import CryptoKit
#endif
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
extension ASN1 {
/// An ECDSA signature is laid out as follows:
@@ -70,4 +62,4 @@ extension ASN1 {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+3 -11
View File
@@ -11,24 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if CRYPTOKIT_STATIC_LIBRARY
@_exported import CryptoKit_Static
#else
#if canImport(CryptoKit)
@_exported import CryptoKit
#endif
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
extension ASN1 {
/// A PEM document is some data, and a discriminator type that is used to advertise the content.
@@ -129,4 +121,4 @@ extension Substring {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+3 -7
View File
@@ -11,19 +11,15 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
extension ASN1 {
// A PKCS#8 private key is one of two formats, depending on the version:
@@ -109,4 +105,4 @@ extension ASN1 {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+3 -11
View File
@@ -11,24 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if CRYPTOKIT_STATIC_LIBRARY
@_exported import CryptoKit_Static
#else
#if canImport(CryptoKit)
@_exported import CryptoKit
#endif
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
extension ASN1 {
// For private keys, SEC 1 uses:
@@ -121,4 +113,4 @@ extension ASN1 {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+3 -11
View File
@@ -11,24 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if CRYPTOKIT_STATIC_LIBRARY
@_exported import CryptoKit_Static
#else
#if canImport(CryptoKit)
@_exported import CryptoKit
#endif
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
extension ASN1 {
struct SubjectPublicKeyInfo: ASN1ImplicitlyTaggable {
@@ -134,4 +126,4 @@ extension ASN1.RFC5480AlgorithmIdentifier {
parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp521r1))
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+1 -7
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"
@@ -115,14 +116,8 @@ add_library(Crypto
target_compile_definitions(Crypto PRIVATE
"$<$<COMPILE_LANGUAGE:Swift>:CRYPTO_IN_SWIFTPM>")
if(NOT CMAKE_SYSTEM_NAME STREQUAL "Darwin")
target_compile_definitions(Crypto PRIVATE
"$<$<COMPILE_LANGUAGE:Swift>:CRYPTO_IN_SWIFTPM_FORCE_BUILD_API>")
endif()
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>)
@@ -130,7 +125,6 @@ target_link_libraries(Crypto PUBLIC
$<$<NOT:$<PLATFORM_ID:Darwin>>:dispatch>
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
CCryptoBoringSSL
CCryptoBoringSSLShims
CryptoBoringWrapper
CXKCP
CXKCPShims)
+6 -24
View File
@@ -11,19 +11,12 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if CRYPTOKIT_STATIC_LIBRARY
@_exported import CryptoKit_Static
#else
#if canImport(CryptoKit)
@_exported import CryptoKit
#endif
#else
/// General cryptography errors used by CryptoKit.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
@nonexhaustive
public enum CryptoKitError: Error {
/// The key size is incorrect.
case incorrectKeySize
@@ -35,29 +28,17 @@ public enum CryptoKitError: Error {
/// action.
case underlyingCoreCryptoError(error: Int32)
/// The framework can't wrap the specified key.
@available(iOS 15.0, macOS 12.0, watchOS 8.0, tvOS 15.0, macCatalyst 15.0, *)
case wrapFailure
/// The framework can't unwrap the specified key.
@available(iOS 15.0, macOS 12.0, watchOS 8.0, tvOS 15.0, macCatalyst 15.0, *)
case unwrapFailure
/// The parameter is invalid.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
case invalidParameter
}
@available(iOS 17.4, macOS 14.4, watchOS 10.4, tvOS 17.4, macCatalyst 17.4, *)
extension CryptoKitError: Equatable, Hashable {}
/// Errors from decoding ASN.1 content.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
@nonexhaustive
public enum CryptoKitASN1Error: Equatable, Error, Hashable {
/// The ASN.1 tag for this field is invalid or unsupported.
case invalidFieldIdentifier
@@ -107,6 +88,7 @@ struct RSAPSSSPKIError: Error {
#endif
#if hasFeature(Embedded)
@nonexhaustive
public enum CryptoKitMetaError: Error {
case cryptoKitError(underlyingError: CryptoKitError)
case asn1Error(underlyingError: CryptoKitASN1Error)
@@ -122,7 +104,7 @@ internal func error(_ error: CryptoKitASN1Error) -> CryptoKitMetaError {
internal func error(_ error: RSAPSSSPKIErrors) -> CryptoKitMetaError {
.rsapssspkiError(underlyingError: RSAPSSSPKIError(error: error))
}
#else /* !hasFeature(Embedded) */
#else
public typealias CryptoKitMetaError = any Error
internal func error(_ error: CryptoKitError) -> CryptoKitError { error }
internal func error(_ error: CryptoKitASN1Error) -> CryptoKitASN1Error { error }
@@ -11,10 +11,14 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
#endif
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
protocol HashFunctionImplementationDetails: HashFunction where Digest: DigestPrivate {}
@@ -210,4 +214,4 @@ private final class DigestContext<H: BoringSSLBackedHashFunction> {
withUnsafeMutablePointer(to: &self.context) { $0.zeroize() }
}
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
+4 -43
View File
@@ -11,44 +11,26 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if CRYPTOKIT_STATIC_LIBRARY
@_exported import CryptoKit_Static
#else
#if canImport(CryptoKit)
@_exported import CryptoKit
#endif
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
#if hasFeature(Embedded)
/// A type that represents the output of a hash.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
@preconcurrency
public protocol Digest: Hashable, Sendable, ContiguousBytes, Sequence where Element == UInt8 {
/// The number of bytes in the digest.
static var byteCount: Int { get }
}
#else // hasFeature(Embedded)
#else
/// A type that represents the output of a hash.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
@preconcurrency
public protocol Digest: Hashable, Sendable, ContiguousBytes, CustomStringConvertible, Sequence where Element == UInt8 {
/// The number of bytes in the digest.
@@ -56,20 +38,10 @@ public protocol Digest: Hashable, Sendable, ContiguousBytes, CustomStringConvert
}
#endif // hasFeature(Embedded)
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
protocol DigestPrivate: Digest {
init?(initializingWith body: (inout OutputRawSpan) -> ())
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension DigestPrivate {
@inlinable
init?(copying bytes: RawSpan) {
@@ -79,11 +51,6 @@ extension DigestPrivate {
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension Digest {
public func makeIterator() -> Array<UInt8>.Iterator {
self.withUnsafeBytes({ (buffPtr) in
@@ -93,11 +60,6 @@ extension Digest {
}
// We want to implement constant-time comparison for digests.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension Digest {
/// Determines whether two digests are equal.
///
@@ -130,7 +92,6 @@ extension Digest {
}
#if !hasFeature(Embedded)
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension Digest {
public var description: String {
return "\(Self.self): \(Array(self).hexString)"
@@ -138,4 +99,4 @@ extension Digest {
}
#endif
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+3 -40
View File
@@ -11,7 +11,8 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
// MARK: - Generated file, do NOT edit
@@ -22,11 +23,6 @@
// MARK: - SHA256Digest + DigestPrivate
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 256-bit digest.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct SHA256Digest: DigestPrivate {
let bytes: (UInt64, UInt64, UInt64, UInt64)
@@ -110,11 +106,6 @@ public struct SHA256Digest: DigestPrivate {
// MARK: - SHA384Digest + DigestPrivate
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 384-bit digest.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct SHA384Digest: DigestPrivate {
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
@@ -200,11 +191,6 @@ public struct SHA384Digest: DigestPrivate {
// MARK: - SHA512Digest + DigestPrivate
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 512-bit digest.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct SHA512Digest: DigestPrivate {
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
@@ -289,19 +275,9 @@ public struct SHA512Digest: DigestPrivate {
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension Insecure {
// MARK: - SHA1Digest + DigestPrivate
/// The output of a SHA1 hash.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct SHA1Digest: DigestPrivate {
let bytes: (UInt64, UInt64, UInt64)
@@ -381,19 +357,9 @@ public struct SHA1Digest: DigestPrivate {
}
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension Insecure {
// MARK: - MD5Digest + DigestPrivate
/// The output of a MD5 hash.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct MD5Digest: DigestPrivate {
let bytes: (UInt64, UInt64)
@@ -478,7 +444,6 @@ public struct MD5Digest: DigestPrivate {
// MARK: - SHA3_256Digest + DigestPrivate
/// The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a 256-bit digest.
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
public struct SHA3_256Digest: DigestPrivate {
let bytes: (UInt64, UInt64, UInt64, UInt64)
@@ -560,7 +525,6 @@ public struct SHA3_256Digest: DigestPrivate {
}
// MARK: - SHA3_384Digest + DigestPrivate
/// The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a 384-bit digest.
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
public struct SHA3_384Digest: DigestPrivate {
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
@@ -644,7 +608,6 @@ public struct SHA3_384Digest: DigestPrivate {
}
// MARK: - SHA3_512Digest + DigestPrivate
/// The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a 512-bit digest.
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
public struct SHA3_512Digest: DigestPrivate {
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
@@ -729,4 +692,4 @@ public struct SHA3_512Digest: DigestPrivate {
}
}
#endif // !CRYPTOKIT_IN_SEP
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
-250
View File
@@ -1,250 +0,0 @@
//===----------------------------------------------------------------------===//
//
// 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 CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
// MARK: - Generated file, do NOT edit
// any edits of this file WILL be overwritten and thus discarded
// see section `gyb` in `README` for details.
%{
digests_and_length = [{"name": "SHA256", "count": 32},{"name": "SHA384","count":48},{"name":"SHA512", "count": 64}]
if "NO_INSECURE_DIGEST" in globals():
pass
else:
digests_and_length.extend([{"name":"SHA1", "count":20, "prefix":"Insecure "},{"name":"MD5", "count":16, "prefix":"Insecure "}])
}%
% for HF in digests_and_length:
%{
name = HF["name"]
byteCount = HF["count"]
wordsCount = (byteCount*8)//64 + (0 if ((byteCount*8)%64) == 0 else 1)
}%
%{
if "prefix" in HF.keys():
protocol_prefix = ""
protocol_prefix = protocol_prefix + "#if !CRYPTOKIT_STATIC_LIBRARY\n"
protocol_prefix = protocol_prefix + "@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)\n"
protocol_prefix = protocol_prefix + "#else // CRYPTOKIT_STATIC_LIBRARY\n"
protocol_prefix = protocol_prefix + "@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)\n"
protocol_prefix = protocol_prefix + "#endif\n"
protocol_prefix = protocol_prefix + "extension " + HF["prefix"] + "{"
protocol_suffix = "}"
parent = HF["prefix"].strip() + "/" + name
else:
protocol_prefix = ""
protocol_suffix = ""
parent = name
if name == "SHA1" or name == "MD5":
abstract = "The output of a " + name + " hash."
else:
abstract = "The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a " + name[-3:] + "-bit digest."
}%
${protocol_prefix}
// MARK: - ${name}Digest + DigestPrivate
/// ${abstract}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct ${name}Digest: DigestPrivate {
let bytes: (${(wordsCount-1)*"UInt64, "+"UInt64"})
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
var bytes = (${(wordsCount-1)*"UInt64(0), "+"UInt64(0)"})
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
body(&output)
return output.finalize(for: targetPtr)
}
guard initialized == ${byteCount} else {
return nil
}
self.bytes = bytes
}
/// The number of bytes in the digest.
public static var byteCount: Int {
return ${byteCount}
}
/// Invokes the given closure with a buffer pointer covering the raw bytes of
/// the digest.
///
/// - Parameters:
/// - body: A closure that takes a raw buffer pointer to the bytes of the digest
/// and returns the digest.
///
/// - Returns: The digest, as returned from the body closure.
#if !hasFeature(Embedded)
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try Swift.withUnsafeBytes(of: bytes) {
let boundsCheckedPtr = UnsafeRawBufferPointer(start: $0.baseAddress,
count: Self.byteCount)
return try body(boundsCheckedPtr)
}
}
#else
public func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
return try Swift.withUnsafeBytes(of: bytes) { ptr throws(E) -> R in
let boundsCheckedPtr = UnsafeRawBufferPointer(start: ptr.baseAddress,
count: Self.byteCount)
return try body(boundsCheckedPtr)
}
}
#endif
private func toArray() -> ArraySlice<UInt8> {
var array = [UInt8]()
array.appendByte(bytes.0)
% for index in range(wordsCount-1):
array.appendByte(bytes.${index+1})
% end
return array.prefix(${name}Digest.byteCount)
}
#if !hasFeature(Embedded)
/// A human-readable description of the digest.
public var description: String {
return "\("${name}") digest: \(toArray().hexString)"
}
#endif
/// Hashes the essential components of the digest by feeding them into the
/// given hash function.
///
/// This method is part of the digest’s conformance to Swift standard library’s
/// <doc://com.apple.documentation/documentation/swift/hashable> protocol, making
/// it possible to compare digests. Don’t confuse that hashing with the
/// cryptographically secure hashing that you use to create the digest in the
/// first place by, for example, calling ``${parent}/hash(data:)``.
///
/// - Parameters:
/// - hasher: The hash function to use when combining the components of
/// the digest.
public func hash(into hasher: inout Hasher) {
self.withUnsafeBytes { hasher.combine(bytes: $0) }
}
}
${protocol_suffix}
% end
#if !CRYPTOKIT_IN_SEP
%{
digests_and_length = [
{"name": "SHA3_256", "count": 32},
{"name": "SHA3_384", "count": 48},
{"name": "SHA3_512", "count": 64}
]
}%
% for HF in digests_and_length:
%{
name = HF["name"]
byteCount = HF["count"]
wordsCount = (byteCount*8)//64 + (0 if ((byteCount*8)%64) == 0 else 1)
}%
%{
parent = name
abstract = "The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a " + name[-3:] + "-bit digest."
}%
// MARK: - ${name}Digest + DigestPrivate
/// ${abstract}
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
public struct ${name}Digest: DigestPrivate {
let bytes: (${(wordsCount-1)*"UInt64, "+"UInt64"})
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
var bytes = (${(wordsCount-1)*"UInt64(0), "+"UInt64(0)"})
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
body(&output)
return output.finalize(for: targetPtr)
}
guard initialized == ${byteCount} else {
return nil
}
self.bytes = bytes
}
/// The number of bytes in the digest.
public static var byteCount: Int {
return ${byteCount}
}
/// Invokes the given closure with a buffer pointer covering the raw bytes of
/// the digest.
///
/// - Parameters:
/// - body: A closure that takes a raw buffer pointer to the bytes of the digest
/// and returns the digest.
///
/// - Returns: The digest, as returned from the body closure.
#if !hasFeature(Embedded)
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try Swift.withUnsafeBytes(of: bytes) {
let boundsCheckedPtr = UnsafeRawBufferPointer(start: $0.baseAddress,
count: Self.byteCount)
return try body(boundsCheckedPtr)
}
}
#else
public func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
return try Swift.withUnsafeBytes(of: bytes) { ptr throws(E) -> R in
let boundsCheckedPtr = UnsafeRawBufferPointer(start: ptr.baseAddress,
count: Self.byteCount)
return try body(boundsCheckedPtr)
}
}
#endif
private func toArray() -> ArraySlice<UInt8> {
var array = [UInt8]()
array.appendByte(bytes.0)
% for index in range(wordsCount-1):
array.appendByte(bytes.${index+1})
% end
return array.prefix(upTo: ${name}Digest.byteCount)
}
#if !hasFeature(Embedded)
/// A human-readable description of the digest.
public var description: String {
return "\("${name}") digest: \(toArray().hexString)"
}
#endif
/// Hashes the essential components of the digest by feeding them into the
/// given hash function.
///
/// This method is part of the digest’s conformance to Swift standard library’s
/// <doc://com.apple.documentation/documentation/swift/hashable> protocol, making
/// it possible to compare digests. Don’t confuse that hashing with the
/// cryptographically secure hashing that you use to create the digest in the
/// first place by, for example, calling ``${parent}/hash(data:)``.
///
/// - Parameters:
/// - hasher: The hash function to use when combining the components of
/// the digest.
public func hash(into hasher: inout Hasher) {
self.withUnsafeBytes { hasher.combine(bytes: $0) }
}
}
% end
#endif // !CRYPTOKIT_IN_SEP
#endif // Linux or !SwiftPM
+3 -46
View File
@@ -11,37 +11,18 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION || CRYPTOKIT_NO_IMPORT_FOUNDATION
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
typealias DigestImpl = CoreCryptoDigestImpl
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
typealias DigestImplSHA3 = CoreCryptoDigestImpl
#else
typealias DigestImpl = OpenSSLDigestImpl
typealias DigestImplSHA3 = XKCPDigestImpl
#endif
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
/// A type that performs cryptographically secure hashing.
///
@@ -61,30 +42,11 @@ public import Foundation
/// authentication code (MAC) like ``HMAC`` instead. MACs rely on hashing, but
/// incorporate a secret cryptographic key into the digest computation. Only a
/// user that has the key can generate a valid MAC.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
@preconcurrency
public protocol HashFunction: Sendable {
/// The number of bytes that represents the hash function’s internal state.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.2, macOS 10.15, watchOS 6.1, tvOS 13.2, macCatalyst 13.2, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.2, macOS 10.13, watchOS 6.1, tvOS 13.2, macCatalyst 13.2, visionOS 1.0, *)
#endif
static var blockByteCount: Int { get }
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION || CRYPTOKIT_NO_IMPORT_FOUNDATION
/// The type of the digest returned by the hash function.
#if CRYPTOKIT_STATIC_LIBRARY
associatedtype Digest: CryptoKit_Static.Digest
#else
associatedtype Digest: CryptoKit.Digest
#endif
#else
associatedtype Digest: Crypto.Digest
#endif
/// Creates a hash function.
///
@@ -139,11 +101,6 @@ extension HashFunction {
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension HashFunction {
/// Computes a digest of the buffer.
///
@@ -216,4 +173,4 @@ extension HashFunction {
}
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,7 +11,8 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
@@ -26,11 +27,6 @@
/// in memory, you can compute the digest iteratively by creating a new hash
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
/// data, and then calling the ``finalize()`` method to get the result.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public typealias SHA2_256 = SHA256
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
@@ -45,18 +41,8 @@ public typealias SHA2_256 = SHA256
/// in memory, you can compute the digest iteratively by creating a new hash
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
/// data, and then calling the ``finalize()`` method to get the result.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct SHA256: HashFunctionImplementationDetails, Sendable {
/// The number of bytes that represents the hash function’s internal state.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.2, macOS 10.15, watchOS 6.1, tvOS 13.2, macCatalyst 13.2, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.2, macOS 10.13, watchOS 6.1, tvOS 13.2, macCatalyst 13.2, visionOS 1.0, *)
#endif
public static let blockByteCount: Int = 64
/// The number of bytes in a SHA256 digest.
public static let byteCount: Int = 32
@@ -126,11 +112,6 @@ public struct SHA256: HashFunctionImplementationDetails, Sendable {
/// in memory, you can compute the digest iteratively by creating a new hash
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
/// data, and then calling the ``finalize()`` method to get the result.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public typealias SHA2_384 = SHA384
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
@@ -145,18 +126,8 @@ public typealias SHA2_384 = SHA384
/// in memory, you can compute the digest iteratively by creating a new hash
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
/// data, and then calling the ``finalize()`` method to get the result.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct SHA384: HashFunctionImplementationDetails, Sendable {
/// The number of bytes that represents the hash function’s internal state.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.2, macOS 10.15, watchOS 6.1, tvOS 13.2, macCatalyst 13.2, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.2, macOS 10.13, watchOS 6.1, tvOS 13.2, macCatalyst 13.2, visionOS 1.0, *)
#endif
public static let blockByteCount: Int = 128
/// The number of bytes in a SHA384 digest.
public static let byteCount: Int = 48
@@ -227,11 +198,6 @@ public struct SHA384: HashFunctionImplementationDetails, Sendable {
/// in memory, you can compute the digest iteratively by creating a new hash
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
/// data, and then calling the ``finalize()`` method to get the result.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public typealias SHA2_512 = SHA512
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
@@ -246,18 +212,8 @@ public typealias SHA2_512 = SHA512
/// in memory, you can compute the digest iteratively by creating a new hash
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
/// data, and then calling the ``finalize()`` method to get the result.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct SHA512: HashFunctionImplementationDetails, Sendable {
/// The number of bytes that represents the hash function’s internal state.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.2, macOS 10.15, watchOS 6.1, tvOS 13.2, macCatalyst 13.2, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.2, macOS 10.13, watchOS 6.1, tvOS 13.2, macCatalyst 13.2, visionOS 1.0, *)
#endif
public static let blockByteCount: Int = 128
/// The number of bytes in a SHA512 digest.
public static let byteCount: Int = 64
@@ -315,4 +271,4 @@ public struct SHA512: HashFunctionImplementationDetails, Sendable {
return impl.finalize()
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,7 +11,8 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if !CRYPTOKIT_IN_SEP
@@ -26,7 +27,6 @@
/// applications can compute the digest iteratively by creating a new hash
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
/// data, and then calling the ``finalize()`` method to get the result.
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
public struct SHA3_256: HashFunctionImplementationDetails, Sendable {
/// The number of bytes that represents the hash function’s internal state.
public static let blockByteCount: Int = 136
@@ -97,7 +97,6 @@ public struct SHA3_256: HashFunctionImplementationDetails, Sendable {
/// applications can compute the digest iteratively by creating a new hash
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
/// data, and then calling the ``finalize()`` method to get the result.
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
public struct SHA3_384: HashFunctionImplementationDetails, Sendable {
/// The number of bytes that represents the hash function’s internal state.
public static let blockByteCount: Int = 104
@@ -168,7 +167,6 @@ public struct SHA3_384: HashFunctionImplementationDetails, Sendable {
/// applications can compute the digest iteratively by creating a new hash
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
/// data, and then calling the ``finalize()`` method to get the result.
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
public struct SHA3_512: HashFunctionImplementationDetails, Sendable {
/// The number of bytes that represents the hash function’s internal state.
public static let blockByteCount: Int = 72
@@ -228,4 +226,4 @@ public struct SHA3_512: HashFunctionImplementationDetails, Sendable {
}
}
#endif // !CRYPTOKIT_IN_SEP
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,11 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CXKCP
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CXKCPShims
#else
@_implementationOnly import CXKCP
@_implementationOnly import CXKCPShims
#endif
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
protocol XKCPBackedHashFunction: HashFunctionImplementationDetails {
@@ -157,4 +162,4 @@ private final class XKCPDigestContext<H: XKCPBackedHashFunction> {
withUnsafeMutablePointer(to: &self.context) { $0.zeroize() }
}
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
@@ -11,28 +11,20 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension HPKE {
/// The authenticated encryption with associated data (AEAD) algorithms to use in HPKE.
@nonexhaustive
public enum AEAD: CaseIterable, Hashable, Sendable {
/// An Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 128 bits.
case AES_GCM_128
@@ -129,4 +121,4 @@ extension HPKE {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,25 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension HPKE {
/// Cipher suites to use in hybrid public key encryption (HPKE).
@@ -53,7 +44,6 @@ extension HPKE {
public static let Curve25519_SHA256_ChachaPoly = Ciphersuite(kem: .Curve25519_HKDF_SHA256, kdf: .HKDF_SHA256, aead: .chaChaPoly)
/// A cipher suite for HPKE that uses the X-Wing KEM (ML-KEM-768 with X25519), SHA-2 key derivation
/// with a 256-bit digest, and the Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 256 bits.
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
public static let XWingMLKEM768X25519_SHA256_AES_GCM_256 = Ciphersuite(kem: .XWingMLKEM768X25519, kdf: .HKDF_SHA256, aead: .AES_GCM_256)
fileprivate static let ciphersuiteLabel = Data("HPKE".utf8)
@@ -87,4 +77,4 @@ extension HPKE {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+4 -15
View File
@@ -11,31 +11,20 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if CRYPTOKIT_STATIC_LIBRARY
@_exported import CryptoKit_Static
#else
#if canImport(CryptoKit)
@_exported import CryptoKit
#endif
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension HPKE {
/// The key derivation functions to use in HPKE.
@nonexhaustive
public enum KDF: CaseIterable, Hashable, Sendable {
/// An HMAC-based key derivation function that uses SHA-2 hashing with a 256-bit digest.
case HKDF_SHA256
@@ -114,4 +103,4 @@ extension HPKE {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,46 +11,28 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
private let suiteIDLabel = Data("KEM".utf8)
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 10.15, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension HPKE {
struct KexUtils {
static func ExtractAndExpand(dh: ContiguousBytes, enc: Data,
pkRm: Data, pkSm: Data? = nil, kem: HPKE.KEM, kdf: HPKE.KDF) -> SymmetricKey {
var suiteID = suiteIDLabel
suiteID.append(kem.identifier)
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if CRYPTOKIT_STATIC_LIBRARY
return CryptoKit_Static.ExtractAndExpand(zz: dh, kemContext: kemContext(enc: enc, pkRm: pkRm, pkSm: pkSm),
suiteID: suiteID, kem: kem, kdf: kdf)
#else
return CryptoKit.ExtractAndExpand(zz: dh, kemContext: kemContext(enc: enc, pkRm: pkRm, pkSm: pkSm),
suiteID: suiteID, kem: kem, kdf: kdf)
#endif
#else
return Crypto.ExtractAndExpand(zz: dh, kemContext: kemContext(enc: enc, pkRm: pkRm, pkSm: pkSm),
suiteID: suiteID, kem: kem, kdf: kdf)
#endif
}
static func kemContext(enc: Data, pkRm: Data, pkSm: Data? = nil) -> Data {
@@ -63,4 +45,4 @@ extension HPKE {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,19 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
private let protocolLabel = Data("HPKE-v1".utf8)
@@ -36,11 +33,6 @@ extension Data {
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 10.15, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
internal func ExtractAndExpand(zz: ContiguousBytes, kemContext: Data, suiteID: Data, kem: HPKE.KEM, kdf: HPKE.KDF) -> SymmetricKey {
let eaePrk = LabeledExtract(salt: Data(), label: eaePRKLabel, ikm: zz, suiteID: suiteID, kdf: kdf)
@@ -48,11 +40,6 @@ internal func ExtractAndExpand(zz: ContiguousBytes, kemContext: Data, suiteID: D
info: kemContext, outputByteCount: kem.nSecret, suiteID: suiteID, kdf: kdf)
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 10.15, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
internal func LabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, suiteID: Data, kdf: HPKE.KDF) -> SymmetricKey {
var labeled_ikm = protocolLabel
labeled_ikm.append(suiteID)
@@ -61,11 +48,6 @@ internal func LabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, su
return kdf.extract(salt: salt ?? Data(), ikm: SymmetricKey(data: labeled_ikm))
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 10.15, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
internal func LabeledExpand<Info: DataProtocol>(prk: SymmetricKey, label: Data, info: Info, outputByteCount: UInt16, suiteID: Data, kdf: HPKE.KDF) -> SymmetricKey {
var labeled_info = I2OSP(value: Int(outputByteCount), outputByteCount: 2)
labeled_info.append(protocolLabel)
@@ -75,22 +57,12 @@ internal func LabeledExpand<Info: DataProtocol>(prk: SymmetricKey, label: Data,
return kdf.expand(prk: prk, info: labeled_info, outputByteCount: Int(outputByteCount))
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 10.15, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
internal func NonSecretOutputLabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, suiteID: Data, kdf: HPKE.KDF) -> Data {
return Data(unsafeFromContiguousBytes: LabeledExtract(salt: salt, label: label, ikm: ikm, suiteID: suiteID, kdf: kdf))
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 10.15, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
internal func NonSecretOutputLabeledExpand(prk: SymmetricKey, label: Data, info: Data, outputByteCount: UInt16, suiteID: Data, kdf: HPKE.KDF) -> Data {
return Data(unsafeFromContiguousBytes: LabeledExpand(prk: prk, label: label, info: info, outputByteCount: outputByteCount, suiteID: suiteID, kdf: kdf))
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,13 +11,11 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#else
#if canImport(FoundationEssentials)
#if os(Windows)
import ucrt
@@ -36,18 +34,13 @@ import FoundationEssentials
#else
import Foundation
#endif
#endif
internal func I2OSP(value: Int, outputByteCount: Int) -> Data {
precondition(outputByteCount > 0, "Cannot I2OSP with no output length.")
precondition(value >= 0, "I2OSP requires a non-null value.")
#if !CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
let requiredBytes = Int(ceil(log2(Double(max(value, 1) + 1)) / 8))
#else
let requiredBytes = Int((log2_bridge(Double(max(value, 1) + 1)) / 8).rounded(.up))
#endif
precondition(outputByteCount >= requiredBytes)
@@ -60,4 +53,4 @@ internal func I2OSP(value: Int, outputByteCount: Int) -> Data {
return data
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,30 +11,18 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if CRYPTOKIT_STATIC_LIBRARY
@_exported import CryptoKit_Static
#else
#if canImport(CryptoKit)
@_exported import CryptoKit
#endif
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
/// A type that ``HPKE`` uses to encode the public key.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
@preconcurrency
public protocol HPKEPublicKeySerialization: Sendable {
/// Creates a public key from an encoded representation.
@@ -53,11 +41,6 @@ public protocol HPKEPublicKeySerialization: Sendable {
}
/// A type that represents the public key in a Diffie-Hellman key exchange.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
@preconcurrency
public protocol HPKEDiffieHellmanPublicKey: HPKEPublicKeySerialization, Sendable where EphemeralPrivateKey.PublicKey == Self {
/// The type of the ephemeral private key.
@@ -65,11 +48,6 @@ public protocol HPKEDiffieHellmanPublicKey: HPKEPublicKeySerialization, Sendable
}
/// A type that represents the public key in HPKE
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
@preconcurrency
public protocol HPKEKEMPublicKey: KEMPublicKey, HPKEPublicKeySerialization where EphemeralPrivateKey.PublicKey == Self {
/// The type of the ephemeral private key.
@@ -77,29 +55,14 @@ public protocol HPKEKEMPublicKey: KEMPublicKey, HPKEPublicKeySerialization where
}
/// A type that represents the private key in a Diffie-Hellman key exchange.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
@preconcurrency
public protocol HPKEDiffieHellmanPrivateKey: Sendable, DiffieHellmanKeyAgreement where PublicKey: HPKEDiffieHellmanPublicKey {}
/// A type that represents the private key in HPKE.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
@preconcurrency
public protocol HPKEKEMPrivateKey: Sendable, KEMPrivateKey where PublicKey: HPKEKEMPublicKey {}
/// A type that represents the generation of private keys in a Diffie-Hellman key exchange.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
@preconcurrency
public protocol HPKEDiffieHellmanPrivateKeyGeneration: HPKEDiffieHellmanPrivateKey, Sendable {
/// Creates a private key generator.
@@ -107,11 +70,6 @@ public protocol HPKEDiffieHellmanPrivateKeyGeneration: HPKEDiffieHellmanPrivateK
}
/// A type that represents the generation of private keys in HPKE
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
@preconcurrency
public protocol HPKEKEMPrivateKeyGeneration: HPKEKEMPrivateKey, Sendable {
/// Creates a private key generator.
@@ -120,30 +78,13 @@ public protocol HPKEKEMPrivateKeyGeneration: HPKEKEMPrivateKey, Sendable {
extension HPKE {
/// A container for Diffie-Hellman key encapsulation mechanisms (KEMs).
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
@nonexhaustive
public enum DHKEM: Sendable {
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
struct PublicKey<DHPK: HPKEDiffieHellmanPublicKey>: KEMPublicKey where DHPK == DHPK.EphemeralPrivateKey.PublicKey {
let kem: HPKE.KEM
let key: DHPK
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if CRYPTOKIT_STATIC_LIBRARY
typealias EncapsulationResult = CryptoKit_Static.KEM.EncapsulationResult
#else
typealias EncapsulationResult = CryptoKit.KEM.EncapsulationResult
#endif
#else
typealias EncapsulationResult = Crypto.KEM.EncapsulationResult
#endif
init(_ publicKey: DHPK, kem: HPKE.KEM) throws {
// TODO: Validate Ciphersuite Mismatches
@@ -167,11 +108,6 @@ extension HPKE {
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, *)
#endif
struct PrivateKey<DHSK: HPKEDiffieHellmanPrivateKey>: KEMPrivateKey {
let kem: HPKE.KEM
let key: DHSK
@@ -232,4 +168,4 @@ extension HPKE {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,33 +11,19 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension Curve25519.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension Curve25519.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
/// The type of the ephemeral private key associated with this public key.
public typealias EphemeralPrivateKey = Curve25519.KeyAgreement.PrivateKey
@@ -80,4 +66,4 @@ extension Curve25519.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
public typealias HPKEEphemeralPrivateKey = Curve25519.KeyAgreement.PrivateKey
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,29 +11,17 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if CRYPTOKIT_STATIC_LIBRARY
@_exported import CryptoKit_Static
#else
#if canImport(CryptoKit)
@_exported import CryptoKit
#endif
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension P256.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
/// Creates a NIST P-256 elliptic curve private key for use with Diffie-Hellman key exchange.
public init() {
@@ -41,12 +29,6 @@ extension P256.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension P256.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
/// The type of the ephemeral private key associated with this public key.
public typealias EphemeralPrivateKey = P256.KeyAgreement.PrivateKey
@@ -86,12 +68,6 @@ extension P256.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
public typealias HPKEEphemeralPrivateKey = P256.KeyAgreement.PrivateKey
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension P384.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
/// Creates a NIST P-384 elliptic curve private key for use with Diffie-Hellman key exchange.
public init() {
@@ -99,12 +75,6 @@ extension P384.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension P384.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
/// The type of the ephemeral private key associated with this public key.
public typealias EphemeralPrivateKey = P384.KeyAgreement.PrivateKey
@@ -144,12 +114,6 @@ extension P384.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension P521.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
/// Creates a NIST P-521 elliptic curve private key for use with Diffie-Hellman key exchange.
public init() {
@@ -157,12 +121,6 @@ extension P521.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension P521.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
/// The type of the ephemeral private key associated with this public key.
public typealias EphemeralPrivateKey = P521.KeyAgreement.PrivateKey
@@ -205,4 +163,4 @@ extension P521.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
public typealias HPKEEphemeralPrivateKey = P521.KeyAgreement.PrivateKey
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,34 +11,22 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension HPKE {
/// The key encapsulation mechanisms to use in HPKE.
///
/// The module-lattice key encapsulation mechanism (ML-KEM) is designed to offer increased security in situations
/// where an adversary uses a quantum computer.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
@nonexhaustive
public enum KEM: CaseIterable, Hashable, Sendable {
public static var allCases: [HPKE.KEM] {
var cases = [KEM.P256_HKDF_SHA256, KEM.P384_HKDF_SHA384, KEM.P521_HKDF_SHA512, KEM.Curve25519_HKDF_SHA256]
@@ -62,7 +50,6 @@ extension HPKE {
case Curve25519_HKDF_SHA256
/// A key encapsulation mechanism using the X-Wing (ML-KEM-768 with X25519) key encapsulation mechanism
/// and SHA-2 hashing with a 256-bit digest.
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
case XWingMLKEM768X25519
/// Return the KEM algorithm identifier as defined in section 7.1 of [RFC 9180](https://www.ietf.org/rfc/rfc9180.pdf).
@@ -113,4 +100,4 @@ extension HPKE {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+4 -11
View File
@@ -11,27 +11,20 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension HPKE {
/// Hybrid public key encryption (HPKE) errors that CryptoKit uses.
@nonexhaustive
public enum Errors: Error {
/// The parameters for initializing an HPKE sender or receiver are inconsistent.
case inconsistentParameters
@@ -52,4 +45,4 @@ extension HPKE {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+4 -32
View File
@@ -11,22 +11,15 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if CRYPTOKIT_STATIC_LIBRARY
@_exported import CryptoKit_Static
#else
#if canImport(CryptoKit)
@_exported import CryptoKit
#endif
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
/// A container for hybrid public key encryption (HPKE) operations.
///
@@ -57,18 +50,9 @@ public import Foundation
///
/// ### Handling errors
/// - ``Errors``
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
@nonexhaustive
public enum HPKE: Sendable {}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension HPKE {
/// Static constant used to store the fixed-string label for the HPKE export API
/// See: https://datatracker.ietf.org/doc/html/rfc9180#name-secret-export
@@ -82,11 +66,6 @@ extension HPKE {
/// in turn to retrieve its ciphertext. The recipient of the messages needs to process them in the
/// same order as the `Sender`, using the same encryption mode, cipher suite, and key schedule information
/// (`info`), as well as the `Sender`'s ``encapsulatedKey``.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
public struct Sender: Sendable {
private var context: Context
/// The encapsulated symmetric key that the recipient uses to decrypt messages.
@@ -141,7 +120,6 @@ extension HPKE {
/// - ciphersuite: The cipher suite that defines the cryptographic algorithms to use.
/// - info: Data that the key derivation function uses to compute the symmetric key material. The sender and the recipient need to use the same `info` data.
/// - Note: The system throws errors from ``CryptoKit/HPKE/Errors`` when it encounters them.
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
public init<PK: HPKEKEMPublicKey>(recipientKey: PK, ciphersuite: Ciphersuite, info: Data) throws {
self.context = try Context(senderRoleWithCiphersuite: ciphersuite, mode: .base, psk: nil, pskID: nil, pkR: recipientKey, info: info)
self.encapsulatedKey = context.encapsulated
@@ -242,11 +220,6 @@ extension HPKE {
/// same order as the `Sender`, using the same cipher suite, encryption mode, and key schedule information
/// (`info` data).
/// Use a separate `Recipient` instance for each stream of messages.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
public struct Recipient: Sendable {
private var context: Context
@@ -295,7 +268,6 @@ extension HPKE {
/// - info: Data that the key derivation function uses to compute the symmetric key material. The sender and the recipient need to use the same `info` data.
/// - encapsulatedKey: The encapsulated symmetric key that the sender provides.
/// - Note: The system throws errors from ``CryptoKit/HPKE/Errors`` when it encounters them.
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
public init<SK: HPKEKEMPrivateKey>(privateKey: SK, ciphersuite: Ciphersuite, info: Data, encapsulatedKey: Data) throws {
self.context = try Context(recipientRoleWithCiphersuite: ciphersuite, mode: .base, enc: encapsulatedKey, psk: nil, pskID: nil, skR: privateKey, info: info, pkS: nil)
}
@@ -386,4 +358,4 @@ extension HPKE {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,25 +11,17 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 10.15, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension HPKE {
struct Context: Sendable {
var keySchedule: KeySchedule
@@ -44,7 +36,6 @@ extension HPKE {
sharedSecret: encapsulationResult.sharedSecret, info: info, psk: psk, pskID: pskID, ciphersuite: ciphersuite)
}
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
init<PublicKey: HPKEKEMPublicKey>(senderRoleWithCiphersuite ciphersuite: Ciphersuite, mode: Mode, psk: SymmetricKey?, pskID: Data?, pkR: PublicKey, info: Data) throws {
let encapsulationResult = try pkR.encapsulate()
encapsulated = encapsulationResult.encapsulated
@@ -77,7 +68,6 @@ extension HPKE {
self.keySchedule = try KeySchedule(mode: mode, sharedSecret: sharedSecret, info: info, psk: psk, pskID: pskID, ciphersuite: ciphersuite)
}
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
init<PrivateKey: HPKEKEMPrivateKey>(recipientRoleWithCiphersuite ciphersuite: Ciphersuite, mode: Mode, enc: Data, psk: SymmetricKey?, pskID: Data?, skR: PrivateKey, info: Data, pkS: PrivateKey.PublicKey?) throws {
let sharedSecret = try skR.decapsulate(enc)
self.encapsulated = enc
@@ -86,4 +76,4 @@ extension HPKE {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,25 +11,17 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 10.15, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension HPKE {
internal struct KeySchedule: Sendable {
fileprivate static let pksIDHashLabel = Data("psk_id_hash".utf8)
@@ -166,4 +158,4 @@ extension HPKE {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+3 -13
View File
@@ -11,22 +11,12 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 10.15, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension HPKE {
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 10.15, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
internal enum Mode: CaseIterable {
case base
case psk
@@ -48,4 +38,4 @@ extension HPKE {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+4 -11
View File
@@ -11,22 +11,15 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if CRYPTOKIT_STATIC_LIBRARY
@_exported import CryptoKit_Static
#else
#if canImport(CryptoKit)
@_exported import CryptoKit
#endif
#else
/// A container for older, cryptographically insecure algorithms.
///
/// - Important: These algorithms aren’t considered cryptographically secure,
/// but the framework provides them for backward compatibility with older
/// services that require them. For new services, avoid these algorithms.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
@nonexhaustive
public enum Insecure: Sendable {}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,14 +11,10 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension Insecure {
/// An implementation of SHA1 hashing.
///
@@ -39,11 +35,6 @@ extension Insecure {
public struct SHA1: HashFunctionImplementationDetails, Sendable {
/// The number of bytes that represents the hash function’s internal
/// state.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.2, macOS 10.15, watchOS 6.1, tvOS 13.2, macCatalyst 13.2, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.2, macOS 10.13, watchOS 6.1, tvOS 13.2, macCatalyst 13.2, visionOS 1.0, *)
#endif
public static let blockByteCount: Int = 64
/// The number of bytes in a SHA1 digest.
@@ -124,11 +115,6 @@ extension Insecure {
public struct MD5: HashFunctionImplementationDetails, Sendable {
/// The number of bytes that represents the hash function’s internal
/// state.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.2, macOS 10.15, watchOS 6.1, tvOS 13.2, macCatalyst 13.2, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.2, macOS 10.13, watchOS 6.1, tvOS 13.2, macCatalyst 13.2, visionOS 1.0, *)
#endif
public static let blockByteCount: Int = 64
/// The number of bytes in an MD5 digest.
public static let byteCount: Int = 16
@@ -189,4 +175,4 @@ extension Insecure {
}
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+24 -25
View File
@@ -16,10 +16,14 @@
// any edits of this file WILL be overwritten and thus discarded
// see section `gyb` in `README` for details.
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#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
@@ -29,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
@@ -146,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,
@@ -161,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
}
}
}
}
@@ -176,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
@@ -298,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
@@ -415,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,
@@ -430,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
}
}
}
}
@@ -445,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
@@ -564,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
@@ -573,4 +572,4 @@ enum MLKEM {
static let sharedSecretByteCount = 32
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
@@ -16,10 +16,14 @@
// any edits of this file WILL be overwritten and thus discarded
// see section `gyb` in `README` for details.
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#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
@@ -149,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,
@@ -164,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
}
}
}
}
@@ -306,4 +310,4 @@ enum MLKEM {
static let sharedSecretByteCount = 32
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
@@ -12,10 +12,14 @@
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#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
@@ -289,4 +293,4 @@ struct OpenSSLMLKEMPrivateKeyImpl<Parameters: BoringSSLBackedMLKEMParameters>: B
}
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
@@ -12,10 +12,14 @@
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#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
@@ -260,4 +264,4 @@ extension OpenSSLXWingPrivateKeyImpl {
}
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
+4 -11
View File
@@ -11,27 +11,20 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension KEM {
/// Errors that CryptoKit throws when it encounters problems in key encapsulation mechanism (KEM) operations.
@nonexhaustive
public enum Errors: Error {
/// The public key CryptoKit receives when it initializes a key encapsulation operation doesn't match the expected value.
case publicKeyMismatchDuringInitialization
@@ -41,4 +34,4 @@ extension KEM {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+4 -26
View File
@@ -11,32 +11,21 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if CRYPTOKIT_STATIC_LIBRARY
@_exported import CryptoKit_Static
#else
#if canImport(CryptoKit)
@_exported import CryptoKit
#endif
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
/// A key encapsulation mechanism.
///
/// Use a key encapsulation mechanism (KEM) to protect a symmetric cryptographic key that you share with another party.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else //CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
@nonexhaustive
public enum KEM: Sendable {
/// The result of a key encapsulation operation.
public struct EncapsulationResult: Sendable {
@@ -54,11 +43,6 @@ public enum KEM: Sendable {
}
/// The public key for a key encapsulation mechanism.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else //CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
@preconcurrency
public protocol KEMPublicKey: Sendable {
/// Generates and encapsulates a shared secret.
@@ -70,11 +54,6 @@ public protocol KEMPublicKey: Sendable {
}
/// The private key for a key encapsulation mechanism.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else //CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
@preconcurrency
public protocol KEMPrivateKey: Sendable {
associatedtype PublicKey: KEMPublicKey
@@ -96,7 +75,6 @@ public protocol KEMPrivateKey: Sendable {
}
/// A one-time private key for a key encapsulation mechanism, which can only decapsulate once but it does so faster.
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
@preconcurrency
public protocol KEMOneTimePrivateKey: ~Copyable, Sendable {
associatedtype PublicKey: KEMPublicKey
@@ -116,4 +94,4 @@ public protocol KEMOneTimePrivateKey: ~Copyable, Sendable {
/// The associated public key.
var publicKey: PublicKey { get }
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+32 -20
View File
@@ -11,7 +11,8 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if canImport(FoundationEssentials)
@@ -20,21 +21,15 @@ public import FoundationEssentials
public import Foundation
#endif
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
typealias MLKEMPublicKeyImpl = CoreCryptoMLKEMPublicKeyImpl
typealias MLKEMPrivateKeyImpl = CoreCryptoMLKEMPrivateKeyImpl
#else
typealias MLKEMPublicKeyImpl = OpenSSLMLKEMPublicKeyImpl
typealias MLKEMPrivateKeyImpl = OpenSSLMLKEMPrivateKeyImpl
#endif
typealias MLKEMOneTimePrivateKeyImpl = OpenSSLMLKEMPrivateKeyImpl
/// The Module-Lattice key encapsulation mechanism (KEM).
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
@nonexhaustive
public enum MLKEM768: Sendable {}
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
extension MLKEM768 {
/// A public key you use to encapsulate shared secrets with the Module-Lattice key encapsulation mechanism.
public struct PublicKey: KEMPublicKey, Sendable {
@@ -151,21 +146,30 @@ extension MLKEM768 {
}
}
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
/// A one-time-use private key to decapsulate a shared secret with the Module-Lattice key encapsulation mechanism.
///
/// The associated decapsulation function can be multiple times faster than the one implemented for PrivateKey,
/// but this private key can only be used to decapsulate a shared secret once.
public struct OneTimePrivateKey: KEMOneTimePrivateKey, ~Copyable {
internal let impl: MLKEMPrivateKeyImpl<MLKEM768>
internal let impl: MLKEMOneTimePrivateKeyImpl<MLKEM768>
internal init(_ impl: MLKEMPrivateKeyImpl<MLKEM768>) {
internal init(_ impl: MLKEMOneTimePrivateKeyImpl<MLKEM768>) {
self.impl = impl
}
/// Creates a one-time-use private key that reuses the key material of an existing private key.
///
/// This is used by the tests to check that the one-time decapsulation function is consistent with the regular one.
internal init(reusingForTestingOnly privateKey: MLKEM768.PrivateKey) {
self.impl = try! MLKEMOneTimePrivateKeyImpl<MLKEM768>(
seedRepresentation: privateKey.impl.seedRepresentation,
publicKeyRawRepresentation: privateKey.impl.publicKey.rawRepresentation
)
}
/// Generates a new, random one-time-use private key.
public static func generate() throws -> MLKEM768.OneTimePrivateKey {
let impl = try MLKEMPrivateKeyImpl<MLKEM768>.generatePrivateKey()
let impl = try MLKEMOneTimePrivateKeyImpl<MLKEM768>.generatePrivateKey()
return OneTimePrivateKey(impl)
}
@@ -194,10 +198,9 @@ extension MLKEM768 {
/// The Module-Lattice key encapsulation mechanism (KEM).
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
@nonexhaustive
public enum MLKEM1024: Sendable {}
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
extension MLKEM1024 {
/// A public key you use to encapsulate shared secrets with the Module-Lattice key encapsulation mechanism.
public struct PublicKey: KEMPublicKey, Sendable {
@@ -314,21 +317,30 @@ extension MLKEM1024 {
}
}
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
/// A one-time-use private key to decapsulate a shared secret with the Module-Lattice key encapsulation mechanism.
///
/// The associated decapsulation function can be multiple times faster than the one implemented for PrivateKey,
/// but this private key can only be used to decapsulate a shared secret once.
public struct OneTimePrivateKey: KEMOneTimePrivateKey, ~Copyable {
internal let impl: MLKEMPrivateKeyImpl<MLKEM1024>
internal let impl: MLKEMOneTimePrivateKeyImpl<MLKEM1024>
internal init(_ impl: MLKEMPrivateKeyImpl<MLKEM1024>) {
internal init(_ impl: MLKEMOneTimePrivateKeyImpl<MLKEM1024>) {
self.impl = impl
}
/// Creates a one-time-use private key that reuses the key material of an existing private key.
///
/// This is used by the tests to check that the one-time decapsulation function is consistent with the regular one.
internal init(reusingForTestingOnly privateKey: MLKEM1024.PrivateKey) {
self.impl = try! MLKEMOneTimePrivateKeyImpl<MLKEM1024>(
seedRepresentation: privateKey.impl.seedRepresentation,
publicKeyRawRepresentation: privateKey.impl.publicKey.rawRepresentation
)
}
/// Generates a new, random one-time-use private key.
public static func generate() throws -> MLKEM1024.OneTimePrivateKey {
let impl = try MLKEMPrivateKeyImpl<MLKEM1024>.generatePrivateKey()
let impl = try MLKEMOneTimePrivateKeyImpl<MLKEM1024>.generatePrivateKey()
return OneTimePrivateKey(impl)
}
@@ -356,4 +368,4 @@ extension MLKEM1024 {
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
-205
View File
@@ -1,205 +0,0 @@
//===----------------------------------------------------------------------===//
//
// 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 CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
%{
MLKEM_VARIANTS = [{"name": "MLKEM768", "ccinfo": "cckem_mlkem768()!"}, {"name": "MLKEM1024", "ccinfo": "cckem_mlkem1024()!"}]
}%
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
typealias MLKEMPublicKeyImpl = CoreCryptoMLKEMPublicKeyImpl
typealias MLKEMPrivateKeyImpl = CoreCryptoMLKEMPrivateKeyImpl
#else
typealias MLKEMPublicKeyImpl = OpenSSLMLKEMPublicKeyImpl
typealias MLKEMPrivateKeyImpl = OpenSSLMLKEMPrivateKeyImpl
#endif
% for MLKEM_VARIANT in MLKEM_VARIANTS:
%{
NAME = MLKEM_VARIANT["name"]
INFO = MLKEM_VARIANT["ccinfo"]
}%
/// The Module-Lattice key encapsulation mechanism (KEM).
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
public enum ${NAME}: Sendable {}
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
extension ${NAME} {
/// A public key you use to encapsulate shared secrets with the Module-Lattice key encapsulation mechanism.
public struct PublicKey: KEMPublicKey, Sendable {
var impl: MLKEMPublicKeyImpl<${NAME}>
/// Initializes a public key from a raw representation.
/// - Parameter rawRepresentation: Data that represents the public key.
public init<D: DataProtocol>(rawRepresentation: D) throws {
self.impl = try MLKEMPublicKeyImpl(rawRepresentation: rawRepresentation)
}
/// A serialized representation of the public key.
public var rawRepresentation: Data {
get {
return self.impl.rawRepresentation
}
}
/// Generates and encapsulates a shared secret.
///
/// - Returns: an encapsulated shared secret, that you decapsulate by calling ``${NAME}/PrivateKey/decapsulate(_:)`` on the corresponding private key.
public func encapsulate() throws -> KEM.EncapsulationResult {
return try self.impl.encapsulate()
}
func encapsulateWithSeed(encapSeed: Data) throws -> KEM.EncapsulationResult {
return try self.impl.encapsulateWithSeed(encapSeed)
}
}
/// A private key you use to decapsulate shared secrets with the Module-Lattice key encapsulation mechanism.
public struct PrivateKey: KEMPrivateKey {
internal let impl: MLKEMPrivateKeyImpl<${NAME}>
internal init(_ impl: MLKEMPrivateKeyImpl<${NAME}>) {
self.impl = impl
}
/// Generates a new, random private key.
public static func generate() throws -> ${NAME}.PrivateKey {
let impl = try MLKEMPrivateKeyImpl<${NAME}>.generatePrivateKey()
return PrivateKey(impl)
}
static func generateWithSeed(_ seed: Data) throws -> ${NAME}.PrivateKey {
let impl = try MLKEMPrivateKeyImpl<${NAME}>.generateWithSeed(seed)
return PrivateKey(impl)
}
/// Initializes a random private key.
public init() throws {
self = try PrivateKey.generate()
}
/// Initializes a private key from a seed representation and optional public key.
///
/// - Parameters:
/// - seedRepresentation: The seed representation `d||z`, as specified in the `ML-KEM.KeyGen_internal(d,z)` algorithm (Algorithm 16) of FIPS 203.
/// - publicKey: An optional public key. Pass this to check that the initialized private key is consistent with the public key. The initializer throws if the public key doesn't match the expected value.
public init<D: DataProtocol>(seedRepresentation: D, publicKey: ${NAME}.PublicKey?) throws {
var publicKeyRawRepresentation: Data? = nil
if publicKey != nil {
publicKeyRawRepresentation = publicKey!.rawRepresentation
}
self.impl = try MLKEMPrivateKeyImpl<${NAME}>(seedRepresentation: seedRepresentation, publicKeyRawRepresentation: publicKeyRawRepresentation)
}
/// The private key's seed representation.
///
/// The seed is `d||z`, as specified in the algorithm `ML-KEM.KeyGen_internal(d,z)` (Algorithm 16) of FIPS 203.
public var seedRepresentation: Data {
get {
return self.impl.seedRepresentation
}
}
/// Decapsulate a shared secret.
///
/// - Parameters:
/// - encapsulated: An encapsulated shared secret, that you get by calling ``${NAME}/PublicKey/encapsulate()`` on the corresponding public key.
/// - Returns: The shared secret.
public func decapsulate<D: DataProtocol>(_ encapsulated: D) throws -> SymmetricKey {
return try impl.decapsulate(encapsulated: encapsulated)
}
/// The corresponding public key.
public var publicKey: ${NAME}.PublicKey {
get {
self.impl.publicKey
}
}
/// Initializes a private key from an integrity-checked representation.
///
/// - Parameter integrityCheckedRepresentation: A representation of the private key that includes the seed value, and a hash of the corresponding public key.
public init<D: DataProtocol>(integrityCheckedRepresentation: D) throws {
guard integrityCheckedRepresentation.count == MLKEMPrivateKeyImpl<${NAME}>.seedSize + 32 else {
throw KEM.Errors.invalidSeed
}
let seed = Data(integrityCheckedRepresentation).subdata(in: 0..<MLKEMPrivateKeyImpl<${NAME}>.seedSize)
let publicKeyHashData = Data(integrityCheckedRepresentation).subdata(in: MLKEMPrivateKeyImpl<${NAME}>.seedSize..<integrityCheckedRepresentation.count)
let publicKeyHash = SHA3_256Digest(copying: publicKeyHashData.bytes)
self.impl = try MLKEMPrivateKeyImpl<${NAME}>(seedRepresentation: seed, publicKeyHash: publicKeyHash)
}
/// An integrity-checked representation of the private key.
///
/// This representation includes the seed value, and a hash of the corresponding public key.
public var integrityCheckedRepresentation: Data {
get {
return self.impl.integrityCheckedRepresentation
}
}
}
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
/// A one-time-use private key to decapsulate a shared secret with the Module-Lattice key encapsulation mechanism.
///
/// The associated decapsulation function can be multiple times faster than the one implemented for PrivateKey,
/// but this private key can only be used to decapsulate a shared secret once.
public struct OneTimePrivateKey: KEMOneTimePrivateKey, ~Copyable {
internal let impl: MLKEMPrivateKeyImpl<${NAME}>
internal init(_ impl: MLKEMPrivateKeyImpl<${NAME}>) {
self.impl = impl
}
/// Generates a new, random one-time-use private key.
public static func generate() throws -> ${NAME}.OneTimePrivateKey {
let impl = try MLKEMPrivateKeyImpl<${NAME}>.generatePrivateKey()
return OneTimePrivateKey(impl)
}
/// Initializes a random one-time-use private key.
public init() throws {
self = try OneTimePrivateKey.generate()
}
/// Decapsulate a shared secret.
///
/// - Parameters:
/// - encapsulated: An encapsulated shared secret, that you get by calling ``${NAME}/PublicKey/encapsulate()`` on the corresponding public key.
/// - Returns: The shared secret.
public consuming func decapsulate<D: DataProtocol>(_ encapsulated: D) throws -> SymmetricKey {
return try impl.decapsulate(encapsulated: encapsulated)
}
/// The corresponding public key.
public var publicKey: ${NAME}.PublicKey {
get {
self.impl.publicKey
}
}
}
}
% end
#endif // Linux or !SwiftPM
+13 -42
View File
@@ -11,54 +11,29 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if CRYPTOKIT_STATIC_LIBRARY
@_exported import CryptoKit_Static
#else
#if canImport(CryptoKit)
@_exported import CryptoKit
#endif
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
typealias XWingPublicKeyImpl = CoreCryptoXWingPublicKeyImpl
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
typealias XWingPrivateKeyImpl = CoreCryptoXWingPrivateKeyImpl
#else
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
typealias XWingPublicKeyImpl = OpenSSLXWingPublicKeyImpl
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
typealias XWingPrivateKeyImpl = OpenSSLXWingPrivateKeyImpl
#endif
/// The X-Wing (ML-KEM768 with X25519) Key Encapsulation Mechanism, defined in
/// https://datatracker.ietf.org/doc/html/draft-connolly-cfrg-xwing-kem-06
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
@nonexhaustive
public enum XWingMLKEM768X25519: Sendable {}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension XWingMLKEM768X25519 {
public struct PublicKey: KEMPublicKey {
var impl: XWingPublicKeyImpl
@@ -83,7 +58,7 @@ extension XWingMLKEM768X25519 {
}
public struct PrivateKey: KEMPrivateKey {
private var impl: XWingPrivateKeyImpl
var impl: XWingPrivateKeyImpl
public var seedRepresentation: Data {
get {
@@ -120,7 +95,6 @@ extension XWingMLKEM768X25519 {
}
}
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
/// A one-time-use private key to decapsulate a shared secret with the X-Wing key encapsulation mechanism.
///
/// The associated decapsulation function can be multiple times faster than the one implemented for PrivateKey,
@@ -132,6 +106,13 @@ extension XWingMLKEM768X25519 {
self.impl = impl
}
/// Creates a one-time-use private key that reuses the key material of an existing private key.
///
/// This is used by the tests to check that the one-time decapsulation function is consistent with the regular one.
internal init(reusingForTestingOnly privateKey: XWingMLKEM768X25519.PrivateKey) {
self.impl = privateKey.impl
}
/// Generates a new, random one-time-use private key.
public static func generate() throws -> XWingMLKEM768X25519.OneTimePrivateKey {
let impl = try XWingPrivateKeyImpl.generate()
@@ -156,11 +137,6 @@ extension XWingMLKEM768X25519 {
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension XWingMLKEM768X25519.PrivateKey: HPKEKEMPrivateKeyGeneration {
public init() throws {
self = try Self.generate()
@@ -190,11 +166,6 @@ extension XWingMLKEM768X25519.PrivateKey: HPKEKEMPrivateKeyGeneration {
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 26.0, macOS 26.0, watchOS 26.0, tvOS 26.0, macCatalyst 26.0, visionOS 26.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
extension XWingMLKEM768X25519.PublicKey: HPKEKEMPublicKey {
/// The type of the ephemeral private key associated with this public key.
public typealias EphemeralPrivateKey = XWingMLKEM768X25519.PrivateKey
@@ -237,4 +208,4 @@ extension XWingMLKEM768X25519.PublicKey: HPKEKEMPublicKey {
public typealias HPKEEphemeralPrivateKey = XWingMLKEM768X25519.PrivateKey
}
#endif
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,10 +11,14 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
#endif
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P256.KeyAgreement.PrivateKey {
@@ -45,4 +49,4 @@ extension P521.KeyAgreement.PrivateKey {
return SharedSecret(ss: key)
}
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
+3 -41
View File
@@ -11,27 +11,18 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
/// A Diffie-Hellman Key Agreement Key
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, macCatalyst 17.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
@preconcurrency
public protocol DiffieHellmanKeyAgreement: Sendable {
/// The public key share type to perform the DH Key Agreement
@@ -63,18 +54,9 @@ public protocol DiffieHellmanKeyAgreement: Sendable {
/// symmetric key suitable for creating a message authentication code like
/// ``HMAC``, or for opening and closing a sealed box with a cipher like
/// ``ChaChaPoly`` or ``AES``.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct SharedSecret: ContiguousBytes, Sendable {
var ss: SecureBytes
internal init<SS:ContiguousBytes>(withExternalSS ss: SS) {
self.ss = SecureBytes(bytes: ss)
}
internal init(ss: SecureBytes){
self.ss = ss
}
@@ -132,11 +114,6 @@ public struct SharedSecret: ContiguousBytes, Sendable {
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension SharedSecret: Hashable {
public func hash(into hasher: inout Hasher) {
ss.withUnsafeBytes { hasher.combine(bytes: $0) }
@@ -144,11 +121,6 @@ extension SharedSecret: Hashable {
}
// We want to implement constant-time comparison for digests.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension SharedSecret: Equatable {
public static func == (lhs: Self, rhs: Self) -> Bool {
return safeCompare(lhs, rhs)
@@ -174,11 +146,6 @@ extension SharedSecret: Equatable {
}
#if !hasFeature(Embedded)
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension SharedSecret: CustomStringConvertible {
public var description: String {
return "\(Self.self): \(ss.hexString)"
@@ -186,11 +153,6 @@ extension SharedSecret: CustomStringConvertible {
}
#endif
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension HashFunction {
// A wrapper function to keep the unsafe code in one place.
mutating func update(_ secret: SharedSecret) {
@@ -205,4 +167,4 @@ extension HashFunction {
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
File diff suppressed because it is too large. Load diff
-385
View File
@@ -1,385 +0,0 @@
//===----------------------------------------------------------------------===//
//
// 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 CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION || CRYPTOKIT_NO_IMPORT_FOUNDATION
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
typealias NISTCurvePublicKeyImpl = CoreCryptoNISTCurvePublicKeyImpl
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
typealias NISTCurvePrivateKeyImpl = CoreCryptoNISTCurvePrivateKeyImpl
#else
typealias NISTCurvePublicKeyImpl = OpenSSLNISTCurvePublicKeyImpl
typealias NISTCurvePrivateKeyImpl = OpenSSLNISTCurvePrivateKeyImpl
#endif
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#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.
%{
NIST_CURVES = ["P256", "P384", "P521"]
CURVES_FUNC = ["Signing", "KeyAgreement"]
}%
% for CURVE in NIST_CURVES:
%{ DISPLAY_CURVE = CURVE[:1] + "-" + CURVE[1:] }%
% for FUNC in CURVES_FUNC:
// MARK: - ${CURVE} + ${FUNC}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension ${CURVE} {
% if FUNC == "Signing":
/// A mechanism used to create or verify a cryptographic signature using
/// the NIST ${DISPLAY_CURVE} elliptic curve digital signature algorithm (ECDSA).
% else:
/// A mechanism used to create a shared secret between two users by
/// performing NIST ${DISPLAY_CURVE} elliptic curve Diffie Hellman (ECDH) key
/// exchange.
% end
public enum ${FUNC}: Sendable {
% if FUNC == "Signing":
%{ READABLE_FUNC = "signing" }%
/// A ${DISPLAY_CURVE} public key used to verify cryptographic signatures.
% else:
%{ READABLE_FUNC = "key agreement" }%
/// A ${DISPLAY_CURVE} public key used for key agreement.
% end
public struct PublicKey: NISTECPublicKey, Sendable {
var impl: NISTCurvePublicKeyImpl<${CURVE}>
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a collection of bytes.
///
/// - Parameters:
/// - rawRepresentation: A raw representation of the key as a collection of
/// contiguous bytes.
public init<D: ContiguousBytes>(rawRepresentation: D) throws(CryptoKitMetaError) {
impl = try NISTCurvePublicKeyImpl(rawRepresentation: rawRepresentation)
}
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a compact
/// representation of the key.
///
/// - Parameters:
/// - compactRepresentation: A compact representation of the key
/// as a collection of contiguous bytes.
public init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws(CryptoKitMetaError) {
impl = try NISTCurvePublicKeyImpl(compactRepresentation: compactRepresentation)
}
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from an ANSI x9.63
/// representation.
///
/// - Parameters:
/// - x963Representation: An ANSI x9.63 representation of the key.
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws(CryptoKitMetaError) {
impl = try NISTCurvePublicKeyImpl(x963Representation: x963Representation)
}
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a compressed representation of
/// the key.
///
/// - Parameters:
/// - compressedRepresentation: A compressed representation of the key as a collection
/// of contiguous bytes.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
public init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws(CryptoKitMetaError) {
impl = try NISTCurvePublicKeyImpl(compressedRepresentation: compressedRepresentation)
}
#if !hasFeature(Embedded)
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a Privacy-Enhanced Mail
/// (PEM) representation.
///
/// - Parameters:
/// - pemRepresentation: A PEM representation of the key.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public init(pemRepresentation: String) throws(CryptoKitMetaError) {
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
guard pem.type == "PUBLIC KEY" else {
throw CryptoKitASN1Error.invalidPEMDocument
}
self = try .init(derRepresentation: pem.derBytes)
}
#endif
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a Distinguished Encoding
/// Rules (DER) encoded representation.
///
/// - Parameters:
/// - derRepresentation: A DER-encoded representation of the key.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws(CryptoKitMetaError) where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
let parsed = try ASN1.SubjectPublicKeyInfo(asn1Encoded: bytes)
self = try .init(x963Representation: parsed.key)
}
init(impl: NISTCurvePublicKeyImpl<${CURVE}>) {
self.impl = impl
}
/// A compact representation of the public key.
public var compactRepresentation: Data? { impl.compactRepresentation }
/// A full representation of the public key.
public var rawRepresentation: Data { impl.rawRepresentation }
/// An ANSI x9.63 representation of the public key.
public var x963Representation: Data { impl.x963Representation }
/// A compressed representation of the public key.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
public var compressedRepresentation: Data { impl.compressedRepresentation }
/// A Distinguished Encoding Rules (DER) encoded representation of the public key.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public var derRepresentation: Data {
let spki = ASN1.SubjectPublicKeyInfo(algorithmIdentifier: .ecdsa${CURVE}, key: Array(self.x963Representation))
var serializer = ASN1.Serializer()
// Serializing these keys can't throw
try! serializer.serialize(spki)
return Data(serializer.serializedBytes)
}
#if !hasFeature(Embedded)
/// A Privacy-Enhanced Mail (PEM) representation of the public key.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PUBLIC KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
#endif
}
% if FUNC == "Signing":
/// A ${DISPLAY_CURVE} private key used to create cryptographic signatures.
% else:
/// A ${DISPLAY_CURVE} private key used for key agreement.
% end
public struct PrivateKey: NISTECPrivateKey, Sendable {
let impl: NISTCurvePrivateKeyImpl<${CURVE}>
/// Creates a random ${DISPLAY_CURVE} private key for ${READABLE_FUNC}.
///
/// Keys that use a compact point encoding enable shorter public keys, but aren’t
/// compliant with FIPS certification. If your app requires FIPS certification,
/// create a key with ``init(rawRepresentation:)``.
///
/// - Parameters:
/// - compactRepresentable: A Boolean value that indicates whether CryptoKit
/// creates the key with the structure to enable compact point encoding.
public init(compactRepresentable: Bool = true) {
impl = NISTCurvePrivateKeyImpl(compactRepresentable: compactRepresentable)
}
/// Creates a ${DISPLAY_CURVE} private key for ${READABLE_FUNC} from an ANSI x9.63
/// representation.
///
/// - Parameters:
/// - x963Representation: An ANSI x9.63 representation of the key.
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws(CryptoKitMetaError) {
impl = try NISTCurvePrivateKeyImpl(x963: x963Representation)
}
/// Creates a ${DISPLAY_CURVE} private key for ${READABLE_FUNC} from a collection of bytes.
///
/// - Parameters:
/// - rawRepresentation: A raw representation of the key as a collection of
/// contiguous bytes.
public init<Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws(CryptoKitMetaError) {
impl = try NISTCurvePrivateKeyImpl(data: rawRepresentation)
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 13.0, watchOS 8.0, tvOS 16.0, macCatalyst 16.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 16.0, macOS 10.13, watchOS 8.0, tvOS 16.0, macCatalyst 16.0, visionOS 1.0, *)
#endif
internal init(seed: Data, compactRepresentable: Bool) throws(CryptoKitMetaError) {
impl = try NISTCurvePrivateKeyImpl(seed: seed, compactRepresentable: compactRepresentable)
}
#if !hasFeature(Embedded)
/// Creates a ${DISPLAY_CURVE} private key for ${READABLE_FUNC} from a Privacy-Enhanced Mail
/// PEM) representation.
///
/// - Parameters:
/// - pemRepresentation: A PEM representation of the key.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public init(pemRepresentation: String) throws(CryptoKitMetaError) {
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
switch pem.type {
case "EC PRIVATE KEY":
let parsed = try ASN1.SEC1PrivateKey(asn1Encoded: Array(pem.derBytes))
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
}
}
#endif
/// Creates a ${DISPLAY_CURVE} private key for ${READABLE_FUNC} from a Distinguished Encoding
/// Rules (DER) encoded representation.
///
/// - Parameters:
/// - derRepresentation: A DER-encoded representation of the key.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws(CryptoKitMetaError) where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
// We have to try to parse this twice because we have no information about what kind of key this is.
// We try with PKCS#8 first, and then fall back to SEC.1.
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
self = try .init(rawRepresentation: key.privateKey)
}
}
init(impl: NISTCurvePrivateKeyImpl<${CURVE}>) {
self.impl = impl
}
/// The corresponding public key.
public var publicKey: ${CURVE}.${FUNC}.PublicKey {
return PublicKey(impl: impl.publicKey())
}
/// A data representation of the private key.
public var rawRepresentation: Data { impl.rawRepresentation }
/// An ANSI x9.63 representation of the private key.
public var x963Representation: Data { impl.x963Representation }
/// A Distinguished Encoding Rules (DER) encoded representation of the private key.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public var derRepresentation: Data {
let pkey = ASN1.PKCS8PrivateKey(algorithm: .ecdsa${CURVE}, privateKey: Array(self.rawRepresentation), publicKey: Array(self.publicKey.x963Representation))
var serializer = ASN1.Serializer()
// Serializing these keys can't throw
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
#if !hasFeature(Embedded)
/// A Privacy-Enhanced Mail (PEM) representation of the private key.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
#endif
}
}
}
% end
% end
% for CURVE in NIST_CURVES:
// MARK: - ${CURVE} + DH
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension ${CURVE}.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
/// Computes a shared secret with the provided public key from another party.
///
/// - Parameters:
/// - publicKeyShare: The public key from another party to be combined with the private
/// key from this user to create the shared secret.
/// - Returns: The computed shared secret.
public func sharedSecretFromKeyAgreement(with publicKeyShare: ${CURVE}.KeyAgreement.PublicKey) throws(CryptoKitMetaError) -> SharedSecret {
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION || CRYPTOKIT_NO_IMPORT_FOUNDATION
return try self.coreCryptoSharedSecretFromKeyAgreement(with: publicKeyShare)
#else
return try self.openSSLSharedSecretFromKeyAgreement(with: publicKeyShare)
#endif
}
}
% end
#endif // Linux or !SwiftPM
+4 -8
View File
@@ -11,19 +11,15 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
import FoundationEssentials
#else
public import Foundation
#endif
import Foundation
#endif
internal struct ANSIKDFx963<H: HashFunction>: Sendable {
+5 -60
View File
@@ -11,20 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
/// A standards-based implementation of an HMAC-based Key Derivation Function
/// (HKDF).
@@ -41,11 +37,6 @@ public import Foundation
/// material in the form of a hashed authentication code, then call
/// ``expand(pseudoRandomKey:info:outputByteCount:)`` using that key material to
/// generate a symmetric key of the length you specify.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public struct HKDF<H: HashFunction>: Sendable {
/// Derives a symmetric encryption key from a main key or passcode using
/// HKDF key derivation with information and salt you specify.
@@ -57,12 +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 !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
#if swift(<6.3)
#if compiler(<6.3)
@_lifetime(outputKey: copy outputKey)
#endif
public static func deriveKey(inputKeyMaterial: SymmetricKey,
@@ -90,11 +76,6 @@ public struct HKDF<H: HashFunction>: Sendable {
/// - outputByteCount: The length in bytes of the resulting symmetric key.
///
/// - Returns: The derived symmetric key.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public static func deriveKey<Salt: DataProtocol, Info: DataProtocol>(
inputKeyMaterial: SymmetricKey,
salt: Salt,
@@ -139,11 +120,6 @@ public struct HKDF<H: HashFunction>: Sendable {
/// - outputByteCount: The length in bytes of the resulting symmetric key.
///
/// - Returns: The derived symmetric key.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public static func deriveKey<Info: DataProtocol>(inputKeyMaterial: SymmetricKey,
info: Info,
outputByteCount: Int) -> SymmetricKey {
@@ -160,11 +136,6 @@ public struct HKDF<H: HashFunction>: Sendable {
/// - outputByteCount: The length in bytes of the resulting symmetric key.
///
/// - Returns: The derived symmetric key.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public static func deriveKey<Salt: DataProtocol>(inputKeyMaterial: SymmetricKey,
salt: Salt,
outputByteCount: Int) -> SymmetricKey {
@@ -180,11 +151,6 @@ public struct HKDF<H: HashFunction>: Sendable {
/// - outputByteCount: The length in bytes of the resulting symmetric key.
///
/// - Returns: The derived symmetric key.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public static func deriveKey(inputKeyMaterial: SymmetricKey,
outputByteCount: Int) -> SymmetricKey {
return deriveKey(inputKeyMaterial: inputKeyMaterial, salt: [UInt8](), info: [UInt8](), outputByteCount: outputByteCount)
@@ -204,11 +170,6 @@ public struct HKDF<H: HashFunction>: Sendable {
///
/// - Returns: A pseudorandom, cryptographically strong key in the form of a
/// hashed authentication code.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public static func extract<Salt: DataProtocol>(inputKeyMaterial: SymmetricKey, salt: Salt?) -> HashedAuthenticationCode<H> {
let key: SymmetricKey
if let salt {
@@ -239,11 +200,6 @@ public struct HKDF<H: HashFunction>: Sendable {
///
/// - Returns: A pseudorandom, cryptographically strong key in the form of a
/// hashed authentication code.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public static func extract(inputKeyMaterial: SymmetricKey, salt: RawSpan?) -> HashedAuthenticationCode<H> {
let key = if let salt {
SymmetricKey(bytes: salt)
@@ -267,11 +223,6 @@ public struct HKDF<H: HashFunction>: Sendable {
/// - outputByteCount: The length in bytes of the resulting symmetric key.
///
/// - Returns: The derived symmetric key.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public static func expand<PRK: ContiguousBytes, Info: DataProtocol>(pseudoRandomKey prk: PRK, info: Info?, outputByteCount: Int) -> SymmetricKey {
SymmetricKey(capacity: outputByteCount) { output in
prk.withUnsafeBytes { prkBuffer in
@@ -307,12 +258,7 @@ public struct HKDF<H: HashFunction>: Sendable {
/// - outputByteCount: The length in bytes of the resulting symmetric key.
///
/// - Returns: The derived symmetric key.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
#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) {
@@ -327,7 +273,6 @@ public struct HKDF<H: HashFunction>: Sendable {
hmac.update(bytes: info)
}
// hmac.update(bytes: CollectionOfOne(i).span.bytes)
var buf = i
withUnsafeBytes(of: &buf) { rawBuffer in
let span = RawSpan(_unsafeBytes: rawBuffer)
@@ -341,4 +286,4 @@ public struct HKDF<H: HashFunction>: Sendable {
}
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+4 -15
View File
@@ -11,32 +11,23 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
@available(iOS 15.0, macOS 12.0, watchOS 8.0, tvOS 15.0, macCatalyst 15.0, *)
typealias AESWRAPImpl = CoreCryptoAESWRAPImpl
#else
typealias AESWRAPImpl = BoringSSLAESWRAPImpl
#endif
@available(iOS 15.0, macOS 12.0, watchOS 8.0, tvOS 15.0, macCatalyst 15.0, *)
extension AES {
/// An implementation of AES Key Wrapping in accordance with the IETF RFC
/// 3394 specification.
@available(iOS 15.0, macOS 12.0, watchOS 8.0, tvOS 15.0, macCatalyst 15.0, *)
@nonexhaustive
public enum KeyWrap: Sendable {
/// Wraps a key using the AES wrap algorithm.
///
@@ -48,7 +39,6 @@ extension AES {
/// - kek: The key encryption key.
///
/// - Returns: The wrapped key.
@available(iOS 15.0, macOS 12.0, watchOS 8.0, tvOS 15.0, macCatalyst 15.0, *)
public static func wrap(_ keyToWrap: SymmetricKey, using kek: SymmetricKey) throws -> Data {
return try AESWRAPImpl.wrap(key: kek, keyToWrap: keyToWrap)
}
@@ -64,11 +54,10 @@ extension AES {
/// - kek: The key encryption key.
///
/// - Returns: The unwrapped key.
@available(iOS 15.0, macOS 12.0, watchOS 8.0, tvOS 15.0, macCatalyst 15.0, *)
public static func unwrap<WrappedKey: DataProtocol>(_ wrappedKey: WrappedKey, using kek: SymmetricKey) throws -> SymmetricKey {
return try AESWRAPImpl.unwrap(key: kek, wrappedKey: wrappedKey)
}
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,10 +11,14 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#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
@@ -29,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,
@@ -72,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,
@@ -95,8 +93,6 @@ enum BoringSSLAESWRAPImpl {
count = Int(rc)
}
}
return SymmetricKey(data: unwrapped)
}
}
@@ -113,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)
@@ -146,4 +140,4 @@ extension SymmetricKey {
}
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
@@ -11,11 +11,14 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
@@ -41,7 +44,7 @@ extension Curve25519.Signing {
privateKeyBytes in
privateKeyBytes = 64
publicKey.withUnsafeMutableBytes { publicKeyPtr in
CCryptoBoringSSLShims_ED25519_keypair(
CCryptoBoringSSL_ED25519_keypair(
publicKeyPtr.baseAddress,
privateKeyPtr.baseAddress
)
@@ -75,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
@@ -123,4 +126,4 @@ extension Curve25519.Signing {
}
}
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
@@ -11,11 +11,14 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
import FoundationEssentials
@@ -143,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
@@ -330,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()
@@ -348,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
@@ -570,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,
@@ -681,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(
@@ -696,9 +699,9 @@ 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
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
@@ -11,11 +11,14 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
@@ -72,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
)
@@ -100,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
)
@@ -118,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),
@@ -130,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.
@@ -162,4 +166,4 @@ extension Curve25519.KeyAgreement {
}
}
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
+4 -7
View File
@@ -11,14 +11,11 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
/// An elliptic curve that enables X25519 key agreement and Ed25519 signatures.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
@nonexhaustive
public enum Curve25519: Sendable {}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+4 -17
View File
@@ -11,19 +11,15 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
extension Curve25519.Signing {
static var keyByteCount: Int {
@@ -31,22 +27,13 @@ extension Curve25519.Signing {
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension Curve25519 {
/// A mechanism used to create or verify a cryptographic signature using
/// Ed25519.
@nonexhaustive
public enum Signing: Sendable {
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION || CRYPTOKIT_NO_IMPORT_FOUNDATION
typealias Curve25519PrivateKeyImpl = Curve25519.Signing.CoreCryptoCurve25519PrivateKeyImpl
typealias Curve25519PublicKeyImpl = Curve25519.Signing.CoreCryptoCurve25519PublicKeyImpl
#else
typealias Curve25519PrivateKeyImpl = Curve25519.Signing.OpenSSLCurve25519PrivateKeyImpl
typealias Curve25519PublicKeyImpl = Curve25519.Signing.OpenSSLCurve25519PublicKeyImpl
#endif
/// A Curve25519 private key used to create cryptographic signatures.
public struct PrivateKey: ECPrivateKey, Sendable {
@@ -111,4 +98,4 @@ extension Curve25519 {
}
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+6 -26
View File
@@ -11,25 +11,17 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION || CRYPTOKIT_NO_IMPORT_FOUNDATION
typealias SupportedCurveDetailsImpl = CorecryptoSupportedNISTCurve
#else
typealias SupportedCurveDetailsImpl = OpenSSLSupportedNISTCurve
#endif
protocol ECPublicKey {
init <Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws(CryptoKitMetaError)
@@ -56,26 +48,14 @@ protocol NISTECPrivateKey: ECPrivateKey where PK: NISTECPublicKey {
}
/// An elliptic curve that enables NIST P-256 signatures and key agreement.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
@nonexhaustive
public enum P256: Sendable { }
/// An elliptic curve that enables NIST P-384 signatures and key agreement.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
@nonexhaustive
public enum P384: Sendable { }
/// An elliptic curve that enables NIST P-521 signatures and key agreement.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
@nonexhaustive
public enum P521: Sendable { }
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+4 -27
View File
@@ -11,19 +11,15 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
extension Curve25519.KeyAgreement {
static var keyByteCount: Int {
@@ -31,29 +27,15 @@ extension Curve25519.KeyAgreement {
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension Curve25519 {
/// A mechanism used to create a shared secret between two users by
/// performing X25519 key agreement.
@nonexhaustive
public enum KeyAgreement: Sendable {
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION || CRYPTOKIT_NO_IMPORT_FOUNDATION
typealias Curve25519PrivateKeyImpl = Curve25519.KeyAgreement.CoreCryptoCurve25519PrivateKeyImpl
typealias Curve25519PublicKeyImpl = Curve25519.KeyAgreement.CoreCryptoCurve25519PublicKeyImpl
#else
typealias Curve25519PrivateKeyImpl = Curve25519.KeyAgreement.OpenSSLCurve25519PrivateKeyImpl
typealias Curve25519PublicKeyImpl = Curve25519.KeyAgreement.OpenSSLCurve25519PublicKeyImpl
#endif
/// A Curve25519 public key used for key agreement.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct PublicKey: ECPublicKey, Sendable {
fileprivate var baseKey: Curve25519PublicKeyImpl
@@ -93,11 +75,6 @@ extension Curve25519 {
}
/// A Curve25519 private key used for key agreement.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct PrivateKey: DiffieHellmanKeyAgreement, Sendable {
fileprivate var baseKey: Curve25519PrivateKeyImpl
@@ -146,4 +123,4 @@ extension Curve25519 {
}
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,20 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
/// The sizes that a symmetric cryptographic key can take.
///
@@ -33,11 +29,6 @@ public import Foundation
/// standard key sizes, like ``bits128``, ``bits192``, or ``bits256``. When you
/// need a key with a non-standard length, use the ``init(bitCount:)``
/// initializer to create a `SymmetricKeySize` instance with a custom bit count.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct SymmetricKeySize: Sendable {
/// The number of bits in the key.
public let bitCount: Int
@@ -78,11 +69,6 @@ public struct SymmetricKeySize: Sendable {
/// symmetric key to compute a message authentication code like ``HMAC``, or to
/// open and close a sealed box (``ChaChaPoly/SealedBox`` or
/// ``AES/GCM/SealedBox``) using a cipher like ``ChaChaPoly`` or ``AES``.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct SymmetricKey: ContiguousBytes, Sendable {
let sb: SecureBytes
@@ -105,11 +91,6 @@ public struct SymmetricKey: ContiguousBytes, Sendable {
#endif
/// Access the raw bytes of the key.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public var bytes: RawSpan {
sb.bytes
}
@@ -146,7 +127,6 @@ public struct SymmetricKey: ContiguousBytes, Sendable {
///
/// - Parameters:
/// - byte: The span of bytes from which to create the key.
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
public init(copyingWithZeroing bytes: inout MutableRawSpan) {
self = bytes.withUnsafeBytes { SymmetricKey(data: $0) }
bytes.withUnsafeMutableBytes { $0.zeroize() }
@@ -188,11 +168,6 @@ public struct SymmetricKey: ContiguousBytes, Sendable {
/// - callback: A callback that will be invoked to initialize the contents
/// of the key. It must initialize the full set of size.bitCount / 8 bytes
/// in the provided output span.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public init<E: Error>(size: SymmetricKeySize, initializingWith callback: (inout OutputRawSpan) throws(E) -> Void) throws(E) {
try self.init(capacity: Int(size.bitCount / 8), initializingWith: callback)
}
@@ -218,15 +193,10 @@ public struct SymmetricKey: ContiguousBytes, Sendable {
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension SymmetricKey: Equatable {
public static func == (lhs: Self, rhs: Self) -> Bool {
return safeCompare(lhs, rhs)
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,24 +11,15 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if CRYPTOKIT_STATIC_LIBRARY
@_exported import CryptoKit_Static
#else
#if canImport(CryptoKit)
@_exported import CryptoKit
#endif
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
/// A hash-based message authentication algorithm.
///
@@ -43,11 +34,6 @@ public import Foundation
/// need to encrypt the data as well as authenticate it, use a cipher like
/// ``AES`` or ``ChaChaPoly`` to put the data into a sealed box (an instance of
/// ``AES/GCM/SealedBox`` or ``ChaChaPoly/SealedBox``).
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else //CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct HMAC<H: HashFunction>: MACAlgorithm, Sendable {
/// An alias for the symmetric key type used to compute or verify a message
/// authentication code.
@@ -79,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
}
@@ -130,11 +106,6 @@ public struct HMAC<H: HashFunction>: MACAlgorithm, Sendable {
/// - key: The symmetric key used to secure the computation.
///
/// - Returns: The message authentication code.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public static func authenticationCode(for data: RawSpan, using key: SymmetricKey) -> MAC {
var authenticator = Self(key: key)
authenticator.update(bytes: data)
@@ -166,11 +137,6 @@ public struct HMAC<H: HashFunction>: MACAlgorithm, Sendable {
///
/// - Returns: A Boolean value that’s `true` if the message authentication
/// code is valid for the specified block of data.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.2, macOS 10.15, watchOS 6.1, tvOS 13.2, macCatalyst 13.2, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.2, macOS 10.13, watchOS 6.1, tvOS 13.2, macCatalyst 13.2, visionOS 1.0, *)
#endif
public static func isValidAuthenticationCode<C: ContiguousBytes, D: DataProtocol>(_ authenticationCode: C,
authenticating authenticatedData: D,
using key: SymmetricKey) -> Bool {
@@ -190,11 +156,6 @@ public struct HMAC<H: HashFunction>: MACAlgorithm, Sendable {
}
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 27.0, macOS 27.0, watchOS 27.0, tvOS 27.0, macCatalyst 27.0, visionOS 27.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 14.0, macOS 10.13, watchOS 7.0, tvOS 14.0, macCatalyst 14.0, visionOS 1.0, *)
#endif
public mutating func update(bytes: RawSpan) {
innerHasher.update(bytes: bytes)
}
@@ -245,11 +206,6 @@ public struct HMAC<H: HashFunction>: MACAlgorithm, Sendable {
}
/// A hash-based message authentication code.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
public struct HashedAuthenticationCode<H: HashFunction>: MessageAuthenticationCode, Sendable {
let digest: H.Digest
@@ -283,4 +239,4 @@ public struct HashedAuthenticationCode<H: HashFunction>: MessageAuthenticationCo
}
#endif
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,36 +11,19 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#endif
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
protocol MACAlgorithm {
associatedtype Key
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION || CRYPTOKIT_NO_IMPORT_FOUNDATION
#if CRYPTOKIT_STATIC_LIBRARY
associatedtype MAC: CryptoKit_Static.MessageAuthenticationCode
#else
associatedtype MAC: CryptoKit.MessageAuthenticationCode
#endif
#else
associatedtype MAC: Crypto.MessageAuthenticationCode
#endif
/// Initializes the MAC Algorithm
///
@@ -58,11 +41,6 @@ protocol MACAlgorithm {
func finalize() -> MAC
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension MACAlgorithm {
/// Computes a Message Authentication Code.
///
@@ -89,4 +67,4 @@ extension MACAlgorithm {
return mac == Self.authenticationCode(bufferPointer: bufferPointer, using: key)
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,39 +11,25 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if CRYPTOKIT_STATIC_LIBRARY
@_exported import CryptoKit_Static
#else
#if canImport(CryptoKit)
@_exported import CryptoKit
#endif
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
#if hasFeature(Embedded)
/// A type that represents a message authentication code.
@preconcurrency
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public protocol MessageAuthenticationCode: Hashable, ContiguousBytes, Sendable, Sequence where Element == UInt8 {
/// The number of bytes in the message authentication code.
var byteCount: Int { get }
}
#else
/// A type that represents a message authentication code.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
@preconcurrency
public protocol MessageAuthenticationCode: Hashable, ContiguousBytes, Sendable, CustomStringConvertible, Sequence where Element == UInt8 {
/// The number of bytes in the message authentication code.
@@ -51,11 +37,6 @@ public protocol MessageAuthenticationCode: Hashable, ContiguousBytes, Sendable,
}
#endif
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension MessageAuthenticationCode {
/// Returns a Boolean value indicating whether two message authentication
/// codes are equal.
@@ -90,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()
})
}
@@ -100,4 +81,4 @@ extension MessageAuthenticationCode {
}
#endif
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
+4 -12
View File
@@ -11,24 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
/// A container for Advanced Encryption Standard (AES) ciphers.
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
@nonexhaustive
public enum AES: Sendable {
static let blockSizeByteCount = 16
}
#if !CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
#else // CRYPTOKIT_STATIC_LIBRARY
@available(iOS 13.0, macOS 10.13, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, visionOS 1.0, *)
#endif
extension AES {
static func isValidKey(_ key: SymmetricKey) -> Bool {
switch key.bitCount {
@@ -43,4 +35,4 @@ extension AES {
}
}
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
@@ -11,11 +11,14 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
import FoundationEssentials
@@ -25,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()
}
@@ -96,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
)
@@ -119,4 +107,4 @@ class ECDSASignature {
try body(self._baseSig)
}
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
@@ -11,10 +11,14 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
import FoundationEssentials
@@ -63,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 {
@@ -100,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 {
@@ -137,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 {
@@ -173,4 +144,4 @@ extension P521.Signing.PublicKey {
return self.impl.key.isValidSignature(baseSignature, for: digest)
}
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
@@ -11,11 +11,14 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
@@ -89,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,
@@ -128,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,
@@ -144,4 +147,4 @@ extension Curve25519.Signing.PrivateKey {
return signature
}
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
@@ -12,21 +12,18 @@
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
@_implementationOnly import CCryptoBoringSSL
#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
@_implementationOnly import CCryptoBoringSSL
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
@@ -642,4 +639,4 @@ enum MLDSA {
static let seedByteCount = 32
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
@@ -12,21 +12,18 @@
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
@_implementationOnly import CCryptoBoringSSL
#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
@_implementationOnly import CCryptoBoringSSL
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
@@ -345,4 +342,4 @@ enum MLDSA {
static let seedByteCount = 32
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
@@ -12,10 +12,14 @@
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#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
@@ -171,4 +175,4 @@ struct OpenSSLMLDSAPublicKeyImpl<Parameters: BoringSSLBackedMLDSAParameters> {
}
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#endif // canImport(CryptoKit)
+3 -50
View File
@@ -11,20 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
public import SwiftSystem
#elseif CRYPTOKIT_NO_IMPORT_FOUNDATION
#else
#if canImport(FoundationEssentials)
public import FoundationEssentials
#else
public import Foundation
#endif
#endif
// MARK: - Generated file, do NOT edit
// any edits of this file WILL be overwritten and thus discarded
@@ -37,7 +33,6 @@ protocol NISTECDSASignature {
var rawRepresentation: Data { get }
}
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
protocol NISTSigning {
associatedtype PublicKey: NISTECPublicKey & DataValidator & DigestValidator
associatedtype PrivateKey: NISTECPrivateKey & Signer
@@ -45,7 +40,6 @@ protocol NISTSigning {
}
// MARK: - P256 + Signing
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P256.Signing {
/// A P-256 elliptic curve digital signature algorithm (ECDSA) signature.
@@ -146,11 +140,9 @@ extension P256.Signing {
}
}
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P256.Signing: NISTSigning {}
// MARK: - P256 + PrivateKey
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P256.Signing.PrivateKey: DigestSigner {
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
/// signature of the digest you provide over the P-256 elliptic curve.
@@ -161,15 +153,10 @@ extension P256.Signing.PrivateKey: DigestSigner {
/// algorithm employs randomization to generate a different signature on
/// every call, even for the same data and key.
public func signature<D: Digest>(for digest: D) throws(CryptoKitMetaError) -> P256.Signing.ECDSASignature {
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION || CRYPTOKIT_NO_IMPORT_FOUNDATION
return try self.coreCryptoSignature(for: digest)
#else
return try self.openSSLSignature(for: digest)
#endif
}
}
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P256.Signing.PrivateKey: Signer {
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
/// signature of the data you provide over the P-256 elliptic curve,
@@ -185,7 +172,6 @@ extension P256.Signing.PrivateKey: Signer {
}
}
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P256.Signing.PublicKey: DigestValidator {
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
/// signature on a digest over the P-256 elliptic curve.
@@ -196,15 +182,10 @@ extension P256.Signing.PublicKey: DigestValidator {
/// - Returns: A Boolean value that’s `true` if the signature is valid for
/// the given digest; otherwise, `false`.
public func isValidSignature<D: Digest>(_ signature: P256.Signing.ECDSASignature, for digest: D) -> Bool {
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION || CRYPTOKIT_NO_IMPORT_FOUNDATION
return self.coreCryptoIsValidSignature(signature, for: digest)
#else
return self.openSSLIsValidSignature(signature, for: digest)
#endif
}
}
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P256.Signing.PublicKey: DataValidator {
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
/// signature on a block of data over the P-256 elliptic curve.
@@ -220,7 +201,6 @@ extension P256.Signing.PublicKey: DataValidator {
}
// MARK: - P384 + Signing
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P384.Signing {
/// A P-384 elliptic curve digital signature algorithm (ECDSA) signature.
@@ -321,11 +301,9 @@ extension P384.Signing {
}
}
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P384.Signing: NISTSigning {}
// MARK: - P384 + PrivateKey
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P384.Signing.PrivateKey: DigestSigner {
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
/// signature of the digest you provide over the P-384 elliptic curve.
@@ -336,15 +314,10 @@ extension P384.Signing.PrivateKey: DigestSigner {
/// algorithm employs randomization to generate a different signature on
/// every call, even for the same data and key.
public func signature<D: Digest>(for digest: D) throws(CryptoKitMetaError) -> P384.Signing.ECDSASignature {
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION || CRYPTOKIT_NO_IMPORT_FOUNDATION
return try self.coreCryptoSignature(for: digest)
#else
return try self.openSSLSignature(for: digest)
#endif
}
}
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P384.Signing.PrivateKey: Signer {
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
/// signature of the data you provide over the P-384 elliptic curve,
@@ -360,7 +333,6 @@ extension P384.Signing.PrivateKey: Signer {
}
}
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P384.Signing.PublicKey: DigestValidator {
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
/// signature on a digest over the P-384 elliptic curve.
@@ -371,15 +343,10 @@ extension P384.Signing.PublicKey: DigestValidator {
/// - Returns: A Boolean value that’s `true` if the signature is valid for
/// the given digest; otherwise, `false`.
public func isValidSignature<D: Digest>(_ signature: P384.Signing.ECDSASignature, for digest: D) -> Bool {
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION || CRYPTOKIT_NO_IMPORT_FOUNDATION
return self.coreCryptoIsValidSignature(signature, for: digest)
#else
return self.openSSLIsValidSignature(signature, for: digest)
#endif
}
}
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P384.Signing.PublicKey: DataValidator {
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
/// signature on a block of data over the P-384 elliptic curve.
@@ -395,7 +362,6 @@ extension P384.Signing.PublicKey: DataValidator {
}
// MARK: - P521 + Signing
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P521.Signing {
/// A P-521 elliptic curve digital signature algorithm (ECDSA) signature.
@@ -496,11 +462,9 @@ extension P521.Signing {
}
}
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P521.Signing: NISTSigning {}
// MARK: - P521 + PrivateKey
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P521.Signing.PrivateKey: DigestSigner {
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
/// signature of the digest you provide over the P-521 elliptic curve.
@@ -511,15 +475,10 @@ extension P521.Signing.PrivateKey: DigestSigner {
/// algorithm employs randomization to generate a different signature on
/// every call, even for the same data and key.
public func signature<D: Digest>(for digest: D) throws(CryptoKitMetaError) -> P521.Signing.ECDSASignature {
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION || CRYPTOKIT_NO_IMPORT_FOUNDATION
return try self.coreCryptoSignature(for: digest)
#else
return try self.openSSLSignature(for: digest)
#endif
}
}
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P521.Signing.PrivateKey: Signer {
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
/// signature of the data you provide over the P-521 elliptic curve,
@@ -535,7 +494,6 @@ extension P521.Signing.PrivateKey: Signer {
}
}
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P521.Signing.PublicKey: DigestValidator {
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
/// signature on a digest over the P-521 elliptic curve.
@@ -546,15 +504,10 @@ extension P521.Signing.PublicKey: DigestValidator {
/// - Returns: A Boolean value that’s `true` if the signature is valid for
/// the given digest; otherwise, `false`.
public func isValidSignature<D: Digest>(_ signature: P521.Signing.ECDSASignature, for digest: D) -> Bool {
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION || CRYPTOKIT_NO_IMPORT_FOUNDATION
return self.coreCryptoIsValidSignature(signature, for: digest)
#else
return self.openSSLIsValidSignature(signature, for: digest)
#endif
}
}
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
extension P521.Signing.PublicKey: DataValidator {
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
/// signature on a block of data over the P-521 elliptic curve.
@@ -570,4 +523,4 @@ extension P521.Signing.PublicKey: DataValidator {
}
#endif // Linux or !SwiftPM
#endif // canImport(CryptoKit)
Loaded 100 of 205 files, more files were not shown because too many files have changed in this diff. Show more