Compare commits

..
Author SHA1 Message Date
Si Beaumont 226c73e725 Revert "(split: benchmarks) Enable CheckImplementationOnly and box properties where needed"
This reverts commit 0f0b20b965.
2026-08-07 09:19:47 +01:00
Si Beaumont 6bed8c0239 Only enable CheckImplementationOnly for Swift 6.4+ 2026-08-07 09:18:15 +01:00
Si Beaumont bc748e9db5 Revert "(split: SHA512256) Enable CheckImplementationOnly and box properties where needed"
This reverts commit d6384ee4548e797894add480dfc0ea2b2e55ba1a.
2026-08-07 09:06:21 +01:00
Si Beaumont dbc7ea1646 Revert "(split: XWing) Enable CheckImplementationOnly and box properties where needed"
This reverts commit 1f780b4d25c02733d1433581c3b7e4d8b657d7a5.
2026-08-07 09:06:21 +01:00
Si Beaumont e08fd36acd Revert "(split: MLKEM) Enable CheckImplementationOnly and box properties where needed"
This reverts commit 02688bd534232b63581dbfa1a8d39476a0429f19.
2026-08-07 09:06:21 +01:00
Si Beaumont 1c92c8063d Revert "(split: ECDSASignature) Enable CheckImplementationOnly and box properties where needed"
This reverts commit af44bc64c0c87e92933a677a5b8e77f0602157f3.
2026-08-07 09:06:21 +01:00
Si Beaumont 5932f787f8 Revert "(split: MLDSA) Enable CheckImplementationOnly and box properties where needed"
This reverts commit 25fbb8efaf823becd0a3c52e3ba3db93d123e2fe.
2026-08-07 09:06:21 +01:00
Si Beaumont 6e917b8a0c Revert "(split: AEAD) Enable CheckImplementationOnly and box properties where needed"
This reverts commit af3e61654b5d3a0e36ce575d15e27d79b6bd7184.
2026-08-07 09:06:21 +01:00
Si Beaumont 9650914954 Revert "(split: BIGNUM) Enable CheckImplementationOnly and box properties where needed"
This reverts commit d2a3a8dd752f59e2e838a28afaa5c7c4f7f48f5a.
2026-08-07 09:06:21 +01:00
Si Beaumont 529e520206 Reapply "(split: SHA512256) Enable CheckImplementationOnly and box properties where needed"
This reverts commit dcb8db367de313cfb98acb3f52b3d83eeb81e4f5.
2026-08-06 14:16:47 +01:00
Si Beaumont 86a77f7140 Reapply "(split: XWing) Enable CheckImplementationOnly and box properties where needed"
This reverts commit 3f4136ae8d8bf06851ee12ada60a8759a5f62a62.
2026-08-06 14:16:47 +01:00
Si Beaumont 549795f323 Reapply "(split: MLKEM) Enable CheckImplementationOnly and box properties where needed"
This reverts commit f5b3e148e546740dc926a4f133fdac918c79bda1.
2026-08-06 14:16:47 +01:00
Si Beaumont 74c924555e Reapply "(split: ECDSASignature) Enable CheckImplementationOnly and box properties where needed"
This reverts commit 7f3eaa188ad5d5f1441f701a8c0302ee92cbb09f.
2026-08-06 14:16:47 +01:00
Si Beaumont 0fe7a8e839 Reapply "(split: MLDSA) Enable CheckImplementationOnly and box properties where needed"
This reverts commit ca023c479b7e268dacdb3a5d2265c41532230d7f.
2026-08-06 14:16:47 +01:00
Si Beaumont f0f7a965e0 Reapply "(split: AEAD) Enable CheckImplementationOnly and box properties where needed"
This reverts commit 0dd9f706777cad2b10526087519c0d01d321a65a.
2026-08-06 14:16:47 +01:00
Si Beaumont 88c237b314 Reapply "(split: BIGNUM) Enable CheckImplementationOnly and box properties where needed"
This reverts commit 32d7b6edae15d232d6f6fa7043443832e18249c3.
2026-08-06 14:16:47 +01:00
Si Beaumont c7b6553a08 Revert "(split: SHA512256) Enable CheckImplementationOnly and box properties where needed"
This reverts commit d6384ee4548e797894add480dfc0ea2b2e55ba1a.
2026-08-06 14:16:47 +01:00
Si Beaumont 56f26fd233 Revert "(split: XWing) Enable CheckImplementationOnly and box properties where needed"
This reverts commit 1f780b4d25c02733d1433581c3b7e4d8b657d7a5.
2026-08-06 14:16:47 +01:00
Si Beaumont 9d8037097c Revert "(split: MLKEM) Enable CheckImplementationOnly and box properties where needed"
This reverts commit 02688bd534232b63581dbfa1a8d39476a0429f19.
2026-08-06 14:16:47 +01:00
Si Beaumont 3c7d51f9df Revert "(split: ECDSASignature) Enable CheckImplementationOnly and box properties where needed"
This reverts commit af44bc64c0c87e92933a677a5b8e77f0602157f3.
2026-08-06 14:16:47 +01:00
Si Beaumont c1718e4722 Revert "(split: MLDSA) Enable CheckImplementationOnly and box properties where needed"
This reverts commit 25fbb8efaf823becd0a3c52e3ba3db93d123e2fe.
2026-08-06 14:16:47 +01:00
Si Beaumont c78a61b4d0 Revert "(split: AEAD) Enable CheckImplementationOnly and box properties where needed"
This reverts commit af3e61654b5d3a0e36ce575d15e27d79b6bd7184.
2026-08-06 14:16:47 +01:00
Si Beaumont 10cec03e61 Revert "(split: BIGNUM) Enable CheckImplementationOnly and box properties where needed"
This reverts commit d2a3a8dd752f59e2e838a28afaa5c7c4f7f48f5a.
2026-08-06 14:16:47 +01:00
Si Beaumont bc7a820fd8 Update swiftlang/github-workflows to 0.0.13 2026-08-06 14:16:47 +01:00
Si Beaumont db7a5b2863 Build with -warnings-as-errors in CI (exclude ImplementationOnlyDeprecated)
We want to lock in the win of getting this package warnings-clean. We
usually do this by building with `-warnings-as-errors` in CI. We still
have one warning, which we need to tolerate until we drop support for
6.3, which is `ImplementationOnlyDeprecated`, but we can still lock in
the win by building with the following flags in CI to downgrade
`ImplementationOnlyDeprecated` back to a warning:

    -Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated

This patch updates the pull request GitHub workflow to build with these
flags.
2026-08-06 14:16:47 +01:00
Si Beaumont ad74759b96 Silence ImplementationOnlyDeprecated for Swift 6.4+
This project is currently warnings-as-errors clean, but only because we
suppress `ImplementationOnlyDeprecated` warnings, using the following:

```
-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated
```

With this setup, the warnings are still generated and are noisy.

Swift 6.4 introduces `SourceWarningControl`, which we can use to
actually _silence_ these warnings, using `@diagnose(_:as:)`.

This patch adds a dance around the `@_implementationOnly imports`:

    #if hasFeature(SourceWarningControl)
    @diagnose(ImplementationOnlyDeprecated, as: ignored)
    #endif
    @_implementationOnly import ...

On Swift 6.4, this project is now warnings free.

When we raise the minimum supported Swift compiler version to one that
supports `SourceWarningControl`, we can remove the `#if hasFeature`
guards.
2026-08-06 14:16:47 +01:00
Si Beaumont 70712b39f7 (split: SHA512256) Enable CheckImplementationOnly and box properties where needed
We've long since used `@_implementationOnly import` (IOI) for our
vendored C modules (BoringSSL and libXKCP) in an attempt to not leak our
dependency into downstream builds. This is important because leaking
might cause symbol collisions (build failures) or, worse, layout
mismatches (latent runtime failures).

