Compare commits

..
Author SHA1 Message Date
Si Beaumont 20f90497e5 [5.x] Align with CryptoKit from Xcode 27 beta 6 (#462)
## Motivation

Xcode 27 beta 6 is now available[^1] with so we can tag a compatible
release with the cross-platform code here.

## Modifications

- Resync with CryptoKit (CryptoKit-383.2.1)

## Result

- Aligned with CryptoKit in latest Xcode beta release.

[^1]: https://developer.apple.com/download/all/?q=Xcode%2027
2026-08-27 15:00:29 +01:00
Si Beaumont 2e074efbe2 [5.x] Remove native SwiftPM build-system workaround in CI (#461)
### Motivation:

Recently we got this branch warnings-as-errors clean[^1]. But, in order
to do so on Swift 6.4 and main, we needed to use `--build-system native`
because the `swiftbuild` backend wasn't handling warning control flags
properly. The SwiftPM fix for this is now available in latest 6.4 and
main nightly images.

### Modifications:

- Remove SwiftPM --build-system native workaround in CI

### Result:

CI now builds cleanly with `-warnings-as-errors` with the default
SwiftPM build-system.

[^1]: https://github.com/apple/swift-crypto/pull/454
2026-08-24 13:59:37 +01:00
Si Beaumont 33785f6746 [5.x] Mark some class types as final (#456)
### Motivation

There are a number of reference types in the codebase that aren't marked
`final`. While we won't expect a perf win by
marking them final because they don't cross the module boundary of our
public API, I'm not sure why they're not marked
`final` and marking them such cleans up the intent.

### Modifications

Mark some reference class types as final.

### Result

Cleaner internal types.
2026-08-11 15:31:46 +01:00
Si Beaumont 2c45ca2f7e [5.x] Remove unused internal code path: ECDSASignature.derBytes (#457)
### Motivation

I was just investigating the way this code path handled it's `Data`
allocation and C call and then noticed that it isn't
called anywhere, or from any test. So rather than fix it, we can just
remove it.

### Modifications:

- Remove unused internal code path: `ECDSASignature.derBytes`

### Result:

Removed unused code -- less code to maintain.
2026-08-11 15:31:03 +01:00
Si Beaumont 57782dc666 [5.x] Remove duplicate imports from gyb-generated MLDSA backend code (#458)
### Motivation

The `MLDSA_boring.swift` backend had a bunch of repeated import
statements. These exist in the gyb too.

### Modifications

- Remove duplicate import statements from `MLDSA_boring.swift.gyb`.
- Regenerate `MLDSA_boring.swift` from gyb.

### Result

- Duplicate imports removed from `MLDSA_boring.swift`.
- Aligns more closely with `MLKEM_boring.swift`, which didn't have this
problem it its code or gyb.
2026-08-11 15:30:28 +01:00
Si Beaumont b3746b1441 [5.x] Remove bindMemory(to:) calls and the CCryptoBoringSSLShims target (#455)
## Motivation

Some of our calls to our C library dependencies use either a C shim
layer or the use of `bindMemory(to:)`, neither of which are still
required. The shims themselves cite that once SR-11087 lands, they are
no longer needed. That issue was addressed and has been available in all
the Swift versions this package currently supports. We can now remove
most of these workarounds that add complexity to the C interop.

## Modifications

- Remove uses of `bindMemory(to:)` calls since we can now pass the
buffer pointer directly to these C functions now.
- Replace use of `BN_mod` (macro, needed shim) with `BN_div` (no shim
required).
- Replace all other shims with call to corresponding un-shimmed function
directly.
- Remove shim target entirely from package.

## Result

Less hand-rolled code for C interop, reducing complexity for project.
2026-08-10 15:57:17 +01:00
Si Beaumont 15b0fb5b45 [5.x] Adopt CheckImplementationOnly and CI with -warnings-as-errors (#454)
## Motivation

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, which we should adopt.

Aside: This feature is visible in 6.3 but is incomplete and the Swift
team only recommend adopting in 6.4+. Indeed, this PR is a cut-back
version of #452, which which included a lengthy patch and discussion,
boxing many types that were a result of false positives from the
`CheckImplementationOnly` feature on 6.3.

## Modifications

This patch enables `CheckImplementationOnly`, when building with 6.4, or
newer.

Additionally, as we're approaching a new major, it's a good opportunity
to get warnings-clean and lock in warnings-as-errors, so this PR does
that, suppressing only `ImplementationOnlyDeprecated`, which we cannot
eliminate. So we now build in CI using:

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

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

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

When we raise the minimum supported Swift compiler version to one that
supports `SourceWarningControl`, we can remove the `#if hasFeature`
guards.

We've had to drop to `--build-system native` (vs swift-build) for Swift
6.4 CI because SwiftPM is not stripping the warning-related compiler
flags when building dependencies.

## Result

- Stricter checks for not leakingC dependencies from BoringSSL and
libXKCP -- project builds cleanly with `CheckImplementationOnly`.
- All other compiler warnings have been addressed and project builds
with `-warnings-as-errors -Wwarning ImplementationOnlyDeprecated` in CI.
- On Swift 6.4+, `ImplementationOnlyDeprecated` warnings are completely
silenced and the project is completely warnings-free.
2026-08-07 11:39:12 +01:00
Si Beaumont ce8db4769d [5.x] Align with CryptoKit APIs from Xcode 27 beta 4 (#453)
## Motivation

Xcode 27 beta 4 is now available[^1] with so we can tag a compatible
release with the cross-platform API here.

## Modifications

- Update shared API surface to align with CryptoKit

## Result

- Aligned with CryptoKit APIs in latest Xcode beta release.

[^1]: https://developer.apple.com/download/all/?q=Xcode%2027
2026-08-07 09:03:41 +01:00
45 changed files with 208 additions and 723 deletions

No files matched your search

+4 -5
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: "--build-system native -Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
linux_nightly_main_arguments_override: "--build-system native --explicit-target-dependency-import-check error"
linux_nightly_next_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
windows_6_2_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
windows_6_3_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
windows_nightly_next_arguments_override: "--build-system native -Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
windows_nightly_main_arguments_override: "--build-system native --explicit-target-dependency-import-check error"
windows_nightly_next_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
release-builds:
name: Release builds
@@ -53,7 +53,6 @@ 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":"CCryptoBoringSSLShims","type":"source","exceptions":[]},{"name":"CryptoBoringWrapper","type":"source","exceptions":[]},{"name":"Crypto","type":"source","exceptions":[]},{"name":"CryptoExtras","type":"source","exceptions":[]},{"name":"CCryptoBoringSSL","type":"assembly","exceptions":["*/AES/*.swift"]}]}' bash
curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/update-cmake-lists.sh | CONFIG_JSON='{"targets":[{"name":"CCryptoBoringSSL","type":"source","exceptions":[]},{"name":"CryptoBoringWrapper","type":"source","exceptions":[]},{"name":"Crypto","type":"source","exceptions":[]},{"name":"CryptoExtras","type":"source","exceptions":[]},{"name":"CCryptoBoringSSL","type":"assembly","exceptions":["*/AES/*.swift"]}]}' bash
```
## API Evolution
-11
View File
@@ -126,14 +126,6 @@ let package = Package(
.disableWarning("macro-redefined"),
]
),
.target(
name: "CCryptoBoringSSLShims",
dependencies: ["CCryptoBoringSSL"],
exclude: privacyManifestExclude + [
"CMakeLists.txt"
],
resources: privacyManifestResource
),
.target(
name: "CXKCPShims",
dependencies: ["CXKCP"],
@@ -146,7 +138,6 @@ let package = Package(
name: "Crypto",
dependencies: [
.target(name: "CCryptoBoringSSL", condition: .when(platforms: nonDarwinPlatforms)),
.target(name: "CCryptoBoringSSLShims", condition: .when(platforms: nonDarwinPlatforms)),
.target(name: "CryptoBoringWrapper", condition: .when(platforms: nonDarwinPlatforms)),
.target(name: "CXKCP", condition: .when(platforms: nonDarwinPlatforms)),
.target(name: "CXKCPShims", condition: .when(platforms: nonDarwinPlatforms)),
@@ -164,7 +155,6 @@ let package = Package(
name: "CryptoExtras",
dependencies: [
"CCryptoBoringSSL",
"CCryptoBoringSSLShims",
"CryptoBoringWrapper",
"Crypto",
.product(name: "SwiftASN1", package: "swift-asn1"),
@@ -186,7 +176,6 @@ let package = Package(
name: "CryptoBoringWrapper",
dependencies: [
"CCryptoBoringSSL",
"CCryptoBoringSSLShims",
],
exclude: privacyManifestExclude + [
"CMakeLists.txt"
@@ -1,29 +0,0 @@
##===----------------------------------------------------------------------===##
##
## This source file is part of the SwiftCrypto open source project
##
## Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors
## Licensed under Apache License v2.0
##
## See LICENSE.txt for license information
## See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
##
## SPDX-License-Identifier: Apache-2.0
##
##===----------------------------------------------------------------------===##
add_library(CCryptoBoringSSLShims STATIC
"shims.c"
)
target_include_directories(CCryptoBoringSSLShims PUBLIC
include
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>)
target_link_libraries(CCryptoBoringSSLShims PUBLIC
CCryptoBoringSSL)
set_target_properties(CCryptoBoringSSLShims PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
set_property(GLOBAL APPEND PROPERTY SWIFT_CRYPTO_EXPORTS CCryptoBoringSSLShims)
@@ -1,15 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyTracking</key>
<false/>
<key>NSPrivacyAccessedAPITypes</key>
<array/>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyTrackingDomains</key>
<array/>
</dict>
</plist>
@@ -1,155 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#ifndef C_CRYPTO_BORINGSSL_SHIMS_H
#define C_CRYPTO_BORINGSSL_SHIMS_H
// This is for instances when `swift package generate-xcodeproj` is used as CCryptoBoringSSL
// is treated as a framework and requires the framework's name as a prefix.
#if __has_include(<CCryptoBoringSSL/CCryptoBoringSSL.h>)
#include <CCryptoBoringSSL/CCryptoBoringSSL.h>
#else
#include <CCryptoBoringSSL.h>
#endif
#if defined(__cplusplus)
extern "C" {
#endif
// MARK:- Pointer type shims
// This section of the code handles shims that change uint8_t* pointers to
// void *s. This is done because Swift does not have the rule that C does, that
// pointers to uint8_t can safely alias any other pointer. That means that Swift
// Unsafe[Mutable]RawPointer cannot be passed to uint8_t * APIs, which is very
// awkward, so we shim these to avoid the need to call bindMemory in Swift (which is
// wrong).
//
// Our relevant citation is: https://github.com/apple/swift-nio-extras/pull/56#discussion_r329330295.
// We want this to land: https://bugs.swift.org/browse/SR-11087. Once that lands we can remove these
// shims.
int CCryptoBoringSSLShims_EVP_AEAD_CTX_init(EVP_AEAD_CTX *ctx, const EVP_AEAD *aead,
const void *key, size_t key_len, size_t tag_len,
ENGINE *impl);
int CCryptoBoringSSLShims_EVP_AEAD_CTX_seal_scatter(
const EVP_AEAD_CTX *ctx,
void *out,
void *out_tag,
size_t *out_tag_len,
size_t max_out_tag_len,
const void *nonce,
size_t nonce_len,
const void *in,
size_t in_len,
const void *extra_in,
size_t extra_in_len,
const void *ad,
size_t ad_len);
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(const EVP_AEAD_CTX *ctx, void *out,
const void *nonce, size_t nonce_len,
const void *in, size_t in_len,
const void *in_tag, size_t in_tag_len,
const void *ad, size_t ad_len);
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open(const EVP_AEAD_CTX *ctx, void *out, size_t *out_len, size_t max_out_len,
const void *nonce, size_t nonce_len,
const void *in, size_t in_len,
const void *ad, size_t ad_len);
void CCryptoBoringSSLShims_ED25519_keypair(void *out_public_key, void *out_private_key);
void CCryptoBoringSSLShims_ED25519_keypair_from_seed(void *out_public_key,
void *out_private_key,
const void *seed);
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_do_sign(const void *digest, size_t digest_len,
const EC_KEY *eckey);
int CCryptoBoringSSLShims_ECDSA_do_verify(const void *digest, size_t digest_len,
const ECDSA_SIG *sig, const EC_KEY *eckey);
void CCryptoBoringSSLShims_X25519_keypair(void *out_public_value, void *out_private_key);
void CCryptoBoringSSLShims_X25519_public_from_private(void *out_public_value,
const void *private_key);
int CCryptoBoringSSLShims_X25519(void *out_shared_key, const void *private_key,
const void *peer_public_value);
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(const void *in, size_t in_len);
int CCryptoBoringSSLShims_ED25519_verify(const void *message, size_t message_len,
const void *signature, const void *public_key);
int CCryptoBoringSSLShims_ED25519_sign(void *out_sig, const void *message,
size_t message_len, const void *private_key);
BIGNUM *CCryptoBoringSSLShims_BN_bin2bn(const void *in, size_t len, BIGNUM *ret);
size_t CCryptoBoringSSLShims_BN_bn2bin(const BIGNUM *in, void *out);
int CCryptoBoringSSLShims_BN_mod(BIGNUM *rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
int CCryptoBoringSSLShims_RSA_verify(int hash_nid, const void *msg, size_t msg_len,
const void *sig, size_t sig_len, RSA *rsa);
int CCryptoBoringSSLShims_RSA_verify_pss_mgf1(RSA *rsa, const void *msg,
size_t msg_len, const EVP_MD *md,
const EVP_MD *mgf1_md, int salt_len,
const void *sig, size_t sig_len);
int CCryptoBoringSSLShims_RSA_sign(int hash_nid, const void *in,
unsigned int in_len, void *out,
unsigned int *out_len, RSA *rsa);
int CCryptoBoringSSLShims_RSA_sign_pss_mgf1(RSA *rsa, size_t *out_len, void *out,
size_t max_out, const void *in,
size_t in_len, const EVP_MD *md,
const EVP_MD *mgf1_md, int salt_len);
int CCryptoBoringSSLShims_RSA_public_encrypt(int flen, const void *from, void *to,
RSA *rsa, int padding);
int CCryptoBoringSSLShims_RSA_private_decrypt(int flen, const void *from, void *to,
RSA *rsa, int padding);
int CCryptoBoringSSLShims_EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, void *out,
size_t *out_len, const void *in,
size_t in_len);
int CCryptoBoringSSLShims_EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, void *out,
size_t *out_len, const void *in,
size_t in_len);
int CCryptoBoringSSLShims_EC_hash_to_curve_p256_xmd_sha256_sswu(const EC_GROUP *group, EC_POINT *out,
const void *dst, size_t dst_len,
const void *msg, size_t msg_len);
int CCryptoBoringSSLShims_EC_hash_to_curve_p384_xmd_sha384_sswu(const EC_GROUP *group, EC_POINT *out,
const void *dst, size_t dst_len,
const void *msg, size_t msg_len);
size_t CCryptoBoringSSLShims_EC_POINT_point2oct(const EC_GROUP *group,
const EC_POINT *point,
point_conversion_form_t form,
void *buf, size_t max_out,
BN_CTX *ctx);
#if defined(__cplusplus)
}
#endif // defined(__cplusplus)
#endif // C_CRYPTO_BORINGSSL_SHIMS_H
@@ -1,4 +0,0 @@
module CCryptoBoringSSLShims {
header "CCryptoBoringSSLShims.h"
export *
}
-190
View File
@@ -1,190 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#include <CCryptoBoringSSLShims.h>
// MARK:- Pointer type shims
// This section of the code handles shims that change uint8_t* pointers to
// void *s. This is done because Swift does not have the rule that C does, that
// pointers to uint8_t can safely alias any other pointer. That means that Swift
// Unsafe[Mutable]RawPointer cannot be passed to uint8_t * APIs, which is very
// awkward, so we shim these to avoid the need to call bindMemory in Swift (which is
// wrong).
//
// Our relevant citation is: https://github.com/apple/swift-nio-extras/pull/56#discussion_r329330295.
// We want this to land: https://bugs.swift.org/browse/SR-11087. Once that lands we can remove these
// shims.
int CCryptoBoringSSLShims_EVP_AEAD_CTX_init(EVP_AEAD_CTX *ctx, const EVP_AEAD *aead,
const void *key, size_t key_len, size_t tag_len,
ENGINE *impl) {
return CCryptoBoringSSL_EVP_AEAD_CTX_init(ctx, aead, key, key_len, tag_len, impl);
}
int CCryptoBoringSSLShims_EVP_AEAD_CTX_seal_scatter(
const EVP_AEAD_CTX *ctx,
void *out,
void *out_tag,
size_t *out_tag_len,
size_t max_out_tag_len,
const void *nonce,
size_t nonce_len,
const void *in,
size_t in_len,
const void *extra_in,
size_t extra_in_len,
const void *ad,
size_t ad_len) {
return CCryptoBoringSSL_EVP_AEAD_CTX_seal_scatter(ctx, out, out_tag, out_tag_len, max_out_tag_len, nonce, nonce_len, in, in_len, extra_in, extra_in_len, ad, ad_len);
}
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(const EVP_AEAD_CTX *ctx, void *out,
const void *nonce, size_t nonce_len,
const void *in, size_t in_len,
const void *in_tag, size_t in_tag_len,
const void *ad, size_t ad_len) {
return CCryptoBoringSSL_EVP_AEAD_CTX_open_gather(ctx, out, nonce, nonce_len, in, in_len, in_tag, in_tag_len, ad, ad_len);
}
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open(const EVP_AEAD_CTX *ctx, void *out, size_t *out_len, size_t max_out_len,
const void *nonce, size_t nonce_len,
const void *in, size_t in_len,
const void *ad, size_t ad_len) {
return CCryptoBoringSSL_EVP_AEAD_CTX_open(ctx, out, out_len, max_out_len, nonce, nonce_len, in, in_len, ad, ad_len);
}
void CCryptoBoringSSLShims_ED25519_keypair(void *out_public_key, void *out_private_key) {
CCryptoBoringSSL_ED25519_keypair(out_public_key, out_private_key);
}
void CCryptoBoringSSLShims_ED25519_keypair_from_seed(void *out_public_key,
void *out_private_key,
const void *seed) {
CCryptoBoringSSL_ED25519_keypair_from_seed(out_public_key, out_private_key, seed);
}
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_do_sign(const void *digest, size_t digest_len,
const EC_KEY *eckey) {
return CCryptoBoringSSL_ECDSA_do_sign(digest, digest_len, eckey);
}
int CCryptoBoringSSLShims_ECDSA_do_verify(const void *digest, size_t digest_len,
const ECDSA_SIG *sig, const EC_KEY *eckey) {
return CCryptoBoringSSL_ECDSA_do_verify(digest, digest_len, sig, eckey);
}
void CCryptoBoringSSLShims_X25519_keypair(void *out_public_value, void *out_private_key) {
CCryptoBoringSSL_X25519_keypair(out_public_value, out_private_key);
}
void CCryptoBoringSSLShims_X25519_public_from_private(void *out_public_value,
const void *private_key) {
CCryptoBoringSSL_X25519_public_from_private(out_public_value, private_key);
}
int CCryptoBoringSSLShims_X25519(void *out_shared_key, const void *private_key,
const void *peer_public_value) {
return CCryptoBoringSSL_X25519(out_shared_key, private_key, peer_public_value);
}
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(const void *in, size_t in_len) {
return CCryptoBoringSSL_ECDSA_SIG_from_bytes(in, in_len);
}
int CCryptoBoringSSLShims_ED25519_verify(const void *message, size_t message_len,
const void *signature, const void *public_key) {
return CCryptoBoringSSL_ED25519_verify(message, message_len, signature, public_key);
}
int CCryptoBoringSSLShims_ED25519_sign(void *out_sig, const void *message,
size_t message_len, const void *private_key) {
return CCryptoBoringSSL_ED25519_sign(out_sig, message, message_len, private_key);
}
BIGNUM *CCryptoBoringSSLShims_BN_bin2bn(const void *in, size_t len, BIGNUM *ret) {
return CCryptoBoringSSL_BN_bin2bn(in, len, ret);
}
size_t CCryptoBoringSSLShims_BN_bn2bin(const BIGNUM *in, void *out) {
return CCryptoBoringSSL_BN_bn2bin(in, out);
}
int CCryptoBoringSSLShims_BN_mod(BIGNUM *rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) {
return BN_mod(rem, a, m, ctx);
}
int CCryptoBoringSSLShims_RSA_verify(int hash_nid, const void *msg, size_t msg_len,
const void *sig, size_t sig_len, RSA *rsa) {
return CCryptoBoringSSL_RSA_verify(hash_nid, msg, msg_len, sig, sig_len, rsa);
}
int CCryptoBoringSSLShims_RSA_verify_pss_mgf1(RSA *rsa, const void *msg,
size_t msg_len, const EVP_MD *md,
const EVP_MD *mgf1_md, int salt_len,
const void *sig, size_t sig_len) {
return CCryptoBoringSSL_RSA_verify_pss_mgf1(rsa, msg, msg_len, md, mgf1_md, salt_len, sig, sig_len);
}
int CCryptoBoringSSLShims_RSA_sign(int hash_nid, const void *in,
unsigned int in_len, void *out,
unsigned int *out_len, RSA *rsa) {
return CCryptoBoringSSL_RSA_sign(hash_nid, in, in_len, out, out_len, rsa);
}
int CCryptoBoringSSLShims_RSA_sign_pss_mgf1(RSA *rsa, size_t *out_len, void *out,
size_t max_out, const void *in,
size_t in_len, const EVP_MD *md,
const EVP_MD *mgf1_md, int salt_len) {
return CCryptoBoringSSL_RSA_sign_pss_mgf1(rsa, out_len, out, max_out, in, in_len, md, mgf1_md, salt_len);
}
int CCryptoBoringSSLShims_RSA_public_encrypt(int flen, const void *from, void *to,
RSA *rsa, int padding) {
return CCryptoBoringSSL_RSA_public_encrypt(flen, from, to, rsa, padding);
}
int CCryptoBoringSSLShims_RSA_private_decrypt(int flen, const void *from, void *to,
RSA *rsa, int padding) {
return CCryptoBoringSSL_RSA_private_decrypt(flen, from, to, rsa, padding);
}
int CCryptoBoringSSLShims_EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, void *out,
size_t *out_len, const void *in,
size_t in_len) {
return CCryptoBoringSSL_EVP_PKEY_encrypt(ctx, out, out_len, in, in_len);
}
int CCryptoBoringSSLShims_EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, void *out,
size_t *out_len, const void *in,
size_t in_len) {
return CCryptoBoringSSL_EVP_PKEY_decrypt(ctx, out, out_len, in, in_len);
}
int CCryptoBoringSSLShims_EC_hash_to_curve_p256_xmd_sha256_sswu(const EC_GROUP *group, EC_POINT *out,
const void *dst, size_t dst_len,
const void *msg, size_t msg_len) {
return CCryptoBoringSSL_EC_hash_to_curve_p256_xmd_sha256_sswu(group, out, dst, dst_len, msg, msg_len);
}
int CCryptoBoringSSLShims_EC_hash_to_curve_p384_xmd_sha384_sswu(const EC_GROUP *group, EC_POINT *out,
const void *dst, size_t dst_len,
const void *msg, size_t msg_len) {
return CCryptoBoringSSL_EC_hash_to_curve_p384_xmd_sha384_sswu(group, out, dst, dst_len, msg, msg_len);
}
size_t CCryptoBoringSSLShims_EC_POINT_point2oct(const EC_GROUP *group,
const EC_POINT *point,
point_conversion_form_t form,
void *buf, size_t max_out,
BN_CTX *ctx) {
return CCryptoBoringSSL_EC_POINT_point2oct(group, point, form, buf, max_out, ctx);
}
-1
View File
@@ -13,7 +13,6 @@
##===----------------------------------------------------------------------===##
add_subdirectory(CCryptoBoringSSL)
add_subdirectory(CCryptoBoringSSLShims)
add_subdirectory(CXKCP)
add_subdirectory(CXKCPShims)
add_subdirectory(CryptoBoringWrapper)
@@ -88,21 +88,6 @@ extension AES {
)
}
// Note: historical version of the above, which should be removed once
// the above is API and clients move over to it.
#if swift(<6.3)
@_lifetime(message: copy message)
#endif
internal static func seal(
inplace message: inout MutableRawSpan,
using key: SymmetricKey,
nonce: RawSpan,
authenticating authenticatedData: RawSpan? = nil,
tag: inout OutputRawSpan
) throws(CryptoKitMetaError) {
return try AESGCMImpl.seal(key: key, message: &message, nonce: nonce, authenticatedData: authenticatedData, tag: &tag)
}
/// Decrypts the message and verifies the authenticity of both the
/// encrypted message and additional data.
///
@@ -161,28 +146,6 @@ 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,10 +16,8 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
@@ -83,21 +83,6 @@ public enum ChaChaPoly: Cipher, Sendable {
try ChaChaPolyImpl.encrypt(key: key, inPlace: &message, nonce: nonce.bytes, authenticatedData: authenticatedData, tag: &tag)
}
// Note: historical version of the above, which should be removed once
// the above is API and clients move over to it.
#if swift(<6.3)
@_lifetime(message: copy message)
#endif
internal static func seal(
inplace message: inout MutableRawSpan,
using key: SymmetricKey,
nonce: RawSpan,
authenticating authenticatedData: RawSpan? = nil,
tag: inout OutputRawSpan
) throws(CryptoKitMetaError) {
try ChaChaPolyImpl.encrypt(key: key, inPlace: &message, nonce: nonce, authenticatedData: authenticatedData, tag: &tag)
}
/// Decrypts the message and verifies the authenticity of both the encrypted
/// message and additional data.
///
@@ -151,21 +136,6 @@ 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,7 +117,6 @@ target_compile_definitions(Crypto PRIVATE
target_include_directories(Crypto PRIVATE
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CCryptoBoringSSLShims,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CryptoBoringWrapper,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CXKCP,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CXKCPShims,INCLUDE_DIRECTORIES>)
@@ -125,7 +124,6 @@ target_link_libraries(Crypto PUBLIC
$<$<NOT:$<PLATFORM_ID:Darwin>>:dispatch>
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
CCryptoBoringSSL
CCryptoBoringSSLShims
CryptoBoringWrapper
CXKCP
CXKCPShims)
+27 -6
View File
@@ -23,6 +23,7 @@ public import Foundation
typealias MLKEMPublicKeyImpl = OpenSSLMLKEMPublicKeyImpl
typealias MLKEMPrivateKeyImpl = OpenSSLMLKEMPrivateKeyImpl
typealias MLKEMOneTimePrivateKeyImpl = OpenSSLMLKEMPrivateKeyImpl
/// The Module-Lattice key encapsulation mechanism (KEM).
@@ -150,15 +151,25 @@ 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: MLKEMPrivateKeyImpl<MLKEM768>
internal let impl: MLKEMOneTimePrivateKeyImpl<MLKEM768>
internal init(_ impl: MLKEMPrivateKeyImpl<MLKEM768>) {
internal init(_ impl: MLKEMOneTimePrivateKeyImpl<MLKEM768>) {
self.impl = impl
}
/// Creates a one-time-use private key that reuses the key material of an existing private key.
///
/// This is used by the tests to check that the one-time decapsulation function is consistent with the regular one.
internal init(reusingForTestingOnly privateKey: MLKEM768.PrivateKey) {
self.impl = try! MLKEMOneTimePrivateKeyImpl<MLKEM768>(
seedRepresentation: privateKey.impl.seedRepresentation,
publicKeyRawRepresentation: privateKey.impl.publicKey.rawRepresentation
)
}
/// Generates a new, random one-time-use private key.
public static func generate() throws -> MLKEM768.OneTimePrivateKey {
let impl = try MLKEMPrivateKeyImpl<MLKEM768>.generatePrivateKey()
let impl = try MLKEMOneTimePrivateKeyImpl<MLKEM768>.generatePrivateKey()
return OneTimePrivateKey(impl)
}
@@ -311,15 +322,25 @@ 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: MLKEMPrivateKeyImpl<MLKEM1024>
internal let impl: MLKEMOneTimePrivateKeyImpl<MLKEM1024>
internal init(_ impl: MLKEMPrivateKeyImpl<MLKEM1024>) {
internal init(_ impl: MLKEMOneTimePrivateKeyImpl<MLKEM1024>) {
self.impl = impl
}
/// Creates a one-time-use private key that reuses the key material of an existing private key.
///
/// This is used by the tests to check that the one-time decapsulation function is consistent with the regular one.
internal init(reusingForTestingOnly privateKey: MLKEM1024.PrivateKey) {
self.impl = try! MLKEMOneTimePrivateKeyImpl<MLKEM1024>(
seedRepresentation: privateKey.impl.seedRepresentation,
publicKeyRawRepresentation: privateKey.impl.publicKey.rawRepresentation
)
}
/// Generates a new, random one-time-use private key.
public static func generate() throws -> MLKEM1024.OneTimePrivateKey {
let impl = try MLKEMPrivateKeyImpl<MLKEM1024>.generatePrivateKey()
let impl = try MLKEMOneTimePrivateKeyImpl<MLKEM1024>.generatePrivateKey()
return OneTimePrivateKey(impl)
}
+8 -1
View File
@@ -58,7 +58,7 @@ extension XWingMLKEM768X25519 {
}
public struct PrivateKey: KEMPrivateKey {
private var impl: XWingPrivateKeyImpl
var impl: XWingPrivateKeyImpl
public var seedRepresentation: Data {
get {
@@ -106,6 +106,13 @@ extension XWingMLKEM768X25519 {
self.impl = impl
}
/// Creates a one-time-use private key that reuses the key material of an existing private key.
///
/// This is used by the tests to check that the one-time decapsulation function is consistent with the regular one.
internal init(reusingForTestingOnly privateKey: XWingMLKEM768X25519.PrivateKey) {
self.impl = privateKey.impl
}
/// Generates a new, random one-time-use private key.
public static func generate() throws -> XWingMLKEM768X25519.OneTimePrivateKey {
let impl = try XWingPrivateKeyImpl.generate()
@@ -33,12 +33,8 @@ enum BoringSSLAESWRAPImpl {
let rc = try key.withUnsafeAESKEY(mode: .encrypting) { aesKey in
output.withUnsafeMutableBytes { outputPtr -> CInt in
// Memory bind is safe: we cannot alias the pointer here.
let outputPtr = outputPtr.bindMemory(to: UInt8.self)
return keyToWrap.withUnsafeBytes { keyToWrapPtr -> CInt in
// Memory bind is safe: we cannot alias the pointer here.
let keyToWrapPtr = keyToWrapPtr.bindMemory(to: UInt8.self)
return CCryptoBoringSSL_AES_wrap_key(
keyToWrap.withUnsafeBytes { keyToWrapPtr -> CInt in
CCryptoBoringSSL_AES_wrap_key(
aesKey,
nil,
outputPtr.baseAddress,
@@ -78,8 +74,6 @@ 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,
@@ -117,8 +111,6 @@ extension SymmetricKey {
_ body: (UnsafePointer<AES_KEY>) throws -> ResultType
) throws -> ResultType {
try self.withUnsafeBytes { bytesPointer in
// Bind is safe: cannot alias the pointer here.
let bytesPointer = bytesPointer.bindMemory(to: UInt8.self)
var aesKey = AES_KEY()
let bitsInKey = UInt32(bytesPointer.count * 8)
@@ -16,10 +16,8 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
@@ -46,7 +44,7 @@ extension Curve25519.Signing {
privateKeyBytes in
privateKeyBytes = 64
publicKey.withUnsafeMutableBytes { publicKeyPtr in
CCryptoBoringSSLShims_ED25519_keypair(
CCryptoBoringSSL_ED25519_keypair(
publicKeyPtr.baseAddress,
privateKeyPtr.baseAddress
)
@@ -80,7 +78,7 @@ extension Curve25519.Signing {
privateKeyBytes in
privateKeyBytes = 64
publicKey.withUnsafeMutableBytes { publicKeyPtr in
CCryptoBoringSSLShims_ED25519_keypair_from_seed(
CCryptoBoringSSL_ED25519_keypair_from_seed(
publicKeyPtr.baseAddress,
privateKeyPtr.baseAddress,
seedPtr.baseAddress
@@ -16,10 +16,8 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
@@ -148,7 +146,7 @@ struct OpenSSLNISTCurvePublicKeyImpl<Curve: OpenSSLSupportedNISTCurve>: Sendable
/// allows some helper operations.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
final class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
@usableFromInline
let key: OpaquePointer
@@ -335,7 +333,7 @@ class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked
func sign<D: Digest>(digest: D) throws -> ECDSASignature {
let optionalRawSignature: UnsafeMutablePointer<ECDSA_SIG>? = digest.withUnsafeBytes {
digestPtr in
CCryptoBoringSSLShims_ECDSA_do_sign(digestPtr.baseAddress, digestPtr.count, self.key)
CCryptoBoringSSL_ECDSA_do_sign(digestPtr.baseAddress, digestPtr.count, self.key)
}
guard let rawSignature = optionalRawSignature else {
throw CryptoKitError.internalBoringSSLError()
@@ -353,7 +351,7 @@ class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked
/// allows some helper operations.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
final class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
@usableFromInline
let key: OpaquePointer
@@ -575,7 +573,7 @@ class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked
func isValidSignature<D: Digest>(_ signature: ECDSASignature, for digest: D) -> Bool {
let rc: CInt = signature.withUnsafeSignaturePointer { signaturePointer in
digest.withUnsafeBytes { digestPointer in
CCryptoBoringSSLShims_ECDSA_do_verify(
CCryptoBoringSSL_ECDSA_do_verify(
digestPointer.baseAddress,
digestPointer.count,
signaturePointer,
@@ -16,10 +16,8 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
@@ -77,7 +75,7 @@ extension Curve25519.KeyAgreement {
publicKey.withUnsafeMutableBytes { publicKeyBytes in
precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
precondition(privateKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
CCryptoBoringSSLShims_X25519_keypair(
CCryptoBoringSSL_X25519_keypair(
publicKeyBytes.baseAddress,
privateKeyBytes.baseAddress
)
@@ -105,7 +103,7 @@ extension Curve25519.KeyAgreement {
publicKeyBytes,
publicKeySize in
precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
CCryptoBoringSSLShims_X25519_public_from_private(
CCryptoBoringSSL_X25519_public_from_private(
publicKeyBytes.baseAddress,
privatePointer.baseAddress
)
@@ -140,7 +138,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.
CCryptoBoringSSLShims_X25519(
CCryptoBoringSSL_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.bindMemory(to: UInt8.self)).makeIterator()
return Array(buffPtr).makeIterator()
})
}
@@ -16,10 +16,8 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
@@ -30,13 +28,13 @@ import Foundation
/// A wrapper around BoringSSL's ECDSA_SIG with some lifetime management.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
class ECDSASignature {
final class ECDSASignature {
private var _baseSig: UnsafeMutablePointer<ECDSA_SIG>
init<ContiguousBuffer: ContiguousBytes>(contiguousDERBytes derBytes: ContiguousBuffer) throws {
self._baseSig = try derBytes.withUnsafeBytes { bytesPtr in
guard
let sig = CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(bytesPtr.baseAddress, bytesPtr.count)
let sig = CCryptoBoringSSL_ECDSA_SIG_from_bytes(bytesPtr.baseAddress, bytesPtr.count)
else {
throw CryptoKitError.internalBoringSSLError()
}
@@ -101,21 +99,6 @@ class ECDSASignature {
)
}
@usableFromInline
var derBytes: Data {
var dataPtr: UnsafeMutablePointer<UInt8>?
var length = 0
guard CCryptoBoringSSL_ECDSA_SIG_to_bytes(&dataPtr, &length, self._baseSig) == 1 else {
fatalError("Unable to marshal signature to DER")
}
defer {
// We must free this pointer.
CCryptoBoringSSL_OPENSSL_free(dataPtr)
}
return Data(UnsafeBufferPointer(start: dataPtr, count: length))
}
func withUnsafeSignaturePointer<T>(
_ body: (UnsafeMutablePointer<ECDSA_SIG>) throws -> T
)
@@ -67,17 +67,6 @@ extension Data {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P256.Signing.ECDSASignature {
init<D: DataProtocol>(openSSLDERSignature derRepresentation: D) throws {
self.rawRepresentation = try Data(derSignature: derRepresentation, over: P256.self)
}
var openSSLDERRepresentation: Data {
try! ECDSASignature(rawRepresentation: self.rawRepresentation).derBytes
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P256.Signing.PrivateKey {
func openSSLSignature<D: Digest>(for digest: D) throws -> P256.Signing.ECDSASignature {
@@ -104,17 +93,6 @@ extension P256.Signing.PublicKey {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P384.Signing.ECDSASignature {
init<D: DataProtocol>(openSSLDERSignature derRepresentation: D) throws {
self.rawRepresentation = try Data(derSignature: derRepresentation, over: P384.self)
}
var openSSLDERRepresentation: Data {
try! ECDSASignature(rawRepresentation: self.rawRepresentation).derBytes
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P384.Signing.PrivateKey {
func openSSLSignature<D: Digest>(for digest: D) throws -> P384.Signing.ECDSASignature {
@@ -141,17 +119,6 @@ extension P384.Signing.PublicKey {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P521.Signing.ECDSASignature {
init<D: DataProtocol>(openSSLDERSignature derRepresentation: D) throws {
self.rawRepresentation = try Data(derSignature: derRepresentation, over: P521.self)
}
var openSSLDERRepresentation: Data {
try! ECDSASignature(rawRepresentation: self.rawRepresentation).derBytes
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P521.Signing.PrivateKey {
func openSSLSignature<D: Digest>(for digest: D) throws -> P521.Signing.ECDSASignature {
@@ -16,10 +16,8 @@
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
@@ -94,7 +92,7 @@ extension Curve25519.Signing.PublicKey {
precondition(signaturePointer.count == Curve25519.Signing.PublicKey.signatureByteCount)
precondition(self.keyBytes.count == 32)
let rc: CInt = self.keyBytes.withUnsafeBytes { keyBytesPtr in
CCryptoBoringSSLShims_ED25519_verify(
CCryptoBoringSSL_ED25519_verify(
dataPointer.baseAddress,
dataPointer.count,
signaturePointer.baseAddress,
@@ -133,7 +131,7 @@ extension Curve25519.Signing.PrivateKey {
precondition(signaturePointer.count == Curve25519.Signing.PublicKey.signatureByteCount)
precondition(keyPointer.count == ED25519_PRIVATE_KEY_LEN)
return CCryptoBoringSSLShims_ED25519_sign(
return CCryptoBoringSSL_ED25519_sign(
signaturePointer.baseAddress,
dataPointer.baseAddress,
dataPointer.count,
@@ -12,24 +12,13 @@
//
//===----------------------------------------------------------------------===//
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
// MARK: - Generated file, do NOT edit
// any edits of this file WILL be overwritten and thus discarded
// see section `gyb` in `README` for details.
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@@ -12,24 +12,13 @@
//
//===----------------------------------------------------------------------===//
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
// MARK: - Generated file, do NOT edit
// any edits of this file WILL be overwritten and thus discarded
// see section `gyb` in `README` for details.
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@@ -14,10 +14,8 @@
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
@@ -43,7 +41,7 @@ extension BoringSSLAEAD {
// Arguably this class is excessive, but it's probably better for this API to be as safe as possible
// rather than rely on defer statements for our cleanup.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
public class AEADContext {
public final class AEADContext {
private var context: EVP_AEAD_CTX
public init<Key: ContiguousBytes>(cipher: BoringSSLAEAD, key: Key) throws {
@@ -52,7 +50,7 @@ extension BoringSSLAEAD {
let rc: CInt = key.withUnsafeBytes { keyPointer in
withUnsafeMutablePointer(to: &self.context) { contextPointer in
// Create the AEAD context with a default tag length using the given key.
CCryptoBoringSSLShims_EVP_AEAD_CTX_init(
CCryptoBoringSSL_EVP_AEAD_CTX_init(
contextPointer,
cipher.boringSSLCipher,
keyPointer.baseAddress,
@@ -177,7 +175,7 @@ extension BoringSSLAEAD.AEADContext {
return authenticatedData.withUnsafeBytes { authenticatedDataBuffer in
nonce.withUnsafeBytes { nonceBuffer in
CCryptoBoringSSLShims_EVP_AEAD_CTX_seal_scatter(
CCryptoBoringSSL_EVP_AEAD_CTX_seal_scatter(
contextPointer,
messageBuffer.baseAddress,
tagBuffer.baseAddress! + tagInitializedCount,
@@ -319,7 +317,7 @@ extension BoringSSLAEAD.AEADContext {
nonce.withUnsafeBytes { nonceBuffer in
tag.withUnsafeBytes { tagBuffer in
authenticatedData.withUnsafeBytes { adBuffer in
CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(
CCryptoBoringSSL_EVP_AEAD_CTX_open_gather(
contextPointer,
messageBuffer.baseAddress,
nonceBuffer.baseAddress,
@@ -430,7 +428,7 @@ extension BoringSSLAEAD.AEADContext {
var writtenBytes = 0
let rc = withUnsafePointer(to: &self.context) { contextPointer in
CCryptoBoringSSLShims_EVP_AEAD_CTX_open(
CCryptoBoringSSL_EVP_AEAD_CTX_open(
contextPointer,
outputBuffer.baseAddress,
&writtenBytes,
+2 -4
View File
@@ -24,13 +24,11 @@ add_library(CryptoBoringWrapper STATIC
)
target_include_directories(CryptoBoringWrapper PUBLIC
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CCryptoBoringSSLShims,INCLUDE_DIRECTORIES>)
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>)
target_link_libraries(CryptoBoringWrapper PUBLIC
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
CCryptoBoringSSL
CCryptoBoringSSLShims)
CCryptoBoringSSL)
target_compile_options(CryptoBoringWrapper PRIVATE ${SWIFT_CRYPTO_COMPILE_OPTIONS})
@@ -13,10 +13,8 @@
//===----------------------------------------------------------------------===//
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
@@ -494,29 +492,35 @@ extension EllipticCurvePoint {
to group: BoringSSLEllipticCurveGroup,
domainSeparationTag: DSTBytes
) throws {
let hashToCurveFunction =
switch group.curveName {
case .p256: CCryptoBoringSSLShims_EC_hash_to_curve_p256_xmd_sha256_sswu
case .p384: CCryptoBoringSSLShims_EC_hash_to_curve_p384_xmd_sha384_sswu
// BoringSSL has no P521 hash_to_curve API.
case .p521: throw CryptoBoringWrapperError.invalidParameter
case .none: throw CryptoBoringWrapperError.internalBoringSSLError()
}
try self.init(_pointAtInfinityOn: group)
try msg.withUnsafeBytes { msgPtr in
try group.withUnsafeGroupPointer { groupPtr in
try domainSeparationTag.withUnsafeBytes { dstPtr in
guard
hashToCurveFunction(
let rc: CInt
switch group.curveName {
case .p256:
rc = CCryptoBoringSSL_EC_hash_to_curve_p256_xmd_sha256_sswu(
groupPtr,
self._basePoint,
dstPtr.baseAddress,
dstPtr.count,
msgPtr.baseAddress,
msgPtr.count
) == 1
else { throw CryptoBoringWrapperError.internalBoringSSLError() }
)
case .p384:
rc = CCryptoBoringSSL_EC_hash_to_curve_p384_xmd_sha384_sswu(
groupPtr,
self._basePoint,
dstPtr.baseAddress,
dstPtr.count,
msgPtr.baseAddress,
msgPtr.count
)
// BoringSSL has no P521 hash_to_curve API.
case .p521: throw CryptoBoringWrapperError.invalidParameter
case .none: throw CryptoBoringWrapperError.internalBoringSSLError()
}
guard rc == 1 else { throw CryptoBoringWrapperError.internalBoringSSLError() }
}
}
}
@@ -603,7 +607,7 @@ extension EllipticCurvePoint {
let numBytesWritten = group.withUnsafeGroupPointer { groupPtr in
buf.withUnsafeMutableBytes { bufPtr in
CCryptoBoringSSLShims_EC_POINT_point2oct(
CCryptoBoringSSL_EC_POINT_point2oct(
groupPtr,
self._basePoint,
compressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED,
@@ -14,10 +14,8 @@
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
@@ -123,7 +121,7 @@ extension ArbitraryPrecisionInteger.BackingStorage {
self.init()
let rc: UnsafeMutablePointer<BIGNUM>? = bytes.withUnsafeBytes { bytesPointer in
CCryptoBoringSSLShims_BN_bin2bn(
CCryptoBoringSSL_BN_bin2bn(
bytesPointer.baseAddress,
bytesPointer.count,
&self._backing
@@ -459,7 +457,8 @@ extension ArbitraryPrecisionInteger {
if nonNegative {
CCryptoBoringSSL_BN_nnmod(resultPtr, selfPtr, modPtr, bnCtx)
} else {
CCryptoBoringSSLShims_BN_mod(resultPtr, selfPtr, modPtr, bnCtx)
// BN_mod is a C macro for BN_div with a nil quotient; call that directly.
CCryptoBoringSSL_BN_div(nil, resultPtr, selfPtr, modPtr, bnCtx)
}
}
}
@@ -718,7 +717,7 @@ extension Data {
assert(bytesPtr.count == byteCount)
return integer.withUnsafeBignumPointer { bnPtr in
CCryptoBoringSSLShims_BN_bn2bin(bnPtr, bytesPtr.baseAddress!)
CCryptoBoringSSL_BN_bn2bin(bnPtr, bytesPtr.baseAddress!)
}
}
@@ -37,7 +37,7 @@ import Foundation
/// ourselves.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
package class FiniteFieldArithmeticContext: @unchecked Sendable {
package final class FiniteFieldArithmeticContext: @unchecked Sendable {
private let fieldSize: ArbitraryPrecisionInteger
package let bnCtx: OpaquePointer
@@ -15,10 +15,8 @@
import Crypto
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
+4 -12
View File
@@ -15,10 +15,8 @@
import Crypto
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import CryptoBoringWrapper
#if canImport(FoundationEssentials)
@@ -99,24 +97,18 @@ extension AES {
precondition(payload.count == Int(Self.blockSize))
key.withUnsafeBytes { keyPtr in
// We bind both pointers here. These binds are not technically safe, but because we
// know the pointers don't persist they can't violate the aliasing rules. We really
// want a "with memory rebound" function but we don't have it yet.
let keyBytes = keyPtr.bindMemory(to: UInt8.self)
let blockBytes = payload.bindMemory(to: UInt8.self)
var key = AES_KEY()
if permutation == .forward {
let rc = CCryptoBoringSSL_AES_set_encrypt_key(keyBytes.baseAddress, UInt32(keyBytes.count * 8), &key)
let rc = CCryptoBoringSSL_AES_set_encrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key)
precondition(rc == 0)
CCryptoBoringSSL_AES_encrypt(blockBytes.baseAddress, blockBytes.baseAddress, &key)
CCryptoBoringSSL_AES_encrypt(payload.baseAddress, payload.baseAddress, &key)
} else {
let rc = CCryptoBoringSSL_AES_set_decrypt_key(keyBytes.baseAddress, UInt32(keyBytes.count * 8), &key)
let rc = CCryptoBoringSSL_AES_set_decrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key)
precondition(rc == 0)
CCryptoBoringSSL_AES_decrypt(blockBytes.baseAddress, blockBytes.baseAddress, &key)
CCryptoBoringSSL_AES_decrypt(payload.baseAddress, payload.baseAddress, &key)
}
}
}
@@ -19,10 +19,8 @@ import CryptoBoringWrapper
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
+2 -4
View File
@@ -86,15 +86,13 @@ add_library(CryptoExtras
target_compile_options(CryptoExtras PRIVATE -DCRYPTO_IN_SWIFTPM)
target_include_directories(CryptoExtras PRIVATE
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CCryptoBoringSSLShims,INCLUDE_DIRECTORIES>)
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>)
target_link_libraries(CryptoExtras PUBLIC
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
Crypto
CryptoBoringWrapper
CCryptoBoringSSL
CCryptoBoringSSLShims)
CCryptoBoringSSL)
target_compile_options(CryptoExtras PRIVATE ${SWIFT_CRYPTO_COMPILE_OPTIONS})
@@ -17,10 +17,8 @@ import CryptoBoringWrapper
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
@@ -72,22 +70,15 @@ enum OpenSSLChaCha20CTRImpl {
key.withUnsafeBytes { keyPtr in
nonce.withUnsafeBytes { noncePtr in
message.withUnsafeBytes { plaintextPtr in
// We bind all three pointers here. These binds are not technically safe, but because we
// know the pointers don't persist they can't violate the aliasing rules. We really
// want a "with memory rebound" function but we don't have it yet.
let keyBytes = keyPtr.bindMemory(to: UInt8.self)
let nonceBytes = noncePtr.bindMemory(to: UInt8.self)
let plaintext = plaintextPtr.bindMemory(to: UInt8.self)
var ciphertext = Data(repeating: 0, count: plaintext.count)
var ciphertext = Data(repeating: 0, count: plaintextPtr.count)
ciphertext.withUnsafeMutableBytes { ciphertext in
CCryptoBoringSSL_CRYPTO_chacha_20(
ciphertext.baseAddress,
plaintext.baseAddress,
plaintext.count,
keyBytes.baseAddress,
nonceBytes.baseAddress,
plaintextPtr.baseAddress,
plaintextPtr.count,
keyPtr.baseAddress,
noncePtr.baseAddress,
counter
)
}
@@ -14,10 +14,8 @@
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
import Crypto
import CryptoBoringWrapper
@@ -12,9 +12,10 @@
//
//===----------------------------------------------------------------------===//
@_implementationOnly import CCryptoBoringSSL
import Crypto
@_implementationOnly import CCryptoBoringSSL
struct BoringSSLSHA512256HashFunction {
static var digestSize: Int {
Int(SHA256_DIGEST_LENGTH)
@@ -22,10 +22,8 @@ import Foundation
#if !canImport(CommonCrypto)
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
@@ -16,10 +16,8 @@ import Crypto
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
+9 -11
View File
@@ -18,10 +18,8 @@ import CryptoBoringWrapper
// NOTE: This file is unconditionally compiled because RSABSSA is implemented using BoringSSL on all platforms.
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
@@ -376,7 +374,7 @@ extension BoringSSLRSAPublicKey {
let rc: CInt = digest.withUnsafeBytes { digestPtr in
switch padding.backing {
case .pkcs1v1_5:
return CCryptoBoringSSLShims_RSA_verify(
return CCryptoBoringSSL_RSA_verify(
hashDigestType.nid,
digestPtr.baseAddress,
digestPtr.count,
@@ -385,7 +383,7 @@ extension BoringSSLRSAPublicKey {
rsaPublicKey
)
case .pss:
return CCryptoBoringSSLShims_RSA_verify_pss_mgf1(
return CCryptoBoringSSL_RSA_verify_pss_mgf1(
rsaPublicKey,
digestPtr.baseAddress,
digestPtr.count,
@@ -396,7 +394,7 @@ extension BoringSSLRSAPublicKey {
signaturePtr.count
)
case .pssZero:
return CCryptoBoringSSLShims_RSA_verify_pss_mgf1(
return CCryptoBoringSSL_RSA_verify_pss_mgf1(
rsaPublicKey,
digestPtr.baseAddress,
digestPtr.count,
@@ -448,7 +446,7 @@ extension BoringSSLRSAPublicKey {
}
var writtenLength = bufferPtr.count
let rc = CCryptoBoringSSLShims_EVP_PKEY_encrypt(
let rc = CCryptoBoringSSL_EVP_PKEY_encrypt(
ctx,
bufferPtr.baseAddress,
&writtenLength,
@@ -863,10 +861,10 @@ extension BoringSSLRSAPrivateKey {
switch padding.backing {
case .pkcs1v1_5:
var writtenLength = CUnsignedInt(0)
let rc = CCryptoBoringSSLShims_RSA_sign(
let rc = CCryptoBoringSSL_RSA_sign(
hashDigestType.nid,
digestPtr.baseAddress,
CUnsignedInt(digestPtr.count),
digestPtr.count,
bufferPtr.baseAddress,
&writtenLength,
rsaPrivateKey
@@ -874,7 +872,7 @@ extension BoringSSLRSAPrivateKey {
outputLength = Int(writtenLength)
return rc
case .pss:
return CCryptoBoringSSLShims_RSA_sign_pss_mgf1(
return CCryptoBoringSSL_RSA_sign_pss_mgf1(
rsaPrivateKey,
&outputLength,
bufferPtr.baseAddress,
@@ -886,7 +884,7 @@ extension BoringSSLRSAPrivateKey {
CInt(hashDigestType.digestLength)
)
case .pssZero:
return CCryptoBoringSSLShims_RSA_sign_pss_mgf1(
return CCryptoBoringSSL_RSA_sign_pss_mgf1(
rsaPrivateKey,
&outputLength,
bufferPtr.baseAddress,
@@ -943,7 +941,7 @@ extension BoringSSLRSAPrivateKey {
var writtenLength = bufferPtr.count
let rc = CCryptoBoringSSLShims_EVP_PKEY_decrypt(
let rc = CCryptoBoringSSL_EVP_PKEY_decrypt(
ctx,
bufferPtr.baseAddress,
&writtenLength,
@@ -15,10 +15,8 @@
// NOTE: This file is unconditionally compiled because RSABSSA is implemented using BoringSSL on all platforms.
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
@@ -29,7 +29,7 @@ final class ThreadSpecificVariable<Value: AnyObject> {
// the actual type in there is `Box<(ThreadSpecificVariable<T>, T)>` but we can't use that as C functions can't capture (even types)
private typealias BoxedType = Box<(AnyObject, AnyObject)>
private class Key {
private final class Key {
private var underlyingKey: ThreadOpsSystem.ThreadSpecificKey
internal init(destructor: @escaping ThreadOpsSystem.ThreadSpecificKeyDestructor) {
+6 -6
View File
@@ -24,7 +24,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 32)
let result = input.withUnsafeBytes { inputBytes in
SHA3_256(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
SHA3_256(&output, inputBytes.baseAddress, inputBytes.count)
}
// Should return 0 on success
@@ -43,7 +43,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 28)
let result = input.withUnsafeBytes { inputBytes in
SHA3_224(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
SHA3_224(&output, inputBytes.baseAddress, inputBytes.count)
}
// Should return 0 on success
@@ -62,7 +62,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 48)
let result = input.withUnsafeBytes { inputBytes in
SHA3_384(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
SHA3_384(&output, inputBytes.baseAddress, inputBytes.count)
}
// Should return 0 on success
@@ -82,7 +82,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 64)
let result = input.withUnsafeBytes { inputBytes in
SHA3_512(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
SHA3_512(&output, inputBytes.baseAddress, inputBytes.count)
}
// Should return 0 on success
@@ -102,7 +102,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 32) // 256 bits output
let result = input.withUnsafeBytes { inputBytes in
SHAKE128(&output, output.count, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
SHAKE128(&output, output.count, inputBytes.baseAddress, inputBytes.count)
}
// Should return 0 on success
@@ -121,7 +121,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 32) // 256 bits output
let result = input.withUnsafeBytes { inputBytes in
SHAKE256(&output, output.count, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
SHAKE256(&output, output.count, inputBytes.baseAddress, inputBytes.count)
}
// Should return 0 on success
+36 -14
View File
@@ -19,6 +19,34 @@ 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
@@ -31,7 +59,7 @@ final class MLKEMTests: XCTestCase {
try XCTAssert(privateKey.integrityCheckedRepresentation == MLKEM768.PrivateKey(integrityCheckedRepresentation: privateKey.integrityCheckedRepresentation).integrityCheckedRepresentation)
let er = try publicKey.encapsulate()
let ss = try privateKey.decapsulate(er.encapsulated)
let ss = try decapsulate(with: privateKey, er.encapsulated)
XCTAssert(er.sharedSecret == ss)
}
@@ -48,24 +76,18 @@ final class MLKEMTests: XCTestCase {
try XCTAssert(privateKey.integrityCheckedRepresentation == MLKEM1024.PrivateKey(integrityCheckedRepresentation: privateKey.integrityCheckedRepresentation).integrityCheckedRepresentation)
let er = try publicKey.encapsulate()
let ss = try privateKey.decapsulate(er.encapsulated)
let ss = try decapsulate(with: privateKey, er.encapsulated)
XCTAssert(er.sharedSecret == ss)
}
func testOneTimeKeys() throws {
let privateKey = try MLKEM1024.OneTimePrivateKey.generate()
let publicKey = privateKey.publicKey
// Test that the private key API function throws on an invalid seed
func testPrivateKeyInitThrowsOnInvalidSeedLength768() {
XCTAssertThrowsError(try MLKEM768.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 testPrivateKeyInitThrowsOnInvalidSeedLength1024() {
XCTAssertThrowsError(try MLKEM1024.PrivateKey(seedRepresentation: Data(count: 1), publicKey: nil))
}
func processKATFile(filename: String) throws -> [MLKEMKAT] {
+49 -16
View File
@@ -19,6 +19,22 @@ 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()
@@ -30,24 +46,10 @@ final class XWingTests: XCTestCase {
try XCTAssert(privateKey.integrityCheckedRepresentation == XWingMLKEM768X25519.PrivateKey(integrityCheckedRepresentation: privateKey.integrityCheckedRepresentation).integrityCheckedRepresentation)
let er = try privateKey.publicKey.encapsulate()
let ss = try privateKey.decapsulate(er.encapsulated)
let ss = try decapsulate(with: privateKey, 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
@@ -69,7 +71,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 privateKey.decapsulate(encapsulatedKey.encapsulated)
let retrievedSharedSecret = try decapsulate(with: privateKey, encapsulatedKey.encapsulated)
XCTAssertEqual(retrievedSharedSecret.dataRepresentation, katTest.ss)
}
}
@@ -91,6 +93,37 @@ final class XWingTests: XCTestCase {
let importedKey = try XWingMLKEM768X25519.PrivateKey.init(integrityCheckedRepresentation: exportedFormat)
XCTAssertEqual(importedKey.seedRepresentation, privateKey.seedRepresentation)
}
func testDecapsulateInputValidation() throws {
let ciphersuite = HPKE.Ciphersuite.XWingMLKEM768X25519_SHA256_AES_GCM_256
let skR = try XWingMLKEM768X25519.PrivateKey.generate()
// Dummy key with the correct size fails with an error from the underlying implementation.
let corretlySizedKey = Data(repeating: 0x00, count: 1120)
XCTAssertThrowsError(
try HPKE.Recipient(
privateKey: skR,
ciphersuite: ciphersuite,
info: Data(),
encapsulatedKey: corretlySizedKey
)
)
// Keys with the wrong size fail input validation.
let keySizesToTest = [0, 1, 1119, 1221, 2000]
for keySize in keySizesToTest {
let wronglySizedKey = Data(repeating: 0x00, count: keySize)
XCTAssertThrowsError(
try HPKE.Recipient(
privateKey: skR,
ciphersuite: ciphersuite,
info: Data(),
encapsulatedKey: wronglySizedKey
),
"Unexpectedly returned from malformed decapsulation path for keySize \(keySize)"
)
}
}
}
// Struct to parse KAT file