Compare commits

..
4 Commits
Author SHA1 Message Date
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
Si Beaumont 8ee9962f37 [5.x] Align with CryptoKit APIs from Xcode 27 beta 2 (#444)
## Motivation

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

As part of this release, we'd like to take the opportunity to streamline
Swift Crypto both for our adopters and the maintainers.

Historically Swift Crypto has had to release a new major version each
time there is a new CryptoKit release. This happens when non-frozen
CryptoKit enums are extended with new cases, which is a source-breaking
change in Swift Crypto, which is not built with library evolution mode.
This presents churn for adopters, even those who do not even switch over
these enums, who need to widen their dependency range. For example, when
Swift Crypto 4.0.0 was released, many adopters updated their version
constraint to `"1.0.0"..<"5.0.0"`. However, Swift now supports
extensible enums[^2] in all versions that Swift Crypto 5 will support.
This presents an opportunity for Swift Crypto to label such enums as
`@nonexhaustive`, which should mitigate the need for future major bumps
for this reason.

## Modifications

- Update shared API surface to align with CryptoKit
- Simplified conditional compilation exported-import of CryptoKit
- Drop support for developing the BoringSSL backend on macOS
- Remove `.gyb` files after synchronisation
- Removed many conditional compilation branches that will never be taken
- Apply `@nonexhaustive` to all public non-frozen enums
- Drop `@available` annotations in Crypto (now unused in all supported
compilation modes)

## Result

- Aligned with CryptoKit APIs in latest Xcode beta release.
- Hopefully Swift Crypto 5.0 will be the last SemVer major release for a
while.
- Development of BoringSSL backend must now be done on target platform,
e.g. Dev Container.

[^1]: https://developer.apple.com/download/all/?q=Xcode%2027
[^2]:
https://github.com/swiftlang/swift-evolution/blob/main/proposals/0487-extensible-enums.md
2026-06-23 15:21:37 +01:00
Si Beaumont 0a26a9e309 [5.x] Align with CryptoKit APIs from Xcode 27 beta 1 (#442)
## Motivation

Xcode 27 beta is now available[^1] with new CryptoKit API so we need to
provide the cross-platform API here.

## Modifications

- Update shared API surface to align with CryptoKit
- Provide backing implementations for non-Apple platforms
- Bump minimum Swift version to 6.2
- Adopt `Lifetimes` language feature
- Provide Dev Container config for maintainers working on Linux backend
- Update CI to 6.2, where required
- Update CMake build
- Remove duplicate tests

## Result

Adopters can try out new APIs via this cross-platform package.

[^1]: https://developer.apple.com/download/all/?q=Xcode%2027
2026-06-08 20:46:03 +01:00
83 changed files with 1214 additions and 1763 deletions

No files matched your search

+6 -10
View File
@@ -14,7 +14,6 @@ jobs:
with:
license_header_check_project_name: "SwiftCrypto"
docs_check_enabled: false
format_check_container_image: "swift:latest"
unit-tests:
name: Unit tests
@@ -22,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
@@ -48,16 +47,13 @@ jobs:
cmake-checks:
name: CMake checks
strategy:
fail-fast: false
matrix:
swift_version: ["6.2", "6.3", "6.4"]
uses: apple/swift-nio/.github/workflows/cmake_tests.yml@main
with:
update_cmake_lists_config: >-
{
"targets": [
{ "name": "CCryptoBoringSSL", "type": "source", "exceptions": [] },
{ "name": "CCryptoBoringSSLShims", "type": "source", "exceptions": [] },
{ "name": "CryptoBoringWrapper", "type": "source", "exceptions": [] },
{ "name": "CXKCP", "type": "source", "exceptions": [] },
{ "name": "CXKCPShims", "type": "source", "exceptions": [] },
@@ -66,7 +62,7 @@ jobs:
{ "name": "CCryptoBoringSSL", "type": "assembly", "exceptions": [ "*/AES/*.swift" ] }
]
}
image: "swift:${{ matrix.swift_version }}"
image: swift:6.2
macos-tests:
name: macOS tests
+1 -142
View File
@@ -21,7 +21,7 @@ import FoundationEssentials
import Foundation
#endif
let benchmarks: @Sendable () -> Void = {
let benchmarks = {
let defaultMetrics: [BenchmarkMetric] = [.mallocCountTotal, .cpuTotal]
Benchmark(
@@ -208,145 +208,4 @@ let benchmarks: @Sendable () -> Void = {
blackHole(try key1.sharedSecretFromKeyAgreement(with: key2.publicKey))
}
}
Benchmark(
"hmac-sha256-authenticate",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .mega,
maxDuration: .seconds(10_000_000),
maxIterations: 5
)
) { benchmark in
let key = SymmetricKey(size: .bits256)
let message = Data(repeating: 0x41, count: 1024)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(HMAC<SHA256>.authenticationCode(for: message, using: key))
}
}
Benchmark(
"hkdf-sha256-derive",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .kilo,
maxDuration: .seconds(10_000_000),
maxIterations: 10
)
) { benchmark in
let inputKeyMaterial = SymmetricKey(size: .bits256)
let salt = Data("benchmark salt".utf8)
let info = Data("benchmark info".utf8)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(
HKDF<SHA256>.deriveKey(
inputKeyMaterial: inputKeyMaterial,
salt: salt,
info: info,
outputByteCount: 1024
)
)
}
}
Benchmark(
"aes-keywrap-unwrap",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .mega,
maxDuration: .seconds(10_000_000),
maxIterations: 5
)
) { benchmark in
let kek = SymmetricKey(size: .bits256)
let wrapped = try AES.KeyWrap.wrap(SymmetricKey(size: .bits256), using: kek)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(try AES.KeyWrap.unwrap(wrapped, using: kek))
}
}
if #available(macOS 26.0, *) {
Benchmark(
"mlkem768-decapsulate",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .kilo,
maxDuration: .seconds(10_000_000),
maxIterations: 10
)
) { benchmark in
let privateKey = try MLKEM768.PrivateKey()
let encapsulated = try privateKey.publicKey.encapsulate().encapsulated
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(try privateKey.decapsulate(encapsulated))
}
}
}
Benchmark(
"pbkdf2-sha256-derive",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .kilo,
maxDuration: .seconds(10_000_000),
maxIterations: 10
)
) { benchmark in
let password = Data("benchmark password".utf8)
let salt = Data("benchmark salt".utf8)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(
try KDF.Insecure.PBKDF2.deriveKey(
from: password,
salt: salt,
using: .sha256,
outputByteCount: 32,
unsafeUncheckedRounds: 1_000
)
)
}
}
Benchmark(
"scrypt-derive",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .kilo,
maxDuration: .seconds(10_000_000),
maxIterations: 3
)
) { benchmark in
let password = Data("benchmark password".utf8)
let salt = Data("benchmark salt".utf8)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(
try KDF.Scrypt.deriveKey(
from: password,
salt: salt,
outputByteCount: 32,
rounds: 1 << 10,
blockSize: 8,
parallelism: 1
)
)
}
}
}
+8 -6
View File
@@ -12,7 +12,7 @@
##
##===----------------------------------------------------------------------===##
cmake_minimum_required(VERSION 3.16)
cmake_minimum_required(VERSION 3.15.1)
if(POLICY CMP0157)
cmake_policy(SET CMP0157 NEW)
@@ -25,8 +25,13 @@ list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules)
include(SwiftSupport)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
if(CMAKE_VERSION VERSION_LESS 3.16 AND CMAKE_SYSTEM_NAME STREQUAL Windows)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
else()
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
endif()
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift)
@@ -74,8 +79,5 @@ if(NOT SwiftASN1_FOUND)
FetchContent_MakeAvailable(ASN1)
endif()
# Set after vending swift-asn1 so its targets keep their own language mode.
set(CMAKE_Swift_LANGUAGE_VERSION 6)
add_subdirectory(Sources)
add_subdirectory(cmake/modules)
+3
View File
@@ -0,0 +1,3 @@
# Code of Conduct
The code of conduct for this project can be found at https://swift.org/code-of-conduct.
+10 -30
View File
@@ -5,18 +5,6 @@ your contribution to Apple and the community, and agree by submitting the patch
that your contributions are licensed under the Apache 2.0 license (see
`LICENSE.txt`).
## AI tools
Human discourse is an essential part of open source development. To encourage
productive collaboration between contributors and maintainers, please refrain
from using AI tools for the following:
- Issues: titles, bodies, and comments.
- Pull requests: titles, descriptions, and comments.
Contributors who feel more comfortable writing in another language may use
automated translation tools, but must include their original content in their
preferred language.
## How to submit a bug report
@@ -56,27 +44,19 @@ $ uname -a
Linux beefy.machine 4.4.0-101-generic #124-Ubuntu SMP Fri Nov 10 18:29:59 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
```
## Contributing a pull request
## Writing a Patch
> [!IMPORTANT]
> To ensure productive use of contributor and maintainer time and resources,
> contributors must first agree their proposed change with a maintainer in an
> issue. Pull requests opened without prior discussion may be closed without
> review.
A good swift-crypto patch is:
If there is no issue already tracking the problem or feature request, please
file a new one using your own voice (see "AI tools" usage above).
1. Concise, and contains as few changes as needed to achieve the end result.
2. Tested, ensuring that any tests provided failed before the patch and pass after it.
3. Documented, adding API documentation as needed to cover new functions and properties.
4. Accompanied by a great commit message, using our commit message template.
Once an issue is assigned to you, follow these steps:
- Prepare your change, keeping in mind that a good patch is:
- Concise, and contains as few changes as needed to achieve the end result.
- Tested, ensuring that any tests provided failed before the patch and pass
after it.
- Documented, adding API documentation as needed to cover new functions and
properties.
- Accompanied by a great commit message.
- Open a pull request and wait for code review by the maintainers.
## How to contribute your work
Please open a pull request at https://github.com/apple/swift-crypto. Make sure the CI passes, and then wait for code review.
### How to update CMakeLists files
@@ -89,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
+14 -2
View File
@@ -49,8 +49,9 @@ var swiftSettings: [SwiftSetting] = [
swiftSettings.append(.enableExperimentalFeature("CheckImplementationOnly"))
#endif
// A resource makes SwiftPM generate a `Bundle.module` accessor that imports Foundation, not just FoundationEssentials.
// `canImport(Darwin)` checks the host, not the target, so cross-compiling from Darwin still adds the resource.
// This doesn't work when cross-compiling: the privacy manifest will be included in the Bundle and
// Foundation will be linked. This is, however, strictly better than unconditionally adding the
// resource.
#if canImport(Darwin)
let privacyManifestExclude: [String] = []
let privacyManifestResource: [PackageDescription.Resource] = [.copy("PrivacyInfo.xcprivacy")]
@@ -125,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"],
@@ -137,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)),
@@ -154,6 +164,7 @@ let package = Package(
name: "CryptoExtras",
dependencies: [
"CCryptoBoringSSL",
"CCryptoBoringSSLShims",
"CryptoBoringWrapper",
"Crypto",
.product(name: "SwiftASN1", package: "swift-asn1"),
@@ -175,6 +186,7 @@ let package = Package(
name: "CryptoBoringWrapper",
dependencies: [
"CCryptoBoringSSL",
"CCryptoBoringSSLShims",
],
exclude: privacyManifestExclude + [
"CMakeLists.txt"
+6 -11
View File
@@ -31,11 +31,10 @@ When building Swift Crypto for use on an Apple platform where CryptoKit is alrea
When building Swift Crypto for use on other platforms, Swift Crypto builds substantially more code. In particular, we build:
1. A vendored copy of BoringSSL's libcrypto.
2. A vendored copy of XKCP's libXKCP.
3. The common API of Swift Crypto and CryptoKit.
4. The backing implementation of this common API, which calls into BoringSSL or XKCP.
2. The common API of Swift Crypto and CryptoKit.
3. The backing implementation of this common API, which calls into BoringSSL.
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The BoringSSL/XKCP backing implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIs predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL/XKCP implementation of the library in your application, no matter the platform.
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The backing BoringSSL-based implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIS predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL implementation of the library in your application, no matter the platform.
## Evolution
@@ -49,11 +48,11 @@ Note that Swift Crypto does not intend to support all possible cryptographic pri
### Code Organisation
Files in this repository are divided into two groups, based on whether they have a name that ends in `_boring`/`_xkcp` or are in a `BoringSSL`/`XKCP` directory, or if they are not.
Files in this repository are divided into two groups, based on whether they have a name that ends in `_boring` or are in a `BoringSSL` directory, or if they are not.
Files that meet the above criteria are specific to the Swift Crypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or `import CXKCP` or access a BoringSSL or XKCP API, it needs to be marked this way.
Files that meet the above criteria are specific to the Swift Crypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or access a BoringSSL API, it needs to be marked this way.
Files that do not have the `_boring` or `_xkcp` suffix are part of the public API of CryptoKit. Changing these requires passing a higher bar, as any change in these files must be accompanied by a change in CryptoKit itself.
Files that do not have the `_boring` suffix are part of the public API of CryptoKit. Changing these requires passing a higher bar, as any change in these files must be accompanied by a change in CryptoKit itself.
## Contributing
@@ -151,7 +150,3 @@ To do so, please use the following dependency in your `Package.swift`:
Swift Crypto normally defers to the OS implementation of CryptoKit on macOS. Naturally, this makes developing Swift Crypto on macOS tricky. To get Swift Crypto to build the open source implementation on macOS, in `Package.swift`, use a Linux container. A Dev Container config is provided in the repo to make this easier.
## Acknowledgements
This project contains source code from the BoringSSL and XKCP projects.
@@ -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)
+2 -2
View File
@@ -72,7 +72,7 @@ extension AES {
/// - nonce: The nonce the sealing process requires.
/// - authenticatedData: Additional data to be authenticated, if provided.
/// - tag: receives the 16-byte authentication tag
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(message: copy message)
#endif
public static func seal(
@@ -127,7 +127,7 @@ extension AES {
/// - authenticatedData: Additional data that was authenticated.
///
/// The call throws an error if decryption or authentication fail.
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(message: copy message)
#endif
public static func open(
@@ -59,7 +59,7 @@ enum OpenSSLAESGCMImpl {
return AES.GCM.SealedBox(combined: combined, nonceByteCount: nonce.count)
}
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(message: copy message)
#endif
@inlinable
@@ -119,7 +119,7 @@ enum OpenSSLAESGCMImpl {
}
/// Open a given message in place.
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(message: copy message)
#endif
@inlinable
@@ -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)
@@ -48,7 +50,7 @@ extension BoringSSLAEAD {
}
/// Seal a given message in place
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(message: copy message)
#endif
func seal(
@@ -93,7 +95,7 @@ extension BoringSSLAEAD {
}
/// Open a given message in place.
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(message: copy message)
#endif
public func open(
@@ -150,7 +152,7 @@ enum OpenSSLChaChaPolyImpl {
return ChaChaPoly.SealedBox(combined: combined, nonceByteCount: nonce.count)
}
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(message: copy message)
#endif
static func encrypt(
@@ -211,7 +213,7 @@ enum OpenSSLChaChaPolyImpl {
}
}
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(message: copy message)
#endif
static func decrypt(
@@ -70,7 +70,7 @@ public enum ChaChaPoly: Cipher, Sendable {
/// - nonce: The nonce the sealing process requires.
/// - authenticatedData: Additional data to be authenticated.
/// - tag: Will be updated with the 16-byte authentication tag.
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(message: copy message)
#endif
public static func seal(
@@ -124,7 +124,7 @@ public enum ChaChaPoly: Cipher, Sendable {
/// - authenticatedData: Additional data that was authenticated.
///
/// The call throws an error if decryption or authentication fail.
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(message: copy message)
#endif
public static func open(
+2 -1
View File
@@ -98,7 +98,6 @@ add_library(Crypto
"Signatures/MLDSA.swift"
"Signatures/Signature.swift"
"Util/ArraySpanHelpers.swift"
"Util/Backports.swift"
"Util/BoringSSL/CryptoKitErrors_boring.swift"
"Util/BoringSSL/InlineArray+withBytes_boring.swift"
"Util/BoringSSL/Optional+withUnsafeBytes_boring.swift"
@@ -118,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>)
@@ -125,6 +125,7 @@ target_link_libraries(Crypto PUBLIC
$<$<NOT:$<PLATFORM_ID:Darwin>>:dispatch>
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
CCryptoBoringSSL
CCryptoBoringSSLShims
CryptoBoringWrapper
CXKCP
CXKCPShims)
+25 -20
View File
@@ -33,6 +33,7 @@ import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension MLKEM768 {
/// A ML-KEM-768 private key.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
struct InternalPrivateKey: @unchecked Sendable, KEMPrivateKey {
private var backing: Backing
@@ -149,14 +150,14 @@ extension MLKEM768 {
throw CryptoKitError.incorrectParameterSize
}
return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) {
symmetricKeyDataPtr,
count in
var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount)
let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in
let bytes: ContiguousBytes =
encapsulated.regions.count == 1
? encapsulated.regions.first!
: Array(encapsulated)
let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in
return bytes.withUnsafeBytes { encapsulatedPtr in
CCryptoBoringSSL_MLKEM768_decap(
symmetricKeyDataPtr.baseAddress,
encapsulatedPtr.baseAddress,
@@ -164,13 +165,13 @@ extension MLKEM768 {
&self.key
)
}
guard rc == 1 else {
throw CryptoKitError.internalBoringSSLError()
}
count = MLKEM.sharedSecretByteCount
}
guard rc == 1 else {
throw CryptoKitError.internalBoringSSLError()
}
return SymmetricKey(data: symmetricKeyData)
}
}
}
@@ -179,6 +180,7 @@ extension MLKEM768 {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension MLKEM768 {
/// A ML-KEM-768 public key.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
struct InternalPublicKey: @unchecked Sendable, KEMPublicKey {
private var backing: Backing
@@ -300,6 +302,7 @@ extension MLKEM768 {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension MLKEM1024 {
/// A ML-KEM-1024 private key.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
struct InternalPrivateKey: @unchecked Sendable, KEMPrivateKey {
private var backing: Backing
@@ -416,14 +419,14 @@ extension MLKEM1024 {
throw CryptoKitError.incorrectParameterSize
}
return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) {
symmetricKeyDataPtr,
count in
var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount)
let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in
let bytes: ContiguousBytes =
encapsulated.regions.count == 1
? encapsulated.regions.first!
: Array(encapsulated)
let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in
return bytes.withUnsafeBytes { encapsulatedPtr in
CCryptoBoringSSL_MLKEM1024_decap(
symmetricKeyDataPtr.baseAddress,
encapsulatedPtr.baseAddress,
@@ -431,13 +434,13 @@ extension MLKEM1024 {
&self.key
)
}
guard rc == 1 else {
throw CryptoKitError.internalBoringSSLError()
}
count = MLKEM.sharedSecretByteCount
}
guard rc == 1 else {
throw CryptoKitError.internalBoringSSLError()
}
return SymmetricKey(data: symmetricKeyData)
}
}
}
@@ -446,6 +449,7 @@ extension MLKEM1024 {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension MLKEM1024 {
/// A ML-KEM-1024 public key.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
struct InternalPublicKey: @unchecked Sendable, KEMPublicKey {
private var backing: Backing
@@ -564,6 +568,7 @@ extension MLKEM1024 {
private static let ciphertextByteCount = Int(MLKEM1024_CIPHERTEXT_BYTES)
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
enum MLKEM {
/// The size of the seed in bytes.
static let seedByteCount = 64
@@ -153,14 +153,14 @@ extension MLKEM${parameter_set} {
throw CryptoKitError.incorrectParameterSize
}
return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) {
symmetricKeyDataPtr,
count in
var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount)
let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in
let bytes: ContiguousBytes =
encapsulated.regions.count == 1
? encapsulated.regions.first!
: Array(encapsulated)
let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in
return bytes.withUnsafeBytes { encapsulatedPtr in
CCryptoBoringSSL_MLKEM${parameter_set}_decap(
symmetricKeyDataPtr.baseAddress,
encapsulatedPtr.baseAddress,
@@ -168,13 +168,13 @@ extension MLKEM${parameter_set} {
&self.key
)
}
guard rc == 1 else {
throw CryptoKitError.internalBoringSSLError()
}
count = MLKEM.sharedSecretByteCount
}
guard rc == 1 else {
throw CryptoKitError.internalBoringSSLError()
}
return SymmetricKey(data: symmetricKeyData)
}
}
}
-36
View File
@@ -189,9 +189,6 @@ extension P256 {
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
guard parsed.algorithm == .ecdsaP256 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
@@ -212,9 +209,6 @@ extension P256 {
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
guard key.algorithm == .ecdsaP256 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
@@ -419,9 +413,6 @@ extension P256 {
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
guard parsed.algorithm == .ecdsaP256 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
@@ -442,9 +433,6 @@ extension P256 {
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
guard key.algorithm == .ecdsaP256 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
@@ -648,9 +636,6 @@ extension P384 {
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
guard parsed.algorithm == .ecdsaP384 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
@@ -671,9 +656,6 @@ extension P384 {
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
guard key.algorithm == .ecdsaP384 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
@@ -878,9 +860,6 @@ extension P384 {
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
guard parsed.algorithm == .ecdsaP384 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
@@ -901,9 +880,6 @@ extension P384 {
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
guard key.algorithm == .ecdsaP384 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
@@ -1107,9 +1083,6 @@ extension P521 {
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
guard parsed.algorithm == .ecdsaP521 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
@@ -1130,9 +1103,6 @@ extension P521 {
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
guard key.algorithm == .ecdsaP521 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
@@ -1337,9 +1307,6 @@ extension P521 {
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
guard parsed.algorithm == .ecdsaP521 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
@@ -1360,9 +1327,6 @@ extension P521 {
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
guard key.algorithm == .ecdsaP521 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
+2 -2
View File
@@ -48,7 +48,7 @@ public struct HKDF<H: HashFunction>: Sendable {
/// - info: The shared information to use for key derivation.
/// - outputKey: An output span that will be populated with the derived
/// symmetric key.
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(outputKey: copy outputKey)
#endif
public static func deriveKey(inputKeyMaterial: SymmetricKey,
@@ -258,7 +258,7 @@ public struct HKDF<H: HashFunction>: Sendable {
/// - outputByteCount: The length in bytes of the resulting symmetric key.
///
/// - Returns: The derived symmetric key.
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(output: copy output)
#endif
public static func expand(pseudoRandomKey prk: RawSpan, info: RawSpan?, into output: inout OutputRawSpan) {
@@ -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,
@@ -72,8 +76,10 @@ enum BoringSSLAESWRAPImpl {
key: SymmetricKey,
contiguousWrappedKey: WrappedKey
) throws -> SymmetricKey {
try contiguousWrappedKey.withUnsafeBytes { inPtr in
try SymmetricKey(unsafeUninitializedCapacity: inPtr.count) { outputPtr, count in
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,
@@ -93,6 +99,8 @@ enum BoringSSLAESWRAPImpl {
count = Int(rc)
}
}
return SymmetricKey(data: unwrapped)
}
}
@@ -109,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,
@@ -684,7 +686,7 @@ func readRawPublicNumbers(
/// In a number of places we need to know if an EC key is compact representable. This function implements that check.
///
/// The check is defined in https://tools.ietf.org/id/draft-jivsov-ecc-compact-05.html#rfc.section.4.2.1. Specifically, a
/// point is compact representable if its y coordinate is the smaller of min(y, p-y) where p is the prime of the base field.
/// point is compact representable if its y coordinate is the smaller of min(y, p-y) where p is the order of the prime field.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
func _isCompactRepresentable(
@@ -699,7 +701,7 @@ func _isCompactRepresentable(
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
let context = try! FiniteFieldArithmeticContext(fieldSize: p)
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
let newY = try! context.subtract(y, from: p)
let newY = try! context.subtract(y, from: group.order)
// The point is compact representable if y is less than or equal to newY.
return y <= newY
@@ -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
)
@@ -121,10 +123,10 @@ extension Curve25519.KeyAgreement {
) throws
-> SharedSecret
{
let sharedSecret = try SecureBytes(
let sharedSecret = SecureBytes(
unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes
) { secretPointer, secretSize in
try self.key.withUnsafeBytes { privateKeyPointer in
self.key.withUnsafeBytes { privateKeyPointer in
// We precondition on all of these sizes because bounds checking is cool.
// These are fatal instead of guards because we allocated the secret (so it must be right),
// we either allocated the private key or validated it on construction (so it must be right),
@@ -133,17 +135,16 @@ extension Curve25519.KeyAgreement {
precondition(privateKeyPointer.count == Curve25519.KeyAgreement.keySizeBytes)
precondition(publicKeyShare.keyBytes.count == Curve25519.KeyAgreement.keySizeBytes)
// BoringSSL returns 0 when the peer's public key has low order, which makes the shared secret
// the weak all-zero value. CryptoKit rejects that key agreement, so we do too.
guard
CCryptoBoringSSL_X25519(
secretPointer.baseAddress,
privateKeyPointer.baseAddress,
publicKeyShare.keyBytes
) == 1
else {
throw CryptoKitError.internalBoringSSLError()
}
// We don't check the return code here. This return code only validates that the generated secret is not the weak all-zero
// secret (it is not possible for BoringSSL's X25519 implementation to fail, which is nice). There is currently what I would
// politely describe as a "lack of consensus" as to whether crypto libraries should reject this secret. CryptoKit on Apple
// platforms currently does not, so for the sake of conformance with our peer implementation I will also refuse to check it.
// We may elect to revisit this decision if the security best-practice thinking changes.
CCryptoBoringSSLShims_X25519(
secretPointer.baseAddress,
privateKeyPointer.baseAddress,
publicKeyShare.keyBytes
)
}
secretSize = Curve25519.KeyAgreement.keySizeBytes // We always use all of it.
@@ -65,24 +65,34 @@ public struct HMAC<H: HashFunction>: MACAlgorithm, Sendable {
#if os(iOS) && (arch(arm) || arch(i386))
fatalError("Unsupported architecture")
#else
// HMAC(K, m) = H((K0 ^ opad) || H((K0 ^ ipad) || m)), where K0 is the
// key normalized to the hash block size (RFC 2104).
self.innerHasher = H()
self.outerHasher = H()
withTemporaryZeroingAllocation(byteCount: H.blockByteCount, alignment: 1) { keyBlock in
if key.byteCount <= keyBlock.freeCapacity {
keyBlock.append(contentsOf: key.bytes)
var innerKey = SecureBytes(capacity: H.blockByteCount) { keyOutput in
if key.byteCount <= keyOutput.freeCapacity {
keyOutput.append(contentsOf: key.bytes)
} else if key.byteCount > H.blockByteCount {
H.hash(bytes: key.bytes).withBytes { keyBlock.append(contentsOf: $0) }
let hash = H.hash(bytes: key.bytes)
hash.withUnsafeBytes {
keyOutput.append(contentsOf: $0.bytes)
}
}
keyBlock.append(repeating: 0, count: keyBlock.freeCapacity, as: UInt8.self)
var k0 = keyBlock.mutableBytes
for i in 0 ..< k0.byteCount { k0[i] ^= 0x36 } // apply ipad
self.innerHasher.update(bytes: k0.bytes)
for i in 0 ..< k0.byteCount { k0[i] ^= 0x36 ^ 0x5c } // undo ipad, apply opad
self.outerHasher.update(bytes: k0.bytes)
keyOutput.append(repeating: 0, count: keyOutput.freeCapacity, as: UInt8.self)
}
var outerKey = innerKey
self.innerHasher = H()
innerKey.withUnsafeMutableBytes {
for i in 0 ..< $0.count {
$0[i] ^= 0x36
}
}
innerHasher.update(bytes: innerKey.bytes)
self.outerHasher = H()
outerKey.withUnsafeMutableBytes {
for i in 0 ..< $0.count {
$0[i] ^= 0x5c
}
}
outerHasher.update(data: outerKey)
#endif
}
@@ -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
+2 -2
View File
@@ -57,7 +57,7 @@ extension ContiguousArray where Element == UInt8 {
extension OutputRawSpan {
/// Append the contents of the given raw span to this output span.
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(self: copy self)
#endif
mutating func append(contentsOf bytes: RawSpan) {
@@ -69,7 +69,7 @@ extension OutputRawSpan {
extension OutputSpan<UInt8> {
/// Append the contents of the given raw span to this output span.
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(self: copy self)
#endif
mutating func append(contentsOf bytes: RawSpan) {
-37
View File
@@ -1,37 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#if compiler(<6.4)
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1.0, *)
extension ContiguousBytes {
func withBytes<R>(_ body: (RawSpan) throws -> R) rethrows -> R {
try withUnsafeBytes { try body(RawSpan(_unsafeBytes: $0)) }
}
}
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1.0, *)
extension MutableRawSpan {
subscript(_ byteOffset: Int) -> UInt8 {
get { unsafeLoad(fromByteOffset: byteOffset, as: UInt8.self) }
@_lifetime(self: copy self)
set { storeBytes(of: newValue, toByteOffset: byteOffset, as: UInt8.self) }
}
}
#endif
@@ -45,7 +45,7 @@ extension UnsafeMutableRawBufferPointer {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension MutableRawSpan {
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(self: copy self)
#endif
mutating func initializeWithRandomBytes(count: Int) {
@@ -55,7 +55,7 @@ extension MutableRawSpan {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension OutputRawSpan {
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(self: copy self)
#endif
mutating func appendingRandomBytes(count: Int) {
+1 -23
View File
@@ -28,7 +28,7 @@ protocol Zeroization {
extension UnsafeMutablePointer: Zeroization {
/// Zeroizes the pointee
func zeroize() {
let size = MemoryLayout<Pointee>.size
let size = MemoryLayout.size(ofValue: Pointee.self)
memset_s(self, size, 0, size)
}
}
@@ -54,26 +54,4 @@ extension Data: Zeroization {
}
}
func withUnsafeTemporaryZeroingAllocation<R>(
byteCount: Int,
alignment: Int,
_ body: (UnsafeMutableRawBufferPointer) throws -> R
) rethrows -> R {
try withUnsafeTemporaryAllocation(byteCount: byteCount, alignment: alignment) { buffer in
defer { buffer.zeroize() }
return try body(buffer)
}
}
func withTemporaryZeroingAllocation<R>(
byteCount: Int,
alignment: Int,
_ body: (inout OutputRawSpan) throws -> R
) rethrows -> R {
try withUnsafeTemporaryZeroingAllocation(byteCount: byteCount, alignment: alignment) { buffer in
var output = OutputRawSpan(buffer: buffer, initializedCount: 0)
return try body(&output)
}
}
#endif // canImport(CryptoKit)
@@ -14,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,
@@ -153,7 +155,7 @@ extension BoringSSLAEAD.AEADContext {
/// Lowest level seal operation that calls into BoringSSL directly and
/// operates on already-allocated memory.
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(tag: copy tag)
#endif
public func seal(
@@ -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,
@@ -303,7 +305,7 @@ extension BoringSSLAEAD.AEADContext {
}
/// Lowest level call into BoringSSL that decrypts in place.
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(message: copy message)
#endif
public func open(
@@ -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)
@@ -77,6 +79,10 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.multiply(by: rhs, on: group, context: context)
}
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package consuming func multiplying(
by rhs: ArbitraryPrecisionInteger,
@@ -86,6 +92,18 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.multiply(by: rhs, on: group, context: context)
return self
}
#else
@usableFromInline
package func multiplying(
by rhs: ArbitraryPrecisionInteger,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var `self` = self
try self.multiply(by: rhs, on: group, context: context)
return self
}
#endif
@usableFromInline
package static func multiplying(
@@ -118,6 +136,10 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.add(rhs, on: group, context: context)
}
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package consuming func adding(
_ rhs: consuming EllipticCurvePoint,
@@ -127,7 +149,23 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.add(rhs, on: group, context: context)
return self
}
#else
@usableFromInline
package func adding(
_ rhs: consuming EllipticCurvePoint,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var `self` = self
try self.add(rhs, on: group, context: context)
return self
}
#endif
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package static func adding(
_ lhs: consuming EllipticCurvePoint,
@@ -138,6 +176,19 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try lhs.add(rhs, on: group, context: context)
return lhs
}
#else
@usableFromInline
package static func adding(
_ lhs: EllipticCurvePoint,
_ rhs: EllipticCurvePoint,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var lhs = lhs
try lhs.add(rhs, on: group, context: context)
return lhs
}
#endif
@usableFromInline
package mutating func invert(
@@ -158,6 +209,10 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.invert(on: group, context: context)
}
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package consuming func inverting(
on group: BoringSSLEllipticCurveGroup,
@@ -166,7 +221,22 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.invert(on: group, context: context)
return self
}
#else
@usableFromInline
package func inverting(
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var `self` = self
try self.invert(on: group, context: context)
return self
}
#endif
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package static func inverting(
_ point: consuming EllipticCurvePoint,
@@ -176,6 +246,18 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try point.invert(on: group, context: context)
return point
}
#else
@usableFromInline
package static func inverting(
_ point: EllipticCurvePoint,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var point = point
try point.invert(on: group, context: context)
return point
}
#endif
@usableFromInline
package mutating func subtract(
@@ -198,6 +280,10 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.subtract(rhs, on: group, context: context)
}
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package consuming func subtracting(
_ rhs: consuming EllipticCurvePoint,
@@ -207,7 +293,23 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.subtract(rhs, on: group, context: context)
return self
}
#else
@usableFromInline
package func subtracting(
_ rhs: EllipticCurvePoint,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var `self` = self
try self.subtract(rhs, on: group, context: context)
return self
}
#endif
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package static func subtracting(
_ rhs: consuming EllipticCurvePoint,
@@ -218,6 +320,19 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try lhs.subtract(rhs, on: group, context: context)
return lhs
}
#else
@usableFromInline
package static func subtracting(
_ rhs: EllipticCurvePoint,
from lhs: EllipticCurvePoint,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var lhs = lhs
try lhs.subtract(rhs, on: group, context: context)
return lhs
}
#endif
@usableFromInline
package init<MessageBytes: ContiguousBytes, DSTBytes: ContiguousBytes>(
@@ -379,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() }
}
}
}
@@ -494,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
@@ -47,7 +47,7 @@ extension UnsafeMutableRawBufferPointer {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension OutputRawSpan {
#if compiler(<6.3)
#if swift(<6.3)
@_lifetime(self: copy self)
#endif
package mutating func appendingRandomBytes(count: Int) {
+94 -8
View File
@@ -25,6 +25,19 @@ extension AES {
/// suite.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
public enum _CBC {
private static var blockSize: Int { 16 }
private static func encryptBlockInPlace(
_ plaintext: inout Block,
priorCiphertextBlock: Block,
using key: SymmetricKey
) throws {
assert([128, 192, 256].contains(key.bitCount))
plaintext ^= priorCiphertextBlock
try AES.permute(&plaintext, key: key)
}
/// Encrypts data using AES-CBC.
///
/// - Parameters:
@@ -47,7 +60,44 @@ extension AES {
///
/// - Note: If `noPadding` is set to `true`, `plainText` has to be a multiple of the blockSize (16 bytes). Otherwise an error will be thrown.
public static func encrypt<Plaintext: DataProtocol>(_ plaintext: Plaintext, using key: SymmetricKey, iv: AES._CBC.IV, noPadding: Bool) throws -> Data {
try OpenSSLAESCBCImpl.encrypt(plaintext, using: key, iv: iv, noPadding: noPadding)
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
let requiresFullPaddingBlock = (plaintext.count % AES._CBC.blockSize) == 0
if noPadding && !requiresFullPaddingBlock {
throw CryptoKitError.incorrectParameterSize
}
var ciphertext = Data()
ciphertext.reserveCapacity(plaintext.count + Self.blockSize) // Room for padding.
var previousBlock = Block(iv)
var plaintext = plaintext[...]
while plaintext.count > 0 {
var block = Block(blockBytes: plaintext.prefix(Self.blockSize))
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
ciphertext.append(contentsOf: block)
previousBlock = block
plaintext = plaintext.dropFirst(Self.blockSize)
}
if requiresFullPaddingBlock && !noPadding {
var block = Block.paddingBlock
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
ciphertext.append(contentsOf: block)
}
return ciphertext
}
private static func decryptBlockInPlace(_ ciphertext: inout Block, priorCiphertextBlock: Block, using key: SymmetricKey) throws {
assert([128, 192, 256].contains(key.bitCount))
try AES.inversePermute(&ciphertext, key: key)
ciphertext ^= priorCiphertextBlock
}
/// Decrypts data using AES-CBC.
@@ -70,7 +120,29 @@ extension AES {
/// - noPadding: If this is set to `true`, padding won't be removed.
/// - Returns: The decrypted message.
public static func decrypt<Ciphertext: DataProtocol>(_ ciphertext: Ciphertext, using key: SymmetricKey, iv: AES._CBC.IV, noPadding: Bool) throws -> Data {
try OpenSSLAESCBCImpl.decrypt(ciphertext, using: key, iv: iv, noPadding: noPadding)
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
var plaintext = Data()
plaintext.reserveCapacity(ciphertext.count)
var previousBlock = Block(iv)
var ciphertext = ciphertext[...]
while ciphertext.count > 0 {
let ctBlock = Block(blockBytes: ciphertext.prefix(Self.blockSize))
var block = ctBlock
try Self.decryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
plaintext.append(contentsOf: block)
previousBlock = ctBlock
ciphertext = ciphertext.dropFirst(Self.blockSize)
}
if !noPadding {
try plaintext.trimPadding()
}
return plaintext
}
}
}
@@ -122,7 +194,7 @@ extension AES._CBC {
0, 0, 0, 0, 0, 0, 0, 0
)
Swift.withUnsafeMutableBytes(of: &self.ivBytes) { bytesPtr in
withUnsafeMutableBytes(of: &self.ivBytes) { bytesPtr in
bytesPtr.copyBytes(from: ivBytes)
}
}
@@ -133,10 +205,24 @@ extension AES._CBC {
Array(unsafeRawBufferPointer).makeIterator()
}
}
mutating func withUnsafeMutableBytes<ReturnType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
return try Swift.withUnsafeMutableBytes(of: &self.ivBytes, body)
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension Data {
fileprivate mutating func trimPadding() throws {
guard let paddingBytes = self.last else {
// Degenerate case, empty string. This is forbidden:
// we must always pad.
throw CryptoKitError.incorrectParameterSize
}
guard paddingBytes > 0 &&
self.count >= paddingBytes &&
self.suffix(Int(paddingBytes)).allSatisfy({ $0 == paddingBytes }) else {
throw CryptoKitError.incorrectParameterSize
}
self = self.dropLast(Int(paddingBytes))
}
}
@@ -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)
@@ -66,6 +68,7 @@ extension AES.GCM {
/// - Parameters:
/// - sealedBox: The sealed box to authenticate and decrypt
/// - key: An encryption key of 128 or 256 bits
/// - nonce: An Nonce for AES-GCM-SIV encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with AES.GCM.Nonce().
/// - authenticatedData: Data that was authenticated as part of the seal
/// - Returns: The ciphertext if opening was successful
/// - Throws: CipherError errors. If the authentication of the sealed box failed, incorrectTag is thrown.
@@ -79,6 +82,7 @@ extension AES.GCM {
/// - Parameters:
/// - sealedBox: The sealed box to authenticate and decrypt
/// - key: An encryption key of 128 or 256 bits
/// - nonce: An Nonce for AES-GCM-SIV encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with AES.GCM.Nonce().
/// - Returns: The ciphertext if opening was successful
/// - Throws: CipherError errors. If the authentication of the sealed box failed, incorrectTag is thrown.
public static func open(_ sealedBox: SealedBox, using key: SymmetricKey) throws -> Data {
+124 -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,24 +99,32 @@ 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)
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
struct Block {
private static var blockSize: Int { 16 }
typealias BlockBytes = (
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8
@@ -130,9 +140,70 @@ extension AES {
)
}
init(_ blockBytes: BlockBytes) {
self.blockBytes = blockBytes
}
init(_ iv: AES._CBC.IV) {
self.blockBytes = iv.ivBytes
}
init<BlockBytes: Collection>(blockBytes: BlockBytes) where BlockBytes.Element == UInt8 {
// The block size is always 16. Pad out past there.
precondition(blockBytes.count <= Self.blockSize)
self.blockBytes = (
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
)
Swift.withUnsafeMutableBytes(of: &self.blockBytes) { bytesPtr in
bytesPtr.copyBytes(from: blockBytes)
// Early exit here.
if blockBytes.count == Self.blockSize {
return
}
var remainingBytes = bytesPtr.dropFirst(blockBytes.count)
let padByte = UInt8(remainingBytes.count)
for index in remainingBytes.indices {
remainingBytes[index] = padByte
}
}
}
static var paddingBlock: Block {
// The padding block is a full block of value blocksize.
let value = UInt8(truncatingIfNeeded: Self.blockSize)
return Block((
value, value, value, value, value, value, value, value,
value, value, value, value, value, value, value, value
))
}
func withUnsafeBytes<ReturnType>(_ body: (UnsafeRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
return try Swift.withUnsafeBytes(of: self.blockBytes, body)
}
mutating func withUnsafeMutableBytes<ReturnType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
return try Swift.withUnsafeMutableBytes(of: &self.blockBytes, body)
}
static func ^= (lhs: inout Block, rhs: Block) {
// Ideally we'd not use raw pointers for this.
lhs.withUnsafeMutableBytes { lhsPtr in
rhs.withUnsafeBytes { rhsPtr in
assert(lhsPtr.count == Self.blockSize)
assert(rhsPtr.count == Self.blockSize)
for index in 0..<Self.blockSize {
lhsPtr[index] ^= rhsPtr[index]
}
}
}
}
}
private static func isValidKey(_ key: SymmetricKey) -> Bool {
@@ -144,3 +215,52 @@ extension AES {
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension AES.Block: RandomAccessCollection, MutableCollection {
var startIndex: Int {
0
}
var endIndex: Int {
Self.blockSize
}
subscript(position: Int) -> UInt8 {
get {
precondition(position >= 0)
precondition(position < Self.blockSize)
return self.withUnsafeBytes { $0[position] }
}
set {
precondition(position >= 0)
precondition(position < Self.blockSize)
self.withUnsafeMutableBytes { $0[position] = newValue }
}
}
func withContiguousStorageIfAvailable<ReturnValue>(
_ body: (UnsafeBufferPointer<UInt8>) throws -> ReturnValue)
rethrows -> ReturnValue? {
return try withUnsafePointer(to: self.blockBytes) { tuplePtr in
// Homogeneous tuples are always bound to the element type as well as to their own type.
let retyped = UnsafeRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
let bufferised = UnsafeBufferPointer(start: retyped, count: Self.blockSize)
return try body(bufferised)
}
}
mutating func withContiguousMutableStorageIfAvailable<ReturnValue>(
_ body: (inout UnsafeMutableBufferPointer<UInt8>) throws -> ReturnValue)
rethrows -> ReturnValue? {
return try withUnsafeMutablePointer(to: &self.blockBytes) { tuplePtr in
// Homogeneous tuples are always bound to the element type as well as to their own type.
let retyped = UnsafeMutableRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
var bufferised = UnsafeMutableBufferPointer(start: retyped, count: Self.blockSize)
return try body(&bufferised)
}
}
}
@@ -1,194 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Crypto
#if hasFeature(SourceWarningControl)
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
#else
@_implementationOnly import CCryptoBoringSSL
#endif
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
@usableFromInline
enum OpenSSLAESCBCImpl {
private static let blockSize = 16
@usableFromInline
enum Direction {
case encrypt
case decrypt
@usableFromInline
var _boringSSLParameter: Int32 {
switch self {
case .encrypt: AES_ENCRYPT
case .decrypt: AES_DECRYPT
}
}
}
/// Encrypts plaintext using AES-CBC.
///
/// PKCS#7 padding is added unless `noPadding` is set, in which case the plaintext must
/// already be a whole number of blocks.
static func encrypt<Plaintext: DataProtocol>(
_ plaintext: Plaintext,
using key: SymmetricKey,
iv: AES._CBC.IV,
noPadding: Bool
) throws -> Data {
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
// With padding disabled the input must be a whole number of blocks.
if noPadding && (plaintext.count % Self.blockSize != 0) {
throw CryptoKitError.incorrectParameterSize
}
// AES_cbc_encrypt performs no padding, so PKCS#7 is applied here.
var padded = Data(plaintext)
if !noPadding {
// PKCS#7 always appends 1...blockSize bytes (a full block when already aligned).
let padLength = Self.blockSize - (plaintext.count % Self.blockSize)
let padding = repeatElement(UInt8(padLength), count: padLength)
padded.append(contentsOf: padding)
}
return padded.withUnsafeBytes { plaintextPtr in
Self._cipher(.encrypt, plaintextPtr, using: key, iv: iv)
}
}
/// Decrypts ciphertext using AES-CBC.
///
/// BoringSSL runs with padding disabled and, unless `noPadding` is set, PKCS#7 padding is
/// removed here in constant time. BoringSSL's own PKCS#7 removal is not constant-time (it is a
/// documented padding oracle absent authentication), so it must not be delegated.
static func decrypt<Ciphertext: DataProtocol>(
_ ciphertext: Ciphertext,
using key: SymmetricKey,
iv: AES._CBC.IV,
noPadding: Bool
) throws -> Data {
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
// CBC ciphertext is always a whole number of non-empty blocks.
guard ciphertext.count > 0, ciphertext.count % Self.blockSize == 0 else {
throw CryptoKitError.incorrectParameterSize
}
let contiguousCiphertext = Data(ciphertext)
let plaintext = contiguousCiphertext.withUnsafeBytes { ciphertextPtr in
Self._cipher(.decrypt, ciphertextPtr, using: key, iv: iv)
}
return noPadding ? plaintext : try plaintext.removingPKCS7PaddingConstantTime(blockSize: Self.blockSize)
}
/// Runs raw AES-CBC in the given direction over a single contiguous buffer.
///
/// `AES_cbc_encrypt` performs no padding, so `input` must be a whole number of blocks and the
/// output has the same length. PKCS#7 is applied and removed by the callers.
@usableFromInline
static func _cipher(
_ direction: Direction,
_ input: UnsafeRawBufferPointer,
using key: SymmetricKey,
iv: AES._CBC.IV
) -> Data {
precondition(input.count % Self.blockSize == 0)
var output = Data(count: input.count)
var iv = iv
key.withUnsafeBytes { keyPtr in
// AES_cbc_encrypt advances the IV in place, so operate on our own copy.
iv.withUnsafeMutableBytes { ivPtr in
var key = AES_KEY()
switch direction {
case .encrypt:
precondition(
CCryptoBoringSSL_AES_set_encrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key) == 0
)
case .decrypt:
precondition(
CCryptoBoringSSL_AES_set_decrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key) == 0
)
}
output.withUnsafeMutableBytes { outputPtr in
CCryptoBoringSSL_AES_cbc_encrypt(
input.baseAddress,
outputPtr.baseAddress,
input.count,
&key,
ivPtr.baseAddress,
direction._boringSSLParameter
)
}
}
}
return output
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension Data {
/// Removes PKCS#7 padding in constant time with respect to the padding bytes.
fileprivate func removingPKCS7PaddingConstantTime(blockSize: Int = 16) throws -> Data {
// The total length is not secret, so branching on it is safe.
guard self.count >= blockSize, self.count % blockSize == 0 else {
throw CryptoKitError.incorrectParameterSize
}
let padLength = self.last!
let lastBlock = self.suffix(blockSize)
// Validate padding in constant time.
var bad: UInt32 = 0
// A valid PKCS#7 pad length is 1...blockSize.
bad |= constantTimeLessThanOrEqual(padLength, 0)
bad |= constantTimeLessThanOrEqual(UInt8(blockSize + 1), padLength)
// We MUST operate on every byte in the block, and each byte in the padding region MUST equal `padLength`.
for index in lastBlock.indices {
let byte = UInt32(lastBlock[index])
let distanceFromEnd = self.endIndex - index
let inPadding = constantTimeLessThanOrEqual(UInt8(distanceFromEnd), padLength)
bad |= inPadding & (byte ^ UInt32(padLength))
}
// Throw if padding was invalid.
guard bad == 0 else {
throw CryptoKitError.incorrectParameterSize
}
// Drop the padding.
return self.dropLast(Int(padLength))
}
}
/// Returns `0xFFFFFFFF` if `lhs <= rhs`, otherwise `0`, without a data-dependent branch.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
private func constantTimeLessThanOrEqual(_ lhs: UInt8, _ rhs: UInt8) -> UInt32 {
// `lhs - rhs - 1` is negative iff `lhs <= rhs`; propagate its sign bit across the word.
let difference = Int32(lhs) - Int32(rhs) - 1
return UInt32(bitPattern: difference >> 31)
}
@@ -19,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)
+14
View File
@@ -71,6 +71,10 @@ extension AES {
self.backing.update(bufferPointer)
}
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
/// Finalizes the message authentication computation and returns the
/// computed code.
///
@@ -83,6 +87,16 @@ extension AES {
self.cowIfNeeded()
return self.backing.finalize()
}
#else
/// Finalizes the message authentication computation and returns the
/// computed code.
///
/// - Returns: The message authentication code.
public func finalize() -> AES.CMAC.MAC {
var `self` = self
return self.backing.finalize()
}
#endif
/// Updates the MAC with data.
///
@@ -108,8 +108,8 @@ extension ARC {
let T = H2G.hashToGroup(presentationContext, domainSeparationString: Data(("HashToGroup-" + ciphersuite.domain + "Tag").utf8))
// Recompute m1Tag = H2G(presentationContext) - nonce * tag
let nonceScalar = try Group.Scalar(bytes: I2OSP(value: nonce, outputByteCount: ciphersuite.scalarByteCount), reductionIsModOrder: true)
let m1Tag = T - nonceScalar * self.tag
var m1Tag = T
for _ in 0..<nonce { m1Tag = m1Tag - self.tag }
// Create a verifier, and allocate variables for the constrained scalars.
var verifier = Verifier<H2G>(label: ciphersuite.domain + ciphersuite.domain + "CredentialPresentation")
+4 -4
View File
@@ -18,7 +18,6 @@ add_library(CryptoExtras
"AES/AES_CTR.swift"
"AES/AES_GCM_SIV.swift"
"AES/Block Function.swift"
"AES/BoringSSL/AES_CBC_boring.swift"
"AES/BoringSSL/AES_CFB_boring.swift"
"AES/BoringSSL/AES_CTR_boring.swift"
"AES/BoringSSL/AES_GCM_SIV_boring.swift"
@@ -78,7 +77,6 @@ add_library(CryptoExtras
"Util/ThreadSpecific/ThreadPosix.swift"
"Util/ThreadSpecific/ThreadSpecific.swift"
"Util/ThreadSpecific/ThreadWindows.swift"
"Util/Zeroization.swift"
"ZKPs/DLEQ.swift"
"ZKPs/Prover.swift"
"ZKPs/Verifier.swift"
@@ -88,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
@@ -72,3 +72,16 @@ final class BoringSSLSHA512256Context {
}
}
}
extension UnsafeMutablePointer {
fileprivate func zeroize() {
let size = MemoryLayout.size(ofValue: Pointee.self)
memset_s(self, size, 0, size)
}
}
extension UnsafeMutableRawBufferPointer {
fileprivate func zeroize() {
memset_s(self.baseAddress!, self.count, 0, self.count)
}
}
@@ -161,7 +161,7 @@ struct OpenSSLGroupScalar<C: OpenSSLSupportedNISTCurve>: GroupScalar, CustomStri
/// Deserializes a scalar from data.
/// - Parameters:
/// - bytes: The serialized scalar
/// - data: The serialized scalar
/// - reductionIsModOrder: Resulting number is taken "mod q" (characteristic) by default. Override by setting true if "mod p" (order) is desired.
/// - Returns: The deserialized scalar
init(bytes: Data, reductionIsModOrder: Bool = false) throws {
@@ -276,9 +276,6 @@ extension OpenSSLCurvePoint {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension OpenSSLCurvePoint: OPRFGroupElement {
init(oprfRepresentation data: Data) throws {
guard data.count == C.compressedx962PointByteCount else {
throw CryptoKitError.incorrectParameterSize
}
let point = try EllipticCurvePoint(x962Representation: data, on: C.group, context: C.__ffac)
self.init(ecPoint: point)
}
@@ -22,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, *)
@@ -43,9 +45,8 @@ internal struct BoringSSLPBKDF2 {
outputByteCount: Int,
rounds: Int
) throws -> SymmetricKey {
// SecureBytes is internal to Crypto, so zero the buffer by hand once the key has been copied out.
// This should be SecureBytes, but we can't use that here.
var derivedKeyData = Data(count: outputByteCount)
defer { derivedKeyData.withUnsafeMutableBytes { $0.zeroize() } }
let rc = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes -> Int32 in
let saltBytes: ContiguousBytes = salt.regions.count == 1 ? salt.regions.first! : Array(salt)
@@ -39,9 +39,8 @@ internal struct CommonCryptoPBKDF2 {
outputByteCount: Int,
rounds: Int
) throws -> SymmetricKey {
// SecureBytes is internal to Crypto, so zero the buffer by hand once the key has been copied out.
// This should be SecureBytes, but we can't use that here.
var derivedKeyData = Data(count: outputByteCount)
defer { derivedKeyData.withUnsafeMutableBytes { $0.zeroize() } }
let derivationStatus = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes -> Int32 in
let saltBytes: ContiguousBytes = salt.regions.count == 1 ? salt.regions.first! : Array(salt)
@@ -16,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)
@@ -81,25 +83,12 @@ internal struct BoringSSLScrypt {
parallelism: Int,
maxMemory: Int? = nil
) throws -> SymmetricKey {
// SecureBytes is internal to Crypto, so zero the buffer by hand once the key has been copied out.
// This should be SecureBytes, but we can't use that here.
var derivedKeyData = Data(count: outputByteCount)
defer { derivedKeyData.withUnsafeMutableBytes { $0.zeroize() } }
let memoryLimit: Int
if let maxMemory {
memoryLimit = maxMemory
} else {
// This computes the maximum amount of memory that will be used by the scrypt algorithm with an additional memory page to spare. This value will be used by the BoringSSL as the memory limit for the algorithm.
// An additional memory page is added to the computed value (using POSIX specification) to ensure that the memory limit is not too tight.
let (blockBytes, blockBytesOverflowed) = 128.multipliedReportingOverflow(by: blockSize)
let (laneBytes, laneBytesOverflowed) = blockBytes.multipliedReportingOverflow(by: rounds)
let (stateBytes, stateBytesOverflowed) = laneBytes.multipliedReportingOverflow(by: parallelism)
let (computedLimit, computedLimitOverflowed) = stateBytes.addingReportingOverflow(getPageSize())
guard !blockBytesOverflowed, !laneBytesOverflowed, !stateBytesOverflowed, !computedLimitOverflowed else {
throw CryptoKitError.incorrectParameterSize
}
memoryLimit = computedLimit
}
// This computes the maximum amount of memory that will be used by the scrypt algorithm with an additional memory page to spare. This value will be used by the BoringSSL as the memory limit for the algorithm.
// An additional memory page is added to the computed value (using POSIX specification) to ensure that the memory limit is not too tight.
let maxMemory = maxMemory ?? (128 * rounds * blockSize * parallelism + getPageSize())
let result = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes -> Int32 in
let saltBytes: ContiguousBytes = salt.regions.count == 1 ? salt.regions.first! : Array(salt)
@@ -115,7 +104,7 @@ internal struct BoringSSLScrypt {
UInt64(rounds),
UInt64(blockSize),
UInt64(parallelism),
memoryLimit,
maxMemory,
derivedKeyBytes.baseAddress!,
derivedKeyBytes.count
)
@@ -35,16 +35,10 @@ extension KDF {
/// - rounds: The number of rounds which should be used to perform key derivation. Must be a power of 2 less than `2^(128 * blockSize / 8)`.
/// - blockSize: The block size to use for key derivation.
/// - parallelism: The parallelism factor to use for key derivation. Must be a positive integer less than or equal to `((2^32 - 1) * 32) / (128 * blockSize)`.
/// - maxMemory: The maximum amount of memory allowed to use for key derivation. Must be positive. If not provided, the default value is computed for the provided parameters.
/// - maxMemory: The maximum amount of memory allowed to use for key derivation. If not provided, the default value is computed for the provided parameters.
/// - Returns: The derived symmetric key.
public static func deriveKey<Passphrase: DataProtocol, Salt: DataProtocol>(from password: Passphrase, salt: Salt, outputByteCount: Int, rounds: Int, blockSize: Int, parallelism: Int, maxMemory: Int? = nil) throws -> SymmetricKey {
guard rounds > 0, blockSize > 0, parallelism > 0, outputByteCount >= 0 else {
throw CryptoKitError.incorrectParameterSize
}
if let maxMemory, maxMemory <= 0 {
throw CryptoKitError.incorrectParameterSize
}
return try BackingScrypt.deriveKey(from: password, salt: salt, outputByteCount: outputByteCount, rounds: rounds, blockSize: blockSize, parallelism: parallelism, maxMemory: maxMemory)
return try BackingScrypt.deriveKey(from: password, salt: salt, outputByteCount: outputByteCount, rounds: rounds, blockSize: blockSize, parallelism: parallelism)
}
}
}
@@ -35,9 +35,6 @@ extension P384 {
static var ciphersuite: Ciphersuite { Ciphersuite(H2G.self) }
/// The maximum length, in bytes, of an input, imposed by the two-byte length prefix in the RFC 9497 framing.
static let maximumInputByteCount = 0xFFFF
/// A P-384 public key used to blind inputs and finalize blinded elements.
public struct PublicKey {
fileprivate typealias BackingPublicKey = P384.Signing.PublicKey
@@ -370,9 +367,6 @@ extension P384._VOPRF {
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P384._VOPRF.PublicKey {
internal func blind<D: DataProtocol>(_ input: D, with fixedBlind: P384._VOPRF.H2G.G.Scalar) throws -> P384._VOPRF.BlindedInput {
guard input.count <= P384._VOPRF.maximumInputByteCount else {
throw CryptoKitError.incorrectParameterSize
}
let input = Data(input)
let (blind, blindedElement) = Self.client.blindMessage(input, blind: fixedBlind)
return P384._VOPRF.BlindedInput(
@@ -442,9 +436,6 @@ extension P384._VOPRF.PrivateKey {
///
/// - Seealso: [RFC 9497: VOPRF Protocol - Evaluate]( https://cfrg.github.io/draft-irtf-cfrg-voprf/draft-irtf-cfrg-voprf.html#section-3.3.2-7).
public func evaluate<D: DataProtocol>(_ input: D) throws -> Data {
guard input.count <= P384._VOPRF.maximumInputByteCount else {
throw CryptoKitError.incorrectParameterSize
}
let inputElement = P384._VOPRF.H2G.hashToGroup(
Data(input),
domainSeparationString: Self.hashToGroupDST
@@ -105,15 +105,9 @@ extension _RSA.BlindSigning {
}
/// Construct a RSA public key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes, parameters: Parameters) throws {
self.backing = try BackingPublicKey(n: n, e: e)
self.parameters = parameters
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
public var pkcs1DERRepresentation: Data {
@@ -212,15 +206,9 @@ extension _RSA.BlindSigning {
}
/// Construct an RSA private key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes, parameters: Parameters) throws {
self.backing = try BackingPrivateKey(n: n, e: e, d: d, p: p, q: q)
self.parameters = parameters
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
/// Randomly generate a new RSA private key of a given size.
+15 -68
View File
@@ -117,14 +117,8 @@ extension _RSA.Signing {
}
/// Construct an RSA public key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.backing = try BackingPublicKey(n: n, e: e)
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
public var pkcs1DERRepresentation: Data {
@@ -254,14 +248,8 @@ extension _RSA.Signing {
}
/// Construct an RSA private key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes) throws {
self.backing = try BackingPrivateKey(n: n, e: e, d: d, p: p, q: q)
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
/// Randomly generate a new RSA private key of a given size.
@@ -530,7 +518,7 @@ extension _RSA.Signing {
extension _RSA.Encryption {
/// Identical to ``_RSA/Signing/PublicKey``.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
public struct PublicKey: Sendable {
public struct PublicKey {
public struct Primitives: Sendable, Hashable {
public var modulus: Data
public var publicExponent: Data
@@ -547,7 +535,6 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
public init(pemRepresentation: String) throws {
self.backing = try BackingPublicKey(pemRepresentation: pemRepresentation)
guard self.keySizeInBits >= 2048, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
@@ -557,7 +544,6 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 1024 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
/// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons.
public init(unsafePEMRepresentation pemRepresentation: String) throws {
self.backing = try BackingPublicKey(pemRepresentation: pemRepresentation)
@@ -568,7 +554,6 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
public init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
self.backing = try BackingPublicKey(derRepresentation: derRepresentation)
guard self.keySizeInBits >= 2048, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
@@ -578,7 +563,6 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 1024 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
/// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons.
public init<Bytes: DataProtocol>(unsafeDERRepresentation derRepresentation: Bytes) throws {
self.backing = try BackingPublicKey(derRepresentation: derRepresentation)
@@ -586,14 +570,8 @@ extension _RSA.Encryption {
}
/// Construct an RSA public key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.backing = try BackingPublicKey(n: n, e: e)
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
public var pkcs1DERRepresentation: Data { self.backing.pkcs1DERRepresentation }
@@ -601,7 +579,6 @@ extension _RSA.Encryption {
public var derRepresentation: Data { self.backing.derRepresentation }
public var pemRepresentation: String { self.backing.pemRepresentation }
public var keySizeInBits: Int { self.backing.keySizeInBits }
internal var modulusByteCount: Int { self.backing.modulusByteCount }
fileprivate init(_ backing: BackingPublicKey) { self.backing = backing }
public func getKeyPrimitives() throws -> Primitives {
@@ -612,14 +589,13 @@ extension _RSA.Encryption {
/// Identical to ``_RSA/Signing/PrivateKey``.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
public struct PrivateKey: Sendable {
public struct PrivateKey {
private var backing: BackingPrivateKey
/// Construct an RSA private key from a PEM representation.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
public init(pemRepresentation: String) throws {
self.backing = try BackingPrivateKey(pemRepresentation: pemRepresentation)
guard self.keySizeInBits >= 2048, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
@@ -629,7 +605,6 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 1024 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
/// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons.
public init(unsafePEMRepresentation pemRepresentation: String) throws {
self.backing = try BackingPrivateKey(pemRepresentation: pemRepresentation)
@@ -640,7 +615,6 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
public init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
self.backing = try BackingPrivateKey(derRepresentation: derRepresentation)
guard self.keySizeInBits >= 2048, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
@@ -650,7 +624,6 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 1024 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
/// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons.
public init<Bytes: DataProtocol>(unsafeDERRepresentation derRepresentation: Bytes) throws {
self.backing = try BackingPrivateKey(derRepresentation: derRepresentation)
@@ -659,14 +632,8 @@ extension _RSA.Encryption {
/// Construct an RSA private key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes) throws {
self.backing = try BackingPrivateKey(n: n, e: e, d: d, p: p, q: q)
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
/// Randomly generate a new RSA private key of a given size.
@@ -774,8 +741,8 @@ extension _RSA.Encryption {
extension _RSA.Encryption.PrivateKey {
/// Decrypt a message encrypted with this key's public key and using the specified padding mode.
///
/// > Important: The size of the data to decrypt must be equal to the block size of the key.
/// Attempting to decrypt data of the wrong size will fail.
/// > Important: The size of the data to decrypt must be equal to the block size of the key (e.g.
/// `keySizeInBits / 8`). Attempting to decrypt data of the wrong size will fail.
public func decrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
return try self.backing.decrypt(data, padding: padding)
}
@@ -797,17 +764,17 @@ extension _RSA.Encryption.PublicKey {
switch padding.backing {
case ._weakAndInsecure_pkcs1v1_5:
// https://www.rfc-editor.org/rfc/rfc8017#section-7.2
return self.modulusByteCount - 11
return (self.keySizeInBits / 8) - 11
case let .pkcs1_oaep(Digest):
// https://datatracker.ietf.org/doc/html/rfc8017#section-7.1.1
return self.modulusByteCount - (2 * Digest.hashBitLength / 8) - 2
return (self.keySizeInBits / 8) - (2 * Digest.hashBitLength / 8) - 2
}
}
/// Encrypt a message with this key, using the specified padding mode.
///
/// > Important: The size of the data to encrypt _must_ not exceed the block size of the key,
/// minus any additional space required by the padding mode. Attempting to
/// > Important: The size of the data to encrypt _must_ not exceed the modulus of the key (e.g.
/// `keySizeInBits / 8`), minus any additional space required by the padding mode. Attempting to
/// encrypt data larger than this will fail. Use ``maximumEncryptSize(with:)`` to determine
/// exactly how many bytes can be encrypted by the key.
public func encrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
@@ -834,37 +801,21 @@ extension _RSA {
d: ArbitraryPrecisionInteger
) throws -> (p: ArbitraryPrecisionInteger, q: ArbitraryPrecisionInteger) {
// This is based on the proof of fact 1 in https://www.ams.org/notices/199902/boneh.pdf
// Valid keys have e < n, and BoringSSL rejects d >= n and moduli over its maximum. Larger
// values let the caller pick the cost of the exponentiations and squaring loop below.
guard n.byteCount <= _RSA.maximumModulusBitCount / 8, e < n, d < n else {
throw CryptoKitError.incorrectParameterSize
}
let k = (d * e) - 1
// k == 0 (that is, e * d == 1) gives r == 0 below, for which every base is trivial.
guard k > 0, k.isEven else {
throw CryptoKitError.incorrectParameterSize
}
let t = k.trailingZeroBitCount
let r = k >> t
guard k.isEven else {
throw CryptoKitError.incorrectParameterSize
}
var y: ArbitraryPrecisionInteger = 0
var i = 1
let context = try FiniteFieldArithmeticContext(fieldSize: n)
// Every attempt must count towards the limit, including those where g^r is trivially
// 1 or n - 1. Inputs for which that holds for every base would otherwise never return.
for _ in 0..<100 {
while i <= 100 {
let g = try ArbitraryPrecisionInteger.random(inclusiveMin: 2, exclusiveMax: n)
// The check at the end of this attempt only holds for bases coprime to n.
guard try ArbitraryPrecisionInteger.gcd(g, n) == 1 else {
continue
}
y = try context.pow(g, r)
guard y != 1, y != n - 1 else {
@@ -893,11 +844,7 @@ extension _RSA {
return (p, q)
}
// Here x is g^k unless the loop stopped at n - 1. For a valid key g^k == 1 for every
// base coprime to n, so any other value means the numbers do not form a key.
guard x == n - 1 else {
throw CryptoKitError.incorrectParameterSize
}
i &+= 1
}
throw CryptoKitError.incorrectParameterSize
+45 -45
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)
@@ -81,10 +83,6 @@ internal struct BoringSSLRSAPublicKey: Sendable {
self.backing.keySizeInBits
}
var modulusByteCount: Int {
self.backing.modulusByteCount
}
fileprivate init(_ backing: Backing) {
self.backing = backing
}
@@ -230,17 +228,17 @@ extension BoringSSLRSAPublicKey {
self.pointer = pointer
}
fileprivate convenience init(copying other: Backing) {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
fileprivate init(copying other: Backing) {
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
let rsaPublicKey = CCryptoBoringSSL_RSAPublicKey_dup(
CCryptoBoringSSL_EVP_PKEY_get0_RSA(other.pointer)
)
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
}
fileprivate convenience init(pemRepresentation: String) throws {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
fileprivate init(pemRepresentation: String) throws {
var pemRepresentation = pemRepresentation
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
// There are two encodings for RSA public keys: PKCS#1 and the SPKI form.
// The SPKI form is what we support for EC keys, so we try that first, then we
@@ -256,15 +254,20 @@ extension BoringSSLRSAPublicKey {
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
let rsaPublicKey = try pemRepresentation.withUTF8 { utf8Ptr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPublicKey(bio, nil, nil, nil) else {
throw CryptoKitError.internalBoringSSLError()
do {
let rsaPublicKey = try pemRepresentation.withUTF8 { utf8Ptr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPublicKey(bio, nil, nil, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
}
return key
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
CCryptoBoringSSL_EVP_PKEY_free(self.pointer)
throw error
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
}
}
@@ -277,8 +280,8 @@ extension BoringSSLRSAPublicKey {
}
}
private convenience init<Bytes: ContiguousBytes>(contiguousDerRepresentation: Bytes) throws {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
private init<Bytes: ContiguousBytes>(contiguousDerRepresentation: Bytes) throws {
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
// There are two encodings for RSA public keys: PKCS#1 and the SPKI form.
// The SPKI form is what we support for EC keys, so we try that first, then we
// fall back to the PKCS#1 form if that parse fails.
@@ -293,20 +296,25 @@ extension BoringSSLRSAPublicKey {
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
let rsaPublicKey = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
guard let key = CCryptoBoringSSL_d2i_RSAPublicKey_bio(bio, nil) else {
throw CryptoKitError.internalBoringSSLError()
do {
let rsaPublicKey = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
guard let key = CCryptoBoringSSL_d2i_RSAPublicKey_bio(bio, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
}
return key
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
CCryptoBoringSSL_EVP_PKEY_free(self.pointer)
throw error
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
}
}
fileprivate convenience init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
fileprivate init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
let n = try ArbitraryPrecisionInteger(bytes: n)
let e = try ArbitraryPrecisionInteger(bytes: e)
@@ -353,12 +361,7 @@ extension BoringSSLRSAPublicKey {
fileprivate var keySizeInBits: Int {
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
return Int(CCryptoBoringSSL_RSA_bits(rsaPublicKey))
}
fileprivate var modulusByteCount: Int {
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
return Int(CCryptoBoringSSL_RSA_size(rsaPublicKey))
return Int(CCryptoBoringSSL_RSA_size(rsaPublicKey)) * 8
}
fileprivate func isValidSignature<D: Digest>(
@@ -373,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,
@@ -382,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,
@@ -393,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,
@@ -445,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,
@@ -470,6 +473,7 @@ extension BoringSSLRSAPublicKey {
parameters: _RSA.BlindSigning.Parameters<H>
) throws -> _RSA.BlindSigning.BlindingResult {
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
let modulusByteCount = Int(CCryptoBoringSSL_RSA_size(rsaPublicKey))
let e = try ArbitraryPrecisionInteger(copying: CCryptoBoringSSL_RSA_get0_e(rsaPublicKey))
let n = try ArbitraryPrecisionInteger(copying: CCryptoBoringSSL_RSA_get0_n(rsaPublicKey))
let finiteField = try FiniteFieldArithmeticContext(fieldSize: n)
@@ -527,6 +531,7 @@ extension BoringSSLRSAPublicKey {
parameters: _RSA.BlindSigning.Parameters<H>
) throws -> _RSA.Signing.RSASignature {
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
let modulusByteCount = Int(CCryptoBoringSSL_RSA_size(rsaPublicKey))
let n = try ArbitraryPrecisionInteger(copying: CCryptoBoringSSL_RSA_get0_n(rsaPublicKey))
let finiteField = try FiniteFieldArithmeticContext(fieldSize: n)
@@ -826,7 +831,7 @@ extension BoringSSLRSAPrivateKey {
fileprivate var keySizeInBits: Int {
let rsaPrivateKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
return Int(CCryptoBoringSSL_RSA_bits(rsaPrivateKey))
return Int(CCryptoBoringSSL_RSA_size(rsaPrivateKey)) * 8
}
fileprivate var publicKey: BoringSSLRSAPublicKey {
@@ -858,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
@@ -869,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,
@@ -881,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,
@@ -938,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,
@@ -1131,8 +1136,3 @@ enum BlindSigningHelpers {
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension _RSA {
static let maximumModulusBitCount = Int(OPENSSL_RSA_MAX_MODULUS_BITS)
}
@@ -15,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
@@ -19,9 +19,14 @@ import Foundation
#endif
extension Data {
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
// This overload reduces allocations when used in a chain of infix operations.
static func + (lhs: consuming Data, rhs: consuming Data) -> Data {
lhs.append(contentsOf: rhs)
return lhs
}
#endif
}
@@ -29,7 +29,7 @@ final class ThreadSpecificVariable<Value: AnyObject> {
// the actual type in there is `Box<(ThreadSpecificVariable<T>, T)>` but we can't use that as C functions can't capture (even types)
private typealias BoxedType = Box<(AnyObject, AnyObject)>
private final class Key {
private class Key {
private var underlyingKey: ThreadOpsSystem.ThreadSpecificKey
internal init(destructor: @escaping ThreadOpsSystem.ThreadSpecificKeyDestructor) {
@@ -1,75 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
protocol Zeroization {
mutating func zeroize()
}
extension UnsafeMutablePointer: Zeroization {
/// Zeroizes the pointee
func zeroize() {
let size = MemoryLayout<Pointee>.size
memset_s(self, size, 0, size)
}
}
extension UnsafeMutableRawBufferPointer: Zeroization {
func zeroize() {
memset_s(self.baseAddress!, self.count, 0, self.count)
}
}
extension Array: Zeroization where Element == UInt8 {
/// Zeroizes the array
mutating func zeroize() {
memset_s(&self, self.count, 0, self.count)
}
}
extension Data: Zeroization {
internal mutating func zeroize() {
_ = self.withUnsafeMutableBytes {
memset_s($0.baseAddress!, $0.count, 0, $0.count)
}
}
}
func withUnsafeTemporaryZeroingAllocation<R>(
byteCount: Int,
alignment: Int,
_ body: (UnsafeMutableRawBufferPointer) throws -> R
) rethrows -> R {
try withUnsafeTemporaryAllocation(byteCount: byteCount, alignment: alignment) { buffer in
defer { buffer.zeroize() }
return try body(buffer)
}
}
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1.0, *)
func withTemporaryZeroingAllocation<R>(
byteCount: Int,
alignment: Int,
_ body: (inout OutputRawSpan) throws -> R
) rethrows -> R {
try withUnsafeTemporaryZeroingAllocation(byteCount: byteCount, alignment: alignment) { buffer in
var output = OutputRawSpan(buffer: buffer, initializedCount: 0)
return try body(&output)
}
}
+6 -6
View File
@@ -24,7 +24,7 @@ final class CXKCPTests: XCTestCase {
var output = [UInt8](repeating: 0, count: 32)
let result = input.withUnsafeBytes { inputBytes in
SHA3_256(&output, inputBytes.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
@@ -163,85 +163,6 @@ final class CBCTests: XCTestCase {
}
}
func testDecryptRejectsPaddingLengthGreaterThanBlockSize() throws {
// A plaintext whose final block claims a PKCS#7 pad length of 17 (0x11)
// is invalid for a 16-byte block: the maximum valid PKCS#7 pad is one
// full block (16). Correct unpadding must reject it. Regression guard:
// the previous `trimPadding` accepted any pad length up to 255 and
// scanned across blocks, so it wrongly stripped 17 bytes here.
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// 32-byte (block-multiple) plaintext ending in 17 bytes of 0x11.
var plaintext = Data(repeating: 0xAB, count: 15)
plaintext.append(Data(repeating: 0x11, count: 17))
precondition(plaintext.count == 32)
let ciphertext = try AES._CBC.encrypt(plaintext, using: key, iv: iv, noPadding: true)
XCTAssertThrowsError(
try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false)
) { error in
guard let error = error as? CryptoKitError, case .incorrectParameterSize = error else {
XCTFail("Unexpected error: \(error)")
return
}
}
}
func testUnpadAcceptsAllValidPaddingLengths() throws {
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// For every valid PKCS#7 pad length (1...16), round-trip a message that
// pads to exactly that length and assert exact recovery.
for padLength in 1...16 {
let messageLength = 32 - padLength // pads to 32 bytes (two blocks)
let message = Data((0..<messageLength).map { UInt8(truncatingIfNeeded: $0) })
let ciphertext = try AES._CBC.encrypt(message, using: key, iv: iv, noPadding: false)
let decrypted = try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false)
XCTAssertEqual(decrypted, message, "round-trip failed for pad length \(padLength)")
}
}
func testUnpadRejectsCorruptedPaddingByte() throws {
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// Build a validly-padded block-multiple plaintext, then corrupt each
// padding byte except the last (which encodes the claimed length). The
// constant-time scan must reject a mismatch at any position.
for padLength in 2...16 {
var padded = Data((0..<(32 - padLength)).map { UInt8(truncatingIfNeeded: $0) })
padded.append(Data(repeating: UInt8(padLength), count: padLength))
precondition(padded.count == 32)
for position in (32 - padLength)..<31 {
var corrupted = padded
corrupted[position] = UInt8(padLength) ^ 0xFF // guaranteed != padLength
let ciphertext = try AES._CBC.encrypt(corrupted, using: key, iv: iv, noPadding: true)
XCTAssertThrowsError(
try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false),
"corruption at pad length \(padLength), position \(position) was not rejected"
)
}
}
}
func testUnpadRejectsZeroPaddingLength() throws {
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// A final byte of 0x00 claims a pad length of zero, which is invalid PKCS#7.
var padded = Data((0..<31).map { UInt8(truncatingIfNeeded: $0) })
padded.append(0x00)
let ciphertext = try AES._CBC.encrypt(padded, using: key, iv: iv, noPadding: true)
XCTAssertThrowsError(try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false))
}
func testToDataConversion() throws {
let randomBytes = (0..<16).map { _ in UInt8.random(in: UInt8.min...UInt8.max) }
let dataIn = Data(randomBytes)
@@ -325,3 +325,28 @@ extension P384._ARCV1: ARCV1 {}
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P384: ARCCurve {}
// Swift 5.10 compiler needs a little more help to infer the conformances.
#if swift(<6.0)
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
fileprivate extension P256._ARCV1.PrivateKey {
typealias H2G = P256._ARCV1.H2G
typealias Credential = P256._ARCV1.Credential
typealias PublicKey = P256._ARCV1.PublicKey
typealias CredentialRequest = P256._ARCV1.CredentialRequest
typealias CredentialResponse = P256._ARCV1.CredentialResponse
typealias Presentation = P256._ARCV1.Presentation
}
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
fileprivate extension P384._ARCV1.PrivateKey {
typealias H2G = P384._ARCV1.H2G
typealias Credential = P384._ARCV1.Credential
typealias PublicKey = P384._ARCV1.PublicKey
typealias CredentialRequest = P384._ARCV1.CredentialRequest
typealias CredentialResponse = P384._ARCV1.CredentialResponse
typealias Presentation = P384._ARCV1.Presentation
}
#endif
@@ -158,61 +158,6 @@ class ARCTests: XCTestCase {
// try endToEndWorkflow(CurveType: P521.self)
}
func testVerifyCostIsIndependentOfTheNonce() async throws {
let ciphersuite = ARC.Ciphersuite(HashToCurveImpl<P256>.self)
let (generatorG, generatorH) = ARC.getGenerators(suite: ciphersuite)
let x0 = GroupImpl<P256>.Scalar.random
let x1 = GroupImpl<P256>.Scalar.random
let x2 = GroupImpl<P256>.Scalar.random
let x0Blinding = GroupImpl<P256>.Scalar.random
let serverPrivateKey = ARC.ServerPrivateKey(x0: x0, x1: x1, x2: x2, x0Blinding: x0Blinding)
let server = ARC.Server(ciphersuite: ciphersuite, x0: x0, x1: x1, x2: x2, x0Blinding: x0Blinding)
let requestContext = Data("test request context".utf8)
let precredential = try ARC.Precredential(
ciphersuite: ciphersuite,
m1: GroupImpl<P256>.Scalar.random,
requestContext: requestContext,
r1: GroupImpl<P256>.Scalar.random,
r2: GroupImpl<P256>.Scalar.random,
serverPublicKey: server.serverPublicKey
)
let credential = try precredential.makeCredential(
credentialResponse: try server.respond(credentialRequest: precredential.credentialRequest)
)
// The nonce comes from the client, so presentation verification cost must not scale with nonce.
// This test uses such a large nonce that the test would hit the timeout if verification was correlated.
let nonce = 1 << 62
let presentationContext = Data("0123456789".utf8)
let presentation = try ARC.Presentation(
credential: credential,
presentationContext: presentationContext,
nonce: nonce,
generatorG: generatorG,
generatorH: generatorH
)
let verificationResult: LockedBox<Bool?> = .init(initialValue: nil)
let finished = expectation(description: "verification finished")
let thread = Thread {
let result = try? presentation.verify(
serverPrivateKey: serverPrivateKey,
X1: x1 * generatorH,
m2: precredential.clientSecrets.m2,
presentationContext: presentationContext,
presentationLimit: Int.max,
nonce: nonce,
generatorG: generatorG,
generatorH: generatorH,
ciphersuite: ciphersuite)
verificationResult.withLockedValue { $0 = result }
finished.fulfill()
}
thread.start()
await fulfillment(of: [finished], timeout: 10)
XCTAssertEqual(verificationResult.withLockedValue { $0 }, true)
}
func testPresentationState() throws {
let context1 = Data("context1".utf8)
let context2 = Data("context2".utf8)
@@ -79,38 +79,4 @@ final class VOPRFPublicAPITests: XCTestCase {
// [Server] Compute the PRF for the input, without blinding or proof generation.
let _: Data = try privateKey.evaluate(input)
}
func testBlindedElementRejectsUncompressedOPRFRepresentation() throws {
/// Check we only accept compressed encoded elements, as per RFC 9497:
///
/// > SerializeElement(A): Implemented using the compressed Elliptic-Curve-Point-to-Octet-String method...
/// >
/// > DeserializeElement(buf): Implemented by attempting to deserialize a 49-byte array to a public key
/// using the compressed Octet-String-to-Elliptic-Curve-Point method...
///
/// - See: https://www.rfc-editor.org/rfc/rfc9497.html#name-oprfp-384-sha-384
let publicKey = P384._VOPRF.PrivateKey().publicKey
let blindedElement = try publicKey.blind(Data("This is some input data".utf8)).blindedElement
let compressed = blindedElement.oprfRepresentation
let uncompressed = try P384.Signing.PublicKey(compressedRepresentation: compressed).x963Representation
XCTAssertThrowsError(try P384._VOPRF.BlindedElement(oprfRepresentation: uncompressed))
}
func testInputLongerThanRFC9497LimitThrows() throws {
let privateKey = P384._VOPRF.PrivateKey()
let publicKey = privateKey.publicKey
// RFC 9497 caps inputs at 2^16 - 1 bytes, the most the two-byte length prefix in the framing can encode.
let maximumInput = Data(repeating: 0x41, count: 0xFFFF)
let blindedInput = try publicKey.blind(maximumInput)
let blindEvaluation = try privateKey.evaluate(blindedInput.blindedElement)
XCTAssertNoThrow(try publicKey.finalize(blindedInput, using: blindEvaluation))
XCTAssertNoThrow(try privateKey.evaluate(maximumInput))
// Oversized inputs are rejected where they enter, so finalize can never be given one.
let oversizedInput = Data(repeating: 0x41, count: 0x1_0000)
XCTAssertThrowsError(try publicKey.blind(oversizedInput))
XCTAssertThrowsError(try privateKey.evaluate(oversizedInput))
}
}
-66
View File
@@ -84,70 +84,4 @@ class ScryptTests: XCTestCase {
try orFail { try self.testRFCVector(vector) }
}
}
func testDeriveKeyWithMaxMemoryBelowRequirementThrows() throws {
let password = Array("password".utf8)
let salt = Array("salt".utf8)
// These parameters need 128 * blockSize * (rounds + parallelism + 1) bytes, just over 1 MiB.
// BoringSSL reads a limit of zero as "use the default limit", and a negative limit as a huge size_t.
for maxMemory in [1024, 0, -1] {
XCTAssertThrowsError(
try KDF.Scrypt.deriveKey(
from: password,
salt: salt,
outputByteCount: 32,
rounds: 1024,
blockSize: 8,
parallelism: 1,
maxMemory: maxMemory
)
)
}
let bounded = try KDF.Scrypt.deriveKey(
from: password,
salt: salt,
outputByteCount: 32,
rounds: 1024,
blockSize: 8,
parallelism: 1,
maxMemory: 2 << 20
)
let unbounded = try KDF.Scrypt.deriveKey(
from: password,
salt: salt,
outputByteCount: 32,
rounds: 1024,
blockSize: 8,
parallelism: 1
)
XCTAssertEqual(bounded, unbounded)
}
func testDeriveKeyWithOutOfRangeParametersThrows() throws {
let password = Array("password".utf8)
let salt = Array("salt".utf8)
for (rounds, blockSize, parallelism, outputByteCount) in [
// Negative values reach UInt64 conversions and Data(count:), both of which trap.
(-1, 8, 1, 32),
(1024, -1, 1, 32),
(1024, 8, -1, 32),
(1024, 8, 1, -1),
// 128 * blockSize * rounds * parallelism overflows Int.
(1 << 32, 1 << 30, 1, 32),
] {
XCTAssertThrowsError(
try KDF.Scrypt.deriveKey(
from: password,
salt: salt,
outputByteCount: outputByteCount,
rounds: rounds,
blockSize: blockSize,
parallelism: parallelism
)
)
}
}
}
@@ -201,17 +201,6 @@ final class TestRSABlindSigning: XCTestCase {
e: bytesValues.randomElement()!,
parameters: .RSABSSA_SHA384_PSS_Randomized
)
// Modulus of a 512-bit key: `openssl rsa -in key.pem -noout -modulus`.
let _512BitModulus =
"e24c4c2c70e673315c2420b0e211542bbccf5b79f2ce6bdaa4aac29650bd064b"
+ "955ae1613a449c7143e906d7f251e49356771d9d6f8f15bcf4044f87de1c1bed"
XCTAssertThrowsError(
try _RSA.BlindSigning.PublicKey(
n: Data(hexString: _512BitModulus),
e: Data(hexString: "010001"),
parameters: .RSABSSA_SHA384_PSS_Randomized
)
)
}
func testConstructAndUseKeyFromRSANumbersWhileRecoveringPrimes() throws {
@@ -111,13 +111,6 @@ final class TestRSAEncryption: XCTestCase {
n: bytesValues.randomElement()!,
e: bytesValues.randomElement()!
)
// Modulus of a 512-bit key: `openssl rsa -in key.pem -noout -modulus`.
let _512BitModulus =
"e24c4c2c70e673315c2420b0e211542bbccf5b79f2ce6bdaa4aac29650bd064b"
+ "955ae1613a449c7143e906d7f251e49356771d9d6f8f15bcf4044f87de1c1bed"
XCTAssertThrowsError(
try _RSA.Encryption.PublicKey(n: Data(hexString: _512BitModulus), e: Data(hexString: "010001"))
)
}
func testConstructAndUseKeyFromRSANumbersWhileRecoveringPrimes() throws {
@@ -177,84 +170,6 @@ final class TestRSAEncryption: XCTestCase {
XCTAssertEqual(190, pubKey2048.maximumEncryptSize(with: .PKCS1_OAEP_SHA256))
}
// The encryption key initializers require the modulus bit length to be a multiple of 8.
func testRejectKeysWithNonByteAlignedModulus() throws {
// Equivalent key: `openssl genrsa -traditional 2050`, converted to the encodings below.
let _2050BitRSAPrivateKeyPEM = """
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQECxVSlteS7/eN5dXzn+RdyApV8JJILQaXaZOgxl/FELWhXq4lY
Uk6+0keFtdLvSsdsBAZlq7VT8vHyfxqhcpb0RkjThWfVhR2BjzO8TNLA+mlKGKZJ
foTE3r7o99Ev4X+H4QxCyAC8oyAKy1lyDA4wT7OFBBXtXJmeQ/PbYCuMMyqrCWUg
VL48rK150QxHQ0U9XsGCnF70X/PMPebKY60OS36pTYhmi77h0maiY4yW2kHNfgeG
Mbc3XQ19Sr42f5zKe0AIQfzK91v6M5PaEIpJAfm+JPDNWf2+RKEVa93gNiuTZ2+p
gUjf7ut8mY5MEn7fZhCeZeNBjNTuKXj3JqdP3wIDAQABAoIBAQC252vPakq7XeOc
0vdx+ISye99GAs6aP+z/pgvbtR+yYbxxg/ndR2bXDBBDYT/I1YFZzFh9HUWnWJIC
CljlFl2onfDE7pBVQdV9moaMfK+8Ilgz4PUEhbHKCgpClJM3H05nTmUN83qwyXtf
EhJhX2s/sfezpP/Op+HyfbfspW4CZrrJmv1zfqIjDiV7LMaoDDU+UDHexcgwoXCa
HKC/U7RcbNYE3hOg/Fjx+nevprXthhf8mpnkAzTcpXsMcATuvh7sSqdFnHkF9egw
CBnlx+iH9J/6Q3VwoZgwggi9S6qT5yrS0/JVWVic4KaiE81dDr+KLmXIpOFRNuYf
8sP79cfRAoGBAcwBZ+XfX5H8Ii7tSjCJWJ+sw6cevH4YQhYWDEgodsmzj2hDRoRj
EaGdATP5dry7RWePTuhN0KlvMYX/xI2kvoRrK6sR4bad0V2J8lKBFxAil55w531L
wZUAhxzAChWZ6uRMR694yati/8wIG+BMdwBPA+00+pMH2Kd9HGN8xoBHAoGBAYrA
0sfOCNqvkf7OsoiShjSdeTYkTqjHrVR7m6DJg2FUL6E9VnaSLG0esnAYGAozKfFl
rQz7gEGckMG2dILOAY9z3wv4ltX12RxmAJMHoO/ENDVxiqSKC7utiKzcii9qy626
RIuAvOwSOeU25VVTOzOm35wabuLAThMYBqdYl9epAoGAYsWKgZlM9BOnY1wgKfvT
w7Vc7W10G78psYRabsQBfZ3IlSKc6aA8EO+daoOOM0gixvHGh6rtuvPdNmCM270c
C2LXpYvZY1TPt73/Aiglw5kp5SNpEUZK8quCV3IEuE6sWQjn+418AAjp0+2Jzsec
ZbyRo0VU6G0u4AfFKLeKB9ECgYAURk8NIBHoWXggJDGbPhtSfHwLQdYgaREH88lM
es0apJ5Fo8bbFCrf9+GmTDZ/35zZ3yUCM7CkrgvpRxu41CfUXFkqXjwxBQ1/neWN
p6imZ+dej1RVmxl7LDCG4FTglpWbeKOonpYVceIzWZxxw3KY9ospk1n6n3HjHSrK
UYyK8QKBgQDWsxq+0VhPgMRDUKg2p1gdnluX9I5lmZVwy1No6QfChJUo/RCRYcIe
jLXlpoAW9UUR5JCx3/hKyKvbl34J/LV3Tc/63vHxOGnh8eAySyCcpFJFmyciIZdY
iRLB6wzq+zLIZkK7+5TdHCZ9jIi5oKyk2YDT6LSTUnuG9DlGpcSmqA==
-----END RSA PRIVATE KEY-----
"""
let _2050BitRSAPublicKeyPEM = """
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQECxVSlteS7/eN5dXzn+Rdy
ApV8JJILQaXaZOgxl/FELWhXq4lYUk6+0keFtdLvSsdsBAZlq7VT8vHyfxqhcpb0
RkjThWfVhR2BjzO8TNLA+mlKGKZJfoTE3r7o99Ev4X+H4QxCyAC8oyAKy1lyDA4w
T7OFBBXtXJmeQ/PbYCuMMyqrCWUgVL48rK150QxHQ0U9XsGCnF70X/PMPebKY60O
S36pTYhmi77h0maiY4yW2kHNfgeGMbc3XQ19Sr42f5zKe0AIQfzK91v6M5PaEIpJ
Afm+JPDNWf2+RKEVa93gNiuTZ2+pgUjf7ut8mY5MEn7fZhCeZeNBjNTuKXj3JqdP
3wIDAQAB
-----END PUBLIC KEY-----
"""
XCTAssertThrowsError(try _RSA.Encryption.PrivateKey(pemRepresentation: _2050BitRSAPrivateKeyPEM))
XCTAssertThrowsError(try _RSA.Encryption.PrivateKey(unsafePEMRepresentation: _2050BitRSAPrivateKeyPEM))
XCTAssertThrowsError(try _RSA.Encryption.PublicKey(pemRepresentation: _2050BitRSAPublicKeyPEM))
XCTAssertThrowsError(try _RSA.Encryption.PublicKey(unsafePEMRepresentation: _2050BitRSAPublicKeyPEM))
}
// The raw number encryption key initializers do not require the key modulus bit length to be a multiple of 8.
func testMaximumEncryptSizeWithNonByteAlignedModulus() throws {
// Modulus of a 2050-bit key: `openssl rsa -in key.pem -noout -modulus`.
let _2050BitModulus = Data(
base64Encoded:
"AsVUpbXku/3jeXV85/kXcgKVfCSSC0Gl2mToMZfxRC1oV6uJWFJOvtJHhbX" +
"S70rHbAQGZau1U/Lx8n8aoXKW9EZI04Vn1YUdgY8zvEzSwPppShimSX6ExN" +
"6+6PfRL+F/h+EMQsgAvKMgCstZcgwOME+zhQQV7VyZnkPz22ArjDMqqwllI" +
"FS+PKytedEMR0NFPV7Bgpxe9F/zzD3mymOtDkt+qU2IZou+4dJmomOMltpB" +
"zX4HhjG3N10NfUq+Nn+cyntACEH8yvdb+jOT2hCKSQH5viTwzVn9vkShFWv" +
"d4DYrk2dvqYFI3+7rfJmOTBJ+32YQnmXjQYzU7il49yanT98="
)!
let publicExponent = Data(base64Encoded: "AQAB")!
let publicKey = try _RSA.Encryption.PublicKey(n: _2050BitModulus, e: publicExponent)
XCTAssertEqual(2050, publicKey.keySizeInBits)
XCTAssertEqual(215, publicKey.maximumEncryptSize(with: .PKCS1_OAEP))
XCTAssertEqual(191, publicKey.maximumEncryptSize(with: .PKCS1_OAEP_SHA256))
}
func testKeysAreSendable() {
func assertSendable<T: Sendable>(_: T.Type) {}
assertSendable(_RSA.Encryption.PublicKey.self)
assertSendable(_RSA.Encryption.PrivateKey.self)
}
func testPKCS1() throws {
let pubKeyPEM = """
-----BEGIN RSA PUBLIC KEY-----
+19 -373
View File
@@ -361,10 +361,8 @@ final class TestRSASigning: XCTestCase {
try XCTAssertThrowsError((_RSA.Signing.PrivateKey(keySize: .init(bitCount: 1024)), 1024))
}
// The default initializers require a modulus of at least 2048 bits.
func testRejectKeysBelow2048BitMinimum() throws {
// Equivalent key: `openssl genrsa -traditional 512`, converted to the encodings below.
let _512BitRSAPrivateKeyPEM = """
func testRejectSmallKeys() throws {
let smallRSAPrivateKeyPEM = """
-----BEGIN RSA PRIVATE KEY-----
MIIBPAIBAAJBAOJMTCxw5nMxXCQgsOIRVCu8z1t58s5r2qSqwpZQvQZLlVrhYTpE
nHFD6QbX8lHkk1Z3HZ1vjxW89ARPh94cG+0CAwEAAQJBAMdmOVyTYswvuyPuVk3s
@@ -376,14 +374,14 @@ final class TestRSASigning: XCTestCase {
-----END RSA PRIVATE KEY-----
"""
let _512BitRSAPublicKeyPEM = """
let smallRSAPublicKeyPEM = """
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOJMTCxw5nMxXCQgsOIRVCu8z1t58s5r
2qSqwpZQvQZLlVrhYTpEnHFD6QbX8lHkk1Z3HZ1vjxW89ARPh94cG+0CAwEAAQ==
-----END PUBLIC KEY-----
"""
let _512BitRSAPrivateKeyPKCS8PEM = """
let smallRSAPrivateKeyPKCS8PEM = """
-----BEGIN PRIVATE KEY-----
MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA4kxMLHDmczFcJCCw
4hFUK7zPW3nyzmvapKrCllC9BkuVWuFhOkSccUPpBtfyUeSTVncdnW+PFbz0BE+H
@@ -396,7 +394,7 @@ final class TestRSASigning: XCTestCase {
-----END PRIVATE KEY-----
"""
let _512BitRSAPrivateKeyDER = Data(base64Encoded:
let smallRSAPrivateKeyDER = Data(base64Encoded:
"MIIBPAIBAAJBAOJMTCxw5nMxXCQgsOIRVCu8z1t58s5r2qSqwpZQvQZLlVr" +
"hYTpEnHFD6QbX8lHkk1Z3HZ1vjxW89ARPh94cG+0CAwEAAQJBAMdmOVyTYs" +
"wvuyPuVk3svQEJDqFpFATFTlP4TxuKKvTmbdQuVCorMmLLKThDI3pDNWKuA" +
@@ -407,7 +405,7 @@ final class TestRSASigning: XCTestCase {
"7MWbrFpUouirbQ="
)!
let _512BitRSAPrivateKeyPKCS8DER = Data(base64Encoded:
let smallRSAPrivateKeyPKCS8DER = Data(base64Encoded:
"MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA4kxMLHDmczF" +
"cJCCw4hFUK7zPW3nyzmvapKrCllC9BkuVWuFhOkSccUPpBtfyUeSTVncdnW" +
"+PFbz0BE+H3hwb7QIDAQABAkEAx2Y5XJNizC+7I+5WTey9AQkOoWkUBMVOU" +
@@ -418,282 +416,18 @@ final class TestRSASigning: XCTestCase {
"w8CIQCNHhOCOnp3lmwZQr0gcaw1Y/XJKtqDsxZusWlSi6KttA=="
)!
let _512BitRSAPublicKeyDER = Data(base64Encoded:
let smallRSAPublicKeyDER = Data(base64Encoded:
"MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOJMTCxw5nMxXCQgsOIRVCu8z1t" +
"58s5r2qSqwpZQvQZLlVrhYTpEnHFD6QbX8lHkk1Z3HZ1vjxW89ARPh94cG+" +
"0CAwEAAQ=="
)!
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: _512BitRSAPrivateKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: _512BitRSAPrivateKeyPKCS8PEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: _512BitRSAPrivateKeyDER))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: _512BitRSAPrivateKeyPKCS8DER))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(pemRepresentation: _512BitRSAPublicKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(derRepresentation: _512BitRSAPublicKeyDER))
// Generated via `openssl genrsa -traditional 2047`, then converted to the encodings below.
let _2047BitRSAPrivateKeyPEM = """
-----BEGIN RSA PRIVATE KEY-----
MIIEoAIBAAKCAQBXog86uwpuCobeXXokHAePMu15O2Cwfvwx7/EzZl6jY70ConNX
mzR5U39kQQpFa0dxRQdgUA8YpU5/8aILp3Yv0S2BssiuqdL5IkzdBzLNRhSQabuM
+vyCQjImHF/bA28+5DKJ9uzIhywA9JS2o/4TtE6mLqWbFAY+dM716llarKJgzLh/
Vg0mH6H5vDoo4D6z+M2jQRiUbV+yIiiaY8/SMyLltsZeEl/hx/NyACPSUAClVlsj
vRRZzQl8oDybMVvUAbrIwR+ZVQltdqVgx5zVf8G3BHi7lUdyqxIt0QWQRBTTd1tY
sSOKmVhYB+DvPv2IJKGXqKo+XKQBLmm9UIuxAgMBAAECggEAN/6hZJGnNHEdhHCO
XwxZ+DI+czxxp9U8KFx87q72wcg1Ob27nbraaLvlppW4jmriF4pYED6XptPZuP8Y
4AF9D0jFnx4yBQkWeYJlQsYau/ePpEcrRAYL2t+ZU6jFxxgGuVTuxiE1Y1ybzXB6
pclbzBNmPeGIh/LfmoDgzVmVBs6FhBrl8z+eWciISgskTaESkboiV+HAzDBJ23gP
LD0fjk69Dw75MS7QHBYm5jDIpXFvh+nPJOfwIAuaEQ9ZaF3Uh8zjBOyhtOSO9cdV
wXME4sIvA7IqlGoacxUtjyoWarPqk/V4UWl7/Q8gZlRagqjaJ+DqpqrD6UFCxwvw
KCyJ0QKBgQDTV7joBHuuw/RuDe8VwxUuRJTIcdrn6g2Kn3CxV9YLJhxr1doEmw3Y
DASY7zddkgJjssbkub5FhySAlqOIz5ok62erHMsyC90VXqWDC1uFHW6EQh/N/S/A
vgEuyIJ/dtxXYLFyozm0Az98A37nGGTSt9tphKsTPiHS1jOB3f9DbwKBgGomcW7T
Slq0+VSGniD+ciB71UMrW9FcF9qsnTPXQGZV4JqpLvE/tEq7uyr/Dp6l3mstVmtL
tBjkPef32oz3JXo32IWS37VZlu+3I2v7VQThFLnc3F0KUcZmH1Uy1my8itjP6jIf
wNwiUObilCubgiGEVxfMb0G7juMETZYyuRLfAoGAVwIFcRfvZ4rrBagc5yOyg6Le
cgtVqSbVvl1Xwts7lslw6ABZyo2fTHPeLKxHafFjpHIEqkPCDtPNdlcOKpP1jP+R
ZYPsL8VslpCpqWKyogH07uReParfzwUqbX1FJH7lxd9cDqseZXr01vSFeVS0pX/m
B/IDkF+DA08GU4/2uGcCgYAV1CP9e1vN/WtMc4ZvGIQVpAF+F5uBGSQapuaI85nd
sYlHpMTvfX8w4xwhQmQaQdfUSHV+CQpXGBCW9EQwOt6tHHDdPw/b9jlwwEN7gCrC
nxqpAf8a7vVUDEojNhocMEWJQnBRsG/zlOb4I93+fbMr+1ABp9u1M8G1c3wVCAdB
FwKBgF8sJlG58EKSfdvhVNDRq4hC/yjcI6987rg2fmeX9QUYiwReniaesEoBdeHz
OYWR3DtC5SNiDKuj7QmnRvNcbFwBz5dGOdiXytRtLkpwDArY/hV/hqeSH1nHU0fp
LUScnTZr95HkLFIle1JCFXw0viGHKEBkdFvcuXIFON9KNTA/
-----END RSA PRIVATE KEY-----
"""
let _2047BitRSAPublicKeyPEM = """
-----BEGIN PUBLIC KEY-----
MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBXog86uwpuCobeXXokHAeP
Mu15O2Cwfvwx7/EzZl6jY70ConNXmzR5U39kQQpFa0dxRQdgUA8YpU5/8aILp3Yv
0S2BssiuqdL5IkzdBzLNRhSQabuM+vyCQjImHF/bA28+5DKJ9uzIhywA9JS2o/4T
tE6mLqWbFAY+dM716llarKJgzLh/Vg0mH6H5vDoo4D6z+M2jQRiUbV+yIiiaY8/S
MyLltsZeEl/hx/NyACPSUAClVlsjvRRZzQl8oDybMVvUAbrIwR+ZVQltdqVgx5zV
f8G3BHi7lUdyqxIt0QWQRBTTd1tYsSOKmVhYB+DvPv2IJKGXqKo+XKQBLmm9UIux
AgMBAAE=
-----END PUBLIC KEY-----
"""
let _2047BitRSAPrivateKeyPKCS8PEM = """
-----BEGIN PRIVATE KEY-----
MIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAFeiDzq7Cm4Kht5d
eiQcB48y7Xk7YLB+/DHv8TNmXqNjvQKic1ebNHlTf2RBCkVrR3FFB2BQDxilTn/x
ogundi/RLYGyyK6p0vkiTN0HMs1GFJBpu4z6/IJCMiYcX9sDbz7kMon27MiHLAD0
lLaj/hO0TqYupZsUBj50zvXqWVqsomDMuH9WDSYfofm8OijgPrP4zaNBGJRtX7Ii
KJpjz9IzIuW2xl4SX+HH83IAI9JQAKVWWyO9FFnNCXygPJsxW9QBusjBH5lVCW12
pWDHnNV/wbcEeLuVR3KrEi3RBZBEFNN3W1ixI4qZWFgH4O8+/YgkoZeoqj5cpAEu
ab1Qi7ECAwEAAQKCAQA3/qFkkac0cR2EcI5fDFn4Mj5zPHGn1TwoXHzurvbByDU5
vbudutpou+WmlbiOauIXilgQPpem09m4/xjgAX0PSMWfHjIFCRZ5gmVCxhq794+k
RytEBgva35lTqMXHGAa5VO7GITVjXJvNcHqlyVvME2Y94YiH8t+agODNWZUGzoWE
GuXzP55ZyIhKCyRNoRKRuiJX4cDMMEnbeA8sPR+OTr0PDvkxLtAcFibmMMilcW+H
6c8k5/AgC5oRD1loXdSHzOME7KG05I71x1XBcwTiwi8DsiqUahpzFS2PKhZqs+qT
9XhRaXv9DyBmVFqCqNon4OqmqsPpQULHC/AoLInRAoGBANNXuOgEe67D9G4N7xXD
FS5ElMhx2ufqDYqfcLFX1gsmHGvV2gSbDdgMBJjvN12SAmOyxuS5vkWHJICWo4jP
miTrZ6scyzIL3RVepYMLW4UdboRCH839L8C+AS7Ign923FdgsXKjObQDP3wDfucY
ZNK322mEqxM+IdLWM4Hd/0NvAoGAaiZxbtNKWrT5VIaeIP5yIHvVQytb0VwX2qyd
M9dAZlXgmqku8T+0Sru7Kv8OnqXeay1Wa0u0GOQ95/fajPclejfYhZLftVmW77cj
a/tVBOEUudzcXQpRxmYfVTLWbLyK2M/qMh/A3CJQ5uKUK5uCIYRXF8xvQbuO4wRN
ljK5Et8CgYBXAgVxF+9niusFqBznI7KDot5yC1WpJtW+XVfC2zuWyXDoAFnKjZ9M
c94srEdp8WOkcgSqQ8IO0812Vw4qk/WM/5Flg+wvxWyWkKmpYrKiAfTu5F49qt/P
BSptfUUkfuXF31wOqx5levTW9IV5VLSlf+YH8gOQX4MDTwZTj/a4ZwKBgBXUI/17
W839a0xzhm8YhBWkAX4Xm4EZJBqm5ojzmd2xiUekxO99fzDjHCFCZBpB19RIdX4J
ClcYEJb0RDA63q0ccN0/D9v2OXDAQ3uAKsKfGqkB/xru9VQMSiM2GhwwRYlCcFGw
b/OU5vgj3f59syv7UAGn27UzwbVzfBUIB0EXAoGAXywmUbnwQpJ92+FU0NGriEL/
KNwjr3zuuDZ+Z5f1BRiLBF6eJp6wSgF14fM5hZHcO0LlI2IMq6PtCadG81xsXAHP
l0Y52JfK1G0uSnAMCtj+FX+Gp5IfWcdTR+ktRJydNmv3keQsUiV7UkIVfDS+IYco
QGR0W9y5cgU430o1MD8=
-----END PRIVATE KEY-----
"""
let _2047BitRSAPrivateKeyDER = Data(base64Encoded:
"MIIEoAIBAAKCAQBXog86uwpuCobeXXokHAePMu15O2Cwfvwx7/EzZl6jY70" +
"ConNXmzR5U39kQQpFa0dxRQdgUA8YpU5/8aILp3Yv0S2BssiuqdL5IkzdBz" +
"LNRhSQabuM+vyCQjImHF/bA28+5DKJ9uzIhywA9JS2o/4TtE6mLqWbFAY+d" +
"M716llarKJgzLh/Vg0mH6H5vDoo4D6z+M2jQRiUbV+yIiiaY8/SMyLltsZe" +
"El/hx/NyACPSUAClVlsjvRRZzQl8oDybMVvUAbrIwR+ZVQltdqVgx5zVf8G" +
"3BHi7lUdyqxIt0QWQRBTTd1tYsSOKmVhYB+DvPv2IJKGXqKo+XKQBLmm9UI" +
"uxAgMBAAECggEAN/6hZJGnNHEdhHCOXwxZ+DI+czxxp9U8KFx87q72wcg1O" +
"b27nbraaLvlppW4jmriF4pYED6XptPZuP8Y4AF9D0jFnx4yBQkWeYJlQsYa" +
"u/ePpEcrRAYL2t+ZU6jFxxgGuVTuxiE1Y1ybzXB6pclbzBNmPeGIh/LfmoD" +
"gzVmVBs6FhBrl8z+eWciISgskTaESkboiV+HAzDBJ23gPLD0fjk69Dw75MS" +
"7QHBYm5jDIpXFvh+nPJOfwIAuaEQ9ZaF3Uh8zjBOyhtOSO9cdVwXME4sIvA" +
"7IqlGoacxUtjyoWarPqk/V4UWl7/Q8gZlRagqjaJ+DqpqrD6UFCxwvwKCyJ" +
"0QKBgQDTV7joBHuuw/RuDe8VwxUuRJTIcdrn6g2Kn3CxV9YLJhxr1doEmw3" +
"YDASY7zddkgJjssbkub5FhySAlqOIz5ok62erHMsyC90VXqWDC1uFHW6EQh" +
"/N/S/AvgEuyIJ/dtxXYLFyozm0Az98A37nGGTSt9tphKsTPiHS1jOB3f9Db" +
"wKBgGomcW7TSlq0+VSGniD+ciB71UMrW9FcF9qsnTPXQGZV4JqpLvE/tEq7" +
"uyr/Dp6l3mstVmtLtBjkPef32oz3JXo32IWS37VZlu+3I2v7VQThFLnc3F0" +
"KUcZmH1Uy1my8itjP6jIfwNwiUObilCubgiGEVxfMb0G7juMETZYyuRLfAo" +
"GAVwIFcRfvZ4rrBagc5yOyg6LecgtVqSbVvl1Xwts7lslw6ABZyo2fTHPeL" +
"KxHafFjpHIEqkPCDtPNdlcOKpP1jP+RZYPsL8VslpCpqWKyogH07uReParf" +
"zwUqbX1FJH7lxd9cDqseZXr01vSFeVS0pX/mB/IDkF+DA08GU4/2uGcCgYA" +
"V1CP9e1vN/WtMc4ZvGIQVpAF+F5uBGSQapuaI85ndsYlHpMTvfX8w4xwhQm" +
"QaQdfUSHV+CQpXGBCW9EQwOt6tHHDdPw/b9jlwwEN7gCrCnxqpAf8a7vVUD" +
"EojNhocMEWJQnBRsG/zlOb4I93+fbMr+1ABp9u1M8G1c3wVCAdBFwKBgF8s" +
"JlG58EKSfdvhVNDRq4hC/yjcI6987rg2fmeX9QUYiwReniaesEoBdeHzOYW" +
"R3DtC5SNiDKuj7QmnRvNcbFwBz5dGOdiXytRtLkpwDArY/hV/hqeSH1nHU0" +
"fpLUScnTZr95HkLFIle1JCFXw0viGHKEBkdFvcuXIFON9KNTA/"
)!
let _2047BitRSAPrivateKeyPKCS8DER = Data(base64Encoded:
"MIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAFeiDzq7Cm4" +
"Kht5deiQcB48y7Xk7YLB+/DHv8TNmXqNjvQKic1ebNHlTf2RBCkVrR3FFB2" +
"BQDxilTn/xogundi/RLYGyyK6p0vkiTN0HMs1GFJBpu4z6/IJCMiYcX9sDb" +
"z7kMon27MiHLAD0lLaj/hO0TqYupZsUBj50zvXqWVqsomDMuH9WDSYfofm8" +
"OijgPrP4zaNBGJRtX7IiKJpjz9IzIuW2xl4SX+HH83IAI9JQAKVWWyO9FFn" +
"NCXygPJsxW9QBusjBH5lVCW12pWDHnNV/wbcEeLuVR3KrEi3RBZBEFNN3W1" +
"ixI4qZWFgH4O8+/YgkoZeoqj5cpAEuab1Qi7ECAwEAAQKCAQA3/qFkkac0c" +
"R2EcI5fDFn4Mj5zPHGn1TwoXHzurvbByDU5vbudutpou+WmlbiOauIXilgQ" +
"Ppem09m4/xjgAX0PSMWfHjIFCRZ5gmVCxhq794+kRytEBgva35lTqMXHGAa" +
"5VO7GITVjXJvNcHqlyVvME2Y94YiH8t+agODNWZUGzoWEGuXzP55ZyIhKCy" +
"RNoRKRuiJX4cDMMEnbeA8sPR+OTr0PDvkxLtAcFibmMMilcW+H6c8k5/AgC" +
"5oRD1loXdSHzOME7KG05I71x1XBcwTiwi8DsiqUahpzFS2PKhZqs+qT9XhR" +
"aXv9DyBmVFqCqNon4OqmqsPpQULHC/AoLInRAoGBANNXuOgEe67D9G4N7xX" +
"DFS5ElMhx2ufqDYqfcLFX1gsmHGvV2gSbDdgMBJjvN12SAmOyxuS5vkWHJI" +
"CWo4jPmiTrZ6scyzIL3RVepYMLW4UdboRCH839L8C+AS7Ign923FdgsXKjO" +
"bQDP3wDfucYZNK322mEqxM+IdLWM4Hd/0NvAoGAaiZxbtNKWrT5VIaeIP5y" +
"IHvVQytb0VwX2qydM9dAZlXgmqku8T+0Sru7Kv8OnqXeay1Wa0u0GOQ95/f" +
"ajPclejfYhZLftVmW77cja/tVBOEUudzcXQpRxmYfVTLWbLyK2M/qMh/A3C" +
"JQ5uKUK5uCIYRXF8xvQbuO4wRNljK5Et8CgYBXAgVxF+9niusFqBznI7KDo" +
"t5yC1WpJtW+XVfC2zuWyXDoAFnKjZ9Mc94srEdp8WOkcgSqQ8IO0812Vw4q" +
"k/WM/5Flg+wvxWyWkKmpYrKiAfTu5F49qt/PBSptfUUkfuXF31wOqx5levT" +
"W9IV5VLSlf+YH8gOQX4MDTwZTj/a4ZwKBgBXUI/17W839a0xzhm8YhBWkAX" +
"4Xm4EZJBqm5ojzmd2xiUekxO99fzDjHCFCZBpB19RIdX4JClcYEJb0RDA63" +
"q0ccN0/D9v2OXDAQ3uAKsKfGqkB/xru9VQMSiM2GhwwRYlCcFGwb/OU5vgj" +
"3f59syv7UAGn27UzwbVzfBUIB0EXAoGAXywmUbnwQpJ92+FU0NGriEL/KNw" +
"jr3zuuDZ+Z5f1BRiLBF6eJp6wSgF14fM5hZHcO0LlI2IMq6PtCadG81xsXA" +
"HPl0Y52JfK1G0uSnAMCtj+FX+Gp5IfWcdTR+ktRJydNmv3keQsUiV7UkIVf" +
"DS+IYcoQGR0W9y5cgU430o1MD8="
)!
let _2047BitRSAPublicKeyDER = Data(base64Encoded:
"MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBXog86uwpuCobeXXo" +
"kHAePMu15O2Cwfvwx7/EzZl6jY70ConNXmzR5U39kQQpFa0dxRQdgUA8YpU" +
"5/8aILp3Yv0S2BssiuqdL5IkzdBzLNRhSQabuM+vyCQjImHF/bA28+5DKJ9" +
"uzIhywA9JS2o/4TtE6mLqWbFAY+dM716llarKJgzLh/Vg0mH6H5vDoo4D6z" +
"+M2jQRiUbV+yIiiaY8/SMyLltsZeEl/hx/NyACPSUAClVlsjvRRZzQl8oDy" +
"bMVvUAbrIwR+ZVQltdqVgx5zVf8G3BHi7lUdyqxIt0QWQRBTTd1tYsSOKmV" +
"hYB+DvPv2IJKGXqKo+XKQBLmm9UIuxAgMBAAE="
)!
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: _2047BitRSAPrivateKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: _2047BitRSAPrivateKeyPKCS8PEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: _2047BitRSAPrivateKeyDER))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: _2047BitRSAPrivateKeyPKCS8DER))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(pemRepresentation: _2047BitRSAPublicKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(derRepresentation: _2047BitRSAPublicKeyDER))
}
// The unsafe initializers require a modulus of at least 1024 bits. 1017 bits occupies 128 bytes,
// the same as 1024.
func testRejectKeysBelow1024BitMinimum() throws {
// Generated via `openssl genrsa -traditional 1017`, then converted to the encodings below.
let _1017BitRSAPrivateKeyPEM = """
-----BEGIN RSA PRIVATE KEY-----
MIICWAIBAAKBgAFVByFodT87fB0oWSEkwybEeqayqUavihFHLu3Ss/XuUxVosi5z
lnzxbta17k8WXJYXa7OZC4jicxQer5xrZr9Op1k99zlJUbMtznl+BiSRKoAOjmsQ
mLPU5er1hF1MnHUJsS1SgoTbR0CLPFNh4ai7WtOY6bWv/k9B03xNPeRVAgMBAAEC
gYAAhvHcYWZL0DELpKSoPdDPLV5PSlE7fEjJD37dcsvtXBIaXaRsRybcZ/jxE2qq
dvHKHphqp/vtfZYF9yKMZd9xcsxceGTRWR9kxQdKe6r9y1gzF1piRAyU4UcyjzFc
h4w4psX3AqqN4qpQJgYUZamSRnnoJ3Vq7u/oR3W0P+PL3QJAGTnDt6UAHahmdryj
KMFyQan+GU/eo6KDD84blk1L8axsEHtKUvtVBOWPRaR2WJI+q26adZbVvp707brW
8sa+9wJADYTjZOw5A2C+mXlbBwV78cLrXwsZ/+5zrlGH5dMuDYbuJH3InXK/SguL
f/OqQmrtUwSmL5QfQ//QPbUpsioIEwJABg1h8/HWsUbyLpLb4q9nJnIO0SvkkwYu
w+ADpnAtRHLGCr5J+tbqcx5Q3biz3FRaTO9gh84EwpOI2HD3mZAtyQJABk3sRQor
5DlfaO7A1ltmW23MmXvx2fn3FFmNCE4c8c30jCvkPBhgwET1/utAgMygc9B9Nz7Z
/bn0AHLVSPJ05QJAFJqFaLd6j9v/WK7noJk0f7lWTZnfeRkZPxJh4AobfnGKV1yO
+mB6mLJo/StOBrM82IdCBXTHRYYS2zUCCoJG1Q==
-----END RSA PRIVATE KEY-----
"""
let _1017BitRSAPublicKeyPEM = """
-----BEGIN PUBLIC KEY-----
MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgAFVByFodT87fB0oWSEkwybEeqay
qUavihFHLu3Ss/XuUxVosi5zlnzxbta17k8WXJYXa7OZC4jicxQer5xrZr9Op1k9
9zlJUbMtznl+BiSRKoAOjmsQmLPU5er1hF1MnHUJsS1SgoTbR0CLPFNh4ai7WtOY
6bWv/k9B03xNPeRVAgMBAAE=
-----END PUBLIC KEY-----
"""
let _1017BitRSAPrivateKeyPKCS8PEM = """
-----BEGIN PRIVATE KEY-----
MIICcgIBADANBgkqhkiG9w0BAQEFAASCAlwwggJYAgEAAoGAAVUHIWh1Pzt8HShZ
ISTDJsR6prKpRq+KEUcu7dKz9e5TFWiyLnOWfPFu1rXuTxZclhdrs5kLiOJzFB6v
nGtmv06nWT33OUlRsy3OeX4GJJEqgA6OaxCYs9Tl6vWEXUycdQmxLVKChNtHQIs8
U2HhqLta05jpta/+T0HTfE095FUCAwEAAQKBgACG8dxhZkvQMQukpKg90M8tXk9K
UTt8SMkPft1yy+1cEhpdpGxHJtxn+PETaqp28coemGqn++19lgX3Ioxl33FyzFx4
ZNFZH2TFB0p7qv3LWDMXWmJEDJThRzKPMVyHjDimxfcCqo3iqlAmBhRlqZJGeegn
dWru7+hHdbQ/48vdAkAZOcO3pQAdqGZ2vKMowXJBqf4ZT96jooMPzhuWTUvxrGwQ
e0pS+1UE5Y9FpHZYkj6rbpp1ltW+nvTtutbyxr73AkANhONk7DkDYL6ZeVsHBXvx
wutfCxn/7nOuUYfl0y4Nhu4kfcidcr9KC4t/86pCau1TBKYvlB9D/9A9tSmyKggT
AkAGDWHz8daxRvIuktvir2cmcg7RK+STBi7D4AOmcC1EcsYKvkn61upzHlDduLPc
VFpM72CHzgTCk4jYcPeZkC3JAkAGTexFCivkOV9o7sDWW2ZbbcyZe/HZ+fcUWY0I
ThzxzfSMK+Q8GGDARPX+60CAzKBz0H03Ptn9ufQActVI8nTlAkAUmoVot3qP2/9Y
ruegmTR/uVZNmd95GRk/EmHgCht+cYpXXI76YHqYsmj9K04GszzYh0IFdMdFhhLb
NQIKgkbV
-----END PRIVATE KEY-----
"""
let _1017BitRSAPrivateKeyDER = Data(base64Encoded:
"MIICWAIBAAKBgAFVByFodT87fB0oWSEkwybEeqayqUavihFHLu3Ss/XuUxV" +
"osi5zlnzxbta17k8WXJYXa7OZC4jicxQer5xrZr9Op1k99zlJUbMtznl+Bi" +
"SRKoAOjmsQmLPU5er1hF1MnHUJsS1SgoTbR0CLPFNh4ai7WtOY6bWv/k9B0" +
"3xNPeRVAgMBAAECgYAAhvHcYWZL0DELpKSoPdDPLV5PSlE7fEjJD37dcsvt" +
"XBIaXaRsRybcZ/jxE2qqdvHKHphqp/vtfZYF9yKMZd9xcsxceGTRWR9kxQd" +
"Ke6r9y1gzF1piRAyU4UcyjzFch4w4psX3AqqN4qpQJgYUZamSRnnoJ3Vq7u" +
"/oR3W0P+PL3QJAGTnDt6UAHahmdryjKMFyQan+GU/eo6KDD84blk1L8axsE" +
"HtKUvtVBOWPRaR2WJI+q26adZbVvp707brW8sa+9wJADYTjZOw5A2C+mXlb" +
"BwV78cLrXwsZ/+5zrlGH5dMuDYbuJH3InXK/SguLf/OqQmrtUwSmL5QfQ//" +
"QPbUpsioIEwJABg1h8/HWsUbyLpLb4q9nJnIO0SvkkwYuw+ADpnAtRHLGCr" +
"5J+tbqcx5Q3biz3FRaTO9gh84EwpOI2HD3mZAtyQJABk3sRQor5DlfaO7A1" +
"ltmW23MmXvx2fn3FFmNCE4c8c30jCvkPBhgwET1/utAgMygc9B9Nz7Z/bn0" +
"AHLVSPJ05QJAFJqFaLd6j9v/WK7noJk0f7lWTZnfeRkZPxJh4AobfnGKV1y" +
"O+mB6mLJo/StOBrM82IdCBXTHRYYS2zUCCoJG1Q=="
)!
let _1017BitRSAPrivateKeyPKCS8DER = Data(base64Encoded:
"MIICcgIBADANBgkqhkiG9w0BAQEFAASCAlwwggJYAgEAAoGAAVUHIWh1Pzt" +
"8HShZISTDJsR6prKpRq+KEUcu7dKz9e5TFWiyLnOWfPFu1rXuTxZclhdrs5" +
"kLiOJzFB6vnGtmv06nWT33OUlRsy3OeX4GJJEqgA6OaxCYs9Tl6vWEXUycd" +
"QmxLVKChNtHQIs8U2HhqLta05jpta/+T0HTfE095FUCAwEAAQKBgACG8dxh" +
"ZkvQMQukpKg90M8tXk9KUTt8SMkPft1yy+1cEhpdpGxHJtxn+PETaqp28co" +
"emGqn++19lgX3Ioxl33FyzFx4ZNFZH2TFB0p7qv3LWDMXWmJEDJThRzKPMV" +
"yHjDimxfcCqo3iqlAmBhRlqZJGeegndWru7+hHdbQ/48vdAkAZOcO3pQAdq" +
"GZ2vKMowXJBqf4ZT96jooMPzhuWTUvxrGwQe0pS+1UE5Y9FpHZYkj6rbpp1" +
"ltW+nvTtutbyxr73AkANhONk7DkDYL6ZeVsHBXvxwutfCxn/7nOuUYfl0y4" +
"Nhu4kfcidcr9KC4t/86pCau1TBKYvlB9D/9A9tSmyKggTAkAGDWHz8daxRv" +
"Iuktvir2cmcg7RK+STBi7D4AOmcC1EcsYKvkn61upzHlDduLPcVFpM72CHz" +
"gTCk4jYcPeZkC3JAkAGTexFCivkOV9o7sDWW2ZbbcyZe/HZ+fcUWY0IThzx" +
"zfSMK+Q8GGDARPX+60CAzKBz0H03Ptn9ufQActVI8nTlAkAUmoVot3qP2/9" +
"YruegmTR/uVZNmd95GRk/EmHgCht+cYpXXI76YHqYsmj9K04GszzYh0IFdM" +
"dFhhLbNQIKgkbV"
)!
let _1017BitRSAPublicKeyDER = Data(base64Encoded:
"MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgAFVByFodT87fB0oWSEkwyb" +
"EeqayqUavihFHLu3Ss/XuUxVosi5zlnzxbta17k8WXJYXa7OZC4jicxQer5" +
"xrZr9Op1k99zlJUbMtznl+BiSRKoAOjmsQmLPU5er1hF1MnHUJsS1SgoTbR" +
"0CLPFNh4ai7WtOY6bWv/k9B03xNPeRVAgMBAAE="
)!
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey(unsafePEMRepresentation: _1017BitRSAPrivateKeyPEM)
)
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey(unsafePEMRepresentation: _1017BitRSAPrivateKeyPKCS8PEM)
)
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey(unsafeDERRepresentation: _1017BitRSAPrivateKeyDER)
)
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey(unsafeDERRepresentation: _1017BitRSAPrivateKeyPKCS8DER)
)
XCTAssertThrowsError(
try _RSA.Signing.PublicKey(unsafePEMRepresentation: _1017BitRSAPublicKeyPEM)
)
XCTAssertThrowsError(
try _RSA.Signing.PublicKey(unsafeDERRepresentation: _1017BitRSAPublicKeyDER)
)
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: smallRSAPrivateKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: smallRSAPrivateKeyPKCS8PEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: smallRSAPrivateKeyDER))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: smallRSAPrivateKeyPKCS8DER))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(pemRepresentation: smallRSAPublicKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(derRepresentation: smallRSAPublicKeyDER))
}
func testHandlingNonStandardKeys() throws {
@@ -841,12 +575,12 @@ final class TestRSASigning: XCTestCase {
"En7fZhCeZeNBjNTuKXj3JqdP3wIDAQAB"
)!
XCTAssertEqual(try _RSA.Signing.PrivateKey(pemRepresentation: awkwardRSAPrivateKeyPEM).keySizeInBits, 2050)
XCTAssertEqual(try _RSA.Signing.PrivateKey(pemRepresentation: awkwardRSAPrivateKeyPKCS8PEM).keySizeInBits, 2050)
XCTAssertEqual(try _RSA.Signing.PrivateKey(derRepresentation: awkwardRSAPrivateKeyDER).keySizeInBits, 2050)
XCTAssertEqual(try _RSA.Signing.PrivateKey(derRepresentation: awkwardRSAPrivateKeyPKCS8DER).keySizeInBits, 2050)
XCTAssertEqual(try _RSA.Signing.PublicKey(pemRepresentation: awkwardRSAPublicKeyPEM).keySizeInBits, 2050)
XCTAssertEqual(try _RSA.Signing.PublicKey(derRepresentation: awkwardRSAPublicKeyDER).keySizeInBits, 2050)
XCTAssertEqual(try _RSA.Signing.PrivateKey(pemRepresentation: awkwardRSAPrivateKeyPEM).keySizeInBits, 2056)
XCTAssertEqual(try _RSA.Signing.PrivateKey(pemRepresentation: awkwardRSAPrivateKeyPKCS8PEM).keySizeInBits, 2056)
XCTAssertEqual(try _RSA.Signing.PrivateKey(derRepresentation: awkwardRSAPrivateKeyDER).keySizeInBits, 2056)
XCTAssertEqual(try _RSA.Signing.PrivateKey(derRepresentation: awkwardRSAPrivateKeyPKCS8DER).keySizeInBits, 2056)
XCTAssertEqual(try _RSA.Signing.PublicKey(pemRepresentation: awkwardRSAPublicKeyPEM).keySizeInBits, 2056)
XCTAssertEqual(try _RSA.Signing.PublicKey(derRepresentation: awkwardRSAPublicKeyDER).keySizeInBits, 2056)
}
func testMangledPKCS8DERKey() throws {
@@ -1036,13 +770,6 @@ final class TestRSASigning: XCTestCase {
n: bytesValues.randomElement()!,
e: bytesValues.randomElement()!
)
// Modulus of the 512-bit key above: `openssl rsa -in key.pem -noout -modulus`.
let _512BitModulus =
"e24c4c2c70e673315c2420b0e211542bbccf5b79f2ce6bdaa4aac29650bd064b"
+ "955ae1613a449c7143e906d7f251e49356771d9d6f8f15bcf4044f87de1c1bed"
XCTAssertThrowsError(
try _RSA.Signing.PublicKey(n: Data(hexString: _512BitModulus), e: Data(hexString: "010001"))
)
}
func testConstructAndUseKeyFromRSANumbersWhileRecoveringPrimes() throws {
@@ -1062,70 +789,6 @@ final class TestRSASigning: XCTestCase {
}
}
func testConstructKeyFromRSANumbersWithDegenerateExponentsThrows() throws {
// e * d == 1 makes g^(e * d - 1) == 1 for every base, so prime recovery can never
// make progress. This must throw rather than retry forever.
var n = [UInt8](repeating: 0xA7, count: 256)
n[255] = 0x01
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey._createFromNumbers(n: n, e: [1] as [UInt8], d: [1] as [UInt8])
)
XCTAssertThrowsError(
try _RSA.Encryption.PrivateKey._createFromNumbers(n: n, e: [1] as [UInt8], d: [1] as [UInt8])
)
XCTAssertThrowsError(
try _RSA.BlindSigning.PrivateKey<SHA384>._createFromNumbers(
n: n, e: [1] as [UInt8], d: [1] as [UInt8], parameters: .RSABSSA_SHA384_PSS_Randomized
)
)
}
func testExtractPrimeFactorsGivesUpWhenEveryBaseIsTrivial() throws {
// n = 7 is prime and e * d - 1 == 24 == 2^3 * 3, so g^3 is 1 or n - 1 for every base g
// (the only cubic residues mod 7). The attempt limit must still apply.
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 7, e: 5, d: 5))
// e * d == 1 gives an exponent of 0, so g^0 == 1 for every base.
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 3233, e: 1, d: 1))
}
func testExtractPrimeFactorsRejectsOversizedNumbers() throws {
// d == 2753 is valid for n == 3233, e == 17. Adding lambda(n) == 780 keeps the numbers
// consistent, so only the range check rejects d >= n.
XCTAssertNoThrow(try _RSA.extractPrimeFactors(n: 3233, e: 17, d: 2753))
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 3233, e: 17, d: 2753 + 780))
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 3233, e: 17 + 780 * 5, d: 2753))
// e * d - 1 == 2^9992, so without the range check the squaring loop runs 9991 times
// per attempt.
var n = [UInt8](repeating: 0xA7, count: 256)
n[255] = 0x01
var d = [UInt8](repeating: 0, count: 1250)
d[0] = 0x01
d[1249] = 0x01
XCTAssertThrowsError(try _RSA.Signing.PrivateKey._createFromNumbers(n: n, e: [1] as [UInt8], d: d))
// A modulus over 8192 bits with d < n would otherwise make each attempt arbitrarily slow.
var bigN = [UInt8](repeating: 0xA7, count: 1025)
bigN[1024] = 0x01
var bigD = [UInt8](repeating: 0, count: 1025)
bigD[1] = 0x01
bigD[1024] = 0x01
XCTAssertThrowsError(try _RSA.Signing.PrivateKey._createFromNumbers(n: bigN, e: [1] as [UInt8], d: bigD))
}
func testExtractPrimeFactorsRejectsInconsistentNumbers() throws {
for testVector in RFC9474TestVector.allValues {
let n = try ArbitraryPrecisionInteger(bytes: Data(hexString: testVector.n))
let e = try ArbitraryPrecisionInteger(bytes: Data(hexString: testVector.e))
let d = try ArbitraryPrecisionInteger(bytes: Data(hexString: testVector.d))
// Using d = d + 2 means d is still even but no longer a multiple of lambda(n).
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: n, e: e, d: d + 2))
}
}
func testGetKeyPrimitives() throws {
for testVector in RFC9474TestVector.allValues {
let n = try Data(hexString: testVector.n)
@@ -1247,23 +910,6 @@ final class TestRSASigning: XCTestCase {
return pemLines.joined(separator: "\n")
}
func test_invalidDERPublicKeyThrowsWithoutDoubleFree() throws {
// SEQUENCE { INTEGER 0, INTEGER 0 }
let badBase64 = "MAYCAQACAQ=="
let badDER = Array(Data(base64Encoded: badBase64)!)
XCTAssertThrowsError(try BoringSSLRSAPublicKey(derRepresentation: badDER))
}
func test_invalidPEMPublicKeyThrowsWithoutDoubleFree() throws {
// SEQUENCE { INTEGER 0, INTEGER 0 }
let badPEM = """
-----BEGIN PUBLIC KEY-----
MAYCAQACAQ==
-----END PUBLIC KEY-----
"""
XCTAssertThrowsError(try BoringSSLRSAPublicKey(pemRepresentation: badPEM))
}
}
-37
View File
@@ -219,43 +219,6 @@ class ASN1Tests: XCTestCase {
XCTAssertEqual(serializer.serializedBytes, decodedPrivateKey)
}
func testPKCS8PrivateKeyWithMismatchedCurveIsRejected() throws {
func pkcs8(_ algorithm: ASN1.RFC5480AlgorithmIdentifier, _ privateKey: Data, _ publicKey: Data) throws -> (der: Data, pem: String) {
let pkey = ASN1.PKCS8PrivateKey(algorithm: algorithm, privateKey: Array(privateKey), publicKey: Array(publicKey))
var serializer = ASN1.Serializer()
try serializer.serialize(pkey)
let der = Data(serializer.serializedBytes)
return (der, ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: der).pemString)
}
let p256 = P256.Signing.PrivateKey()
let p384 = P384.Signing.PrivateKey()
let p521 = P521.Signing.PrivateKey()
let p256InP384 = try pkcs8(.ecdsaP384, p256.rawRepresentation, p256.publicKey.x963Representation)
XCTAssertThrowsError(try P256.Signing.PrivateKey(derRepresentation: p256InP384.der))
XCTAssertThrowsError(try P256.Signing.PrivateKey(pemRepresentation: p256InP384.pem))
XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(derRepresentation: p256InP384.der))
XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(pemRepresentation: p256InP384.pem))
let p384InP521 = try pkcs8(.ecdsaP521, p384.rawRepresentation, p384.publicKey.x963Representation)
XCTAssertThrowsError(try P384.Signing.PrivateKey(derRepresentation: p384InP521.der))
XCTAssertThrowsError(try P384.Signing.PrivateKey(pemRepresentation: p384InP521.pem))
XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(derRepresentation: p384InP521.der))
XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(pemRepresentation: p384InP521.pem))
let p521InP256 = try pkcs8(.ecdsaP256, p521.rawRepresentation, p521.publicKey.x963Representation)
XCTAssertThrowsError(try P521.Signing.PrivateKey(derRepresentation: p521InP256.der))
XCTAssertThrowsError(try P521.Signing.PrivateKey(pemRepresentation: p521InP256.pem))
XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(derRepresentation: p521InP256.der))
XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(pemRepresentation: p521InP256.pem))
// The correctly labelled encodings still load.
let p256InP256 = try pkcs8(.ecdsaP256, p256.rawRepresentation, p256.publicKey.x963Representation)
XCTAssertEqual(try P256.Signing.PrivateKey(derRepresentation: p256InP256.der).rawRepresentation, p256.rawRepresentation)
XCTAssertEqual(try P256.KeyAgreement.PrivateKey(pemRepresentation: p256InP256.pem).rawRepresentation, p256.rawRepresentation)
}
func testRejectDripFedASN1SPKIP256() throws {
// This test drip-feeds an ASN.1 P256 SPKI block. It should never parse correctly until we feed the entire block.
let encodedSPKI = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2adMrdG7aUfZH57aeKFFM01dPnkxC18ScRb4Z6poMBgJtYlVtd9ly63URv57ZW0Ncs1LiZB7WATb3svu+1c7HQ=="
@@ -1,50 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
#if canImport(CryptoKit)
// Skip tests that require @testable imports of CryptoKit.
#else
@testable import Crypto
extension X25519Tests {
func testKeyAgreementWithLowOrderPublicKeyThrows() throws {
// The vectors whose shared secret is all-zero: the seven low-order u-coordinates, which are
// 0, 1, both points of order 8, p-1, p and p+1, plus a non-canonical spelling of each.
try wycheproofTest(
bundleType: self,
jsonName: "x25519_test",
testFunction: { (group: ECDHTestGroup) in
let zeroSharedSecretTests = group.tests.filter { $0.flags.contains("ZeroSharedSecret") }
XCTAssert(!zeroSharedSecretTests.isEmpty)
for testVector in zeroSharedSecretTests {
// The public key itself is accepted, as it is by CryptoKit; only the agreement fails.
let publicKey = try Curve25519.KeyAgreement.PublicKey(
rawRepresentation: Array(hexString: testVector.publicKey)
)
let privateKey = try Curve25519.KeyAgreement.PrivateKey(
rawRepresentation: Array(hexString: testVector.privateKey)
)
XCTAssertThrowsError(
try privateKey.sharedSecretFromKeyAgreement(with: publicKey),
"tcId \(testVector.tcId)"
)
}
}
)
}
}
#endif // canImport(CryptoKit)
@@ -1,37 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
#if canImport(CryptoKit)
// Skip tests that require @testable imports of CryptoKit.
#else
@testable import Crypto
extension ECKeyEncodingsTests {
func testCompactRepresentabilityIsDecidedByTheFieldPrime() throws {
// y = n + 1, the larger of the two square roots, so not compact representable.
let aboveMidpointX = try Data(hexString: "d1db3668128866847e66864aa97c37a04f65f6ff201a7d02345dffd738908975")
let aboveMidpointY = try Data(hexString: "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632552")
let aboveMidpoint = try P256.Signing.PublicKey(rawRepresentation: aboveMidpointX + aboveMidpointY)
XCTAssertNil(aboveMidpoint.compactRepresentation)
// n/2 < y <= (p-1)/2, the smaller of the two square roots, so compact representable.
let belowMidpointX = try Data(hexString: "ce2afeafa686293c6c93f644b3f6d796c659a9277ca4af6c15ef3bfdc6e00f89")
let belowMidpointY = try Data(hexString: "7fffffff800000007fffffffffffffffde737d56d38bcf4279dce5617e3192aa")
let belowMidpoint = try P256.Signing.PublicKey(rawRepresentation: belowMidpointX + belowMidpointY)
XCTAssertEqual(belowMidpoint.compactRepresentation, belowMidpointX)
}
}
#endif // canImport(CryptoKit)
-31
View File
@@ -93,37 +93,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
@@ -217,12 +217,6 @@ final class SecureBytesTests: XCTestCase {
XCTAssertEqual(base.count, 22)
XCTAssertEqual(Array(copy), [0, 1, 2, 3, 4])
}
func testZeroizePointerToMultiWordValueClearsAllBytes() {
var value: (UInt64, UInt64, UInt64, UInt64) = (1, 2, 3, 4)
withUnsafeMutablePointer(to: &value) { $0.zeroize() }
XCTAssertEqual(withUnsafeBytes(of: value) { Array($0) }, Array(repeating: UInt8(0), count: 32))
}
}
#endif // canImport(CryptoKit)
+5
View File
@@ -34,6 +34,7 @@ struct RFCVectorDecoder {
for _ in 0..<3 {
fileURL!.deleteLastPathComponent()
}
#if compiler(>=6.0)
if #available(macOS 13, iOS 16, watchOS 9, tvOS 16, visionOS 1, macCatalyst 16, *) {
fileURL!.append(path: "Test Vectors", directoryHint: .isDirectory)
fileURL!.append(path: "\(fileName).txt", directoryHint: .notDirectory)
@@ -41,6 +42,10 @@ struct RFCVectorDecoder {
fileURL! = fileURL!.appendingPathComponent("Test Vectors", isDirectory: true)
fileURL! = fileURL!.appendingPathComponent("\(fileName).txt", isDirectory: false)
}
#else
fileURL! = fileURL!.appendingPathComponent("Test Vectors", isDirectory: true)
fileURL! = fileURL!.appendingPathComponent("\(fileName).txt", isDirectory: false)
#endif
let rfcVectorData = try Data(contentsOf: fileURL!)
self.rfcVectorData = String(decoding: rfcVectorData, as: Unicode.UTF8.self)
+5
View File
@@ -26,6 +26,7 @@ extension XCTestCase {
for _ in 0..<3 {
fileURL.deleteLastPathComponent()
}
#if compiler(>=6.0)
if #available(macOS 13, iOS 16, watchOS 9, tvOS 16, visionOS 1, macCatalyst 16, *) {
fileURL.append(path: "Test Vectors", directoryHint: .isDirectory)
fileURL.append(path: "\(jsonName).json", directoryHint: .notDirectory)
@@ -33,6 +34,10 @@ extension XCTestCase {
fileURL = fileURL.appendingPathComponent("Test Vectors", isDirectory: true)
fileURL = fileURL.appendingPathComponent("\(jsonName).json", isDirectory: false)
}
#else
fileURL = fileURL.appendingPathComponent("Test Vectors", isDirectory: true)
fileURL = fileURL.appendingPathComponent("\(jsonName).json", isDirectory: false)
#endif
let data = try orFail(file: file, line: line) { try Data(contentsOf: unwrap(fileURL, file: file, line: line)) }