IOI was intended to be used with library evolution, which this project
does not support, and use of IOI without library evolution has been
soft-deprecated. Users are encouraged to move to `internal import` (II),
which is usually the right choice for Swift packages. But II does _not_
provide the same guarantees as IOI and, for this project, we really need
the protections given by IOI so we will continue to use it, even with
library evolution disabled.

One of the reasons for the soft-deprecation was the implementation of
IOI used an incomplete checker, that won't catch all interface leaks
without library evolution. However, Swift has also introduced a new
feature, `CheckImplementationOnly` (CIO), which enables the stricter
interface checking that we need.

Enabling CIO for this project today actually exposes a number of places
where we _are_ leaking the C types into our interface in ways that could
cause build- or runtime problems in downstream projects, and rightly
causes the build to fail. These types will need to have their C struct
members boxed behind an `OpaquePointer`.

This patch enables CIO, and adds the required boxing to the offending
types.

The public API is unchanged.

Additional refactoring is also done to ensure a single designated
initializer, responsible for the allocation, forcing all convenience
initializers through an `init(takingOwnershipOf:)` spelling, to reduce
the chances of introducing future double free bugs in complex
initializers.

This patch also adds some benchmarks for some of the paths that would be
implicated by these changes. While they show the expected increase in
allocations, there's only a modest-to-negligible performance regression,
since the majority of the compute is dominated by the time spent doing
the crypto routines in the C library themselves.
2026-08-06 14:16:47 +01:00
Si Beaumont 451fdb305b (split: XWing) Enable CheckImplementationOnly and box properties where needed
We've long since used `@_implementationOnly import` (IOI) for our
vendored C modules (BoringSSL and libXKCP) in an attempt to not leak our
dependency into downstream builds. This is important because leaking
might cause symbol collisions (build failures) or, worse, layout
mismatches (latent runtime failures).

IOI was intended to be used with library evolution, which this project
does not support, and use of IOI without library evolution has been
soft-deprecated. Users are encouraged to move to `internal import` (II),
which is usually the right choice for Swift packages. But II does _not_
provide the same guarantees as IOI and, for this project, we really need
the protections given by IOI so we will continue to use it, even with
library evolution disabled.

One of the reasons for the soft-deprecation was the implementation of
IOI used an incomplete checker, that won't catch all interface leaks
without library evolution. However, Swift has also introduced a new
feature, `CheckImplementationOnly` (CIO), which enables the stricter
interface checking that we need.

Enabling CIO for this project today actually exposes a number of places
where we _are_ leaking the C types into our interface in ways that could
cause build- or runtime problems in downstream projects, and rightly
causes the build to fail. These types will need to have their C struct
members boxed behind an `OpaquePointer`.

This patch enables CIO, and adds the required boxing to the offending
types.

The public API is unchanged.

Additional refactoring is also done to ensure a single designated
initializer, responsible for the allocation, forcing all convenience
initializers through an `init(takingOwnershipOf:)` spelling, to reduce
the chances of introducing future double free bugs in complex
initializers.

This patch also adds some benchmarks for some of the paths that would be
implicated by these changes. While they show the expected increase in
allocations, there's only a modest-to-negligible performance regression,
since the majority of the compute is dominated by the time spent doing
the crypto routines in the C library themselves.
2026-08-06 14:16:47 +01:00
Si Beaumont eca81332d9 (split: MLKEM) Enable CheckImplementationOnly and box properties where needed
We've long since used `@_implementationOnly import` (IOI) for our
vendored C modules (BoringSSL and libXKCP) in an attempt to not leak our
dependency into downstream builds. This is important because leaking
might cause symbol collisions (build failures) or, worse, layout
mismatches (latent runtime failures).

IOI was intended to be used with library evolution, which this project
does not support, and use of IOI without library evolution has been
soft-deprecated. Users are encouraged to move to `internal import` (II),
which is usually the right choice for Swift packages. But II does _not_
provide the same guarantees as IOI and, for this project, we really need
the protections given by IOI so we will continue to use it, even with
library evolution disabled.

One of the reasons for the soft-deprecation was the implementation of
IOI used an incomplete checker, that won't catch all interface leaks
without library evolution. However, Swift has also introduced a new
feature, `CheckImplementationOnly` (CIO), which enables the stricter
interface checking that we need.

Enabling CIO for this project today actually exposes a number of places
where we _are_ leaking the C types into our interface in ways that could
cause build- or runtime problems in downstream projects, and rightly
causes the build to fail. These types will need to have their C struct
members boxed behind an `OpaquePointer`.

This patch enables CIO, and adds the required boxing to the offending
types.

The public API is unchanged.

Additional refactoring is also done to ensure a single designated
initializer, responsible for the allocation, forcing all convenience
initializers through an `init(takingOwnershipOf:)` spelling, to reduce
the chances of introducing future double free bugs in complex
initializers.

This patch also adds some benchmarks for some of the paths that would be
implicated by these changes. While they show the expected increase in
allocations, there's only a modest-to-negligible performance regression,
since the majority of the compute is dominated by the time spent doing
the crypto routines in the C library themselves.
2026-08-06 14:16:47 +01:00
Si Beaumont 4304fd7dcf (split: ECDSASignature) Enable CheckImplementationOnly and box properties where needed
We've long since used `@_implementationOnly import` (IOI) for our
vendored C modules (BoringSSL and libXKCP) in an attempt to not leak our
dependency into downstream builds. This is important because leaking
might cause symbol collisions (build failures) or, worse, layout
mismatches (latent runtime failures).

IOI was intended to be used with library evolution, which this project
does not support, and use of IOI without library evolution has been
soft-deprecated. Users are encouraged to move to `internal import` (II),
which is usually the right choice for Swift packages. But II does _not_
provide the same guarantees as IOI and, for this project, we really need
the protections given by IOI so we will continue to use it, even with
library evolution disabled.

One of the reasons for the soft-deprecation was the implementation of
IOI used an incomplete checker, that won't catch all interface leaks
without library evolution. However, Swift has also introduced a new
feature, `CheckImplementationOnly` (CIO), which enables the stricter
interface checking that we need.

Enabling CIO for this project today actually exposes a number of places
where we _are_ leaking the C types into our interface in ways that could
cause build- or runtime problems in downstream projects, and rightly
causes the build to fail. These types will need to have their C struct
members boxed behind an `OpaquePointer`.

This patch enables CIO, and adds the required boxing to the offending
types.

The public API is unchanged.

Additional refactoring is also done to ensure a single designated
initializer, responsible for the allocation, forcing all convenience
initializers through an `init(takingOwnershipOf:)` spelling, to reduce
the chances of introducing future double free bugs in complex
initializers.

This patch also adds some benchmarks for some of the paths that would be
implicated by these changes. While they show the expected increase in
allocations, there's only a modest-to-negligible performance regression,
since the majority of the compute is dominated by the time spent doing
the crypto routines in the C library themselves.
2026-08-06 14:16:47 +01:00
Si Beaumont 61e60e023b (split: MLDSA) Enable CheckImplementationOnly and box properties where needed
We've long since used `@_implementationOnly import` (IOI) for our
vendored C modules (BoringSSL and libXKCP) in an attempt to not leak our
dependency into downstream builds. This is important because leaking
might cause symbol collisions (build failures) or, worse, layout
mismatches (latent runtime failures).

IOI was intended to be used with library evolution, which this project
does not support, and use of IOI without library evolution has been
soft-deprecated. Users are encouraged to move to `internal import` (II),
which is usually the right choice for Swift packages. But II does _not_
provide the same guarantees as IOI and, for this project, we really need
the protections given by IOI so we will continue to use it, even with
library evolution disabled.

One of the reasons for the soft-deprecation was the implementation of
IOI used an incomplete checker, that won't catch all interface leaks
without library evolution. However, Swift has also introduced a new
feature, `CheckImplementationOnly` (CIO), which enables the stricter
interface checking that we need.

Enabling CIO for this project today actually exposes a number of places
where we _are_ leaking the C types into our interface in ways that could
cause build- or runtime problems in downstream projects, and rightly
causes the build to fail. These types will need to have their C struct
members boxed behind an `OpaquePointer`.

This patch enables CIO, and adds the required boxing to the offending
types.

The public API is unchanged.

Additional refactoring is also done to ensure a single designated
initializer, responsible for the allocation, forcing all convenience
initializers through an `init(takingOwnershipOf:)` spelling, to reduce
the chances of introducing future double free bugs in complex
initializers.

This patch also adds some benchmarks for some of the paths that would be
implicated by these changes. While they show the expected increase in
allocations, there's only a modest-to-negligible performance regression,
since the majority of the compute is dominated by the time spent doing
the crypto routines in the C library themselves.
2026-08-06 14:16:47 +01:00
Si Beaumont 2cf2acbd9b (split: AEAD) Enable CheckImplementationOnly and box properties where needed
We've long since used `@_implementationOnly import` (IOI) for our
vendored C modules (BoringSSL and libXKCP) in an attempt to not leak our
dependency into downstream builds. This is important because leaking
might cause symbol collisions (build failures) or, worse, layout
mismatches (latent runtime failures).

IOI was intended to be used with library evolution, which this project
does not support, and use of IOI without library evolution has been
soft-deprecated. Users are encouraged to move to `internal import` (II),
which is usually the right choice for Swift packages. But II does _not_
provide the same guarantees as IOI and, for this project, we really need
the protections given by IOI so we will continue to use it, even with
library evolution disabled.

One of the reasons for the soft-deprecation was the implementation of
IOI used an incomplete checker, that won't catch all interface leaks
without library evolution. However, Swift has also introduced a new
feature, `CheckImplementationOnly` (CIO), which enables the stricter
interface checking that we need.

Enabling CIO for this project today actually exposes a number of places
where we _are_ leaking the C types into our interface in ways that could
cause build- or runtime problems in downstream projects, and rightly
causes the build to fail. These types will need to have their C struct
members boxed behind an `OpaquePointer`.

This patch enables CIO, and adds the required boxing to the offending
types.

The public API is unchanged.

Additional refactoring is also done to ensure a single designated
initializer, responsible for the allocation, forcing all convenience
initializers through an `init(takingOwnershipOf:)` spelling, to reduce
the chances of introducing future double free bugs in complex
initializers.

This patch also adds some benchmarks for some of the paths that would be
implicated by these changes. While they show the expected increase in
allocations, there's only a modest-to-negligible performance regression,
since the majority of the compute is dominated by the time spent doing
the crypto routines in the C library themselves.
2026-08-06 14:16:47 +01:00
Si Beaumont b810e1a634 (split: BIGNUM) Enable CheckImplementationOnly and box properties where needed
We've long since used `@_implementationOnly import` (IOI) for our
vendored C modules (BoringSSL and libXKCP) in an attempt to not leak our
dependency into downstream builds. This is important because leaking
might cause symbol collisions (build failures) or, worse, layout
mismatches (latent runtime failures).

IOI was intended to be used with library evolution, which this project
does not support, and use of IOI without library evolution has been
soft-deprecated. Users are encouraged to move to `internal import` (II),
which is usually the right choice for Swift packages. But II does _not_
provide the same guarantees as IOI and, for this project, we really need
the protections given by IOI so we will continue to use it, even with
library evolution disabled.

One of the reasons for the soft-deprecation was the implementation of
IOI used an incomplete checker, that won't catch all interface leaks
without library evolution. However, Swift has also introduced a new
feature, `CheckImplementationOnly` (CIO), which enables the stricter
interface checking that we need.

Enabling CIO for this project today actually exposes a number of places
where we _are_ leaking the C types into our interface in ways that could
cause build- or runtime problems in downstream projects, and rightly
causes the build to fail. These types will need to have their C struct
members boxed behind an `OpaquePointer`.

This patch enables CIO, and adds the required boxing to the offending
types.

The public API is unchanged.

Additional refactoring is also done to ensure a single designated
initializer, responsible for the allocation, forcing all convenience
initializers through an `init(takingOwnershipOf:)` spelling, to reduce
the chances of introducing future double free bugs in complex
initializers.

This patch also adds some benchmarks for some of the paths that would be
implicated by these changes. While they show the expected increase in
allocations, there's only a modest-to-negligible performance regression,
since the majority of the compute is dominated by the time spent doing
the crypto routines in the C library themselves.
2026-08-06 14:16:47 +01:00
Si Beaumont 1416991053 (split: setting) Enable CheckImplementationOnly and box properties where needed
We've long since used `@_implementationOnly import` (IOI) for our
vendored C modules (BoringSSL and libXKCP) in an attempt to not leak our
dependency into downstream builds. This is important because leaking
might cause symbol collisions (build failures) or, worse, layout
mismatches (latent runtime failures).

IOI was intended to be used with library evolution, which this project
does not support, and use of IOI without library evolution has been
soft-deprecated. Users are encouraged to move to `internal import` (II),
which is usually the right choice for Swift packages. But II does _not_
provide the same guarantees as IOI and, for this project, we really need
the protections given by IOI so we will continue to use it, even with
library evolution disabled.

One of the reasons for the soft-deprecation was the implementation of
IOI used an incomplete checker, that won't catch all interface leaks
without library evolution. However, Swift has also introduced a new
feature, `CheckImplementationOnly` (CIO), which enables the stricter
interface checking that we need.

Enabling CIO for this project today actually exposes a number of places
where we _are_ leaking the C types into our interface in ways that could
cause build- or runtime problems in downstream projects, and rightly
causes the build to fail. These types will need to have their C struct
members boxed behind an `OpaquePointer`.

This patch enables CIO, and adds the required boxing to the offending
types.

The public API is unchanged.

Additional refactoring is also done to ensure a single designated
initializer, responsible for the allocation, forcing all convenience
initializers through an `init(takingOwnershipOf:)` spelling, to reduce
the chances of introducing future double free bugs in complex
initializers.

This patch also adds some benchmarks for some of the paths that would be
implicated by these changes. While they show the expected increase in
allocations, there's only a modest-to-negligible performance regression,
since the majority of the compute is dominated by the time spent doing
the crypto routines in the C library themselves.
2026-08-06 07:34:22 +01:00
Si Beaumont 0f0b20b965 (split: benchmarks) Enable CheckImplementationOnly and box properties where needed
We've long since used `@_implementationOnly import` (IOI) for our
vendored C modules (BoringSSL and libXKCP) in an attempt to not leak our
dependency into downstream builds. This is important because leaking
might cause symbol collisions (build failures) or, worse, layout
mismatches (latent runtime failures).

IOI was intended to be used with library evolution, which this project
does not support, and use of IOI without library evolution has been
soft-deprecated. Users are encouraged to move to `internal import` (II),
which is usually the right choice for Swift packages. But II does _not_
provide the same guarantees as IOI and, for this project, we really need
the protections given by IOI so we will continue to use it, even with
library evolution disabled.

One of the reasons for the soft-deprecation was the implementation of
IOI used an incomplete checker, that won't catch all interface leaks
without library evolution. However, Swift has also introduced a new
feature, `CheckImplementationOnly` (CIO), which enables the stricter
interface checking that we need.

Enabling CIO for this project today actually exposes a number of places
where we _are_ leaking the C types into our interface in ways that could
cause build- or runtime problems in downstream projects, and rightly
causes the build to fail. These types will need to have their C struct
members boxed behind an `OpaquePointer`.

This patch enables CIO, and adds the required boxing to the offending
types.

The public API is unchanged.

Additional refactoring is also done to ensure a single designated
initializer, responsible for the allocation, forcing all convenience
initializers through an `init(takingOwnershipOf:)` spelling, to reduce
the chances of introducing future double free bugs in complex
initializers.

This patch also adds some benchmarks for some of the paths that would be
implicated by these changes. While they show the expected increase in
allocations, there's only a modest-to-negligible performance regression,
since the majority of the compute is dominated by the time spent doing
the crypto routines in the C library themselves.
2026-08-06 07:33:46 +01:00
Si Beaumont 60572672b1 Add vendored-sources.txt to excludes to remove SwiftPM warning 2026-08-05 13:25:40 +01:00
Si Beaumont ff138e8694 Drop public import where needed to resolve UnusedImportAccess warning 2026-08-05 13:23:59 +01:00
Si Beaumont 4ebd26ddef Use ExistentialAny keyword in tests to resolve warning in 6.4 2026-08-05 13:23:00 +01:00
Si Beaumont 8979b7465c Remove try keywords to resolve UnnecessaryEffectMarker warnings 2026-08-05 13:22:07 +01:00
Si Beaumont 9fc4058c1d Disable macro-redefined warnings in CXKCP target 2026-08-05 13:22:07 +01:00
Si Beaumont cc50346097 Disable shorten-64-to-32 warnings in BoringSSL target 2026-08-05 10:11:35 +01:00
45 changed files with 723 additions and 208 deletions

No files matched your search

+5 -4
View File
@@ -21,16 +21,16 @@ jobs:
with:
linux_6_2_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
linux_6_3_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
linux_nightly_next_arguments_override: "-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"
linux_nightly_next_arguments_override: "--build-system native -Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
linux_nightly_main_arguments_override: "--build-system native --explicit-target-dependency-import-check error"
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
windows_6_2_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
windows_6_3_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
windows_nightly_next_arguments_override: "-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"
windows_nightly_next_arguments_override: "--build-system native -Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
windows_nightly_main_arguments_override: "--build-system native --explicit-target-dependency-import-check error"
release-builds:
name: Release builds
@@ -53,6 +53,7 @@ jobs:
{
"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": [] },
+1 -1
View File
@@ -69,7 +69,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":"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":"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
```
## API Evolution
+11
View File
@@ -126,6 +126,14 @@ let package = Package(
.disableWarning("macro-redefined"),
]
),
.target(
name: "CCryptoBoringSSLShims",
dependencies: ["CCryptoBoringSSL"],
exclude: privacyManifestExclude + [
"CMakeLists.txt"
],
resources: privacyManifestResource
),
.target(
name: "CXKCPShims",
dependencies: ["CXKCP"],
@@ -138,6 +146,7 @@ let package = Package(
name: "Crypto",
dependencies: [
.target(name: "CCryptoBoringSSL", condition: .when(platforms: nonDarwinPlatforms)),
.target(name: "CCryptoBoringSSLShims", condition: .when(platforms: nonDarwinPlatforms)),
.target(name: "CryptoBoringWrapper", condition: .when(platforms: nonDarwinPlatforms)),
.target(name: "CXKCP", condition: .when(platforms: nonDarwinPlatforms)),
.target(name: "CXKCPShims", condition: .when(platforms: nonDarwinPlatforms)),
@@ -155,6 +164,7 @@ let package = Package(
name: "CryptoExtras",
dependencies: [
"CCryptoBoringSSL",
"CCryptoBoringSSLShims",
"CryptoBoringWrapper",
"Crypto",
.product(name: "SwiftASN1", package: "swift-asn1"),
@@ -176,6 +186,7 @@ let package = Package(
name: "CryptoBoringWrapper",
dependencies: [
"CCryptoBoringSSL",
"CCryptoBoringSSLShims",
],
exclude: privacyManifestExclude + [
"CMakeLists.txt"
@@ -0,0 +1,29 @@
##===----------------------------------------------------------------------===##
##
## 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)
@@ -0,0 +1,15 @@
<?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>
@@ -0,0 +1,155 @@
//===----------------------------------------------------------------------===//
//
// 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
@@ -0,0 +1,4 @@
module CCryptoBoringSSLShims {
header "CCryptoBoringSSLShims.h"
export *
}
+190
View File
@@ -0,0 +1,190 @@
//===----------------------------------------------------------------------===//
//
// 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,6 +13,7 @@
##===----------------------------------------------------------------------===##
add_subdirectory(CCryptoBoringSSL)
add_subdirectory(CCryptoBoringSSLShims)
add_subdirectory(CXKCP)
add_subdirectory(CXKCPShims)
add_subdirectory(CryptoBoringWrapper)
@@ -88,6 +88,21 @@ 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.
///
@@ -146,6 +161,28 @@ 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
)
}
}
}
@@ -16,8 +16,10 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
@@ -83,6 +83,21 @@ 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.
///
@@ -136,6 +151,21 @@ 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)
}
}
extension ChaChaPoly {
+2
View File
@@ -117,6 +117,7 @@ target_compile_definitions(Crypto PRIVATE
target_include_directories(Crypto PRIVATE
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CCryptoBoringSSLShims,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CryptoBoringWrapper,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CXKCP,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CXKCPShims,INCLUDE_DIRECTORIES>)
@@ -124,6 +125,7 @@ target_link_libraries(Crypto PUBLIC
$<$<NOT:$<PLATFORM_ID:Darwin>>:dispatch>
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
CCryptoBoringSSL
CCryptoBoringSSLShims
CryptoBoringWrapper
CXKCP
CXKCPShims)
+6 -27
View File
@@ -23,7 +23,6 @@ public import Foundation
typealias MLKEMPublicKeyImpl = OpenSSLMLKEMPublicKeyImpl
typealias MLKEMPrivateKeyImpl = OpenSSLMLKEMPrivateKeyImpl
typealias MLKEMOneTimePrivateKeyImpl = OpenSSLMLKEMPrivateKeyImpl
/// The Module-Lattice key encapsulation mechanism (KEM).
@@ -151,25 +150,15 @@ extension MLKEM768 {
/// 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: MLKEMOneTimePrivateKeyImpl<MLKEM768>
internal let impl: MLKEMPrivateKeyImpl<MLKEM768>
internal init(_ impl: MLKEMOneTimePrivateKeyImpl<MLKEM768>) {
internal init(_ impl: MLKEMPrivateKeyImpl<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 MLKEMOneTimePrivateKeyImpl<MLKEM768>.generatePrivateKey()
let impl = try MLKEMPrivateKeyImpl<MLKEM768>.generatePrivateKey()
return OneTimePrivateKey(impl)
}
@@ -322,25 +311,15 @@ extension MLKEM1024 {
/// 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: MLKEMOneTimePrivateKeyImpl<MLKEM1024>
internal let impl: MLKEMPrivateKeyImpl<MLKEM1024>
internal init(_ impl: MLKEMOneTimePrivateKeyImpl<MLKEM1024>) {
internal init(_ impl: MLKEMPrivateKeyImpl<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 MLKEMOneTimePrivateKeyImpl<MLKEM1024>.generatePrivateKey()
let impl = try MLKEMPrivateKeyImpl<MLKEM1024>.generatePrivateKey()
return OneTimePrivateKey(impl)
}
+1 -8
View File
@@ -58,7 +58,7 @@ extension XWingMLKEM768X25519 {
}
public struct PrivateKey: KEMPrivateKey {
var impl: XWingPrivateKeyImpl
private var impl: XWingPrivateKeyImpl
public var seedRepresentation: Data {
get {
@@ -106,13 +106,6 @@ 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()
@@ -33,8 +33,12 @@ enum BoringSSLAESWRAPImpl {
let rc = try key.withUnsafeAESKEY(mode: .encrypting) { aesKey in
output.withUnsafeMutableBytes { outputPtr -> CInt in
keyToWrap.withUnsafeBytes { keyToWrapPtr -> CInt in
CCryptoBoringSSL_AES_wrap_key(
// 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(
aesKey,
nil,
outputPtr.baseAddress,
@@ -74,6 +78,8 @@ enum BoringSSLAESWRAPImpl {
) 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)
let rc = try key.withUnsafeAESKEY(mode: .decrypting) { aesKey in
CCryptoBoringSSL_AES_unwrap_key(
aesKey,
@@ -111,6 +117,8 @@ extension SymmetricKey {
_ body: (UnsafePointer<AES_KEY>) throws -> ResultType
) throws -> ResultType {
try self.withUnsafeBytes { bytesPointer in
// Bind is safe: cannot alias the pointer here.
let bytesPointer = bytesPointer.bindMemory(to: UInt8.self)
var aesKey = AES_KEY()
let bitsInKey = UInt32(bytesPointer.count * 8)
@@ -16,8 +16,10 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
@@ -44,7 +46,7 @@ extension Curve25519.Signing {
privateKeyBytes in
privateKeyBytes = 64
publicKey.withUnsafeMutableBytes { publicKeyPtr in
CCryptoBoringSSL_ED25519_keypair(
CCryptoBoringSSLShims_ED25519_keypair(
publicKeyPtr.baseAddress,
privateKeyPtr.baseAddress
)
@@ -78,7 +80,7 @@ extension Curve25519.Signing {
privateKeyBytes in
privateKeyBytes = 64
publicKey.withUnsafeMutableBytes { publicKeyPtr in
CCryptoBoringSSL_ED25519_keypair_from_seed(
CCryptoBoringSSLShims_ED25519_keypair_from_seed(
publicKeyPtr.baseAddress,
privateKeyPtr.baseAddress,
seedPtr.baseAddress
@@ -16,8 +16,10 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
@@ -146,7 +148,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, *)
final class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
@usableFromInline
let key: OpaquePointer
@@ -333,7 +335,7 @@ final class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unc
func sign<D: Digest>(digest: D) throws -> ECDSASignature {
let optionalRawSignature: UnsafeMutablePointer<ECDSA_SIG>? = digest.withUnsafeBytes {
digestPtr in
CCryptoBoringSSL_ECDSA_do_sign(digestPtr.baseAddress, digestPtr.count, self.key)
CCryptoBoringSSLShims_ECDSA_do_sign(digestPtr.baseAddress, digestPtr.count, self.key)
}
guard let rawSignature = optionalRawSignature else {
throw CryptoKitError.internalBoringSSLError()
@@ -351,7 +353,7 @@ final class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unc
/// allows some helper operations.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
final class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
@usableFromInline
let key: OpaquePointer
@@ -573,7 +575,7 @@ final class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unch
func isValidSignature<D: Digest>(_ signature: ECDSASignature, for digest: D) -> Bool {
let rc: CInt = signature.withUnsafeSignaturePointer { signaturePointer in
digest.withUnsafeBytes { digestPointer in
CCryptoBoringSSL_ECDSA_do_verify(
CCryptoBoringSSLShims_ECDSA_do_verify(
digestPointer.baseAddress,
digestPointer.count,
signaturePointer,
@@ -16,8 +16,10 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
@@ -75,7 +77,7 @@ extension Curve25519.KeyAgreement {
publicKey.withUnsafeMutableBytes { publicKeyBytes in
precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
precondition(privateKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
CCryptoBoringSSL_X25519_keypair(
CCryptoBoringSSLShims_X25519_keypair(
publicKeyBytes.baseAddress,
privateKeyBytes.baseAddress
)
@@ -103,7 +105,7 @@ extension Curve25519.KeyAgreement {
publicKeyBytes,
publicKeySize in
precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
CCryptoBoringSSL_X25519_public_from_private(
CCryptoBoringSSLShims_X25519_public_from_private(
publicKeyBytes.baseAddress,
privatePointer.baseAddress
)
@@ -138,7 +140,7 @@ extension Curve25519.KeyAgreement {
// politely describe as a "lack of consensus" as to whether crypto libraries should reject this secret. CryptoKit on Apple
// platforms currently does not, so for the sake of conformance with our peer implementation I will also refuse to check it.
// We may elect to revisit this decision if the security best-practice thinking changes.
CCryptoBoringSSL_X25519(
CCryptoBoringSSLShims_X25519(
secretPointer.baseAddress,
privateKeyPointer.baseAddress,
publicKeyShare.keyBytes
@@ -71,7 +71,7 @@ extension MessageAuthenticationCode {
public func makeIterator() -> Array<UInt8>.Iterator {
self.withUnsafeBytes({ (buffPtr) in
return Array(buffPtr).makeIterator()
return Array(buffPtr.bindMemory(to: UInt8.self)).makeIterator()
})
}
@@ -16,8 +16,10 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
@@ -28,13 +30,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, *)
final class ECDSASignature {
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 = CCryptoBoringSSL_ECDSA_SIG_from_bytes(bytesPtr.baseAddress, bytesPtr.count)
let sig = CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(bytesPtr.baseAddress, bytesPtr.count)
else {
throw CryptoKitError.internalBoringSSLError()
}
@@ -99,6 +101,21 @@ final class ECDSASignature {
)
}
@usableFromInline
var derBytes: Data {
var dataPtr: UnsafeMutablePointer<UInt8>?
var length = 0
guard CCryptoBoringSSL_ECDSA_SIG_to_bytes(&dataPtr, &length, self._baseSig) == 1 else {
fatalError("Unable to marshal signature to DER")
}
defer {
// We must free this pointer.
CCryptoBoringSSL_OPENSSL_free(dataPtr)
}
return Data(UnsafeBufferPointer(start: dataPtr, count: length))
}
func withUnsafeSignaturePointer<T>(
_ body: (UnsafeMutablePointer<ECDSA_SIG>) throws -> T
)
@@ -67,6 +67,17 @@ 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 {
@@ -93,6 +104,17 @@ 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 {
@@ -119,6 +141,17 @@ extension P384.Signing.PublicKey {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P521.Signing.ECDSASignature {
init<D: DataProtocol>(openSSLDERSignature derRepresentation: D) throws {
self.rawRepresentation = try Data(derSignature: derRepresentation, over: P521.self)
}
var openSSLDERRepresentation: Data {
try! ECDSASignature(rawRepresentation: self.rawRepresentation).derBytes
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P521.Signing.PrivateKey {
func openSSLSignature<D: Digest>(for digest: D) throws -> P521.Signing.ECDSASignature {
@@ -16,8 +16,10 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
@@ -92,7 +94,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
CCryptoBoringSSL_ED25519_verify(
CCryptoBoringSSLShims_ED25519_verify(
dataPointer.baseAddress,
dataPointer.count,
signaturePointer.baseAddress,
@@ -131,7 +133,7 @@ extension Curve25519.Signing.PrivateKey {
precondition(signaturePointer.count == Curve25519.Signing.PublicKey.signatureByteCount)
precondition(keyPointer.count == ED25519_PRIVATE_KEY_LEN)
return CCryptoBoringSSL_ED25519_sign(
return CCryptoBoringSSLShims_ED25519_sign(
signaturePointer.baseAddress,
dataPointer.baseAddress,
dataPointer.count,
@@ -12,13 +12,24 @@
//
//===----------------------------------------------------------------------===//
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
// MARK: - Generated file, do NOT edit
// any edits of this file WILL be overwritten and thus discarded
// see section `gyb` in `README` for details.
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@@ -12,13 +12,24 @@
//
//===----------------------------------------------------------------------===//
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
// MARK: - Generated file, do NOT edit
// any edits of this file WILL be overwritten and thus discarded
// see section `gyb` in `README` for details.
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@@ -14,8 +14,10 @@
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
@@ -41,7 +43,7 @@ extension BoringSSLAEAD {
// Arguably this class is excessive, but it's probably better for this API to be as safe as possible
// rather than rely on defer statements for our cleanup.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
public final class AEADContext {
public class AEADContext {
private var context: EVP_AEAD_CTX
public init<Key: ContiguousBytes>(cipher: BoringSSLAEAD, key: Key) throws {
@@ -50,7 +52,7 @@ extension BoringSSLAEAD {
let rc: CInt = key.withUnsafeBytes { keyPointer in
withUnsafeMutablePointer(to: &self.context) { contextPointer in
// Create the AEAD context with a default tag length using the given key.
CCryptoBoringSSL_EVP_AEAD_CTX_init(
CCryptoBoringSSLShims_EVP_AEAD_CTX_init(
contextPointer,
cipher.boringSSLCipher,
keyPointer.baseAddress,
@@ -175,7 +177,7 @@ extension BoringSSLAEAD.AEADContext {
return authenticatedData.withUnsafeBytes { authenticatedDataBuffer in
nonce.withUnsafeBytes { nonceBuffer in
CCryptoBoringSSL_EVP_AEAD_CTX_seal_scatter(
CCryptoBoringSSLShims_EVP_AEAD_CTX_seal_scatter(
contextPointer,
messageBuffer.baseAddress,
tagBuffer.baseAddress! + tagInitializedCount,
@@ -317,7 +319,7 @@ extension BoringSSLAEAD.AEADContext {
nonce.withUnsafeBytes { nonceBuffer in
tag.withUnsafeBytes { tagBuffer in
authenticatedData.withUnsafeBytes { adBuffer in
CCryptoBoringSSL_EVP_AEAD_CTX_open_gather(
CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(
contextPointer,
messageBuffer.baseAddress,
nonceBuffer.baseAddress,
@@ -428,7 +430,7 @@ extension BoringSSLAEAD.AEADContext {
var writtenBytes = 0
let rc = withUnsafePointer(to: &self.context) { contextPointer in
CCryptoBoringSSL_EVP_AEAD_CTX_open(
CCryptoBoringSSLShims_EVP_AEAD_CTX_open(
contextPointer,
outputBuffer.baseAddress,
&writtenBytes,
+4 -2
View File
@@ -24,11 +24,13 @@ add_library(CryptoBoringWrapper STATIC
)
target_include_directories(CryptoBoringWrapper PUBLIC
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>)
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CCryptoBoringSSLShims,INCLUDE_DIRECTORIES>)
target_link_libraries(CryptoBoringWrapper PUBLIC
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
CCryptoBoringSSL)
CCryptoBoringSSL
CCryptoBoringSSLShims)
target_compile_options(CryptoBoringWrapper PRIVATE ${SWIFT_CRYPTO_COMPILE_OPTIONS})
@@ -13,8 +13,10 @@
//===----------------------------------------------------------------------===//
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
@@ -492,35 +494,29 @@ extension EllipticCurvePoint {
to group: BoringSSLEllipticCurveGroup,
domainSeparationTag: DSTBytes
) throws {
let hashToCurveFunction =
switch group.curveName {
case .p256: CCryptoBoringSSLShims_EC_hash_to_curve_p256_xmd_sha256_sswu
case .p384: CCryptoBoringSSLShims_EC_hash_to_curve_p384_xmd_sha384_sswu
// BoringSSL has no P521 hash_to_curve API.
case .p521: throw CryptoBoringWrapperError.invalidParameter
case .none: throw CryptoBoringWrapperError.internalBoringSSLError()
}
try self.init(_pointAtInfinityOn: group)
try msg.withUnsafeBytes { msgPtr in
try group.withUnsafeGroupPointer { groupPtr in
try domainSeparationTag.withUnsafeBytes { dstPtr in
let rc: CInt
switch group.curveName {
case .p256:
rc = CCryptoBoringSSL_EC_hash_to_curve_p256_xmd_sha256_sswu(
guard
hashToCurveFunction(
groupPtr,
self._basePoint,
dstPtr.baseAddress,
dstPtr.count,
msgPtr.baseAddress,
msgPtr.count
)
case .p384:
rc = CCryptoBoringSSL_EC_hash_to_curve_p384_xmd_sha384_sswu(
groupPtr,
self._basePoint,
dstPtr.baseAddress,
dstPtr.count,
msgPtr.baseAddress,
msgPtr.count
)
// BoringSSL has no P521 hash_to_curve API.
case .p521: throw CryptoBoringWrapperError.invalidParameter
case .none: throw CryptoBoringWrapperError.internalBoringSSLError()
}
guard rc == 1 else { throw CryptoBoringWrapperError.internalBoringSSLError() }
) == 1
else { throw CryptoBoringWrapperError.internalBoringSSLError() }
}
}
}
@@ -607,7 +603,7 @@ extension EllipticCurvePoint {
let numBytesWritten = group.withUnsafeGroupPointer { groupPtr in
buf.withUnsafeMutableBytes { bufPtr in
CCryptoBoringSSL_EC_POINT_point2oct(
CCryptoBoringSSLShims_EC_POINT_point2oct(
groupPtr,
self._basePoint,
compressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED,
@@ -14,8 +14,10 @@
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
@@ -121,7 +123,7 @@ extension ArbitraryPrecisionInteger.BackingStorage {
self.init()
let rc: UnsafeMutablePointer<BIGNUM>? = bytes.withUnsafeBytes { bytesPointer in
CCryptoBoringSSL_BN_bin2bn(
CCryptoBoringSSLShims_BN_bin2bn(
bytesPointer.baseAddress,
bytesPointer.count,
&self._backing
@@ -457,8 +459,7 @@ extension ArbitraryPrecisionInteger {
if nonNegative {
CCryptoBoringSSL_BN_nnmod(resultPtr, selfPtr, modPtr, bnCtx)
} else {
// BN_mod is a C macro for BN_div with a nil quotient; call that directly.
CCryptoBoringSSL_BN_div(nil, resultPtr, selfPtr, modPtr, bnCtx)
CCryptoBoringSSLShims_BN_mod(resultPtr, selfPtr, modPtr, bnCtx)
}
}
}
@@ -717,7 +718,7 @@ extension Data {
assert(bytesPtr.count == byteCount)
return integer.withUnsafeBignumPointer { bnPtr in
CCryptoBoringSSL_BN_bn2bin(bnPtr, bytesPtr.baseAddress!)
CCryptoBoringSSLShims_BN_bn2bin(bnPtr, bytesPtr.baseAddress!)
}
}
@@ -37,7 +37,7 @@ import Foundation
/// ourselves.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
package final class FiniteFieldArithmeticContext: @unchecked Sendable {
package class FiniteFieldArithmeticContext: @unchecked Sendable {
private let fieldSize: ArbitraryPrecisionInteger
package let bnCtx: OpaquePointer
@@ -15,8 +15,10 @@
import Crypto
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
+12 -4
View File
@@ -15,8 +15,10 @@
import Crypto
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
@@ -97,18 +99,24 @@ extension AES {
precondition(payload.count == Int(Self.blockSize))
key.withUnsafeBytes { keyPtr in
// We bind both pointers here. These binds are not technically safe, but because we
// know the pointers don't persist they can't violate the aliasing rules. We really
// want a "with memory rebound" function but we don't have it yet.
let keyBytes = keyPtr.bindMemory(to: UInt8.self)
let blockBytes = payload.bindMemory(to: UInt8.self)
var key = AES_KEY()
if permutation == .forward {
let rc = CCryptoBoringSSL_AES_set_encrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key)
let rc = CCryptoBoringSSL_AES_set_encrypt_key(keyBytes.baseAddress, UInt32(keyBytes.count * 8), &key)
precondition(rc == 0)
CCryptoBoringSSL_AES_encrypt(payload.baseAddress, payload.baseAddress, &key)
CCryptoBoringSSL_AES_encrypt(blockBytes.baseAddress, blockBytes.baseAddress, &key)
} else {
let rc = CCryptoBoringSSL_AES_set_decrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key)
let rc = CCryptoBoringSSL_AES_set_decrypt_key(keyBytes.baseAddress, UInt32(keyBytes.count * 8), &key)
precondition(rc == 0)
CCryptoBoringSSL_AES_decrypt(payload.baseAddress, payload.baseAddress, &key)
CCryptoBoringSSL_AES_decrypt(blockBytes.baseAddress, blockBytes.baseAddress, &key)
}
}
}
@@ -19,8 +19,10 @@ import CryptoBoringWrapper
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
+4 -2
View File
@@ -86,13 +86,15 @@ add_library(CryptoExtras
target_compile_options(CryptoExtras PRIVATE -DCRYPTO_IN_SWIFTPM)
target_include_directories(CryptoExtras PRIVATE
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>)
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CCryptoBoringSSLShims,INCLUDE_DIRECTORIES>)
target_link_libraries(CryptoExtras PUBLIC
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
Crypto
CryptoBoringWrapper
CCryptoBoringSSL)
CCryptoBoringSSL
CCryptoBoringSSLShims)
target_compile_options(CryptoExtras PRIVATE ${SWIFT_CRYPTO_COMPILE_OPTIONS})
@@ -17,8 +17,10 @@ import CryptoBoringWrapper
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
@@ -70,15 +72,22 @@ enum OpenSSLChaCha20CTRImpl {
key.withUnsafeBytes { keyPtr in
nonce.withUnsafeBytes { noncePtr in
message.withUnsafeBytes { plaintextPtr in
var ciphertext = Data(repeating: 0, count: plaintextPtr.count)
// We bind all three pointers here. These binds are not technically safe, but because we
// know the pointers don't persist they can't violate the aliasing rules. We really
// want a "with memory rebound" function but we don't have it yet.
let keyBytes = keyPtr.bindMemory(to: UInt8.self)
let nonceBytes = noncePtr.bindMemory(to: UInt8.self)
let plaintext = plaintextPtr.bindMemory(to: UInt8.self)
var ciphertext = Data(repeating: 0, count: plaintext.count)
ciphertext.withUnsafeMutableBytes { ciphertext in
CCryptoBoringSSL_CRYPTO_chacha_20(
ciphertext.baseAddress,
plaintextPtr.baseAddress,
plaintextPtr.count,
keyPtr.baseAddress,
noncePtr.baseAddress,
plaintext.baseAddress,
plaintext.count,
keyBytes.baseAddress,
nonceBytes.baseAddress,
counter
)
}
@@ -14,8 +14,10 @@
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import Crypto
import CryptoBoringWrapper
@@ -12,9 +12,8 @@
//
//===----------------------------------------------------------------------===//
import Crypto
@_implementationOnly import CCryptoBoringSSL
import Crypto
struct BoringSSLSHA512256HashFunction {
static var digestSize: Int {
@@ -22,8 +22,10 @@ import Foundation
#if !canImport(CommonCrypto)
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
@@ -16,8 +16,10 @@ import Crypto
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
+11 -9
View File
@@ -18,8 +18,10 @@ import CryptoBoringWrapper
// NOTE: This file is unconditionally compiled because RSABSSA is implemented using BoringSSL on all platforms.
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
@@ -374,7 +376,7 @@ extension BoringSSLRSAPublicKey {
let rc: CInt = digest.withUnsafeBytes { digestPtr in
switch padding.backing {
case .pkcs1v1_5:
return CCryptoBoringSSL_RSA_verify(
return CCryptoBoringSSLShims_RSA_verify(
hashDigestType.nid,
digestPtr.baseAddress,
digestPtr.count,
@@ -383,7 +385,7 @@ extension BoringSSLRSAPublicKey {
rsaPublicKey
)
case .pss:
return CCryptoBoringSSL_RSA_verify_pss_mgf1(
return CCryptoBoringSSLShims_RSA_verify_pss_mgf1(
rsaPublicKey,
digestPtr.baseAddress,
digestPtr.count,
@@ -394,7 +396,7 @@ extension BoringSSLRSAPublicKey {
signaturePtr.count
)
case .pssZero:
return CCryptoBoringSSL_RSA_verify_pss_mgf1(
return CCryptoBoringSSLShims_RSA_verify_pss_mgf1(
rsaPublicKey,
digestPtr.baseAddress,
digestPtr.count,
@@ -446,7 +448,7 @@ extension BoringSSLRSAPublicKey {
}
var writtenLength = bufferPtr.count
let rc = CCryptoBoringSSL_EVP_PKEY_encrypt(
let rc = CCryptoBoringSSLShims_EVP_PKEY_encrypt(
ctx,
bufferPtr.baseAddress,
&writtenLength,
@@ -861,10 +863,10 @@ extension BoringSSLRSAPrivateKey {
switch padding.backing {
case .pkcs1v1_5:
var writtenLength = CUnsignedInt(0)
let rc = CCryptoBoringSSL_RSA_sign(
let rc = CCryptoBoringSSLShims_RSA_sign(
hashDigestType.nid,
digestPtr.baseAddress,
digestPtr.count,
CUnsignedInt(digestPtr.count),
bufferPtr.baseAddress,
&writtenLength,
rsaPrivateKey
@@ -872,7 +874,7 @@ extension BoringSSLRSAPrivateKey {
outputLength = Int(writtenLength)
return rc
case .pss:
return CCryptoBoringSSL_RSA_sign_pss_mgf1(
return CCryptoBoringSSLShims_RSA_sign_pss_mgf1(
rsaPrivateKey,
&outputLength,
bufferPtr.baseAddress,
@@ -884,7 +886,7 @@ extension BoringSSLRSAPrivateKey {
CInt(hashDigestType.digestLength)
)
case .pssZero:
return CCryptoBoringSSL_RSA_sign_pss_mgf1(
return CCryptoBoringSSLShims_RSA_sign_pss_mgf1(
rsaPrivateKey,
&outputLength,
bufferPtr.baseAddress,
@@ -941,7 +943,7 @@ extension BoringSSLRSAPrivateKey {
var writtenLength = bufferPtr.count
let rc = CCryptoBoringSSL_EVP_PKEY_decrypt(
let rc = CCryptoBoringSSLShims_EVP_PKEY_decrypt(
ctx,
bufferPtr.baseAddress,
&writtenLength,
@@ -15,8 +15,10 @@
// NOTE: This file is unconditionally compiled because RSABSSA is implemented using BoringSSL on all platforms.
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
@@ -29,7 +29,7 @@ final class ThreadSpecificVariable<Value: AnyObject> {
// the actual type in there is `Box<(ThreadSpecificVariable<T>, T)>` but we can't use that as C functions can't capture (even types)
private typealias BoxedType = Box<(AnyObject, AnyObject)>
private final class Key {
private class Key {
private var underlyingKey: ThreadOpsSystem.ThreadSpecificKey
internal init(destructor: @escaping ThreadOpsSystem.ThreadSpecificKeyDestructor) {
+6 -6
View File
@@ -24,7 +24,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 32)
let result = input.withUnsafeBytes { inputBytes in
SHA3_256(&output, inputBytes.baseAddress, inputBytes.count)
SHA3_256(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
}
// Should return 0 on success
@@ -43,7 +43,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 28)
let result = input.withUnsafeBytes { inputBytes in
SHA3_224(&output, inputBytes.baseAddress, inputBytes.count)
SHA3_224(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
}
// Should return 0 on success
@@ -62,7 +62,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 48)
let result = input.withUnsafeBytes { inputBytes in
SHA3_384(&output, inputBytes.baseAddress, inputBytes.count)
SHA3_384(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
}
// Should return 0 on success
@@ -82,7 +82,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 64)
let result = input.withUnsafeBytes { inputBytes in
SHA3_512(&output, inputBytes.baseAddress, inputBytes.count)
SHA3_512(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
}
// Should return 0 on success
@@ -102,7 +102,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 32) // 256 bits output
let result = input.withUnsafeBytes { inputBytes in
SHAKE128(&output, output.count, inputBytes.baseAddress, inputBytes.count)
SHAKE128(&output, output.count, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
}
// Should return 0 on success
@@ -121,7 +121,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 32) // 256 bits output
let result = input.withUnsafeBytes { inputBytes in
SHAKE256(&output, output.count, inputBytes.baseAddress, inputBytes.count)
SHAKE256(&output, output.count, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
}
// Should return 0 on success
+14 -36
View File
@@ -19,34 +19,6 @@ import XCTest
@testable import Crypto
final class MLKEMTests: XCTestCase {
/// Decapsulates with the regular private key and also with a one-time private key built from the
/// same key material, asserting that both paths recover the same shared secret. Returns the shared
/// secret so callers can run their own assertions (e.g. against a known-answer value), guaranteeing
/// the one-time and regular decapsulation functions are tested identically everywhere.
private func decapsulate(
with privateKey: MLKEM768.PrivateKey,
_ encapsulated: Data,
file: StaticString = #filePath,
line: UInt = #line
) throws -> SymmetricKey {
let sharedSecret = try privateKey.decapsulate(encapsulated)
let oneTimeSharedSecret = try MLKEM768.OneTimePrivateKey(reusingForTestingOnly: privateKey).decapsulate(encapsulated)
XCTAssertEqual(sharedSecret, oneTimeSharedSecret, "one-time decapsulation diverged from regular decapsulation", file: file, line: line)
return sharedSecret
}
private func decapsulate(
with privateKey: MLKEM1024.PrivateKey,
_ encapsulated: Data,
file: StaticString = #filePath,
line: UInt = #line
) throws -> SymmetricKey {
let sharedSecret = try privateKey.decapsulate(encapsulated)
let oneTimeSharedSecret = try MLKEM1024.OneTimePrivateKey(reusingForTestingOnly: privateKey).decapsulate(encapsulated)
XCTAssertEqual(sharedSecret, oneTimeSharedSecret, "one-time decapsulation diverged from regular decapsulation", file: file, line: line)
return sharedSecret
}
func testMLKEM768() throws {
let privateKey = try MLKEM768.PrivateKey.generate()
let publicKey = privateKey.publicKey
@@ -59,7 +31,7 @@ final class MLKEMTests: XCTestCase {
try XCTAssert(privateKey.integrityCheckedRepresentation == MLKEM768.PrivateKey(integrityCheckedRepresentation: privateKey.integrityCheckedRepresentation).integrityCheckedRepresentation)
let er = try publicKey.encapsulate()
let ss = try decapsulate(with: privateKey, er.encapsulated)
let ss = try privateKey.decapsulate(er.encapsulated)
XCTAssert(er.sharedSecret == ss)
}
@@ -76,18 +48,24 @@ final class MLKEMTests: XCTestCase {
try XCTAssert(privateKey.integrityCheckedRepresentation == MLKEM1024.PrivateKey(integrityCheckedRepresentation: privateKey.integrityCheckedRepresentation).integrityCheckedRepresentation)
let er = try publicKey.encapsulate()
let ss = try decapsulate(with: privateKey, er.encapsulated)
let ss = try privateKey.decapsulate(er.encapsulated)
XCTAssert(er.sharedSecret == ss)
}
// Test that the private key API function throws on an invalid seed
func testPrivateKeyInitThrowsOnInvalidSeedLength768() {
XCTAssertThrowsError(try MLKEM768.PrivateKey(seedRepresentation: Data(count: 1), publicKey: nil))
}
func testOneTimeKeys() throws {
let privateKey = try MLKEM1024.OneTimePrivateKey.generate()
let publicKey = privateKey.publicKey
func testPrivateKeyInitThrowsOnInvalidSeedLength1024() {
XCTAssertThrowsError(try MLKEM1024.PrivateKey(seedRepresentation: Data(count: 1), publicKey: nil))
// Test encapsulation and decapsulation
let er = try publicKey.encapsulate()
let ss = try privateKey.decapsulate(er.encapsulated)
XCTAssert(er.sharedSecret == ss)
// The following would (and should) produce a compile-time error
// let er2 = try publicKey.encapsulate()
// let ss2 = try privateKey.decapsulate(er.encapsulated)
// XCTAssert(er2.sharedSecret == ss2)
}
func processKATFile(filename: String) throws -> [MLKEMKAT] {
+16 -49
View File
@@ -19,22 +19,6 @@ import XCTest
@testable import Crypto
final class XWingTests: XCTestCase {
/// Decapsulates with the regular private key and also with a one-time private key built from the
/// same key material, asserting that both paths recover the same shared secret. Returns the shared
/// secret so callers can run their own assertions (e.g. against a known-answer value), guaranteeing
/// the one-time and regular decapsulation functions are tested identically everywhere.
private func decapsulate(
with privateKey: XWingMLKEM768X25519.PrivateKey,
_ encapsulated: Data,
file: StaticString = #filePath,
line: UInt = #line
) throws -> SymmetricKey {
let sharedSecret = try privateKey.decapsulate(encapsulated)
let oneTimeSharedSecret = try XWingMLKEM768X25519.OneTimePrivateKey(reusingForTestingOnly: privateKey).decapsulate(encapsulated)
XCTAssertEqual(sharedSecret, oneTimeSharedSecret, "one-time decapsulation diverged from regular decapsulation", file: file, line: line)
return sharedSecret
}
func testKEM() throws {
let privateKey = try XWingMLKEM768X25519.PrivateKey.generate()
@@ -46,10 +30,24 @@ final class XWingTests: XCTestCase {
try XCTAssert(privateKey.integrityCheckedRepresentation == XWingMLKEM768X25519.PrivateKey(integrityCheckedRepresentation: privateKey.integrityCheckedRepresentation).integrityCheckedRepresentation)
let er = try privateKey.publicKey.encapsulate()
let ss = try decapsulate(with: privateKey, er.encapsulated)
let ss = try privateKey.decapsulate(er.encapsulated)
XCTAssert(er.sharedSecret == ss)
}
func testOneTimeKeys() throws {
let privateKey = try XWingMLKEM768X25519.OneTimePrivateKey.generate()
let publicKey = privateKey.publicKey
let er = try publicKey.encapsulate()
let ss = try privateKey.decapsulate(er.encapsulated)
XCTAssert(er.sharedSecret == ss)
// The following would (and should) produce a compile-time error
// let er2 = try publicKey.encapsulate()
// let ss2 = try privateKey.decapsulate(er.encapsulated)
// XCTAssert(er2.sharedSecret == ss2)
}
func processKATFile(filename: String) throws -> [XWingKAT] {
let bundle = Bundle.module
@@ -71,7 +69,7 @@ final class XWingTests: XCTestCase {
let encapsulatedKey = try privateKey.publicKey.encapsulateWithRng(rngState: encapDrbg)
XCTAssertEqual(encapsulatedKey.encapsulated, katTest.ct)
XCTAssertEqual(encapsulatedKey.sharedSecret.dataRepresentation, katTest.ss)
let retrievedSharedSecret = try decapsulate(with: privateKey, encapsulatedKey.encapsulated)
let retrievedSharedSecret = try privateKey.decapsulate(encapsulatedKey.encapsulated)
XCTAssertEqual(retrievedSharedSecret.dataRepresentation, katTest.ss)
}
}
@@ -93,37 +91,6 @@ final class XWingTests: XCTestCase {
let importedKey = try XWingMLKEM768X25519.PrivateKey.init(integrityCheckedRepresentation: exportedFormat)
XCTAssertEqual(importedKey.seedRepresentation, privateKey.seedRepresentation)
}
func testDecapsulateInputValidation() throws {
let ciphersuite = HPKE.Ciphersuite.XWingMLKEM768X25519_SHA256_AES_GCM_256
let skR = try XWingMLKEM768X25519.PrivateKey.generate()
// Dummy key with the correct size fails with an error from the underlying implementation.
let corretlySizedKey = Data(repeating: 0x00, count: 1120)
XCTAssertThrowsError(
try HPKE.Recipient(
privateKey: skR,
ciphersuite: ciphersuite,
info: Data(),
encapsulatedKey: corretlySizedKey
)
)
// Keys with the wrong size fail input validation.
let keySizesToTest = [0, 1, 1119, 1221, 2000]
for keySize in keySizesToTest {
let wronglySizedKey = Data(repeating: 0x00, count: keySize)
XCTAssertThrowsError(
try HPKE.Recipient(
privateKey: skR,
ciphersuite: ciphersuite,
info: Data(),
encapsulatedKey: wronglySizedKey
),
"Unexpectedly returned from malformed decapsulation path for keySize \(keySize)"
)
}
}
}
// Struct to parse KAT file