diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 00000000..1fb6025f --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,28 @@ +{ + "name": "swift-crypto", + "image": "swift:latest", + "features": { + "ghcr.io/devcontainers/features/common-utils:2": { + "installZsh": "false", + "username": "vscode", + "upgradePackages": "false" + }, + "ghcr.io/devcontainers/features/git:1": { + "version": "latest" + } + }, + "capAdd": ["CAP_SYS_PTRACE"], + "securityOpt": ["seccomp=unconfined"], + "customizations": { + "vscode": { + "settings": { + "swift.path": "/usr/bin", + "lldb.library": "/usr/lib/liblldb.so" + }, + "extensions": [ + "swiftlang.swift-vscode" + ] + } + }, + "remoteUser": "vscode" +} diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 50500714..200cbeab 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -55,3 +55,4 @@ jobs: with: runner_pool: nightly build_scheme: swift-crypto-Package + swift_6_1_enabled: false diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index d82913b8..9d21bb17 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -10,7 +10,7 @@ on: jobs: soundness: name: Soundness - uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.7 + uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.13 with: license_header_check_project_name: "SwiftCrypto" docs_check_enabled: false @@ -19,28 +19,23 @@ jobs: name: Unit tests uses: apple/swift-nio/.github/workflows/unit_tests.yml@main with: - linux_5_10_arguments_override: "--explicit-target-dependency-import-check error" - linux_6_1_arguments_override: "--explicit-target-dependency-import-check error" - linux_6_2_arguments_override: "--explicit-target-dependency-import-check error" - linux_6_3_arguments_override: "--explicit-target-dependency-import-check error" - linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error" + linux_6_2_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error" + linux_6_3_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error" + linux_nightly_next_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error" linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error" - windows_6_1_enabled: true windows_6_2_enabled: true windows_6_3_enabled: true windows_nightly_next_enabled: true windows_nightly_main_enabled: true - windows_6_1_arguments_override: "--explicit-target-dependency-import-check error" - windows_6_2_arguments_override: "--explicit-target-dependency-import-check error" - windows_6_3_arguments_override: "--explicit-target-dependency-import-check error" - windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error" + windows_6_2_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error" + windows_6_3_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error" + windows_nightly_next_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error" windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error" release-builds: name: Release builds uses: apple/swift-nio/.github/workflows/release_builds.yml@main with: - windows_6_1_enabled: true windows_6_2_enabled: true windows_6_3_enabled: true windows_nightly_next_enabled: true @@ -58,7 +53,6 @@ jobs: { "targets": [ { "name": "CCryptoBoringSSL", "type": "source", "exceptions": [] }, - { "name": "CCryptoBoringSSLShims", "type": "source", "exceptions": [] }, { "name": "CryptoBoringWrapper", "type": "source", "exceptions": [] }, { "name": "CXKCP", "type": "source", "exceptions": [] }, { "name": "CXKCPShims", "type": "source", "exceptions": [] }, @@ -67,6 +61,7 @@ jobs: { "name": "CCryptoBoringSSL", "type": "assembly", "exceptions": [ "*/AES/*.swift" ] } ] } + image: swift:6.2 macos-tests: name: macOS tests @@ -74,6 +69,7 @@ jobs: with: runner_pool: general build_scheme: swift-crypto-Package + swift_6_1_enabled: false static-sdk: name: Static SDK diff --git a/.swiftformatignore b/.swiftformatignore index 730c28ab..fe7d5231 100644 --- a/.swiftformatignore +++ b/.swiftformatignore @@ -65,6 +65,8 @@ Sources/Crypto/Signatures/ECDSA.swift Sources/Crypto/Signatures/Ed25519.swift Sources/Crypto/Signatures/MLDSA.swift Sources/Crypto/Signatures/Signature.swift +Sources/Crypto/Util/ArraySpanHelpers.swift +Sources/Crypto/Util/Data+ArraySpan.swift Sources/Crypto/Util/PrettyBytes.swift Sources/Crypto/Util/SafeCompare.swift Sources/Crypto/Util/SecureBytes.swift @@ -136,6 +138,7 @@ Tests/CryptoTests/Signatures/ECDSA/RawECDSASignaturesTests.swift Tests/CryptoTests/Signatures/EdDSA/Ed25519-Runner.swift Tests/CryptoTests/Signatures/MLDSA/MLDSAKeyGenTests.swift Tests/CryptoTests/Signatures/MLDSA/MLDSATests.swift +Tests/CryptoTests/SymmetricKeyTests/SymmetricKeyTests.swift Tests/CryptoTests/Utils/PrettyBytes.swift Tests/CryptoTests/Utils/RFCVector.swift Tests/CryptoTests/Utils/SplitData.swift diff --git a/Benchmarks/Package.swift b/Benchmarks/Package.swift index c71fec27..0a91bbdd 100644 --- a/Benchmarks/Package.swift +++ b/Benchmarks/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:6.1 +// swift-tools-version:6.2 import PackageDescription let package = Package( diff --git a/CMakeLists.txt b/CMakeLists.txt index f0538704..fd9da589 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -37,6 +37,7 @@ set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift) set(SWIFT_CRYPTO_COMPILE_OPTIONS -package-name com.apple.swift-crypto + -enable-experimental-feature Lifetimes ) option(BUILD_SHARED_LIBS "Build shared libraries by default" YES) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2b80a998..cf79d29a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -89,7 +89,7 @@ act --container-architecture linux/amd64 pull_request -j cmake-lists -W ./.githu You can find the underlying script at https://github.com/apple/swift-nio/blob/main/scripts/update-cmake-lists.sh . Using the script directly is less straightforwards because it requires you to pass the JSON config from the `pull_request.yml` file into the script, such as: ``` -curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/update-cmake-lists.sh | CONFIG_JSON='{"targets":[{"name":"CCryptoBoringSSL","type":"source","exceptions":[]},{"name":"CCryptoBoringSSLShims","type":"source","exceptions":[]},{"name":"CryptoBoringWrapper","type":"source","exceptions":[]},{"name":"Crypto","type":"source","exceptions":[]},{"name":"CryptoExtras","type":"source","exceptions":[]},{"name":"CCryptoBoringSSL","type":"assembly","exceptions":["*/AES/*.swift"]}]}' bash +curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/update-cmake-lists.sh | CONFIG_JSON='{"targets":[{"name":"CCryptoBoringSSL","type":"source","exceptions":[]},{"name":"CryptoBoringWrapper","type":"source","exceptions":[]},{"name":"Crypto","type":"source","exceptions":[]},{"name":"CryptoExtras","type":"source","exceptions":[]},{"name":"CCryptoBoringSSL","type":"assembly","exceptions":["*/AES/*.swift"]}]}' bash ``` ## API Evolution diff --git a/Package.swift b/Package.swift index 227c9d75..13c452ef 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:6.1 +// swift-tools-version:6.2 //===----------------------------------------------------------------------===// // // This source file is part of the SwiftCrypto open source project @@ -26,53 +26,29 @@ import PackageDescription import class Foundation.ProcessInfo -// To develop this on Apple platforms, set this to true -let development = false +// NOTE: To develop the the non-Darwin Crypto target on macOS, use a Dev Container. +let nonDarwinPlatforms: [Platform] = [ + .linux, + .android, + .windows, + .wasi, + .openbsd, + // The SwiftPM Platform symbol is not yet public but the underlying platform name is set. + // -- https://github.com/swiftlang/swift-package-manager/blob/swift-6.2.3-RELEASE/Sources/PackageDescription/SupportedPlatforms.swift#L75 + .custom("freebsd"), +] -// Ideally, we should use `.when(platforms:)` to set `swiftSettings` and -// `dependencies` like on other platforms. However, `Platform.freebsd` is not -// yet available, and therefore we guard the settings behind this boolean. -#if os(FreeBSD) -let isFreeBSD = true -#else -let isFreeBSD = false +var swiftSettings: [SwiftSetting] = [ + .define("CRYPTO_IN_SWIFTPM"), + .enableExperimentalFeature("Lifetimes"), + .enableExperimentalFeature("SourceWarningControl"), +] + +// Only enable CheckImplementationOnly on 6.4 -- 6.3 has the feature, but produces many false positives. +#if compiler(>=6.4) +swiftSettings.append(.enableExperimentalFeature("CheckImplementationOnly")) #endif -let swiftSettings: [SwiftSetting] -let dependencies: [Target.Dependency] -if development || isFreeBSD { - swiftSettings = [ - .define("CRYPTO_IN_SWIFTPM"), - .define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API"), - ] - dependencies = [ - "CCryptoBoringSSL", - "CCryptoBoringSSLShims", - "CryptoBoringWrapper", - "CXKCP", - "CXKCPShims", - ] -} else { - let platforms: [Platform] = [ - Platform.linux, - Platform.android, - Platform.windows, - Platform.wasi, - Platform.openbsd, - ] - swiftSettings = [ - .define("CRYPTO_IN_SWIFTPM"), - .define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API", .when(platforms: platforms)), - ] - dependencies = [ - .target(name: "CCryptoBoringSSL", condition: .when(platforms: platforms)), - .target(name: "CCryptoBoringSSLShims", condition: .when(platforms: platforms)), - .target(name: "CryptoBoringWrapper", condition: .when(platforms: platforms)), - .target(name: "CXKCP", condition: .when(platforms: platforms)), - .target(name: "CXKCPShims", condition: .when(platforms: platforms)), - ] -} - // This doesn't work when cross-compiling: the privacy manifest will be included in the Bundle and // Foundation will be linked. This is, however, strictly better than unconditionally adding the // resource. @@ -128,6 +104,10 @@ let package = Package( .when(platforms: [Platform.wasi]) ), .define("OPENSSL_NO_ASM", .when(platforms: [Platform.wasi])), + // BoringSSL is vendored verbatim; we don't fix its warnings. Xcode enables + // -Wshorten-64-to-32 by default (SwiftPM does not), which produces dozens + // of warnings. Silence that group here. + .disableWarning("shorten-64-to-32"), ] ), .target( @@ -143,16 +123,9 @@ let package = Package( .headerSearchPath("low/KeccakP-1600"), .headerSearchPath("low/common"), .headerSearchPath("common"), + .disableWarning("macro-redefined"), ] ), - .target( - name: "CCryptoBoringSSLShims", - dependencies: ["CCryptoBoringSSL"], - exclude: privacyManifestExclude + [ - "CMakeLists.txt" - ], - resources: privacyManifestResource - ), .target( name: "CXKCPShims", dependencies: ["CXKCP"], @@ -163,16 +136,16 @@ let package = Package( ), .target( name: "Crypto", - dependencies: dependencies, + dependencies: [ + .target(name: "CCryptoBoringSSL", condition: .when(platforms: nonDarwinPlatforms)), + .target(name: "CryptoBoringWrapper", condition: .when(platforms: nonDarwinPlatforms)), + .target(name: "CXKCP", condition: .when(platforms: nonDarwinPlatforms)), + .target(name: "CXKCPShims", condition: .when(platforms: nonDarwinPlatforms)), + ], exclude: privacyManifestExclude + [ + "vendored-sources.txt", "CMakeLists.txt", - "AEADs/Nonces.swift.gyb", - "Digests/Digests.swift.gyb", - "Key Agreement/ECDH.swift.gyb", - "Signatures/ECDSA.swift.gyb", - "Signatures/MLDSA.swift.gyb", "Signatures/BoringSSL/MLDSA_boring.swift.gyb", - "KEM/MLKEM.swift.gyb", "KEM/BoringSSL/MLKEM_boring.swift.gyb", ], resources: privacyManifestResource, @@ -182,7 +155,6 @@ let package = Package( name: "CryptoExtras", dependencies: [ "CCryptoBoringSSL", - "CCryptoBoringSSLShims", "CryptoBoringWrapper", "Crypto", .product(name: "SwiftASN1", package: "swift-asn1"), @@ -204,12 +176,12 @@ let package = Package( name: "CryptoBoringWrapper", dependencies: [ "CCryptoBoringSSL", - "CCryptoBoringSSLShims", ], exclude: privacyManifestExclude + [ "CMakeLists.txt" ], - resources: privacyManifestResource + resources: privacyManifestResource, + swiftSettings: swiftSettings ), .executableTarget(name: "crypto-shasum", dependencies: ["Crypto"]), .testTarget( diff --git a/README.md b/README.md index b448b36b..ea015a0c 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,9 @@ Swift Crypto is an open-source implementation of a substantial portion of the AP Swift Crypto is available as a Swift Package Manager package. To use it, add the following dependency in your `Package.swift`: ```swift -// swift-crypto 1.x, 2.x, 3.x, and 4.x are almost API compatible, so most clients +// swift-crypto 1.x, 2.x, 3.x, 4.x, and 5.x are almost API compatible, so most clients // should allow any of them -.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "5.0.0"), +.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "6.0.0"), ``` and to your target, add `Crypto` to your dependencies. You can then `import Crypto` to get access to Swift Crypto's functionality. @@ -28,7 +28,7 @@ Swift Crypto compiles in two distinct modes depending on the platform for which When building Swift Crypto for use on an Apple platform where CryptoKit is already available, Swift Crypto compiles its entire API surface down to nothing and simply re-exports the API of CryptoKit. This means that when using Apple platforms Swift Crypto simply delegates all work to the core implementation of CryptoKit, as though Swift Crypto was not even there. -When building Swift Crypto for use on Linux or Windows, Swift Crypto builds substantially more code. In particular, we build: +When building Swift Crypto for use on other platforms, Swift Crypto builds substantially more code. In particular, we build: 1. A vendored copy of BoringSSL's libcrypto. 2. A vendored copy of XKCP's libXKCP. @@ -109,7 +109,7 @@ If you believe you have identified a vulnerability in Swift Crypto, please [repo ### Swift versions -The most recent versions of Swift Crypto support Swift 6 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below: +The most recent versions of Swift Crypto support Swift 6.2 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below: Swift Crypto | Minimum Swift Version --------------------|---------------------- @@ -121,7 +121,9 @@ Swift Crypto | Minimum Swift Version `3.3.0 ..< 3.8.0` | 5.8 `3.9.0 ..< 3.13.0` | 5.9 `3.13.0 ..< 4.0.0` | 5.10 -`4.0.0 ...` | 6.0 +`4.0.0 ..< 4.4.0` | 6.0 +`4.4.0 ..< 5.0.0` | 6.1 +`5.0.0 ...` | 6.2 ### Compatibility @@ -137,15 +139,17 @@ Swift Crypto 3.0.0 was released in September 2023. Again the only breaking chang Swift Crypto 4.0.0 was released in September 2025. Again the only breaking change was the addition of new cases in the `CryptoError` enumeration, so most users can safely depend on the 1.0.0, 2.0.0, 3.0.0, or 4.0.0 series of releases. Note that in this release `_CryptoExtras` was renamed to `CryptoExtras`. The old products and targets have been kept around for compatibility reasons, but users depending only on new code should use `CryptoExtras` not `_CryptoExtras`. +Swift Crypto 5.0.0 was released in September 2026. Because this version is only supported on Swift versions that support extensible enums, this release has mechanically marked all non-frozen public enums in CryptoKit as `@nonexhaustive`, which should mitigate the need for any future major releases of Swift Crypto. Most users will be able to depend on the 1.0.0, 2.0.0, 3.0.0, 4.0.0 or 5.0.0 series of releases. + To do so, please use the following dependency in your `Package.swift`: ```swift -.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "5.0.0"), +.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "6.0.0"), ``` ### Developing Swift Crypto on macOS -Swift Crypto normally defers to the OS implementation of CryptoKit on macOS. Naturally, this makes developing Swift Crypto on macOS tricky. To get Swift Crypto to build the open source implementation on macOS, in `Package.swift`, change `let development = false` to `let development = true`, as this will force Swift Crypto to build its public API. +Swift Crypto normally defers to the OS implementation of CryptoKit on macOS. Naturally, this makes developing Swift Crypto on macOS tricky. To get Swift Crypto to build the open source implementation on macOS, in `Package.swift`, use a Linux container. A Dev Container config is provided in the repo to make this easier. ## Acknowledgements diff --git a/Sources/CCryptoBoringSSLShims/CMakeLists.txt b/Sources/CCryptoBoringSSLShims/CMakeLists.txt deleted file mode 100644 index 73d5e085..00000000 --- a/Sources/CCryptoBoringSSLShims/CMakeLists.txt +++ /dev/null @@ -1,29 +0,0 @@ -##===----------------------------------------------------------------------===## -## -## This source file is part of the SwiftCrypto open source project -## -## Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors -## Licensed under Apache License v2.0 -## -## See LICENSE.txt for license information -## See CONTRIBUTORS.txt for the list of SwiftCrypto project authors -## -## SPDX-License-Identifier: Apache-2.0 -## -##===----------------------------------------------------------------------===## - -add_library(CCryptoBoringSSLShims STATIC - "shims.c" -) - -target_include_directories(CCryptoBoringSSLShims PUBLIC - include - $) - -target_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) diff --git a/Sources/CCryptoBoringSSLShims/PrivacyInfo.xcprivacy b/Sources/CCryptoBoringSSLShims/PrivacyInfo.xcprivacy deleted file mode 100644 index 1a71db6f..00000000 --- a/Sources/CCryptoBoringSSLShims/PrivacyInfo.xcprivacy +++ /dev/null @@ -1,15 +0,0 @@ - - - - - NSPrivacyTracking - - NSPrivacyAccessedAPITypes - - NSPrivacyCollectedDataTypes - - NSPrivacyTrackingDomains - - - - diff --git a/Sources/CCryptoBoringSSLShims/include/CCryptoBoringSSLShims.h b/Sources/CCryptoBoringSSLShims/include/CCryptoBoringSSLShims.h deleted file mode 100644 index c99ff507..00000000 --- a/Sources/CCryptoBoringSSLShims/include/CCryptoBoringSSLShims.h +++ /dev/null @@ -1,155 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the SwiftCrypto open source project -// -// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// -#ifndef C_CRYPTO_BORINGSSL_SHIMS_H -#define C_CRYPTO_BORINGSSL_SHIMS_H - -// This is for instances when `swift package generate-xcodeproj` is used as CCryptoBoringSSL -// is treated as a framework and requires the framework's name as a prefix. -#if __has_include() -#include -#else -#include -#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 diff --git a/Sources/CCryptoBoringSSLShims/include/module.modulemap b/Sources/CCryptoBoringSSLShims/include/module.modulemap deleted file mode 100644 index 533962ae..00000000 --- a/Sources/CCryptoBoringSSLShims/include/module.modulemap +++ /dev/null @@ -1,4 +0,0 @@ -module CCryptoBoringSSLShims { - header "CCryptoBoringSSLShims.h" - export * -} diff --git a/Sources/CCryptoBoringSSLShims/shims.c b/Sources/CCryptoBoringSSLShims/shims.c deleted file mode 100644 index df8178c4..00000000 --- a/Sources/CCryptoBoringSSLShims/shims.c +++ /dev/null @@ -1,190 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the SwiftCrypto open source project -// -// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// -#include - -// 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); -} diff --git a/Sources/CMakeLists.txt b/Sources/CMakeLists.txt index 4616a1f1..3803cfe6 100644 --- a/Sources/CMakeLists.txt +++ b/Sources/CMakeLists.txt @@ -13,7 +13,6 @@ ##===----------------------------------------------------------------------===## add_subdirectory(CCryptoBoringSSL) -add_subdirectory(CCryptoBoringSSLShims) add_subdirectory(CXKCP) add_subdirectory(CXKCPShims) add_subdirectory(CryptoBoringWrapper) diff --git a/Sources/Crypto/AEADs/AES/GCM/AES-GCM.swift b/Sources/Crypto/AEADs/AES/GCM/AES-GCM.swift index df016ce6..fd5526ad 100644 --- a/Sources/Crypto/AEADs/AES/GCM/AES-GCM.swift +++ b/Sources/Crypto/AEADs/AES/GCM/AES-GCM.swift @@ -11,36 +11,29 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -typealias AESGCMImpl = CoreCryptoGCMImpl -#else -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) typealias AESGCMImpl = OpenSSLAESGCMImpl -#endif -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension AES { /// The Advanced Encryption Standard (AES) Galois Counter Mode (GCM) cipher /// suite. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + @nonexhaustive public enum GCM: Cipher, Sendable { static let tagByteCount = 16 static let defaultNonceByteCount = 12 - + + /// Fixed-length array of tagByteCount bytes. + typealias TagStorage = [16 of UInt8] + /// Secures the given plaintext message with encryption and an /// authentication tag that covers both the encrypted data and /// additional data. @@ -71,6 +64,30 @@ extension AES { return try AESGCMImpl.seal(key: key, message: message, nonce: nonce, authenticatedData: Data?.none) } + /// Secures the given plaintext message with encryption and an optional authentication tag. + /// + /// - Parameters: + /// - message: The plaintext data to seal, which will be updated in place. + /// - key: A cryptographic key used to seal the message. + /// - nonce: The nonce the sealing process requires. + /// - authenticatedData: Additional data to be authenticated, if provided. + /// - tag: receives the 16-byte authentication tag + #if swift(<6.3) + @_lifetime(message: copy message) + #endif + public static func seal( + inPlace message: inout MutableRawSpan, + using key: SymmetricKey, + nonce: Nonce, + authenticating authenticatedData: RawSpan? = nil, + tag: inout OutputRawSpan + ) throws(CryptoKitMetaError) { + return try AESGCMImpl.seal( + key: key, message: &message, nonce: nonce.bytes, + authenticatedData: authenticatedData, tag: &tag + ) + } + /// Decrypts the message and verifies the authenticity of both the /// encrypted message and additional data. /// @@ -99,10 +116,39 @@ extension AES { public static func open(_ sealedBox: SealedBox, using key: SymmetricKey) throws(CryptoKitMetaError) -> Data { return try AESGCMImpl.open(key: key, sealedBox: sealedBox, authenticatedData: Data?.none) } + + /// Decrypts the message and verifies its authenticity. + /// + /// - Parameters: + /// - message: The message, which will be decrypted in place. + /// - key: The cryptographic key that was used to seal the message. + /// - nonce: The nonce used to encrypt the message. + /// - tag : The 16-byte authentication tag. + /// - authenticatedData: Additional data that was authenticated. + /// + /// The call throws an error if decryption or authentication fail. + #if swift(<6.3) + @_lifetime(message: copy message) + #endif + public static func open( + inPlace message: inout MutableRawSpan, + using key: SymmetricKey, + nonce: Nonce, + authenticating authenticatedData: RawSpan? = nil, + tag: RawSpan + ) throws(CryptoKitMetaError) { + try AESGCMImpl + .open( + key: key, + message: &message, + nonce: nonce.bytes, + authenticatedData: authenticatedData, + tag: tag + ) + } } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension AES.GCM { /// A secure container for your data that you can access using a cipher. /// @@ -118,7 +164,6 @@ extension AES.GCM { /// /// The receiver uses another instance of the same cipher, like the /// ``open(_:using:)`` method, to open the box. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SealedBox: AEADSealedBox, Sendable { private let combinedRepresentation: Data private let nonceByteCount: Int @@ -201,10 +246,10 @@ extension AES.GCM { throw error(CryptoKitError.incorrectParameterSize) } - let nonceByteCount = nonce.bytes.count + let nonceByteCount = nonce.storage.count var combinedRepresentation = Data() combinedRepresentation.reserveCapacity(nonceByteCount + ciphertext.count + tag.count) - combinedRepresentation.append(contentsOf: nonce.bytes) + combinedRepresentation.append(contentsOf: nonce.storage) combinedRepresentation.append(contentsOf: ciphertext) combinedRepresentation.append(contentsOf: tag) @@ -213,4 +258,4 @@ extension AES.GCM { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/AEADs/AES/GCM/BoringSSL/AES-GCM_boring.swift b/Sources/Crypto/AEADs/AES/GCM/BoringSSL/AES-GCM_boring.swift index 33ae0ca0..b697571e 100644 --- a/Sources/Crypto/AEADs/AES/GCM/BoringSSL/AES-GCM_boring.swift +++ b/Sources/Crypto/AEADs/AES/GCM/BoringSSL/AES-GCM_boring.swift @@ -11,10 +11,14 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL +#endif import CryptoBoringWrapper #if canImport(FoundationEssentials) import FoundationEssentials @@ -35,17 +39,16 @@ enum OpenSSLAESGCMImpl { let aead = try Self._backingAEAD(key: key) - let ciphertext: Data - let tag: Data + let combined: Data if let ad = authenticatedData { - (ciphertext, tag) = try aead.seal( + combined = try aead.seal( message: message, key: key, nonce: nonce, authenticatedData: ad ) } else { - (ciphertext, tag) = try aead.seal( + combined = try aead.seal( message: message, key: key, nonce: nonce, @@ -53,7 +56,39 @@ enum OpenSSLAESGCMImpl { ) } - return try AES.GCM.SealedBox(nonce: nonce, ciphertext: ciphertext, tag: tag) + return AES.GCM.SealedBox(combined: combined, nonceByteCount: nonce.count) + } + + #if swift(<6.3) + @_lifetime(message: copy message) + #endif + @inlinable + static func seal( + key: SymmetricKey, + message: inout MutableRawSpan, + nonce: RawSpan, + authenticatedData: RawSpan?, + tag: inout OutputRawSpan + ) throws { + let aead = try Self._backingAEAD(key: key) + + if let ad = authenticatedData { + try aead.seal( + message: &message, + key: key, + nonce: nonce, + authenticatedData: ad, + tag: &tag + ) + } else { + try aead.seal( + message: &message, + key: key, + nonce: nonce, + authenticatedData: RawSpan(), + tag: &tag + ) + } } @inlinable @@ -83,6 +118,38 @@ enum OpenSSLAESGCMImpl { } } + /// Open a given message in place. + #if swift(<6.3) + @_lifetime(message: copy message) + #endif + @inlinable + static func open( + key: SymmetricKey, + message: inout MutableRawSpan, + nonce: RawSpan, + authenticatedData: RawSpan?, + tag: RawSpan + ) throws { + let aead = try Self._backingAEAD(key: key) + if let authenticatedData { + return try aead.open( + message: &message, + key: key, + nonce: nonce, + tag: tag, + authenticatedData: authenticatedData + ) + } else { + return try aead.open( + message: &message, + key: key, + nonce: nonce, + tag: tag, + authenticatedData: RawSpan() + ) + } + } + @usableFromInline static func _backingAEAD(key: SymmetricKey) throws -> BoringSSLAEAD { switch key.bitCount { @@ -97,4 +164,4 @@ enum OpenSSLAESGCMImpl { } } } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/AEADs/ChachaPoly/BoringSSL/ChaChaPoly_boring.swift b/Sources/Crypto/AEADs/ChachaPoly/BoringSSL/ChaChaPoly_boring.swift index 349cd99a..3e27bb1a 100644 --- a/Sources/Crypto/AEADs/ChachaPoly/BoringSSL/ChaChaPoly_boring.swift +++ b/Sources/Crypto/AEADs/ChachaPoly/BoringSSL/ChaChaPoly_boring.swift @@ -11,11 +11,14 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL -@_implementationOnly import CCryptoBoringSSLShims +#endif import CryptoBoringWrapper #if canImport(FoundationEssentials) import FoundationEssentials @@ -31,7 +34,7 @@ extension BoringSSLAEAD { key: SymmetricKey, nonce: Nonce, authenticatedData: AuthenticatedData - ) throws -> (ciphertext: Data, tag: Data) { + ) throws -> Data { do { let context = try AEADContext(cipher: self, key: key) return try context.seal( @@ -44,6 +47,30 @@ extension BoringSSLAEAD { } } + /// Seal a given message in place + #if swift(<6.3) + @_lifetime(message: copy message) + #endif + func seal( + message: inout MutableRawSpan, + key: SymmetricKey, + nonce: RawSpan, + authenticatedData: RawSpan, + tag: inout OutputRawSpan + ) throws { + do { + let context = try AEADContext(cipher: self, key: key) + return try context.seal( + message: &message, + nonce: nonce, + authenticatedData: authenticatedData, + tag: &tag, + ) + } catch CryptoBoringWrapperError.underlyingCoreCryptoError(let errorCode) { + throw CryptoKitError.underlyingCoreCryptoError(error: errorCode) + } + } + /// Open a given message. func open( ciphertext: Data, @@ -64,6 +91,30 @@ extension BoringSSLAEAD { throw CryptoKitError.underlyingCoreCryptoError(error: errorCode) } } + + /// Open a given message in place. + #if swift(<6.3) + @_lifetime(message: copy message) + #endif + public func open( + message: inout MutableRawSpan, + key: SymmetricKey, + nonce: RawSpan, + tag: RawSpan, + authenticatedData: RawSpan + ) throws { + do { + let context = try AEADContext(cipher: self, key: key) + return try context.open( + message: &message, + nonce: nonce, + tag: tag, + authenticatedData: authenticatedData + ) + } catch CryptoBoringWrapperError.underlyingCoreCryptoError(let errorCode) { + throw CryptoKitError.underlyingCoreCryptoError(error: errorCode) + } + } } @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) @@ -79,17 +130,16 @@ enum OpenSSLChaChaPolyImpl { } let nonce = nonce ?? ChaChaPoly.Nonce() - let ciphertext: Data - let tag: Data + let combined: Data if let ad = authenticatedData { - (ciphertext, tag) = try BoringSSLAEAD.chacha20.seal( + combined = try BoringSSLAEAD.chacha20.seal( message: message, key: key, nonce: nonce, authenticatedData: ad ) } else { - (ciphertext, tag) = try BoringSSLAEAD.chacha20.seal( + combined = try BoringSSLAEAD.chacha20.seal( message: message, key: key, nonce: nonce, @@ -97,7 +147,40 @@ enum OpenSSLChaChaPolyImpl { ) } - return try ChaChaPoly.SealedBox(nonce: nonce, ciphertext: ciphertext, tag: tag) + return ChaChaPoly.SealedBox(combined: combined, nonceByteCount: nonce.count) + } + + #if swift(<6.3) + @_lifetime(message: copy message) + #endif + static func encrypt( + key: SymmetricKey, + inPlace message: inout MutableRawSpan, + nonce: RawSpan, + authenticatedData: RawSpan?, + tag: inout OutputRawSpan + ) throws { + guard key.bitCount == ChaChaPoly.keyBitsCount else { + throw CryptoKitError.incorrectKeySize + } + + if let ad = authenticatedData { + try BoringSSLAEAD.chacha20.seal( + message: &message, + key: key, + nonce: nonce, + authenticatedData: ad, + tag: &tag + ) + } else { + try BoringSSLAEAD.chacha20.seal( + message: &message, + key: key, + nonce: nonce, + authenticatedData: RawSpan(), + tag: &tag + ) + } } static func decrypt( @@ -127,5 +210,39 @@ enum OpenSSLChaChaPolyImpl { ) } } + + #if swift(<6.3) + @_lifetime(message: copy message) + #endif + static func decrypt( + key: SymmetricKey, + inPlace message: inout MutableRawSpan, + nonce: RawSpan, + tag: RawSpan, + authenticatedData: RawSpan? + ) throws { + guard key.bitCount == ChaChaPoly.keyBitsCount else { + throw CryptoKitError.incorrectKeySize + } + + if let authenticatedData { + try BoringSSLAEAD.chacha20.open( + message: &message, + key: key, + nonce: nonce, + tag: tag, + authenticatedData: authenticatedData + ) + } else { + try BoringSSLAEAD.chacha20.open( + message: &message, + key: key, + nonce: nonce, + tag: tag, + authenticatedData: RawSpan() + ) + } + + } } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/AEADs/ChachaPoly/ChaChaPoly.swift b/Sources/Crypto/AEADs/ChachaPoly/ChaChaPoly.swift index e242c5ff..b1661e5b 100644 --- a/Sources/Crypto/AEADs/ChachaPoly/ChaChaPoly.swift +++ b/Sources/Crypto/AEADs/ChachaPoly/ChaChaPoly.swift @@ -11,30 +11,21 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -typealias ChaChaPolyImpl = CoreCryptoChaChaPolyImpl -#else -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) typealias ChaChaPolyImpl = OpenSSLChaChaPolyImpl -#endif -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif /// An implementation of the ChaCha20-Poly1305 cipher. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +@nonexhaustive public enum ChaChaPoly: Cipher, Sendable { static let tagByteCount = 16 static let keyBitsCount = 256 @@ -70,6 +61,28 @@ public enum ChaChaPoly: Cipher, Sendable { return try ChaChaPolyImpl.encrypt(key: key, message: message, nonce: nonce, authenticatedData: Data?.none) } + /// Secures the given plaintext message in place with encryption and an + /// authentication tag. + /// + /// - Parameters: + /// - message: The plaintext data to seal. + /// - key: A cryptographic key used to seal the message. + /// - nonce: The nonce the sealing process requires. + /// - authenticatedData: Additional data to be authenticated. + /// - tag: Will be updated with the 16-byte authentication tag. + #if swift(<6.3) + @_lifetime(message: copy message) + #endif + public static func seal( + inPlace message: inout MutableRawSpan, + using key: SymmetricKey, + nonce: Nonce, + authenticating authenticatedData: RawSpan? = nil, + tag: inout OutputRawSpan + ) throws(CryptoKitMetaError) { + try ChaChaPolyImpl.encrypt(key: key, inPlace: &message, nonce: nonce.bytes, authenticatedData: authenticatedData, tag: &tag) + } + /// Decrypts the message and verifies the authenticity of both the encrypted /// message and additional data. /// @@ -99,9 +112,32 @@ public enum ChaChaPoly: Cipher, Sendable { (_ sealedBox: SealedBox, using key: SymmetricKey) throws -> Data { return try ChaChaPolyImpl.decrypt(key: key, ciphertext: sealedBox, authenticatedData: Data?.none) } + + /// Decrypts the message and verifies the authenticity of both the encrypted + /// message and additional data. + /// + /// - Parameters: + /// - message: The message, which will be decrypted in place. + /// - key: The cryptographic key that was used to seal the message. + /// - nonce: The nonce used to encrypt the message. + /// - tag : The 16-byte authentication tag. + /// - authenticatedData: Additional data that was authenticated. + /// + /// The call throws an error if decryption or authentication fail. + #if swift(<6.3) + @_lifetime(message: copy message) + #endif + public static func open( + inPlace message: inout MutableRawSpan, + using key: SymmetricKey, + nonce: Nonce, + authenticating authenticatedData: RawSpan? = nil, + tag: RawSpan + ) throws(CryptoKitMetaError) { + try ChaChaPolyImpl.decrypt(key: key, inPlace: &message, nonce: nonce.bytes, tag: tag, authenticatedData: authenticatedData) + } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ChaChaPoly { /// A secure container for your data that you access using a cipher. /// @@ -118,7 +154,6 @@ extension ChaChaPoly { /// The receiver uses another instance of the same cipher, like the /// ``open(_:using:)`` method, to open the box. @frozen - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SealedBox: AEADSealedBox, Sendable { /// A combined element composed of the tag, the nonce, and the /// ciphertext. @@ -178,4 +213,4 @@ extension ChaChaPoly { } } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/AEADs/Cipher.swift b/Sources/Crypto/AEADs/Cipher.swift index 2e7dc81e..518b9cd4 100644 --- a/Sources/Crypto/AEADs/Cipher.swift +++ b/Sources/Crypto/AEADs/Cipher.swift @@ -11,22 +11,18 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol AEADSealedBox: Sendable { associatedtype Nonce: Sequence /// The authentication tag @@ -46,7 +42,6 @@ protocol AEADSealedBox: Sendable { } /// A type representing authenticated encryption with associated data. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol Cipher { associatedtype Key associatedtype SealedBox: AEADSealedBox diff --git a/Sources/Crypto/AEADs/Nonces.swift b/Sources/Crypto/AEADs/Nonces.swift index a9f17c75..4d4591be 100644 --- a/Sources/Crypto/AEADs/Nonces.swift +++ b/Sources/Crypto/AEADs/Nonces.swift @@ -11,18 +11,15 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif // MARK: - Generated file, do NOT edit // any edits of this file WILL be overwritten and thus discarded // see section `gyb` in `README` for details. @@ -31,29 +28,56 @@ public import Foundation // MARK: - AES.GCM + Nonce -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension AES.GCM { /// A value used once during a cryptographic operation and then discarded. /// /// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical /// that nonces are unique per call to encryption APIs in order to protect the /// integrity of the encryption. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct Nonce: ContiguousBytes, Sequence, Sendable { - let bytes: Data + typealias Storage = ContiguousArray + + let storage: Storage /// Creates a new random nonce. /// /// The default nonce is a 12-byte random nonce. public init() { - var data = Data(repeating: 0, count: AES.GCM.defaultNonceByteCount) - data.withUnsafeMutableBytes { - assert($0.count == AES.GCM.defaultNonceByteCount) - $0.initializeWithRandomBytes(count: AES.GCM.defaultNonceByteCount) - } - self.bytes = data + self.storage = Self.randomNonceStorage } - + + /// Creates a nonce from the given data. + /// + /// Unless your use case calls for a nonce with a specific value, use the + /// ``init()`` method to instead create a random nonce. + /// + /// - Parameters: +/// - data: A data representation of the nonce. +/// The initializer throws an error if the data has a length smaller than 12 bytes. + internal init(data: RawSpan) throws(CryptoKitMetaError) { + if data.byteCount < AES.GCM.defaultNonceByteCount { + throw error(CryptoKitError.incorrectParameterSize) + } + + self.storage = Storage(copying: data) + } + + /// Creates a nonce from the given data. + /// + /// Unless your use case calls for a nonce with a specific value, use the + /// ``init()`` method to instead create a random nonce. + /// + /// - Parameters: +/// - bytes: The bytes that represent the nonce. +/// The initializer throws an error if the data has a length smaller than 12 bytes. + public init(copying bytes: RawSpan) throws(CryptoKitMetaError) { + if bytes.byteCount < AES.GCM.defaultNonceByteCount { + throw error(CryptoKitError.incorrectParameterSize) + } + + self.storage = Storage(copying: bytes) + } + /// Creates a nonce from the given data. /// /// Unless your use case calls for a nonce with a specific value, use the @@ -67,9 +91,9 @@ extension AES.GCM { throw error(CryptoKitError.incorrectParameterSize) } - self.bytes = Data(data) + self.storage = Storage(data) } - + /// Calls the given closure with a pointer to the underlying bytes of the array’s /// contiguous storage. /// @@ -91,39 +115,93 @@ extension AES.GCM { } #endif + /// The bytes stored in the nonce. + public var bytes: RawSpan { + get { + storage.span.bytes + } + } + + /// The number of bytes stored in the nonce. + public var count: Int { storage.count } + /// Returns an iterator over the elements of the nonce. public func makeIterator() -> Array.Iterator { self.withUnsafeBytes({ (buffPtr) in return Array(buffPtr).makeIterator() }) } + + /// Storage for a new, random nonce. + static var randomNonceStorage: Storage { + var data = Storage(repeating: 0, count: AES.GCM.defaultNonceByteCount) + assert(data.count == AES.GCM.defaultNonceByteCount) + + var mutableSpan = data.mutableSpan + var mutableBytes = mutableSpan.mutableBytes + initializeRandomNonce(into: &mutableBytes) + + return data + } + + /// Initialize the given mutable span with random bytes. + static func initializeRandomNonce(into data: inout MutableRawSpan) { + data.initializeWithRandomBytes(count: data.byteCount) + } } } // MARK: - ChaChaPoly + Nonce -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ChaChaPoly { /// A value used once during a cryptographic operation and then discarded. /// /// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical /// that nonces are unique per call to encryption APIs in order to protect the /// integrity of the encryption. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct Nonce: ContiguousBytes, Sequence, Sendable { - let bytes: Data + typealias Storage = [12 of UInt8] + + let storage: Storage /// Creates a new random nonce. /// /// The default nonce is a 12-byte random nonce. public init() { - var data = Data(repeating: 0, count: ChaChaPoly.nonceByteCount) - data.withUnsafeMutableBytes { - assert($0.count == ChaChaPoly.nonceByteCount) - $0.initializeWithRandomBytes(count: ChaChaPoly.nonceByteCount) - } - self.bytes = data + self.storage = Self.randomNonceStorage } - + + /// Creates a nonce from the given data. + /// + /// Unless your use case calls for a nonce with a specific value, use the + /// ``init()`` method to instead create a random nonce. + /// + /// - Parameters: +/// - data: A 12-byte data representation of the nonce. +/// The initializer throws an error if the data isn't 12 bytes long. + internal init(data: RawSpan) throws(CryptoKitMetaError) { + if data.byteCount != ChaChaPoly.nonceByteCount { + throw error(CryptoKitError.incorrectParameterSize) + } + + self.storage = Storage(copying: data) + } + + /// Creates a nonce from the given data. + /// + /// Unless your use case calls for a nonce with a specific value, use the + /// ``init()`` method to instead create a random nonce. + /// + /// - Parameters: +/// - bytes: The bytes that represent the nonce. +/// The initializer throws an error if the data isn't 12 bytes long. + public init(copying bytes: RawSpan) throws(CryptoKitMetaError) { + if bytes.byteCount != ChaChaPoly.nonceByteCount { + throw error(CryptoKitError.incorrectParameterSize) + } + + self.storage = Storage(copying: bytes) + } + /// Creates a nonce from the given data. /// /// Unless your use case calls for a nonce with a specific value, use the @@ -137,9 +215,9 @@ extension ChaChaPoly { throw error(CryptoKitError.incorrectParameterSize) } - self.bytes = Data(data) + self.storage = Storage(copying: data) } - + /// Calls the given closure with a pointer to the underlying bytes of the array’s /// contiguous storage. /// @@ -161,12 +239,38 @@ extension ChaChaPoly { } #endif + /// The bytes stored in the nonce. + public var bytes: RawSpan { + get { + storage.span.bytes + } + } + + /// The number of bytes stored in the nonce. + public var count: Int { storage.count } + /// Returns an iterator over the elements of the nonce. public func makeIterator() -> Array.Iterator { self.withUnsafeBytes({ (buffPtr) in return Array(buffPtr).makeIterator() }) } + + /// Storage for a new, random nonce. + static var randomNonceStorage: Storage { + var data = Storage(repeating: 0) + + var mutableSpan = data.mutableSpan + var mutableBytes = mutableSpan.mutableBytes + initializeRandomNonce(into: &mutableBytes) + + return data + } + + /// Initialize the given mutable span with random bytes. + static func initializeRandomNonce(into data: inout MutableRawSpan) { + data.initializeWithRandomBytes(count: data.byteCount) + } } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/AEADs/Nonces.swift.gyb b/Sources/Crypto/AEADs/Nonces.swift.gyb deleted file mode 100644 index 83f6c594..00000000 --- a/Sources/Crypto/AEADs/Nonces.swift.gyb +++ /dev/null @@ -1,115 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the SwiftCrypto open source project -// -// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@_exported import CryptoKit -#else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else -#if canImport(FoundationEssentials) -public import FoundationEssentials -#else -public import Foundation -#endif -#endif -// MARK: - Generated file, do NOT edit -// any edits of this file WILL be overwritten and thus discarded -// see section `gyb` in `README` for details. - -%{ -ciphers = [{"name": "AES.GCM", "recommendedNonceSize": "AES.GCM.defaultNonceByteCount", "nonceValidation": "< AES.GCM.defaultNonceByteCount", "dataDescription": "/// - data: A data representation of the nonce.\n/// The initializer throws an error if the data has a length smaller than 12 bytes."}] - -if "NO_CHACHAPOLY" in globals(): - pass -else: - ciphers.append({"name": "ChaChaPoly", "recommendedNonceSize": "ChaChaPoly.nonceByteCount", "nonceValidation": "!= ChaChaPoly.nonceByteCount", "dataDescription": "/// - data: A 12-byte data representation of the nonce.\n/// The initializer throws an error if the data isn't 12 bytes long."}) -}% - - -% for cipher in ciphers: -%{ -name = cipher["name"] -nonceSize = cipher["recommendedNonceSize"] -nonceValidation = cipher["nonceValidation"] -dataDescription = cipher["dataDescription"] -}% - -// MARK: - ${name} + Nonce -extension ${name} { - /// A value used once during a cryptographic operation and then discarded. - /// - /// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical - /// that nonces are unique per call to encryption APIs in order to protect the - /// integrity of the encryption. - public struct Nonce: ContiguousBytes, Sequence, Sendable { - let bytes: Data - - /// Creates a new random nonce. - /// - /// The default nonce is a 12-byte random nonce. - public init() { - var data = Data(repeating: 0, count: ${nonceSize}) - data.withUnsafeMutableBytes { - assert($0.count == ${nonceSize}) - $0.initializeWithRandomBytes(count: ${nonceSize}) - } - self.bytes = data - } - - /// Creates a nonce from the given data. - /// - /// Unless your use case calls for a nonce with a specific value, use the - /// ``init()`` method to instead create a random nonce. - /// - /// - Parameters: -${dataDescription} - public init(data: D) throws(CryptoKitMetaError) { - if data.count ${nonceValidation} { - throw error(CryptoKitError.incorrectParameterSize) - } - - self.bytes = Data(data) - } - - /// Calls the given closure with a pointer to the underlying bytes of the array’s - /// contiguous storage. - /// - /// - Parameters: - /// - body: A closure with an `UnsafeRawBufferPointer` parameter that points to the - /// contiguous storage for the array. The system creates the storage if it doesn’t - /// exist. If body has a return value, that value is also used as the return value - /// for the ``withUnsafeBytes(_:)`` method. The argument is valid only for - /// the duration of the closure’s execution. - /// - /// - Returns: The return value, if any, of the body closure parameter. -#if !hasFeature(Embedded) - public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { - return try self.bytes.withUnsafeBytes(body) - } -#else - public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R { - return try self.bytes.withUnsafeBytes(body) - } -#endif - - /// Returns an iterator over the elements of the nonce. - public func makeIterator() -> Array.Iterator { - self.withUnsafeBytes({ (buffPtr) in - return Array(buffPtr).makeIterator() - }) - } - } -} -% end -#endif // Linux or !SwiftPM diff --git a/Sources/Crypto/ASN1/ASN1.swift b/Sources/Crypto/ASN1/ASN1.swift index 4cba7ff2..3c69c0a0 100644 --- a/Sources/Crypto/ASN1/ASN1.swift +++ b/Sources/Crypto/ASN1/ASN1.swift @@ -11,19 +11,16 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif // This module implements "just enough" ASN.1. Specifically, we implement exactly enough ASN.1 DER parsing to handle // the following use-cases: @@ -112,18 +109,15 @@ import Foundation // generally: that is, we don't hard-code special knowledge of these formats as part of the parsing process. Instead we have written a // parser that can divide the world of ASN.1 into parseable chunks, and then we try to decode specific formats from those chunks. This // allows us to extend things in the future without too much pain. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal enum ASN1 { } // MARK: - Parser Node -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { /// An `ASN1ParserNode` is a representation of a parsed ASN.1 TLV section. An `ASN1ParserNode` may be primitive, or may be composed of other `ASN1ParserNode`s. /// In our representation, we keep track of this by storing a node "depth", which allows rapid forward and backward scans to hop over sections /// we're uninterested in. /// /// This type is not exposed to users of the API: it is only used internally for implementation of the user-level API. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) fileprivate struct ASN1ParserNode { /// The identifier. var identifier: ASN1Identifier @@ -136,11 +130,9 @@ extension ASN1 { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1ParserNode: Hashable { } #if !hasFeature(Embedded) -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1ParserNode: CustomStringConvertible { var description: String { return "ASN1.ASN1ParserNode(identifier: \(self.identifier), depth: \(self.depth), dataBytes: \(self.dataBytes?.count ?? 0))" @@ -149,7 +141,6 @@ extension ASN1.ASN1ParserNode: CustomStringConvertible { #endif // MARK: - Sequence, SequenceOf, and Set -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { /// Parse the node as an ASN.1 sequence. internal static func sequence(_ node: ASN1Node, identifier: ASN1.ASN1Identifier, _ builder: (inout ASN1.ASN1NodeCollection.Iterator) throws(CryptoKitMetaError) -> T) throws(CryptoKitMetaError) -> T { @@ -198,7 +189,6 @@ extension ASN1 { } // MARK: - Optional explicitly tagged -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { /// Parses an optional explicitly tagged element. Throws on a tag mismatch, returns nil if the element simply isn't there. /// @@ -236,7 +226,6 @@ extension ASN1 { } // MARK: - DEFAULT -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { /// Parses a value that is encoded with a DEFAULT. Such a value is optional, and if absent will /// be replaced with its default. @@ -285,10 +274,8 @@ extension ASN1 { } // MARK: - Parsing -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { /// A parsed representation of ASN.1. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) fileprivate struct ASN1ParseResult { private static let maximumNodeDepth = 10 @@ -352,10 +339,8 @@ extension ASN1 { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1ParseResult: Hashable { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { static func parse(_ data: [UInt8]) throws(CryptoKitMetaError) -> ASN1Node { return try parse(data[...]) @@ -384,13 +369,11 @@ extension ASN1 { } // MARK: - ASN1NodeCollection -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { /// Represents a collection of ASN.1 nodes contained in a constructed ASN.1 node. /// /// Constructed ASN.1 nodes are made up of multiple child nodes. This object represents the collection of those child nodes. /// It allows us to lazily construct the child nodes, potentially skipping over them when we don't care about them. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal struct ASN1NodeCollection { private var nodes: ArraySlice @@ -408,9 +391,7 @@ extension ASN1 { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1NodeCollection: Sequence { - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct Iterator: IteratorProtocol { private var nodes: ArraySlice private var depth: Int @@ -444,7 +425,6 @@ extension ASN1.ASN1NodeCollection: Sequence { } // MARK: - ASN1Node -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { /// An `ASN1Node` is a single entry in the ASN.1 representation of a data structure. /// @@ -454,7 +434,6 @@ extension ASN1 { /// /// In this way, ASN.1 objects tend to form a "tree", where each object is represented by a single top-level constructed /// node that contains other objects and primitives, eventually reaching the bottom which is made up of primitive objects. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal struct ASN1Node { internal var identifier: ASN1Identifier @@ -463,10 +442,8 @@ extension ASN1 { } // MARK: - ASN1Node.Content -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1Node { /// The content of a single ASN1Node. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) enum Content { case constructed(ASN1.ASN1NodeCollection) case primitive(ArraySlice) @@ -474,9 +451,7 @@ extension ASN1.ASN1Node { } // MARK: - Serializing -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct Serializer { var serializedBytes: [UInt8] @@ -586,12 +561,10 @@ extension ASN1 { } // MARK: - Helpers -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal protocol ASN1Parseable { init(asn1Encoded: ASN1.ASN1Node) throws(CryptoKitMetaError) } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1Parseable { internal init(asn1Encoded sequenceNodeIterator: inout ASN1.ASN1NodeCollection.Iterator) throws(CryptoKitMetaError) { guard let node = sequenceNodeIterator.next() else { @@ -610,13 +583,11 @@ extension ASN1Parseable { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal protocol ASN1Serializable { func serialize(into coder: inout ASN1.Serializer) throws(CryptoKitMetaError) } /// Covers ASN.1 types that may be implicitly tagged. Not all nodes can be! -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal protocol ASN1ImplicitlyTaggable: ASN1Parseable, ASN1Serializable { /// The tag that the first node will use "by default" if the grammar omits /// any more specific tag definition. @@ -627,7 +598,6 @@ internal protocol ASN1ImplicitlyTaggable: ASN1Parseable, ASN1Serializable { func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1ImplicitlyTaggable { internal init(asn1Encoded sequenceNodeIterator: inout ASN1.ASN1NodeCollection.Iterator, withIdentifier identifier: ASN1.ASN1Identifier = Self.defaultIdentifier) throws(CryptoKitMetaError) { @@ -655,7 +625,6 @@ extension ASN1ImplicitlyTaggable { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ArraySlice where Element == UInt8 { fileprivate mutating func readASN1Length() throws(CryptoKitMetaError) -> UInt? { guard let firstByte = self.popFirst() else { @@ -704,7 +673,6 @@ extension ArraySlice where Element == UInt8 { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension FixedWidthInteger { internal init(bigEndianBytes bytes: Bytes) throws(CryptoKitMetaError) where Bytes.Element == UInt8 { guard bytes.count <= (Self.bitWidth / 8) else { @@ -722,7 +690,6 @@ extension FixedWidthInteger { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Array where Element == UInt8 { fileprivate mutating func writeIdentifier(_ identifier: ASN1.ASN1Identifier) { self.append(identifier.baseTag) @@ -748,7 +715,6 @@ extension Array where Element == UInt8 { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Int { fileprivate var bytesNeededToEncode: Int { // ASN.1 lengths are in two forms. If we can store the length in 7 bits, we should: @@ -766,7 +732,6 @@ extension Int { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension FixedWidthInteger { // Bytes needed to store a given integer. internal var neededBytes: Int { @@ -775,4 +740,4 @@ extension FixedWidthInteger { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Any.swift b/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Any.swift index ec3a95cb..edaafa0e 100644 --- a/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Any.swift +++ b/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Any.swift @@ -11,21 +11,17 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { /// An ASN1 ANY represents...well, anything. /// @@ -34,7 +30,6 @@ extension ASN1 { /// /// The only things we allow users to do with ASN.1 ANYs is to try to decode them as something else, /// to create them from something else, or to serialize them. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct ASN1Any: ASN1Parseable, ASN1Serializable, Hashable { fileprivate var serializedBytes: ArraySlice @@ -66,18 +61,16 @@ extension ASN1 { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1Parseable { init(asn1Any: ASN1.ASN1Any) throws(CryptoKitMetaError) { try self.init(asn1Encoded: asn1Any.serializedBytes) } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1ImplicitlyTaggable { init(asn1Any: ASN1.ASN1Any, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) { try self.init(asn1Encoded: asn1Any.serializedBytes, withIdentifier: identifier) } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1BitString.swift b/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1BitString.swift index c5babc68..bd195d89 100644 --- a/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1BitString.swift +++ b/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1BitString.swift @@ -11,24 +11,19 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { /// A bitstring is a representation of...well...some bits. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct ASN1BitString: ASN1ImplicitlyTaggable { static var defaultIdentifier: ASN1.ASN1Identifier { .primitiveBitString @@ -67,10 +62,8 @@ extension ASN1 { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1BitString: Hashable { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1BitString: ContiguousBytes { #if hasFeature(Embedded) func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R { @@ -83,4 +76,4 @@ extension ASN1.ASN1BitString: ContiguousBytes { #endif } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Boolean.swift b/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Boolean.swift index 3e4ce428..5b1ffe52 100644 --- a/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Boolean.swift +++ b/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Boolean.swift @@ -11,21 +11,17 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Bool: ASN1ImplicitlyTaggable { static var defaultIdentifier: ASN1.ASN1Identifier { .boolean @@ -64,4 +60,4 @@ extension Bool: ASN1ImplicitlyTaggable { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Identifier.swift b/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Identifier.swift index 54c9f537..c3314c19 100644 --- a/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Identifier.swift +++ b/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Identifier.swift @@ -11,25 +11,20 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { /// An `ASN1Identifier` is a representation of the abstract notion of an ASN.1 identifier. Identifiers have a number of properties that relate to both the specific /// tag number as well as the properties of the identifier in the stream. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal struct ASN1Identifier { /// The base tag. In a general ASN.1 implementation we'd need an arbitrary precision integer here as the tag number can be arbitrarily large, but /// we don't need the full generality here. @@ -122,7 +117,6 @@ extension ASN1 { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1Identifier { internal static let objectIdentifier = try! ASN1.ASN1Identifier(rawIdentifier: 0x06) internal static let primitiveBitString = try! ASN1.ASN1Identifier(rawIdentifier: 0x03) @@ -147,11 +141,9 @@ extension ASN1.ASN1Identifier { internal static let generalizedTime = try! ASN1.ASN1Identifier(rawIdentifier: 0x18) } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1Identifier: Hashable { } #if !hasFeature(Embedded) -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1Identifier: CustomStringConvertible { var description: String { return "ASN1Identifier(\(self.baseTag))" @@ -159,4 +151,4 @@ extension ASN1.ASN1Identifier: CustomStringConvertible { } #endif -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Integer.swift b/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Integer.swift index 0238a9ca..7cdb672e 100644 --- a/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Integer.swift +++ b/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Integer.swift @@ -11,19 +11,16 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif /// A protocol that represents any internal object that can present itself as a INTEGER, or be parsed from /// a INTEGER. @@ -31,7 +28,6 @@ import Foundation /// This is not a very good solution for a fully-fledged ASN.1 library: we'd rather have a better numerics /// protocol that could both initialize from and serialize to either bytes or words. However, no such /// protocol exists today. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol ASN1IntegerRepresentable: ASN1ImplicitlyTaggable { associatedtype IntegerBytes: RandomAccessCollection where IntegerBytes.Element == UInt8 @@ -44,7 +40,6 @@ protocol ASN1IntegerRepresentable: ASN1ImplicitlyTaggable { func withBigEndianIntegerBytes(_ body: (IntegerBytes) throws(CryptoKitMetaError) -> ReturnType) throws(CryptoKitMetaError) -> ReturnType } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1IntegerRepresentable { static var defaultIdentifier: ASN1.ASN1Identifier { .integer @@ -113,7 +108,6 @@ extension ASN1IntegerRepresentable { } // MARK: - Auto-conformance for FixedWidthInteger with fixed width magnitude. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1IntegerRepresentable where Self: FixedWidthInteger { init(asn1IntegerBytes bytes: ArraySlice) throws(CryptoKitMetaError) { // Defer to the FixedWidthInteger constructor. @@ -134,7 +128,6 @@ extension ASN1IntegerRepresentable where Self: FixedWidthInteger { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct IntegerBytesCollection { private var integer: Integer @@ -143,9 +136,7 @@ struct IntegerBytesCollection { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension IntegerBytesCollection: RandomAccessCollection { - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct Index { fileprivate var byteNumber: Int @@ -179,10 +170,8 @@ extension IntegerBytesCollection: RandomAccessCollection { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension IntegerBytesCollection.Index: Equatable { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension IntegerBytesCollection.Index: Comparable { // Comparable here is backwards to the original ordering. static func <(lhs: Self, rhs: Self) -> Bool { @@ -202,7 +191,6 @@ extension IntegerBytesCollection.Index: Comparable { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension IntegerBytesCollection.Index: Strideable { func advanced(by n: Int) -> IntegerBytesCollection.Index { return IntegerBytesCollection.Index(byteNumber: self.byteNumber - n) @@ -214,37 +202,26 @@ extension IntegerBytesCollection.Index: Strideable { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Int8: ASN1IntegerRepresentable { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension UInt8: ASN1IntegerRepresentable { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Int16: ASN1IntegerRepresentable { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension UInt16: ASN1IntegerRepresentable { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Int32: ASN1IntegerRepresentable { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension UInt32: ASN1IntegerRepresentable { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Int64: ASN1IntegerRepresentable { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension UInt64: ASN1IntegerRepresentable { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Int: ASN1IntegerRepresentable { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension UInt: ASN1IntegerRepresentable { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension RandomAccessCollection where Element == UInt8 { fileprivate func trimLeadingExcessBytes() -> SubSequence { var slice = self[...] @@ -292,11 +269,10 @@ extension RandomAccessCollection where Element == UInt8 { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension UInt8 { fileprivate var topBitSet: Bool { return (self & 0x80) != 0 } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Null.swift b/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Null.swift index eb0caade..ca5041f2 100644 --- a/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Null.swift +++ b/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Null.swift @@ -11,24 +11,19 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { /// An ASN1 NULL represents nothing. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct ASN1Null: ASN1ImplicitlyTaggable, Hashable { static var defaultIdentifier: ASN1.ASN1Identifier { .null @@ -52,4 +47,4 @@ extension ASN1 { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1OctetString.swift b/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1OctetString.swift index ced74024..ce8bf46b 100644 --- a/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1OctetString.swift +++ b/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1OctetString.swift @@ -11,24 +11,19 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { /// An octet string is a representation of a string of octets. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct ASN1OctetString: ASN1ImplicitlyTaggable { static var defaultIdentifier: ASN1.ASN1Identifier { .primitiveOctetString @@ -60,10 +55,8 @@ extension ASN1 { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1OctetString: Hashable { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1OctetString: ContiguousBytes { #if hasFeature(Embedded) func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R { @@ -76,4 +69,4 @@ extension ASN1.ASN1OctetString: ContiguousBytes { #endif } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Strings.swift b/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Strings.swift index 8fc52ec1..61eb5509 100644 --- a/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Strings.swift +++ b/Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Strings.swift @@ -11,21 +11,17 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) private func contents(of string: StaticString) -> ArraySlice { if string.hasPointerRepresentation { return ArraySlice( @@ -41,11 +37,9 @@ private func contents(of string: StaticString) -> ArraySlice { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { /// A UTF8String is roughly what it sounds like. We note that all the string types are encoded as implicitly tagged /// octet strings, and so for now we just piggyback on the decoder and encoder for that type. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct ASN1UTF8String: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes { static var defaultIdentifier: ASN1.ASN1Identifier { .primitiveUTF8String @@ -89,7 +83,6 @@ extension ASN1 { /// We note that all the string types are encoded as implicitly tagged /// octet strings, and so for now we just piggyback on the decoder and encoder for that type. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct ASN1TeletexString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes { static var defaultIdentifier: ASN1.ASN1Identifier { .primitiveTeletexString @@ -133,7 +126,6 @@ extension ASN1 { /// We note that all the string types are encoded as implicitly tagged /// octet strings, and so for now we just piggyback on the decoder and encoder for that type. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct ASN1PrintableString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes { static var defaultIdentifier: ASN1.ASN1Identifier { .primitivePrintableString @@ -177,7 +169,6 @@ extension ASN1 { /// We note that all the string types are encoded as implicitly tagged /// octet strings, and so for now we just piggyback on the decoder and encoder for that type. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct ASN1UniversalString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes { static var defaultIdentifier: ASN1.ASN1Identifier { .primitiveUniversalString @@ -221,7 +212,6 @@ extension ASN1 { /// We note that all the string types are encoded as implicitly tagged /// octet strings, and so for now we just piggyback on the decoder and encoder for that type. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct ASN1BMPString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes { static var defaultIdentifier: ASN1.ASN1Identifier { .primitiveBMPString @@ -265,35 +255,30 @@ extension ASN1 { } #if !hasFeature(Embedded) -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1TeletexString: ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { self.bytes = ArraySlice(value.utf8) } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1UTF8String: ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { self.bytes = ArraySlice(value.utf8) } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1PrintableString: ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { self.bytes = ArraySlice(value.utf8) } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1UniversalString: ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { self.bytes = ArraySlice(value.utf8) } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1BMPString: ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { self.bytes = ArraySlice(value.utf8) @@ -302,4 +287,4 @@ extension ASN1.ASN1BMPString: ExpressibleByStringLiteral { #endif -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/ASN1/Basic ASN1 Types/ArraySliceBigint.swift b/Sources/Crypto/ASN1/Basic ASN1 Types/ArraySliceBigint.swift index 73ba9404..4937b2eb 100644 --- a/Sources/Crypto/ASN1/Basic ASN1 Types/ArraySliceBigint.swift +++ b/Sources/Crypto/ASN1/Basic ASN1 Types/ArraySliceBigint.swift @@ -11,31 +11,24 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif // For temporary purposes we pretend that ArraySlice is our "bigint" type. We don't really need anything else. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ArraySlice: ASN1Serializable where Element == UInt8 { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ArraySlice: ASN1Parseable where Element == UInt8 { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ArraySlice: ASN1ImplicitlyTaggable where Element == UInt8 { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 { // We only use unsigned "bigint"s static var isSigned: Bool { @@ -51,4 +44,4 @@ extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/ASN1/Basic ASN1 Types/GeneralizedTime.swift b/Sources/Crypto/ASN1/Basic ASN1 Types/GeneralizedTime.swift index 95789c70..947669e0 100644 --- a/Sources/Crypto/ASN1/Basic ASN1 Types/GeneralizedTime.swift +++ b/Sources/Crypto/ASN1/Basic ASN1 Types/GeneralizedTime.swift @@ -11,23 +11,18 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct GeneralizedTime: ASN1ImplicitlyTaggable, Hashable { static var defaultIdentifier: ASN1.ASN1Identifier { .generalizedTime @@ -180,7 +175,6 @@ extension ASN1 { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.GeneralizedTime { fileprivate static func parseDateBytes(_ bytes: ArraySlice) throws(CryptoKitMetaError) -> ASN1.GeneralizedTime { var bytes = bytes @@ -263,7 +257,6 @@ extension ASN1.GeneralizedTime { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ArraySlice where Element == UInt8 { fileprivate mutating func readFourDigitDecimalInteger() -> Int? { guard let first = self.readTwoDigitDecimalInteger(), @@ -329,7 +322,6 @@ extension ArraySlice where Element == UInt8 { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Array where Element == UInt8 { fileprivate mutating func append(_ generalizedTime: ASN1.GeneralizedTime) { self.appendFourDigitDecimal(generalizedTime.year) @@ -401,7 +393,6 @@ extension Array where Element == UInt8 { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Int { fileprivate init?(fromDecimalASCII ascii: UInt8) { let asciiZero = UInt8(48 /* "0" */) @@ -418,4 +409,4 @@ extension Int { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/ASN1/Basic ASN1 Types/ObjectIdentifier.swift b/Sources/Crypto/ASN1/Basic ASN1 Types/ObjectIdentifier.swift index a4283bb2..5ca10b5c 100644 --- a/Sources/Crypto/ASN1/Basic ASN1 Types/ObjectIdentifier.swift +++ b/Sources/Crypto/ASN1/Basic ASN1 Types/ObjectIdentifier.swift @@ -11,28 +11,23 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { /// An Object Identifier is a representation of some kind of object: really any kind of object. /// /// It represents a node in an OID hierarchy, and is usually represented as an ordered sequence of numbers. /// /// We mostly don't care about the semantics of the thing, we just care about being able to store and compare them. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct ASN1ObjectIdentifier: ASN1ImplicitlyTaggable { static var defaultIdentifier: ASN1.ASN1Identifier { .objectIdentifier @@ -142,19 +137,15 @@ extension ASN1 { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1ObjectIdentifier: Hashable {} -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1ObjectIdentifier: ExpressibleByArrayLiteral { init(arrayLiteral elements: UInt...) { self.oidComponents = elements } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.ASN1ObjectIdentifier { - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) enum NamedCurves { static let secp256r1: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10_045, 3, 1, 7] @@ -163,19 +154,16 @@ extension ASN1.ASN1ObjectIdentifier { static let secp521r1: ASN1.ASN1ObjectIdentifier = [1, 3, 132, 0, 35] } - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) enum HashFunctions { static let sha256: ASN1.ASN1ObjectIdentifier = [2, 16, 840, 1, 101, 3, 4, 2, 1] static let sha384: ASN1.ASN1ObjectIdentifier = [2, 16, 840, 1, 101, 3, 4, 2, 2] static let sha512: ASN1.ASN1ObjectIdentifier = [2, 16, 840, 1, 101, 3, 4, 2, 3] } - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) enum AlgorithmIdentifier { static let idEcPublicKey: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10_045, 2, 1] } - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) enum NameAttributes { static let name: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 41] static let surname: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 4] @@ -198,7 +186,6 @@ extension ASN1.ASN1ObjectIdentifier { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ArraySlice where Element == UInt8 { mutating fileprivate func readOIDSubidentifier() throws(CryptoKitMetaError) -> UInt { // In principle OID subidentifiers can be too large to fit into a UInt. We are choosing to not care about that @@ -215,7 +202,6 @@ extension ArraySlice where Element == UInt8 { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension UInt { fileprivate init(sevenBitBigEndianBytes bytes: Bytes) throws(CryptoKitMetaError) where Bytes.Element == UInt8 { // We need to know how many bytes we _need_ to store this "int". @@ -234,4 +220,4 @@ extension UInt { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/ASN1/ECDSASignature.swift b/Sources/Crypto/ASN1/ECDSASignature.swift index 09bfafba..aa2477fa 100644 --- a/Sources/Crypto/ASN1/ECDSASignature.swift +++ b/Sources/Crypto/ASN1/ECDSASignature.swift @@ -11,21 +11,17 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { /// An ECDSA signature is laid out as follows: /// @@ -35,7 +31,6 @@ extension ASN1 { /// } /// /// This type is generic because our different backends want to use different bignum representations. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct ECDSASignature: ASN1ImplicitlyTaggable { static var defaultIdentifier: ASN1.ASN1Identifier { .sequence @@ -67,4 +62,4 @@ extension ASN1 { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/ASN1/PEMDocument.swift b/Sources/Crypto/ASN1/PEMDocument.swift index 1cd182c1..16d62811 100644 --- a/Sources/Crypto/ASN1/PEMDocument.swift +++ b/Sources/Crypto/ASN1/PEMDocument.swift @@ -11,24 +11,19 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { /// A PEM document is some data, and a discriminator type that is used to advertise the content. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct PEMDocument { private static let lineLength = 64 @@ -97,7 +92,6 @@ extension ASN1 { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Substring { fileprivate var pemStartDiscriminator: String? { return self.pemDiscriminator(expectedPrefix: "-----BEGIN ", expectedSuffix: "-----") @@ -127,4 +121,4 @@ extension Substring { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/ASN1/PKCS8PrivateKey.swift b/Sources/Crypto/ASN1/PKCS8PrivateKey.swift index 2b3693d7..901f1f3b 100644 --- a/Sources/Crypto/ASN1/PKCS8PrivateKey.swift +++ b/Sources/Crypto/ASN1/PKCS8PrivateKey.swift @@ -11,20 +11,16 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { // A PKCS#8 private key is one of two formats, depending on the version: // @@ -48,7 +44,6 @@ extension ASN1 { // // The private key octet string contains (surprise!) a SEC1-encoded private key! So we recursively invoke the // ASN.1 parser and go again. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct PKCS8PrivateKey: ASN1ImplicitlyTaggable { static var defaultIdentifier: ASN1.ASN1Identifier { return .sequence @@ -110,4 +105,4 @@ extension ASN1 { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/ASN1/SEC1PrivateKey.swift b/Sources/Crypto/ASN1/SEC1PrivateKey.swift index 3a299118..0ee4a593 100644 --- a/Sources/Crypto/ASN1/SEC1PrivateKey.swift +++ b/Sources/Crypto/ASN1/SEC1PrivateKey.swift @@ -11,21 +11,17 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { // For private keys, SEC 1 uses: // @@ -35,7 +31,6 @@ extension ASN1 { // parameters [0] EXPLICIT ECDomainParameters OPTIONAL, // publicKey [1] EXPLICIT BIT STRING OPTIONAL // } - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct SEC1PrivateKey: ASN1ImplicitlyTaggable { static var defaultIdentifier: ASN1.ASN1Identifier { return .sequence @@ -118,4 +113,4 @@ extension ASN1 { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/ASN1/SubjectPublicKeyInfo.swift b/Sources/Crypto/ASN1/SubjectPublicKeyInfo.swift index 00f82def..3e5898ce 100644 --- a/Sources/Crypto/ASN1/SubjectPublicKeyInfo.swift +++ b/Sources/Crypto/ASN1/SubjectPublicKeyInfo.swift @@ -11,23 +11,18 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1 { - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct SubjectPublicKeyInfo: ASN1ImplicitlyTaggable { static var defaultIdentifier: ASN1.ASN1Identifier { .sequence @@ -70,7 +65,6 @@ extension ASN1 { } } - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct RFC5480AlgorithmIdentifier: ASN1ImplicitlyTaggable, Hashable { static var defaultIdentifier: ASN1.ASN1Identifier { .sequence @@ -121,7 +115,6 @@ extension ASN1 { } // MARK: Algorithm Identifier Statics -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension ASN1.RFC5480AlgorithmIdentifier { static let ecdsaP256 = ASN1.RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey, parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp256r1)) @@ -133,4 +126,4 @@ extension ASN1.RFC5480AlgorithmIdentifier { parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp521r1)) } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/CMakeLists.txt b/Sources/Crypto/CMakeLists.txt index 0dc9f4f4..c528ab9d 100644 --- a/Sources/Crypto/CMakeLists.txt +++ b/Sources/Crypto/CMakeLists.txt @@ -97,12 +97,15 @@ add_library(Crypto "Signatures/Ed25519.swift" "Signatures/MLDSA.swift" "Signatures/Signature.swift" + "Util/ArraySpanHelpers.swift" "Util/BoringSSL/CryptoKitErrors_boring.swift" + "Util/BoringSSL/InlineArray+withBytes_boring.swift" "Util/BoringSSL/Optional+withUnsafeBytes_boring.swift" "Util/BoringSSL/RNG_boring.swift" "Util/BoringSSL/SafeCompare_boring.swift" "Util/BoringSSL/Zeroization_boring.swift" "Util/BoringSSL/_CryptoModuleAnchor.swift" + "Util/Data+ArraySpan.swift" "Util/PrettyBytes.swift" "Util/SafeCompare.swift" "Util/SecureBytes.swift" @@ -112,14 +115,8 @@ add_library(Crypto target_compile_definitions(Crypto PRIVATE "$<$:CRYPTO_IN_SWIFTPM>") -if(NOT CMAKE_SYSTEM_NAME STREQUAL "Darwin") - target_compile_definitions(Crypto PRIVATE - "$<$:CRYPTO_IN_SWIFTPM_FORCE_BUILD_API>") -endif() - target_include_directories(Crypto PRIVATE $ - $ $ $ $) @@ -127,7 +124,6 @@ target_link_libraries(Crypto PUBLIC $<$>:dispatch> $<$>:Foundation> CCryptoBoringSSL - CCryptoBoringSSLShims CryptoBoringWrapper CXKCP CXKCPShims) diff --git a/Sources/Crypto/CryptoKitErrors.swift b/Sources/Crypto/CryptoKitErrors.swift index 6823f6ba..b811d510 100644 --- a/Sources/Crypto/CryptoKitErrors.swift +++ b/Sources/Crypto/CryptoKitErrors.swift @@ -11,11 +11,12 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else /// General cryptography errors used by CryptoKit. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +@nonexhaustive public enum CryptoKitError: Error { /// The key size is incorrect. case incorrectKeySize @@ -34,11 +35,10 @@ public enum CryptoKitError: Error { case invalidParameter } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension CryptoKitError: Equatable, Hashable {} /// Errors from decoding ASN.1 content. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +@nonexhaustive public enum CryptoKitASN1Error: Equatable, Error, Hashable { /// The ASN.1 tag for this field is invalid or unsupported. case invalidFieldIdentifier @@ -67,7 +67,6 @@ public enum CryptoKitASN1Error: Equatable, Error, Hashable { case invalidPEMDocument } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) enum RSAPSSSPKIErrors: Error { case invalidPSSOID case missingParameters @@ -79,45 +78,36 @@ enum RSAPSSSPKIErrors: Error { } #if hasFeature(Embedded) -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct RSAPSSSPKIError: Error { internal var error: RSAPSSSPKIErrors } #else -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct RSAPSSSPKIError: Error { internal var error: RSAPSSSPKIErrors } #endif #if hasFeature(Embedded) -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +@nonexhaustive public enum CryptoKitMetaError: Error { case cryptoKitError(underlyingError: CryptoKitError) case asn1Error(underlyingError: CryptoKitASN1Error) case rsapssspkiError(underlyingError: RSAPSSSPKIError) } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal func error(_ error: CryptoKitError) -> CryptoKitMetaError { .cryptoKitError(underlyingError: error) } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal func error(_ error: CryptoKitASN1Error) -> CryptoKitMetaError { .asn1Error(underlyingError: error) } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal func error(_ error: RSAPSSSPKIErrors) -> CryptoKitMetaError { .rsapssspkiError(underlyingError: RSAPSSSPKIError(error: error)) } -#else /* !hasFeature(Embedded) */ -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +#else public typealias CryptoKitMetaError = any Error -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal func error(_ error: CryptoKitError) -> CryptoKitError { error } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal func error(_ error: CryptoKitASN1Error) -> CryptoKitASN1Error { error } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal func error(_ error: RSAPSSSPKIErrors) -> RSAPSSSPKIErrors { error } #endif diff --git a/Sources/Crypto/Digests/BoringSSL/Digest_boring.swift b/Sources/Crypto/Digests/BoringSSL/Digest_boring.swift index 0551af55..1d134f99 100644 --- a/Sources/Crypto/Digests/BoringSSL/Digest_boring.swift +++ b/Sources/Crypto/Digests/BoringSSL/Digest_boring.swift @@ -11,10 +11,14 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL +#endif @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol HashFunctionImplementationDetails: HashFunction where Digest: DigestPrivate {} @@ -202,7 +206,7 @@ private final class DigestContext { preconditionFailure("Unable to finalize digest state") } // We force unwrap here because if the digest size is wrong it's an internal error. - return H.Digest(bufferPointer: UnsafeRawBufferPointer(digestPointer))! + return H.Digest(copying: digestPointer.bytes)! } } @@ -210,4 +214,4 @@ private final class DigestContext { withUnsafeMutablePointer(to: &self.context) { $0.zeroize() } } } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Digests/Digest.swift b/Sources/Crypto/Digests/Digest.swift index a7b5c735..d7e3463d 100644 --- a/Sources/Crypto/Digests/Digest.swift +++ b/Sources/Crypto/Digests/Digest.swift @@ -11,60 +11,46 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif #if hasFeature(Embedded) /// A type that represents the output of a hash. @preconcurrency -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public protocol Digest: Hashable, Sendable, ContiguousBytes, Sequence where Element == UInt8 { /// The number of bytes in the digest. static var byteCount: Int { get } } -#else // hasFeature(Embedded) +#else /// A type that represents the output of a hash. @preconcurrency -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public protocol Digest: Hashable, Sendable, ContiguousBytes, CustomStringConvertible, Sequence where Element == UInt8 { /// The number of bytes in the digest. static var byteCount: Int { get } } #endif // hasFeature(Embedded) -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol DigestPrivate: Digest { - init?(bufferPointer: UnsafeRawBufferPointer) + init?(initializingWith body: (inout OutputRawSpan) -> ()) } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension DigestPrivate { @inlinable - init?(bytes: [UInt8]) { - let some = bytes.withUnsafeBytes { bufferPointer in - return Self(bufferPointer: bufferPointer) - } - - if some != nil { - self = some! - } else { - return nil + init?(copying bytes: RawSpan) { + self.init() { + $0.append(contentsOf: bytes) } } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Digest { public func makeIterator() -> Array.Iterator { self.withUnsafeBytes({ (buffPtr) in @@ -74,7 +60,6 @@ extension Digest { } // We want to implement constant-time comparison for digests. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Digest { /// Determines whether two digests are equal. /// @@ -107,7 +92,6 @@ extension Digest { } #if !hasFeature(Embedded) -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Digest { public var description: String { return "\(Self.self): \(Array(self).hexString)" @@ -115,4 +99,4 @@ extension Digest { } #endif -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Digests/Digests.swift b/Sources/Crypto/Digests/Digests.swift index b394acee..396218cb 100644 --- a/Sources/Crypto/Digests/Digests.swift +++ b/Sources/Crypto/Digests/Digests.swift @@ -11,7 +11,8 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else // MARK: - Generated file, do NOT edit @@ -22,18 +23,18 @@ // MARK: - SHA256Digest + DigestPrivate /// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 256-bit digest. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SHA256Digest: DigestPrivate { let bytes: (UInt64, UInt64, UInt64, UInt64) - init?(bufferPointer: UnsafeRawBufferPointer) { - guard bufferPointer.count == 32 else { - return nil - } - + init?(initializingWith body: (inout OutputRawSpan) -> ()) { var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0)) - withUnsafeMutableBytes(of: &bytes) { targetPtr in - targetPtr.copyMemory(from: bufferPointer) + let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in + var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0) + body(&output) + return output.finalize(for: targetPtr) + } + guard initialized == 32 else { + return nil } self.bytes = bytes } @@ -105,18 +106,18 @@ public struct SHA256Digest: DigestPrivate { // MARK: - SHA384Digest + DigestPrivate /// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 384-bit digest. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SHA384Digest: DigestPrivate { let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64) - init?(bufferPointer: UnsafeRawBufferPointer) { - guard bufferPointer.count == 48 else { - return nil - } - + init?(initializingWith body: (inout OutputRawSpan) -> ()) { var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0)) - withUnsafeMutableBytes(of: &bytes) { targetPtr in - targetPtr.copyMemory(from: bufferPointer) + let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in + var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0) + body(&output) + return output.finalize(for: targetPtr) + } + guard initialized == 48 else { + return nil } self.bytes = bytes } @@ -190,18 +191,18 @@ public struct SHA384Digest: DigestPrivate { // MARK: - SHA512Digest + DigestPrivate /// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 512-bit digest. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SHA512Digest: DigestPrivate { let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64) - init?(bufferPointer: UnsafeRawBufferPointer) { - guard bufferPointer.count == 64 else { - return nil - } - + init?(initializingWith body: (inout OutputRawSpan) -> ()) { var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0)) - withUnsafeMutableBytes(of: &bytes) { targetPtr in - targetPtr.copyMemory(from: bufferPointer) + let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in + var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0) + body(&output) + return output.finalize(for: targetPtr) + } + guard initialized == 64 else { + return nil } self.bytes = bytes } @@ -274,22 +275,21 @@ public struct SHA512Digest: DigestPrivate { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Insecure { // MARK: - SHA1Digest + DigestPrivate /// The output of a SHA1 hash. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SHA1Digest: DigestPrivate { let bytes: (UInt64, UInt64, UInt64) - init?(bufferPointer: UnsafeRawBufferPointer) { - guard bufferPointer.count == 20 else { - return nil - } - + init?(initializingWith body: (inout OutputRawSpan) -> ()) { var bytes = (UInt64(0), UInt64(0), UInt64(0)) - withUnsafeMutableBytes(of: &bytes) { targetPtr in - targetPtr.copyMemory(from: bufferPointer) + let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in + var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0) + body(&output) + return output.finalize(for: targetPtr) + } + guard initialized == 20 else { + return nil } self.bytes = bytes } @@ -357,22 +357,21 @@ public struct SHA1Digest: DigestPrivate { } } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Insecure { // MARK: - MD5Digest + DigestPrivate /// The output of a MD5 hash. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct MD5Digest: DigestPrivate { let bytes: (UInt64, UInt64) - init?(bufferPointer: UnsafeRawBufferPointer) { - guard bufferPointer.count == 16 else { - return nil - } - + init?(initializingWith body: (inout OutputRawSpan) -> ()) { var bytes = (UInt64(0), UInt64(0)) - withUnsafeMutableBytes(of: &bytes) { targetPtr in - targetPtr.copyMemory(from: bufferPointer) + let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in + var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0) + body(&output) + return output.finalize(for: targetPtr) + } + guard initialized == 16 else { + return nil } self.bytes = bytes } @@ -445,18 +444,18 @@ public struct MD5Digest: DigestPrivate { // MARK: - SHA3_256Digest + DigestPrivate /// The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a 256-bit digest. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SHA3_256Digest: DigestPrivate { let bytes: (UInt64, UInt64, UInt64, UInt64) - init?(bufferPointer: UnsafeRawBufferPointer) { - guard bufferPointer.count == 32 else { - return nil - } - + init?(initializingWith body: (inout OutputRawSpan) -> ()) { var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0)) - withUnsafeMutableBytes(of: &bytes) { targetPtr in - targetPtr.copyMemory(from: bufferPointer) + let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in + var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0) + body(&output) + return output.finalize(for: targetPtr) + } + guard initialized == 32 else { + return nil } self.bytes = bytes } @@ -526,18 +525,18 @@ public struct SHA3_256Digest: DigestPrivate { } // MARK: - SHA3_384Digest + DigestPrivate /// The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a 384-bit digest. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SHA3_384Digest: DigestPrivate { let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64) - init?(bufferPointer: UnsafeRawBufferPointer) { - guard bufferPointer.count == 48 else { - return nil - } - + init?(initializingWith body: (inout OutputRawSpan) -> ()) { var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0)) - withUnsafeMutableBytes(of: &bytes) { targetPtr in - targetPtr.copyMemory(from: bufferPointer) + let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in + var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0) + body(&output) + return output.finalize(for: targetPtr) + } + guard initialized == 48 else { + return nil } self.bytes = bytes } @@ -609,18 +608,18 @@ public struct SHA3_384Digest: DigestPrivate { } // MARK: - SHA3_512Digest + DigestPrivate /// The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a 512-bit digest. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SHA3_512Digest: DigestPrivate { let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64) - init?(bufferPointer: UnsafeRawBufferPointer) { - guard bufferPointer.count == 64 else { - return nil - } - + init?(initializingWith body: (inout OutputRawSpan) -> ()) { var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0)) - withUnsafeMutableBytes(of: &bytes) { targetPtr in - targetPtr.copyMemory(from: bufferPointer) + let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in + var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0) + body(&output) + return output.finalize(for: targetPtr) + } + guard initialized == 64 else { + return nil } self.bytes = bytes } @@ -693,4 +692,4 @@ public struct SHA3_512Digest: DigestPrivate { } } #endif // !CRYPTOKIT_IN_SEP -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Digests/Digests.swift.gyb b/Sources/Crypto/Digests/Digests.swift.gyb deleted file mode 100644 index f5104fab..00000000 --- a/Sources/Crypto/Digests/Digests.swift.gyb +++ /dev/null @@ -1,237 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the SwiftCrypto open source project -// -// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@_exported import CryptoKit -#else -// MARK: - Generated file, do NOT edit -// any edits of this file WILL be overwritten and thus discarded -// see section `gyb` in `README` for details. - -%{ -digests_and_length = [{"name": "SHA256", "count": 32},{"name": "SHA384","count":48},{"name":"SHA512", "count": 64}] -if "NO_INSECURE_DIGEST" in globals(): - pass -else: - digests_and_length.extend([{"name":"SHA1", "count":20, "prefix":"Insecure "},{"name":"MD5", "count":16, "prefix":"Insecure "}]) -}% - -% for HF in digests_and_length: -%{ - name = HF["name"] - byteCount = HF["count"] - wordsCount = (byteCount*8)//64 + (0 if ((byteCount*8)%64) == 0 else 1) -}% -%{ - if "prefix" in HF.keys(): - protocol_prefix = "" - protocol_prefix = protocol_prefix + "extension " + HF["prefix"] + "{" - protocol_suffix = "}" - parent = HF["prefix"].strip() + "/" + name - else: - protocol_prefix = "" - protocol_suffix = "" - parent = name - - if name == "SHA1" or name == "MD5": - abstract = "The output of a " + name + " hash." - else: - abstract = "The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a " + name[-3:] + "-bit digest." -}% -${protocol_prefix} -// MARK: - ${name}Digest + DigestPrivate -/// ${abstract} -public struct ${name}Digest: DigestPrivate { - let bytes: (${(wordsCount-1)*"UInt64, "+"UInt64"}) - - init?(bufferPointer: UnsafeRawBufferPointer) { - guard bufferPointer.count == ${byteCount} else { - return nil - } - - var bytes = (${(wordsCount-1)*"UInt64(0), "+"UInt64(0)"}) - withUnsafeMutableBytes(of: &bytes) { targetPtr in - targetPtr.copyMemory(from: bufferPointer) - } - self.bytes = bytes - } - - /// The number of bytes in the digest. - public static var byteCount: Int { - return ${byteCount} - } - - /// Invokes the given closure with a buffer pointer covering the raw bytes of - /// the digest. - /// - /// - Parameters: - /// - body: A closure that takes a raw buffer pointer to the bytes of the digest - /// and returns the digest. - /// - /// - Returns: The digest, as returned from the body closure. -#if !hasFeature(Embedded) - public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { - return try Swift.withUnsafeBytes(of: bytes) { - let boundsCheckedPtr = UnsafeRawBufferPointer(start: $0.baseAddress, - count: Self.byteCount) - return try body(boundsCheckedPtr) - } - } -#else - public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R { - return try Swift.withUnsafeBytes(of: bytes) { ptr throws(E) -> R in - let boundsCheckedPtr = UnsafeRawBufferPointer(start: ptr.baseAddress, - count: Self.byteCount) - return try body(boundsCheckedPtr) - } - } -#endif - - private func toArray() -> ArraySlice { - var array = [UInt8]() - array.appendByte(bytes.0) - % for index in range(wordsCount-1): - array.appendByte(bytes.${index+1}) - % end - return array.prefix(${name}Digest.byteCount) - } - -#if !hasFeature(Embedded) - /// A human-readable description of the digest. - public var description: String { - return "\("${name}") digest: \(toArray().hexString)" - } -#endif - - /// Hashes the essential components of the digest by feeding them into the - /// given hash function. - /// - /// This method is part of the digest’s conformance to Swift standard library’s - /// protocol, making - /// it possible to compare digests. Don’t confuse that hashing with the - /// cryptographically secure hashing that you use to create the digest in the - /// first place by, for example, calling ``${parent}/hash(data:)``. - /// - /// - Parameters: - /// - hasher: The hash function to use when combining the components of - /// the digest. - public func hash(into hasher: inout Hasher) { - self.withUnsafeBytes { hasher.combine(bytes: $0) } - } -} -${protocol_suffix} -% end - - -#if !CRYPTOKIT_IN_SEP -%{ -digests_and_length = [ - {"name": "SHA3_256", "count": 32}, - {"name": "SHA3_384", "count": 48}, - {"name": "SHA3_512", "count": 64} -] -}% - -% for HF in digests_and_length: -%{ - name = HF["name"] - byteCount = HF["count"] - wordsCount = (byteCount*8)//64 + (0 if ((byteCount*8)%64) == 0 else 1) -}% -%{ - parent = name - abstract = "The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a " + name[-3:] + "-bit digest." -}% -// MARK: - ${name}Digest + DigestPrivate -/// ${abstract} -public struct ${name}Digest: DigestPrivate { - let bytes: (${(wordsCount-1)*"UInt64, "+"UInt64"}) - - init?(bufferPointer: UnsafeRawBufferPointer) { - guard bufferPointer.count == ${byteCount} else { - return nil - } - - var bytes = (${(wordsCount-1)*"UInt64(0), "+"UInt64(0)"}) - withUnsafeMutableBytes(of: &bytes) { targetPtr in - targetPtr.copyMemory(from: bufferPointer) - } - self.bytes = bytes - } - - /// The number of bytes in the digest. - public static var byteCount: Int { - return ${byteCount} - } - - /// Invokes the given closure with a buffer pointer covering the raw bytes of - /// the digest. - /// - /// - Parameters: - /// - body: A closure that takes a raw buffer pointer to the bytes of the digest - /// and returns the digest. - /// - /// - Returns: The digest, as returned from the body closure. -#if !hasFeature(Embedded) - public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { - return try Swift.withUnsafeBytes(of: bytes) { - let boundsCheckedPtr = UnsafeRawBufferPointer(start: $0.baseAddress, - count: Self.byteCount) - return try body(boundsCheckedPtr) - } - } -#else - public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R { - return try Swift.withUnsafeBytes(of: bytes) { ptr throws(E) -> R in - let boundsCheckedPtr = UnsafeRawBufferPointer(start: ptr.baseAddress, - count: Self.byteCount) - return try body(boundsCheckedPtr) - } - } -#endif - - private func toArray() -> ArraySlice { - var array = [UInt8]() - array.appendByte(bytes.0) - % for index in range(wordsCount-1): - array.appendByte(bytes.${index+1}) - % end - return array.prefix(upTo: ${name}Digest.byteCount) - } - -#if !hasFeature(Embedded) - /// A human-readable description of the digest. - public var description: String { - return "\("${name}") digest: \(toArray().hexString)" - } -#endif - - /// Hashes the essential components of the digest by feeding them into the - /// given hash function. - /// - /// This method is part of the digest’s conformance to Swift standard library’s - /// protocol, making - /// it possible to compare digests. Don’t confuse that hashing with the - /// cryptographically secure hashing that you use to create the digest in the - /// first place by, for example, calling ``${parent}/hash(data:)``. - /// - /// - Parameters: - /// - hasher: The hash function to use when combining the components of - /// the digest. - public func hash(into hasher: inout Hasher) { - self.withUnsafeBytes { hasher.combine(bytes: $0) } - } -} -% end -#endif // !CRYPTOKIT_IN_SEP -#endif // Linux or !SwiftPM diff --git a/Sources/Crypto/Digests/HashFunctions.swift b/Sources/Crypto/Digests/HashFunctions.swift index 5b6d97ba..3ff1a3cd 100644 --- a/Sources/Crypto/Digests/HashFunctions.swift +++ b/Sources/Crypto/Digests/HashFunctions.swift @@ -11,30 +11,18 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -typealias DigestImpl = CoreCryptoDigestImpl -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -typealias DigestImplSHA3 = CoreCryptoDigestImpl -#else -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) typealias DigestImpl = OpenSSLDigestImpl -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) typealias DigestImplSHA3 = XKCPDigestImpl -#endif -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif /// A type that performs cryptographically secure hashing. /// @@ -55,16 +43,10 @@ public import Foundation /// incorporate a secret cryptographic key into the digest computation. Only a /// user that has the key can generate a valid MAC. @preconcurrency -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public protocol HashFunction: Sendable { /// The number of bytes that represents the hash function’s internal state. static var blockByteCount: Int { get } - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - /// The type of the digest returned by the hash function. - associatedtype Digest: CryptoKit.Digest - #else associatedtype Digest: Crypto.Digest - #endif /// Creates a hash function. /// @@ -110,7 +92,15 @@ public protocol HashFunction: Sendable { func finalize() -> Digest } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +extension HashFunction { + @inlinable + public mutating func update(bytes: RawSpan) { + bytes.withUnsafeBytes { + self.update(bufferPointer: $0) + } + } +} + extension HashFunction { /// Computes a digest of the buffer. /// @@ -123,6 +113,18 @@ extension HashFunction { hasher.update(bufferPointer: bufferPointer) return hasher.finalize() } + + /// Computes a digest of a span of bytes. + /// + /// - Parameters: + /// - bytes: The bytes to be hashed. + /// - Returns: The computed digest. + @inlinable + public static func hash(bytes: RawSpan) -> Digest { + var hasher = Self() + hasher.update(bytes: bytes) + return hasher.finalize() + } /// Computes the digest of the bytes in the given data instance and /// returns the computed digest. @@ -171,4 +173,4 @@ extension HashFunction { } } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Digests/HashFunctions_SHA2.swift b/Sources/Crypto/Digests/HashFunctions_SHA2.swift index 4ef40d75..3e406527 100644 --- a/Sources/Crypto/Digests/HashFunctions_SHA2.swift +++ b/Sources/Crypto/Digests/HashFunctions_SHA2.swift @@ -11,7 +11,8 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else /// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a @@ -26,7 +27,6 @@ /// in memory, you can compute the digest iteratively by creating a new hash /// instance, calling the ``update(data:)`` method repeatedly with blocks of /// data, and then calling the ``finalize()`` method to get the result. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public typealias SHA2_256 = SHA256 /// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a @@ -41,7 +41,6 @@ public typealias SHA2_256 = SHA256 /// in memory, you can compute the digest iteratively by creating a new hash /// instance, calling the ``update(data:)`` method repeatedly with blocks of /// data, and then calling the ``finalize()`` method to get the result. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SHA256: HashFunctionImplementationDetails, Sendable { /// The number of bytes that represents the hash function’s internal state. public static let blockByteCount: Int = 64 @@ -113,7 +112,6 @@ public struct SHA256: HashFunctionImplementationDetails, Sendable { /// in memory, you can compute the digest iteratively by creating a new hash /// instance, calling the ``update(data:)`` method repeatedly with blocks of /// data, and then calling the ``finalize()`` method to get the result. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public typealias SHA2_384 = SHA384 /// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a @@ -128,7 +126,6 @@ public typealias SHA2_384 = SHA384 /// in memory, you can compute the digest iteratively by creating a new hash /// instance, calling the ``update(data:)`` method repeatedly with blocks of /// data, and then calling the ``finalize()`` method to get the result. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SHA384: HashFunctionImplementationDetails, Sendable { /// The number of bytes that represents the hash function’s internal state. public static let blockByteCount: Int = 128 @@ -201,7 +198,6 @@ public struct SHA384: HashFunctionImplementationDetails, Sendable { /// in memory, you can compute the digest iteratively by creating a new hash /// instance, calling the ``update(data:)`` method repeatedly with blocks of /// data, and then calling the ``finalize()`` method to get the result. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public typealias SHA2_512 = SHA512 /// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a @@ -216,7 +212,6 @@ public typealias SHA2_512 = SHA512 /// in memory, you can compute the digest iteratively by creating a new hash /// instance, calling the ``update(data:)`` method repeatedly with blocks of /// data, and then calling the ``finalize()`` method to get the result. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SHA512: HashFunctionImplementationDetails, Sendable { /// The number of bytes that represents the hash function’s internal state. public static let blockByteCount: Int = 128 @@ -276,4 +271,4 @@ public struct SHA512: HashFunctionImplementationDetails, Sendable { return impl.finalize() } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Digests/HashFunctions_SHA3.swift b/Sources/Crypto/Digests/HashFunctions_SHA3.swift index bd4d8c56..f36a8ae6 100644 --- a/Sources/Crypto/Digests/HashFunctions_SHA3.swift +++ b/Sources/Crypto/Digests/HashFunctions_SHA3.swift @@ -11,7 +11,8 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else #if !CRYPTOKIT_IN_SEP @@ -26,7 +27,6 @@ /// applications can compute the digest iteratively by creating a new hash /// instance, calling the ``update(data:)`` method repeatedly with blocks of /// data, and then calling the ``finalize()`` method to get the result. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SHA3_256: HashFunctionImplementationDetails, Sendable { /// The number of bytes that represents the hash function’s internal state. public static let blockByteCount: Int = 136 @@ -97,7 +97,6 @@ public struct SHA3_256: HashFunctionImplementationDetails, Sendable { /// applications can compute the digest iteratively by creating a new hash /// instance, calling the ``update(data:)`` method repeatedly with blocks of /// data, and then calling the ``finalize()`` method to get the result. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SHA3_384: HashFunctionImplementationDetails, Sendable { /// The number of bytes that represents the hash function’s internal state. public static let blockByteCount: Int = 104 @@ -168,7 +167,6 @@ public struct SHA3_384: HashFunctionImplementationDetails, Sendable { /// applications can compute the digest iteratively by creating a new hash /// instance, calling the ``update(data:)`` method repeatedly with blocks of /// data, and then calling the ``finalize()`` method to get the result. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SHA3_512: HashFunctionImplementationDetails, Sendable { /// The number of bytes that represents the hash function’s internal state. public static let blockByteCount: Int = 72 @@ -228,4 +226,4 @@ public struct SHA3_512: HashFunctionImplementationDetails, Sendable { } } #endif // !CRYPTOKIT_IN_SEP -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Digests/XKCP/Digest_xkcp.swift b/Sources/Crypto/Digests/XKCP/Digest_xkcp.swift index 91a8c6f5..4cb54a8c 100644 --- a/Sources/Crypto/Digests/XKCP/Digest_xkcp.swift +++ b/Sources/Crypto/Digests/XKCP/Digest_xkcp.swift @@ -11,11 +11,16 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CXKCP +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CXKCPShims +#else @_implementationOnly import CXKCP @_implementationOnly import CXKCPShims +#endif @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol XKCPBackedHashFunction: HashFunctionImplementationDetails { @@ -149,7 +154,7 @@ private final class XKCPDigestContext { preconditionFailure("Unable to finalize digest state") } // We force unwrap here because if the digest size is wrong it's an internal error. - return H.Digest(bufferPointer: UnsafeRawBufferPointer(digestPointer))! + return H.Digest(copying: digestPointer.bytes)! } } @@ -157,4 +162,4 @@ private final class XKCPDigestContext { withUnsafeMutablePointer(to: &self.context) { $0.zeroize() } } } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/HPKE/Ciphersuite/HPKE-AEAD.swift b/Sources/Crypto/HPKE/Ciphersuite/HPKE-AEAD.swift index db00f1b1..4a2bd501 100644 --- a/Sources/Crypto/HPKE/Ciphersuite/HPKE-AEAD.swift +++ b/Sources/Crypto/HPKE/Ciphersuite/HPKE-AEAD.swift @@ -11,25 +11,20 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif - -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension HPKE { /// The authenticated encryption with associated data (AEAD) algorithms to use in HPKE. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + @nonexhaustive public enum AEAD: CaseIterable, Hashable, Sendable { /// An Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 128 bits. case AES_GCM_128 @@ -43,8 +38,7 @@ extension HPKE { case exportOnly /// Return the AEAD algorithm identifier as defined in section 7.3 of [RFC 9180](https://www.ietf.org/rfc/rfc9180.pdf). - @_spi(HPKEAlgID) - public var value: UInt16 { + internal var value: UInt16 { switch self { case .AES_GCM_128: return 0x0001 case .AES_GCM_256: return 0x0002 @@ -58,8 +52,7 @@ extension HPKE { } /// Return the AEAD key size in bytes - @_spi(HPKEAlgID) - public var keyByteCount: Int { + internal var keyByteCount: Int { switch self { case .AES_GCM_128: return 16 @@ -73,8 +66,7 @@ extension HPKE { } /// Return the AEAD nonce size in bytes - @_spi(HPKEAlgID) - public var nonceByteCount: Int { + internal var nonceByteCount: Int { switch self { case .AES_GCM_128, .AES_GCM_256, .chaChaPoly: return 12 @@ -84,8 +76,7 @@ extension HPKE { } /// Return the AEAD tag size in bytes - @_spi(HPKEAlgID) - public var tagByteCount: Int { + internal var tagByteCount: Int { switch self { case .AES_GCM_128, .AES_GCM_256, .chaChaPoly: return 16 @@ -98,8 +89,7 @@ extension HPKE { return I2OSP(value: Int(self.value), outputByteCount: 2) } - @_spi(MLS) - public func seal(_ message: D, authenticating aad: AD, nonce: Data, using key: SymmetricKey) throws -> Data { + internal func seal(_ message: D, authenticating aad: AD, nonce: Data, using key: SymmetricKey) throws -> Data { switch self { case .chaChaPoly: return try ChaChaPoly.seal(message, using: key, nonce: ChaChaPoly.Nonce(data: nonce), authenticating: aad).combined.dropFirst(nonce.count) @@ -108,8 +98,7 @@ extension HPKE { } } - @_spi(MLS) - public func open(_ ct: C, nonce: Data, authenticating aad: AD, using key: SymmetricKey) throws -> Data { + internal func open(_ ct: C, nonce: Data, authenticating aad: AD, using key: SymmetricKey) throws -> Data { guard ct.count >= self.tagByteCount else { throw HPKE.Errors.expectedPSK } @@ -132,4 +121,4 @@ extension HPKE { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/HPKE/Ciphersuite/HPKE-Ciphersuite.swift b/Sources/Crypto/HPKE/Ciphersuite/HPKE-Ciphersuite.swift index 69fbc0c9..b96591c5 100644 --- a/Sources/Crypto/HPKE/Ciphersuite/HPKE-Ciphersuite.swift +++ b/Sources/Crypto/HPKE/Ciphersuite/HPKE-Ciphersuite.swift @@ -11,22 +11,17 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif - -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension HPKE { /// Cipher suites to use in hybrid public key encryption (HPKE). /// @@ -34,7 +29,6 @@ extension HPKE { /// and decrypting messages, the key derivation function (KDF) for deriving the shared key, and the key encapsulation /// mechanism (KEM) for sharing the symmetric key. The sender and recipient of encrypted messages need to use the /// same cipher suite. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct Ciphersuite: Sendable { /// A cipher suite for HPKE that uses NIST P-256 elliptic curve key agreement, SHA-2 key derivation /// with a 256-bit digest, and the Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 256 bits. @@ -83,4 +77,4 @@ extension HPKE { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/HPKE/Ciphersuite/HPKE-KDF.swift b/Sources/Crypto/HPKE/Ciphersuite/HPKE-KDF.swift index 19f0158f..d45f65c8 100644 --- a/Sources/Crypto/HPKE/Ciphersuite/HPKE-KDF.swift +++ b/Sources/Crypto/HPKE/Ciphersuite/HPKE-KDF.swift @@ -11,24 +11,20 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension HPKE { /// The key derivation functions to use in HPKE. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + @nonexhaustive public enum KDF: CaseIterable, Hashable, Sendable { /// An HMAC-based key derivation function that uses SHA-2 hashing with a 256-bit digest. case HKDF_SHA256 @@ -38,8 +34,7 @@ extension HPKE { case HKDF_SHA512 /// Return the KDF algorithm identifier as defined in section 7.2 of [RFC 9180](https://www.ietf.org/rfc/rfc9180.pdf). - @_spi(HPKEAlgID) - public var value: UInt16 { + internal var value: UInt16 { switch self { case .HKDF_SHA256: return 0x0001 case .HKDF_SHA384: return 0x0002 @@ -73,8 +68,7 @@ extension HPKE { /// - ikm: The initial key material the derivation function uses to derive a key. /// /// - Returns: A pseudorandom, cryptographically strong key in the form of a hashed authentication code. - @_spi(MLS) - public func extract(salt: S, ikm: SymmetricKey) -> SymmetricKey { + internal func extract(salt: S, ikm: SymmetricKey) -> SymmetricKey { switch self { case .HKDF_SHA256: return SymmetricKey(data: HKDF.extract(inputKeyMaterial: ikm, salt: salt)) @@ -96,8 +90,7 @@ extension HPKE { /// - outputByteCount: The length in bytes of the resulting symmetric key. /// /// - Returns: The derived symmetric key. - @_spi(MLS) - public func expand(prk: SymmetricKey, info: Data, outputByteCount: Int) -> SymmetricKey { + internal func expand(prk: SymmetricKey, info: Data, outputByteCount: Int) -> SymmetricKey { switch self { case .HKDF_SHA256: return SymmetricKey(data: HKDF.expand(pseudoRandomKey: prk, info: info, outputByteCount: outputByteCount)) @@ -110,4 +103,4 @@ extension HPKE { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/HPKE/Ciphersuite/HPKE-KexKeyDerivation.swift b/Sources/Crypto/HPKE/Ciphersuite/HPKE-KexKeyDerivation.swift index 45220fd3..aea30291 100644 --- a/Sources/Crypto/HPKE/Ciphersuite/HPKE-KexKeyDerivation.swift +++ b/Sources/Crypto/HPKE/Ciphersuite/HPKE-KexKeyDerivation.swift @@ -11,39 +11,28 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) private let suiteIDLabel = Data("KEM".utf8) -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension HPKE { - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct KexUtils { static func ExtractAndExpand(dh: ContiguousBytes, enc: Data, pkRm: Data, pkSm: Data? = nil, kem: HPKE.KEM, kdf: HPKE.KDF) -> SymmetricKey { var suiteID = suiteIDLabel suiteID.append(kem.identifier) - #if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API - return CryptoKit.ExtractAndExpand(zz: dh, kemContext: kemContext(enc: enc, pkRm: pkRm, pkSm: pkSm), - suiteID: suiteID, kem: kem, kdf: kdf) - #else return Crypto.ExtractAndExpand(zz: dh, kemContext: kemContext(enc: enc, pkRm: pkRm, pkSm: pkSm), suiteID: suiteID, kem: kem, kdf: kdf) - #endif } static func kemContext(enc: Data, pkRm: Data, pkSm: Data? = nil) -> Data { @@ -56,4 +45,4 @@ extension HPKE { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/HPKE/Ciphersuite/HPKE-LabeledExtract.swift b/Sources/Crypto/HPKE/Ciphersuite/HPKE-LabeledExtract.swift index ba8d4b38..c468e997 100644 --- a/Sources/Crypto/HPKE/Ciphersuite/HPKE-LabeledExtract.swift +++ b/Sources/Crypto/HPKE/Ciphersuite/HPKE-LabeledExtract.swift @@ -11,47 +11,36 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) private let protocolLabel = Data("HPKE-v1".utf8) -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) private let eaePRKLabel = Data("eae_prk".utf8) -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) private let sharedSecretLabel = Data("shared_secret".utf8) -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Data { internal init(unsafeFromContiguousBytes cb: ContiguousBytes) { self = cb.withUnsafeBytes { return Data($0) } } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal func ExtractAndExpand(zz: ContiguousBytes, kemContext: Data, suiteID: Data, kem: HPKE.KEM, kdf: HPKE.KDF) -> SymmetricKey { - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) let eaePrk = LabeledExtract(salt: Data(), label: eaePRKLabel, ikm: zz, suiteID: suiteID, kdf: kdf) return LabeledExpand(prk: eaePrk, label: sharedSecretLabel, info: kemContext, outputByteCount: kem.nSecret, suiteID: suiteID, kdf: kdf) } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal func LabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, suiteID: Data, kdf: HPKE.KDF) -> SymmetricKey { - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) var labeled_ikm = protocolLabel labeled_ikm.append(suiteID) labeled_ikm.append(label) @@ -59,9 +48,7 @@ internal func LabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, su return kdf.extract(salt: salt ?? Data(), ikm: SymmetricKey(data: labeled_ikm)) } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal func LabeledExpand(prk: SymmetricKey, label: Data, info: Info, outputByteCount: UInt16, suiteID: Data, kdf: HPKE.KDF) -> SymmetricKey { - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) var labeled_info = I2OSP(value: Int(outputByteCount), outputByteCount: 2) labeled_info.append(protocolLabel) labeled_info.append(suiteID) @@ -70,14 +57,12 @@ internal func LabeledExpand(prk: SymmetricKey, label: Data, return kdf.expand(prk: prk, info: labeled_info, outputByteCount: Int(outputByteCount)) } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal func NonSecretOutputLabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, suiteID: Data, kdf: HPKE.KDF) -> Data { return Data(unsafeFromContiguousBytes: LabeledExtract(salt: salt, label: label, ikm: ikm, suiteID: suiteID, kdf: kdf)) } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal func NonSecretOutputLabeledExpand(prk: SymmetricKey, label: Data, info: Data, outputByteCount: UInt16, suiteID: Data, kdf: HPKE.KDF) -> Data { return Data(unsafeFromContiguousBytes: LabeledExpand(prk: prk, label: label, info: info, outputByteCount: outputByteCount, suiteID: suiteID, kdf: kdf)) } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/HPKE/Ciphersuite/HPKE-Utils.swift b/Sources/Crypto/HPKE/Ciphersuite/HPKE-Utils.swift index e60e6ef7..89bc056f 100644 --- a/Sources/Crypto/HPKE/Ciphersuite/HPKE-Utils.swift +++ b/Sources/Crypto/HPKE/Ciphersuite/HPKE-Utils.swift @@ -11,13 +11,11 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) #if os(Windows) import ucrt @@ -36,25 +34,16 @@ import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal func I2OSP(value: Int, outputByteCount: Int) -> Data { precondition(outputByteCount > 0, "Cannot I2OSP with no output length.") precondition(value >= 0, "I2OSP requires a non-null value.") - #if !CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) let requiredBytes = Int(ceil(log2(Double(max(value, 1) + 1)) / 8)) - #else - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) - let requiredBytes = Int((log2_bridge(Double(max(value, 1) + 1)) / 8).rounded(.up)) - #endif precondition(outputByteCount >= requiredBytes) - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) var data = Data(repeating: 0, count: outputByteCount) for i in (outputByteCount - requiredBytes)...(outputByteCount - 1) { @@ -64,4 +53,4 @@ internal func I2OSP(value: Int, outputByteCount: Int) -> Data { return data } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/HPKE/Ciphersuite/KEM/Conformances/DHKEM.swift b/Sources/Crypto/HPKE/Ciphersuite/KEM/Conformances/DHKEM.swift index e6e483ac..0f34c661 100644 --- a/Sources/Crypto/HPKE/Ciphersuite/KEM/Conformances/DHKEM.swift +++ b/Sources/Crypto/HPKE/Ciphersuite/KEM/Conformances/DHKEM.swift @@ -11,23 +11,19 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif /// A type that ``HPKE`` uses to encode the public key. @preconcurrency -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public protocol HPKEPublicKeySerialization: Sendable { /// Creates a public key from an encoded representation. /// @@ -46,7 +42,6 @@ public protocol HPKEPublicKeySerialization: Sendable { /// A type that represents the public key in a Diffie-Hellman key exchange. @preconcurrency -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public protocol HPKEDiffieHellmanPublicKey: HPKEPublicKeySerialization, Sendable where EphemeralPrivateKey.PublicKey == Self { /// The type of the ephemeral private key. associatedtype EphemeralPrivateKey: HPKEDiffieHellmanPrivateKeyGeneration @@ -54,7 +49,6 @@ public protocol HPKEDiffieHellmanPublicKey: HPKEPublicKeySerialization, Sendable /// A type that represents the public key in HPKE @preconcurrency -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public protocol HPKEKEMPublicKey: KEMPublicKey, HPKEPublicKeySerialization where EphemeralPrivateKey.PublicKey == Self { /// The type of the ephemeral private key. associatedtype EphemeralPrivateKey: HPKEKEMPrivateKeyGeneration @@ -62,17 +56,14 @@ public protocol HPKEKEMPublicKey: KEMPublicKey, HPKEPublicKeySerialization where /// A type that represents the private key in a Diffie-Hellman key exchange. @preconcurrency -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public protocol HPKEDiffieHellmanPrivateKey: Sendable, DiffieHellmanKeyAgreement where PublicKey: HPKEDiffieHellmanPublicKey {} /// A type that represents the private key in HPKE. @preconcurrency -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public protocol HPKEKEMPrivateKey: Sendable, KEMPrivateKey where PublicKey: HPKEKEMPublicKey {} /// A type that represents the generation of private keys in a Diffie-Hellman key exchange. @preconcurrency -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public protocol HPKEDiffieHellmanPrivateKeyGeneration: HPKEDiffieHellmanPrivateKey, Sendable { /// Creates a private key generator. init() @@ -80,27 +71,20 @@ public protocol HPKEDiffieHellmanPrivateKeyGeneration: HPKEDiffieHellmanPrivateK /// A type that represents the generation of private keys in HPKE @preconcurrency -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public protocol HPKEKEMPrivateKeyGeneration: HPKEKEMPrivateKey, Sendable { /// Creates a private key generator. init() throws } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension HPKE { /// A container for Diffie-Hellman key encapsulation mechanisms (KEMs). - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + @nonexhaustive public enum DHKEM: Sendable { - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct PublicKey: KEMPublicKey where DHPK == DHPK.EphemeralPrivateKey.PublicKey { let kem: HPKE.KEM let key: DHPK - #if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API - typealias EncapsulationResult = CryptoKit.KEM.EncapsulationResult - #else typealias EncapsulationResult = Crypto.KEM.EncapsulationResult - #endif init(_ publicKey: DHPK, kem: HPKE.KEM) throws { // TODO: Validate Ciphersuite Mismatches @@ -124,7 +108,6 @@ extension HPKE { } } - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct PrivateKey: KEMPrivateKey { let kem: HPKE.KEM let key: DHSK @@ -185,4 +168,4 @@ extension HPKE { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/HPKE/Ciphersuite/KEM/Conformances/HPKE-KEM-Curve25519.swift b/Sources/Crypto/HPKE/Ciphersuite/KEM/Conformances/HPKE-KEM-Curve25519.swift index 2d707f3a..e8c02175 100644 --- a/Sources/Crypto/HPKE/Ciphersuite/KEM/Conformances/HPKE-KEM-Curve25519.swift +++ b/Sources/Crypto/HPKE/Ciphersuite/KEM/Conformances/HPKE-KEM-Curve25519.swift @@ -11,26 +11,19 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif - -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Curve25519.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {} - -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Curve25519.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey { /// The type of the ephemeral private key associated with this public key. public typealias EphemeralPrivateKey = Curve25519.KeyAgreement.PrivateKey @@ -73,4 +66,4 @@ extension Curve25519.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey { public typealias HPKEEphemeralPrivateKey = Curve25519.KeyAgreement.PrivateKey } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/HPKE/Ciphersuite/KEM/Conformances/HPKE-NIST-EC-KEMs.swift b/Sources/Crypto/HPKE/Ciphersuite/KEM/Conformances/HPKE-NIST-EC-KEMs.swift index 2d20fdad..f73dc930 100644 --- a/Sources/Crypto/HPKE/Ciphersuite/KEM/Conformances/HPKE-NIST-EC-KEMs.swift +++ b/Sources/Crypto/HPKE/Ciphersuite/KEM/Conformances/HPKE-NIST-EC-KEMs.swift @@ -11,21 +11,17 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P256.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration { /// Creates a NIST P-256 elliptic curve private key for use with Diffie-Hellman key exchange. public init() { @@ -33,8 +29,6 @@ extension P256.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration { } } - -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P256.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey { /// The type of the ephemeral private key associated with this public key. public typealias EphemeralPrivateKey = P256.KeyAgreement.PrivateKey @@ -74,8 +68,6 @@ extension P256.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey { public typealias HPKEEphemeralPrivateKey = P256.KeyAgreement.PrivateKey } - -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P384.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration { /// Creates a NIST P-384 elliptic curve private key for use with Diffie-Hellman key exchange. public init() { @@ -83,8 +75,6 @@ extension P384.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration { } } - -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P384.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey { /// The type of the ephemeral private key associated with this public key. public typealias EphemeralPrivateKey = P384.KeyAgreement.PrivateKey @@ -124,8 +114,6 @@ extension P384.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey { } } - -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P521.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration { /// Creates a NIST P-521 elliptic curve private key for use with Diffie-Hellman key exchange. public init() { @@ -133,8 +121,6 @@ extension P521.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration { } } - -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P521.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey { /// The type of the ephemeral private key associated with this public key. public typealias EphemeralPrivateKey = P521.KeyAgreement.PrivateKey @@ -177,4 +163,4 @@ extension P521.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey { public typealias HPKEEphemeralPrivateKey = P521.KeyAgreement.PrivateKey } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/HPKE/Ciphersuite/KEM/HPKE-KEM.swift b/Sources/Crypto/HPKE/Ciphersuite/KEM/HPKE-KEM.swift index a3e51c75..a0cbf575 100644 --- a/Sources/Crypto/HPKE/Ciphersuite/KEM/HPKE-KEM.swift +++ b/Sources/Crypto/HPKE/Ciphersuite/KEM/HPKE-KEM.swift @@ -11,30 +11,28 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension HPKE { /// The key encapsulation mechanisms to use in HPKE. /// /// The module-lattice key encapsulation mechanism (ML-KEM) is designed to offer increased security in situations /// where an adversary uses a quantum computer. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + @nonexhaustive public enum KEM: CaseIterable, Hashable, Sendable { public static var allCases: [HPKE.KEM] { var cases = [KEM.P256_HKDF_SHA256, KEM.P384_HKDF_SHA384, KEM.P521_HKDF_SHA512, KEM.Curve25519_HKDF_SHA256] - cases.append(KEM.XWingMLKEM768X25519) + if #available(iOS 19.0, macOS 16.0, watchOS 12.0, tvOS 19.0, macCatalyst 19.0, *) { + cases.append(KEM.XWingMLKEM768X25519) + } return cases } @@ -55,8 +53,7 @@ extension HPKE { case XWingMLKEM768X25519 /// Return the KEM algorithm identifier as defined in section 7.1 of [RFC 9180](https://www.ietf.org/rfc/rfc9180.pdf). - @_spi(HPKEAlgID) - public var value: UInt16 { + internal var value: UInt16 { switch self { case .P256_HKDF_SHA256: return 0x0010 case .P384_HKDF_SHA384: return 0x0011 @@ -91,8 +88,7 @@ extension HPKE { } /// Return the size of the encapsulation in bytes - @_spi(HPKEAlgID) - public var nEnc: UInt16 { + internal var nEnc: UInt16 { switch self { case .P256_HKDF_SHA256: return 65 case .P384_HKDF_SHA384: return 97 @@ -104,4 +100,4 @@ extension HPKE { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/HPKE/HPKE-Errors.swift b/Sources/Crypto/HPKE/HPKE-Errors.swift index 677bcfb5..14d6a129 100644 --- a/Sources/Crypto/HPKE/HPKE-Errors.swift +++ b/Sources/Crypto/HPKE/HPKE-Errors.swift @@ -11,24 +11,20 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension HPKE { /// Hybrid public key encryption (HPKE) errors that CryptoKit uses. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + @nonexhaustive public enum Errors: Error { /// The parameters for initializing an HPKE sender or receiver are inconsistent. case inconsistentParameters @@ -49,4 +45,4 @@ extension HPKE { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/HPKE/HPKE.swift b/Sources/Crypto/HPKE/HPKE.swift index 9a3c3958..7305decf 100644 --- a/Sources/Crypto/HPKE/HPKE.swift +++ b/Sources/Crypto/HPKE/HPKE.swift @@ -11,18 +11,15 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif /// A container for hybrid public key encryption (HPKE) operations. /// @@ -53,10 +50,9 @@ public import Foundation /// /// ### Handling errors /// - ``Errors`` -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +@nonexhaustive public enum HPKE: Sendable {} -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension HPKE { /// Static constant used to store the fixed-string label for the HPKE export API /// See: https://datatracker.ietf.org/doc/html/rfc9180#name-secret-export @@ -70,7 +66,6 @@ extension HPKE { /// in turn to retrieve its ciphertext. The recipient of the messages needs to process them in the /// same order as the `Sender`, using the same encryption mode, cipher suite, and key schedule information /// (`info`), as well as the `Sender`'s ``encapsulatedKey``. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct Sender: Sendable { private var context: Context /// The encapsulated symmetric key that the recipient uses to decrypt messages. @@ -225,7 +220,6 @@ extension HPKE { /// same order as the `Sender`, using the same cipher suite, encryption mode, and key schedule information /// (`info` data). /// Use a separate `Recipient` instance for each stream of messages. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct Recipient: Sendable { private var context: Context @@ -364,4 +358,4 @@ extension HPKE { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/HPKE/Key Schedule/HPKE-Context.swift b/Sources/Crypto/HPKE/Key Schedule/HPKE-Context.swift index 41ab963f..3a0a7212 100644 --- a/Sources/Crypto/HPKE/Key Schedule/HPKE-Context.swift +++ b/Sources/Crypto/HPKE/Key Schedule/HPKE-Context.swift @@ -11,23 +11,18 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension HPKE { - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct Context: Sendable { var keySchedule: KeySchedule var encapsulated: Data @@ -81,4 +76,4 @@ extension HPKE { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/HPKE/Key Schedule/HPKE-KeySchedule.swift b/Sources/Crypto/HPKE/Key Schedule/HPKE-KeySchedule.swift index 1569a88f..2d63daaf 100644 --- a/Sources/Crypto/HPKE/Key Schedule/HPKE-KeySchedule.swift +++ b/Sources/Crypto/HPKE/Key Schedule/HPKE-KeySchedule.swift @@ -11,23 +11,18 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension HPKE { - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal struct KeySchedule: Sendable { fileprivate static let pksIDHashLabel = Data("psk_id_hash".utf8) fileprivate static let infoHashLabel = Data("info_hash".utf8) @@ -163,4 +158,4 @@ extension HPKE { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/HPKE/Modes/HPKE-Modes.swift b/Sources/Crypto/HPKE/Modes/HPKE-Modes.swift index bae1d76d..e0f6e314 100644 --- a/Sources/Crypto/HPKE/Modes/HPKE-Modes.swift +++ b/Sources/Crypto/HPKE/Modes/HPKE-Modes.swift @@ -11,14 +11,12 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension HPKE { - - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal enum Mode: CaseIterable { case base case psk @@ -40,4 +38,4 @@ extension HPKE { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Insecure/Insecure.swift b/Sources/Crypto/Insecure/Insecure.swift index da38f7c8..0c4163c1 100644 --- a/Sources/Crypto/Insecure/Insecure.swift +++ b/Sources/Crypto/Insecure/Insecure.swift @@ -11,7 +11,8 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else /// A container for older, cryptographically insecure algorithms. @@ -19,6 +20,6 @@ /// - Important: These algorithms aren’t considered cryptographically secure, /// but the framework provides them for backward compatibility with older /// services that require them. For new services, avoid these algorithms. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +@nonexhaustive public enum Insecure: Sendable {} -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Insecure/Insecure_HashFunctions.swift b/Sources/Crypto/Insecure/Insecure_HashFunctions.swift index 6d12e6a3..95dcbc0d 100644 --- a/Sources/Crypto/Insecure/Insecure_HashFunctions.swift +++ b/Sources/Crypto/Insecure/Insecure_HashFunctions.swift @@ -11,10 +11,10 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Insecure { /// An implementation of SHA1 hashing. /// @@ -32,7 +32,6 @@ extension Insecure { /// secure, but is provided for backward compatibility with older services /// that require it. For new services, prefer one of the secure hashes, like /// ``SHA512``. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SHA1: HashFunctionImplementationDetails, Sendable { /// The number of bytes that represents the hash function’s internal /// state. @@ -113,7 +112,6 @@ extension Insecure { /// secure, but is provided for backward compatibility with older services /// that require it. For new services, prefer one of the secure hashes, like /// ``SHA512``. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct MD5: HashFunctionImplementationDetails, Sendable { /// The number of bytes that represents the hash function’s internal /// state. @@ -177,4 +175,4 @@ extension Insecure { } } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/KEM/BoringSSL/MLKEM_boring.swift b/Sources/Crypto/KEM/BoringSSL/MLKEM_boring.swift index 77b6d6cb..c51c616c 100644 --- a/Sources/Crypto/KEM/BoringSSL/MLKEM_boring.swift +++ b/Sources/Crypto/KEM/BoringSSL/MLKEM_boring.swift @@ -16,10 +16,14 @@ // any edits of this file WILL be overwritten and thus discarded // see section `gyb` in `README` for details. -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL +#endif #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -29,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 @@ -175,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 @@ -296,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 @@ -442,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 @@ -560,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 @@ -568,4 +577,4 @@ enum MLKEM { static let sharedSecretByteCount = 32 } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/KEM/BoringSSL/MLKEM_boring.swift.gyb b/Sources/Crypto/KEM/BoringSSL/MLKEM_boring.swift.gyb index 112376e5..825fe21b 100644 --- a/Sources/Crypto/KEM/BoringSSL/MLKEM_boring.swift.gyb +++ b/Sources/Crypto/KEM/BoringSSL/MLKEM_boring.swift.gyb @@ -16,10 +16,14 @@ // any edits of this file WILL be overwritten and thus discarded // see section `gyb` in `README` for details. -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL +#endif #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -306,4 +310,4 @@ enum MLKEM { static let sharedSecretByteCount = 32 } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/KEM/BoringSSL/MLKEM_wrapper.swift b/Sources/Crypto/KEM/BoringSSL/MLKEM_wrapper.swift index 4400dbd7..743379db 100644 --- a/Sources/Crypto/KEM/BoringSSL/MLKEM_wrapper.swift +++ b/Sources/Crypto/KEM/BoringSSL/MLKEM_wrapper.swift @@ -12,10 +12,14 @@ // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL +#endif #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -289,4 +293,4 @@ struct OpenSSLMLKEMPrivateKeyImpl: B } } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/KEM/BoringSSL/XWing_boring.swift b/Sources/Crypto/KEM/BoringSSL/XWing_boring.swift index 9496f3dc..332e58cf 100644 --- a/Sources/Crypto/KEM/BoringSSL/XWing_boring.swift +++ b/Sources/Crypto/KEM/BoringSSL/XWing_boring.swift @@ -12,10 +12,14 @@ // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL +#endif #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -127,6 +131,7 @@ struct OpenSSLXWingPrivateKeyImpl: Sendable { @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension OpenSSLXWingPrivateKeyImpl { + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) final class Backing: @unchecked Sendable { private var privateKey: XWING_private_key @@ -259,4 +264,4 @@ extension OpenSSLXWingPrivateKeyImpl { } } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/KEM/KEM-Errors.swift b/Sources/Crypto/KEM/KEM-Errors.swift index 2f2fdfb3..67d3b5ad 100644 --- a/Sources/Crypto/KEM/KEM-Errors.swift +++ b/Sources/Crypto/KEM/KEM-Errors.swift @@ -11,24 +11,20 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension KEM { /// Errors that CryptoKit throws when it encounters problems in key encapsulation mechanism (KEM) operations. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + @nonexhaustive public enum Errors: Error { /// The public key CryptoKit receives when it initializes a key encapsulation operation doesn't match the expected value. case publicKeyMismatchDuringInitialization @@ -38,4 +34,4 @@ extension KEM { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/KEM/KEM.swift b/Sources/Crypto/KEM/KEM.swift index 9b8466aa..915d7090 100644 --- a/Sources/Crypto/KEM/KEM.swift +++ b/Sources/Crypto/KEM/KEM.swift @@ -11,27 +11,23 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif /// A key encapsulation mechanism. /// /// Use a key encapsulation mechanism (KEM) to protect a symmetric cryptographic key that you share with another party. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +@nonexhaustive public enum KEM: Sendable { /// The result of a key encapsulation operation. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct EncapsulationResult: Sendable { /// The shared secret. public let sharedSecret: SymmetricKey @@ -48,7 +44,6 @@ public enum KEM: Sendable { /// The public key for a key encapsulation mechanism. @preconcurrency -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public protocol KEMPublicKey: Sendable { /// Generates and encapsulates a shared secret. /// @@ -60,7 +55,6 @@ public protocol KEMPublicKey: Sendable { /// The private key for a key encapsulation mechanism. @preconcurrency -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public protocol KEMPrivateKey: Sendable { associatedtype PublicKey: KEMPublicKey @@ -79,4 +73,25 @@ public protocol KEMPrivateKey: Sendable { /// The associated public key. var publicKey: PublicKey { get } } -#endif // Linux or !SwiftPM + +/// A one-time private key for a key encapsulation mechanism, which can only decapsulate once but it does so faster. +@preconcurrency +public protocol KEMOneTimePrivateKey: ~Copyable, Sendable { + associatedtype PublicKey: KEMPublicKey + + /// Generates a new random private key. + /// - Returns: The generated private key. + /// + /// Give the ``publicKey`` to another person so that they can encapsulate + /// shared secrets that you recover by calling ``decapsulate(_:)``. + static func generate() throws -> Self + + /// Recovers a shared secret from an encapsulated representation. + /// - Parameter encapsulated: The encapsulated shared secret that someone created using this key's ``publicKey``. + /// - Returns: The decapsulated shared secret. + consuming func decapsulate(_ encapsulated: Data) throws -> SymmetricKey + + /// The associated public key. + var publicKey: PublicKey { get } +} +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/KEM/MLKEM.swift b/Sources/Crypto/KEM/MLKEM.swift index 3883fbd4..16585ae3 100644 --- a/Sources/Crypto/KEM/MLKEM.swift +++ b/Sources/Crypto/KEM/MLKEM.swift @@ -11,7 +11,8 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else #if canImport(FoundationEssentials) @@ -20,27 +21,17 @@ public import FoundationEssentials public import Foundation #endif -#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -typealias MLKEMPublicKeyImpl = CoreCryptoMLKEMPublicKeyImpl -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -typealias MLKEMPrivateKeyImpl = CoreCryptoMLKEMPrivateKeyImpl -#else -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) typealias MLKEMPublicKeyImpl = OpenSSLMLKEMPublicKeyImpl -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) typealias MLKEMPrivateKeyImpl = OpenSSLMLKEMPrivateKeyImpl -#endif +typealias MLKEMOneTimePrivateKeyImpl = OpenSSLMLKEMPrivateKeyImpl /// The Module-Lattice key encapsulation mechanism (KEM). -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +@nonexhaustive public enum MLKEM768: Sendable {} -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension MLKEM768 { /// A public key you use to encapsulate shared secrets with the Module-Lattice key encapsulation mechanism. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PublicKey: KEMPublicKey, Sendable { var impl: MLKEMPublicKeyImpl @@ -70,7 +61,6 @@ extension MLKEM768 { } /// A private key you use to decapsulate shared secrets with the Module-Lattice key encapsulation mechanism. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PrivateKey: KEMPrivateKey { internal let impl: MLKEMPrivateKeyImpl @@ -116,7 +106,7 @@ extension MLKEM768 { } } - /// Decapsulated a shared secret. + /// Decapsulate a shared secret. /// /// - Parameters: /// - encapsulated: An encapsulated shared secret, that you get by calling ``MLKEM768/PublicKey/encapsulate()`` on the corresponding public key. @@ -128,7 +118,7 @@ extension MLKEM768 { /// The corresponding public key. public var publicKey: MLKEM768.PublicKey { get { - try self.impl.publicKey + self.impl.publicKey } } @@ -141,7 +131,7 @@ extension MLKEM768 { } let seed = Data(integrityCheckedRepresentation).subdata(in: 0...seedSize) let publicKeyHashData = Data(integrityCheckedRepresentation).subdata(in: MLKEMPrivateKeyImpl.seedSize..(seedRepresentation: seed, publicKeyHash: publicKeyHash) } @@ -155,17 +145,64 @@ extension MLKEM768 { } } } + + /// A one-time-use private key to decapsulate a shared secret with the Module-Lattice key encapsulation mechanism. + /// + /// The associated decapsulation function can be multiple times faster than the one implemented for PrivateKey, + /// but this private key can only be used to decapsulate a shared secret once. + public struct OneTimePrivateKey: KEMOneTimePrivateKey, ~Copyable { + internal let impl: MLKEMOneTimePrivateKeyImpl + + internal init(_ impl: MLKEMOneTimePrivateKeyImpl) { + self.impl = impl + } + + /// Creates a one-time-use private key that reuses the key material of an existing private key. + /// + /// This is used by the tests to check that the one-time decapsulation function is consistent with the regular one. + internal init(reusingForTestingOnly privateKey: MLKEM768.PrivateKey) { + self.impl = try! MLKEMOneTimePrivateKeyImpl( + seedRepresentation: privateKey.impl.seedRepresentation, + publicKeyRawRepresentation: privateKey.impl.publicKey.rawRepresentation + ) + } + + /// Generates a new, random one-time-use private key. + public static func generate() throws -> MLKEM768.OneTimePrivateKey { + let impl = try MLKEMOneTimePrivateKeyImpl.generatePrivateKey() + return OneTimePrivateKey(impl) + } + + /// Initializes a random one-time-use private key. + public init() throws { + self = try OneTimePrivateKey.generate() + } + + /// Decapsulate a shared secret. + /// + /// - Parameters: + /// - encapsulated: An encapsulated shared secret, that you get by calling ``MLKEM768/PublicKey/encapsulate()`` on the corresponding public key. + /// - Returns: The shared secret. + public consuming func decapsulate(_ encapsulated: D) throws -> SymmetricKey { + return try impl.decapsulate(encapsulated: encapsulated) + } + + /// The corresponding public key. + public var publicKey: MLKEM768.PublicKey { + get { + self.impl.publicKey + } + } + } } /// The Module-Lattice key encapsulation mechanism (KEM). -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +@nonexhaustive public enum MLKEM1024: Sendable {} -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension MLKEM1024 { /// A public key you use to encapsulate shared secrets with the Module-Lattice key encapsulation mechanism. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PublicKey: KEMPublicKey, Sendable { var impl: MLKEMPublicKeyImpl @@ -195,7 +232,6 @@ extension MLKEM1024 { } /// A private key you use to decapsulate shared secrets with the Module-Lattice key encapsulation mechanism. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PrivateKey: KEMPrivateKey { internal let impl: MLKEMPrivateKeyImpl @@ -241,7 +277,7 @@ extension MLKEM1024 { } } - /// Decapsulated a shared secret. + /// Decapsulate a shared secret. /// /// - Parameters: /// - encapsulated: An encapsulated shared secret, that you get by calling ``MLKEM1024/PublicKey/encapsulate()`` on the corresponding public key. @@ -253,7 +289,7 @@ extension MLKEM1024 { /// The corresponding public key. public var publicKey: MLKEM1024.PublicKey { get { - try self.impl.publicKey + self.impl.publicKey } } @@ -266,7 +302,7 @@ extension MLKEM1024 { } let seed = Data(integrityCheckedRepresentation).subdata(in: 0...seedSize) let publicKeyHashData = Data(integrityCheckedRepresentation).subdata(in: MLKEMPrivateKeyImpl.seedSize..(seedRepresentation: seed, publicKeyHash: publicKeyHash) } @@ -280,7 +316,56 @@ extension MLKEM1024 { } } } + + /// A one-time-use private key to decapsulate a shared secret with the Module-Lattice key encapsulation mechanism. + /// + /// The associated decapsulation function can be multiple times faster than the one implemented for PrivateKey, + /// but this private key can only be used to decapsulate a shared secret once. + public struct OneTimePrivateKey: KEMOneTimePrivateKey, ~Copyable { + internal let impl: MLKEMOneTimePrivateKeyImpl + + internal init(_ impl: MLKEMOneTimePrivateKeyImpl) { + self.impl = impl + } + + /// Creates a one-time-use private key that reuses the key material of an existing private key. + /// + /// This is used by the tests to check that the one-time decapsulation function is consistent with the regular one. + internal init(reusingForTestingOnly privateKey: MLKEM1024.PrivateKey) { + self.impl = try! MLKEMOneTimePrivateKeyImpl( + seedRepresentation: privateKey.impl.seedRepresentation, + publicKeyRawRepresentation: privateKey.impl.publicKey.rawRepresentation + ) + } + + /// Generates a new, random one-time-use private key. + public static func generate() throws -> MLKEM1024.OneTimePrivateKey { + let impl = try MLKEMOneTimePrivateKeyImpl.generatePrivateKey() + return OneTimePrivateKey(impl) + } + + /// Initializes a random one-time-use private key. + public init() throws { + self = try OneTimePrivateKey.generate() + } + + /// Decapsulate a shared secret. + /// + /// - Parameters: + /// - encapsulated: An encapsulated shared secret, that you get by calling ``MLKEM1024/PublicKey/encapsulate()`` on the corresponding public key. + /// - Returns: The shared secret. + public consuming func decapsulate(_ encapsulated: D) throws -> SymmetricKey { + return try impl.decapsulate(encapsulated: encapsulated) + } + + /// The corresponding public key. + public var publicKey: MLKEM1024.PublicKey { + get { + self.impl.publicKey + } + } + } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/KEM/MLKEM.swift.gyb b/Sources/Crypto/KEM/MLKEM.swift.gyb deleted file mode 100644 index 3a171943..00000000 --- a/Sources/Crypto/KEM/MLKEM.swift.gyb +++ /dev/null @@ -1,162 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the SwiftCrypto open source project -// -// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@_exported import CryptoKit -#else -#if canImport(FoundationEssentials) -public import FoundationEssentials -#else -public import Foundation -#endif -%{ - MLKEM_VARIANTS = [{"name": "MLKEM768", "ccinfo": "cckem_mlkem768()!"}, {"name": "MLKEM1024", "ccinfo": "cckem_mlkem1024()!"}] -}% - -#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -typealias MLKEMPublicKeyImpl = CoreCryptoMLKEMPublicKeyImpl -typealias MLKEMPrivateKeyImpl = CoreCryptoMLKEMPrivateKeyImpl -#else -typealias MLKEMPublicKeyImpl = OpenSSLMLKEMPublicKeyImpl -typealias MLKEMPrivateKeyImpl = OpenSSLMLKEMPrivateKeyImpl -#endif - -% for MLKEM_VARIANT in MLKEM_VARIANTS: -%{ - NAME = MLKEM_VARIANT["name"] - INFO = MLKEM_VARIANT["ccinfo"] -}% - -/// The Module-Lattice key encapsulation mechanism (KEM). -public enum ${NAME}: Sendable {} - -extension ${NAME} { - /// A public key you use to encapsulate shared secrets with the Module-Lattice key encapsulation mechanism. - public struct PublicKey: KEMPublicKey, Sendable { - var impl: MLKEMPublicKeyImpl<${NAME}> - - /// Initializes a public key from a raw representation. - /// - Parameter rawRepresentation: Data that represents the public key. - public init(rawRepresentation: D) throws { - self.impl = try MLKEMPublicKeyImpl(rawRepresentation: rawRepresentation) - } - - /// A serialized representation of the public key. - public var rawRepresentation: Data { - get { - return self.impl.rawRepresentation - } - } - - /// Generates and encapsulates a shared secret. - /// - /// - Returns: an encapsulated shared secret, that you decapsulate by calling ``${NAME}/PrivateKey/decapsulate(_:)`` on the corresponding private key. - public func encapsulate() throws -> KEM.EncapsulationResult { - return try self.impl.encapsulate() - } - - func encapsulateWithSeed(encapSeed: Data) throws -> KEM.EncapsulationResult { - return try self.impl.encapsulateWithSeed(encapSeed) - } - } - - /// A private key you use to decapsulate shared secrets with the Module-Lattice key encapsulation mechanism. - public struct PrivateKey: KEMPrivateKey { - internal let impl: MLKEMPrivateKeyImpl<${NAME}> - - internal init(_ impl: MLKEMPrivateKeyImpl<${NAME}>) { - self.impl = impl - } - - /// Generates a new, random private key. - public static func generate() throws -> ${NAME}.PrivateKey { - let impl = try MLKEMPrivateKeyImpl<${NAME}>.generatePrivateKey() - return PrivateKey(impl) - } - - static func generateWithSeed(_ seed: Data) throws -> ${NAME}.PrivateKey { - let impl = try MLKEMPrivateKeyImpl<${NAME}>.generateWithSeed(seed) - return PrivateKey(impl) - } - - /// Initializes a random private key. - public init() throws { - self = try PrivateKey.generate() - } - - /// Initializes a private key from a seed representation and optional public key. - /// - /// - Parameters: - /// - seedRepresentation: The seed representation `d||z`, as specified in the `ML-KEM.KeyGen_internal(d,z)` algorithm (Algorithm 16) of FIPS 203. - /// - publicKey: An optional public key. Pass this to check that the initialized private key is consistent with the public key. The initializer throws if the public key doesn't match the expected value. - public init(seedRepresentation: D, publicKey: ${NAME}.PublicKey?) throws { - var publicKeyRawRepresentation: Data? = nil - if publicKey != nil { - publicKeyRawRepresentation = publicKey!.rawRepresentation - } - self.impl = try MLKEMPrivateKeyImpl<${NAME}>(seedRepresentation: seedRepresentation, publicKeyRawRepresentation: publicKeyRawRepresentation) - } - - /// The private key's seed representation. - /// - /// The seed is `d||z`, as specified in the algorithm `ML-KEM.KeyGen_internal(d,z)` (Algorithm 16) of FIPS 203. - public var seedRepresentation: Data { - get { - return self.impl.seedRepresentation - } - } - - /// Decapsulated a shared secret. - /// - /// - Parameters: - /// - encapsulated: An encapsulated shared secret, that you get by calling ``${NAME}/PublicKey/encapsulate()`` on the corresponding public key. - /// - Returns: The shared secret. - public func decapsulate(_ encapsulated: D) throws -> SymmetricKey { - return try impl.decapsulate(encapsulated: encapsulated) - } - - /// The corresponding public key. - public var publicKey: ${NAME}.PublicKey { - get { - try self.impl.publicKey - } - } - - /// Initializes a private key from an integrity-checked representation. - /// - /// - Parameter integrityCheckedRepresentation: A representation of the private key that includes the seed value, and a hash of the corresponding public key. - public init(integrityCheckedRepresentation: D) throws { - guard integrityCheckedRepresentation.count == MLKEMPrivateKeyImpl<${NAME}>.seedSize + 32 else { - throw KEM.Errors.invalidSeed - } - let seed = Data(integrityCheckedRepresentation).subdata(in: 0...seedSize) - let publicKeyHashData = Data(integrityCheckedRepresentation).subdata(in: MLKEMPrivateKeyImpl<${NAME}>.seedSize..(seedRepresentation: seed, publicKeyHash: publicKeyHash) - } - - /// An integrity-checked representation of the private key. - /// - /// This representation includes the seed value, and a hash of the corresponding public key. - public var integrityCheckedRepresentation: Data { - get { - return self.impl.integrityCheckedRepresentation - } - } - } -} - -% end - -#endif // Linux or !SwiftPM diff --git a/Sources/Crypto/KEM/XWing.swift b/Sources/Crypto/KEM/XWing.swift index 2a368fce..435bac51 100644 --- a/Sources/Crypto/KEM/XWing.swift +++ b/Sources/Crypto/KEM/XWing.swift @@ -11,7 +11,12 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) +@_exported import CryptoKit +#else + +#if canImport(CryptoKit) @_exported import CryptoKit #else @@ -21,26 +26,15 @@ import FoundationEssentials import Foundation #endif -#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -typealias XWingPublicKeyImpl = CoreCryptoXWingPublicKeyImpl -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -typealias XWingPrivateKeyImpl = CoreCryptoXWingPrivateKeyImpl -#else -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) typealias XWingPublicKeyImpl = OpenSSLXWingPublicKeyImpl -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) typealias XWingPrivateKeyImpl = OpenSSLXWingPrivateKeyImpl -#endif /// The X-Wing (ML-KEM768 with X25519) Key Encapsulation Mechanism, defined in /// https://datatracker.ietf.org/doc/html/draft-connolly-cfrg-xwing-kem-06 -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +@nonexhaustive public enum XWingMLKEM768X25519: Sendable {} -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension XWingMLKEM768X25519 { - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PublicKey: KEMPublicKey { var impl: XWingPublicKeyImpl @@ -63,9 +57,8 @@ extension XWingMLKEM768X25519 { } } - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PrivateKey: KEMPrivateKey { - private var impl: XWingPrivateKeyImpl + var impl: XWingPrivateKeyImpl public var seedRepresentation: Data { get { @@ -101,9 +94,49 @@ extension XWingMLKEM768X25519 { } } } + + /// A one-time-use private key to decapsulate a shared secret with the X-Wing key encapsulation mechanism. + /// + /// The associated decapsulation function can be multiple times faster than the one implemented for PrivateKey, + /// but this private key can only be used to decapsulate a shared secret once. + public struct OneTimePrivateKey: KEMOneTimePrivateKey, ~Copyable { + private var impl: XWingPrivateKeyImpl + + internal init(impl: XWingPrivateKeyImpl) { + self.impl = impl + } + + /// Creates a one-time-use private key that reuses the key material of an existing private key. + /// + /// This is used by the tests to check that the one-time decapsulation function is consistent with the regular one. + internal init(reusingForTestingOnly privateKey: XWingMLKEM768X25519.PrivateKey) { + self.impl = privateKey.impl + } + + /// Generates a new, random one-time-use private key. + public static func generate() throws -> XWingMLKEM768X25519.OneTimePrivateKey { + let impl = try XWingPrivateKeyImpl.generate() + return OneTimePrivateKey(impl: impl) + } + + /// Decapsulate a shared secret. + /// + /// - Parameters: + /// - encapsulated: An encapsulated shared secret, that you get by calling ``XWingMLKEM768X25519/PublicKey/encapsulate()`` on the corresponding public key. + /// - Returns: The shared secret. + public consuming func decapsulate(_ encapsulated: Data) throws -> SymmetricKey { + return try impl.decapsulate(encapsulated) + } + + /// The corresponding public key. + public var publicKey: XWingMLKEM768X25519.PublicKey { + get { + XWingMLKEM768X25519.PublicKey(impl: self.impl.publicKey) + } + } + } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension XWingMLKEM768X25519.PrivateKey: HPKEKEMPrivateKeyGeneration { public init() throws { self = try Self.generate() @@ -121,13 +154,18 @@ extension XWingMLKEM768X25519.PrivateKey: HPKEKEMPrivateKeyGeneration { public init(integrityCheckedRepresentation: D) throws { let seed = integrityCheckedRepresentation.dropLast(32) // sizeof(SHA3-256 digest) let publicKeyHashBytes = integrityCheckedRepresentation.dropFirst(32) - let publicKeyHash = SHA3_256Digest(bytes: [UInt8](publicKeyHashBytes)) + let publicKeyHash = SHA3_256Digest { output in + for region in publicKeyHashBytes.regions { + region.withUnsafeBytes { + output.append(contentsOf: $0.bytes) + } + } + } self = try XWingMLKEM768X25519.PrivateKey.init(seedRepresentation: seed, publicKeyHash: publicKeyHash) } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension XWingMLKEM768X25519.PublicKey: HPKEKEMPublicKey { /// The type of the ephemeral private key associated with this public key. public typealias EphemeralPrivateKey = XWingMLKEM768X25519.PrivateKey @@ -169,4 +207,5 @@ extension XWingMLKEM768X25519.PublicKey: HPKEKEMPublicKey { /// The type of the ephemeral private key associated with this public key. public typealias HPKEEphemeralPrivateKey = XWingMLKEM768X25519.PrivateKey } -#endif // Linux or !SwiftPM +#endif +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Key Agreement/BoringSSL/ECDH_boring.swift b/Sources/Crypto/Key Agreement/BoringSSL/ECDH_boring.swift index 932d61b4..9910016b 100644 --- a/Sources/Crypto/Key Agreement/BoringSSL/ECDH_boring.swift +++ b/Sources/Crypto/Key Agreement/BoringSSL/ECDH_boring.swift @@ -11,10 +11,14 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL +#endif @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P256.KeyAgreement.PrivateKey { @@ -45,4 +49,4 @@ extension P521.KeyAgreement.PrivateKey { return SharedSecret(ss: key) } } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Key Agreement/DH.swift b/Sources/Crypto/Key Agreement/DH.swift index 1d7c9a20..31f3eb27 100644 --- a/Sources/Crypto/Key Agreement/DH.swift +++ b/Sources/Crypto/Key Agreement/DH.swift @@ -11,23 +11,19 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif /// A Diffie-Hellman Key Agreement Key @preconcurrency -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public protocol DiffieHellmanKeyAgreement: Sendable { /// The public key share type to perform the DH Key Agreement associatedtype PublicKey: Sendable @@ -58,7 +54,6 @@ public protocol DiffieHellmanKeyAgreement: Sendable { /// symmetric key suitable for creating a message authentication code like /// ``HMAC``, or for opening and closing a sealed box with a cipher like /// ``ChaChaPoly`` or ``AES``. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SharedSecret: ContiguousBytes, Sendable { var ss: SecureBytes @@ -119,7 +114,6 @@ public struct SharedSecret: ContiguousBytes, Sendable { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SharedSecret: Hashable { public func hash(into hasher: inout Hasher) { ss.withUnsafeBytes { hasher.combine(bytes: $0) } @@ -127,7 +121,6 @@ extension SharedSecret: Hashable { } // We want to implement constant-time comparison for digests. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SharedSecret: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { return safeCompare(lhs, rhs) @@ -153,7 +146,6 @@ extension SharedSecret: Equatable { } #if !hasFeature(Embedded) -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SharedSecret: CustomStringConvertible { public var description: String { return "\(Self.self): \(ss.hexString)" @@ -161,7 +153,6 @@ extension SharedSecret: CustomStringConvertible { } #endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension HashFunction { // A wrapper function to keep the unsafe code in one place. mutating func update(_ secret: SharedSecret) { @@ -176,4 +167,4 @@ extension HashFunction { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Key Agreement/ECDH.swift b/Sources/Crypto/Key Agreement/ECDH.swift index 243aaee0..6dc51272 100644 --- a/Sources/Crypto/Key Agreement/ECDH.swift +++ b/Sources/Crypto/Key Agreement/ECDH.swift @@ -11,46 +11,32 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -typealias NISTCurvePublicKeyImpl = CoreCryptoNISTCurvePublicKeyImpl -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -typealias NISTCurvePrivateKeyImpl = CoreCryptoNISTCurvePrivateKeyImpl -#else -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) typealias NISTCurvePublicKeyImpl = OpenSSLNISTCurvePublicKeyImpl -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) typealias NISTCurvePrivateKeyImpl = OpenSSLNISTCurvePrivateKeyImpl -#endif -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif // MARK: - Generated file, do NOT edit // any edits of this file WILL be overwritten and thus discarded // see section `gyb` in `README` for details. // MARK: - P256 + Signing -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P256 { /// A mechanism used to create or verify a cryptographic signature using /// the NIST P-256 elliptic curve digital signature algorithm (ECDSA). - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + @nonexhaustive public enum Signing: Sendable { /// A P-256 public key used to verify cryptographic signatures. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PublicKey: NISTECPublicKey, Sendable { var impl: NISTCurvePublicKeyImpl @@ -154,7 +140,6 @@ extension P256 { } /// A P-256 private key used to create cryptographic signatures. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PrivateKey: NISTECPrivateKey, Sendable { let impl: NISTCurvePrivateKeyImpl @@ -267,17 +252,15 @@ extension P256 { } } // MARK: - P256 + KeyAgreement -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P256 { /// A mechanism used to create a shared secret between two users by /// performing NIST P-256 elliptic curve Diffie Hellman (ECDH) key /// exchange. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + @nonexhaustive public enum KeyAgreement: Sendable { /// A P-256 public key used for key agreement. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PublicKey: NISTECPublicKey, Sendable { var impl: NISTCurvePublicKeyImpl @@ -381,7 +364,6 @@ extension P256 { } /// A P-256 private key used for key agreement. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PrivateKey: NISTECPrivateKey, Sendable { let impl: NISTCurvePrivateKeyImpl @@ -494,16 +476,14 @@ extension P256 { } } // MARK: - P384 + Signing -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P384 { /// A mechanism used to create or verify a cryptographic signature using /// the NIST P-384 elliptic curve digital signature algorithm (ECDSA). - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + @nonexhaustive public enum Signing: Sendable { /// A P-384 public key used to verify cryptographic signatures. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PublicKey: NISTECPublicKey, Sendable { var impl: NISTCurvePublicKeyImpl @@ -607,7 +587,6 @@ extension P384 { } /// A P-384 private key used to create cryptographic signatures. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PrivateKey: NISTECPrivateKey, Sendable { let impl: NISTCurvePrivateKeyImpl @@ -720,17 +699,15 @@ extension P384 { } } // MARK: - P384 + KeyAgreement -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P384 { /// A mechanism used to create a shared secret between two users by /// performing NIST P-384 elliptic curve Diffie Hellman (ECDH) key /// exchange. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + @nonexhaustive public enum KeyAgreement: Sendable { /// A P-384 public key used for key agreement. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PublicKey: NISTECPublicKey, Sendable { var impl: NISTCurvePublicKeyImpl @@ -834,7 +811,6 @@ extension P384 { } /// A P-384 private key used for key agreement. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PrivateKey: NISTECPrivateKey, Sendable { let impl: NISTCurvePrivateKeyImpl @@ -947,16 +923,14 @@ extension P384 { } } // MARK: - P521 + Signing -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P521 { /// A mechanism used to create or verify a cryptographic signature using /// the NIST P-521 elliptic curve digital signature algorithm (ECDSA). - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + @nonexhaustive public enum Signing: Sendable { /// A P-521 public key used to verify cryptographic signatures. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PublicKey: NISTECPublicKey, Sendable { var impl: NISTCurvePublicKeyImpl @@ -1060,7 +1034,6 @@ extension P521 { } /// A P-521 private key used to create cryptographic signatures. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PrivateKey: NISTECPrivateKey, Sendable { let impl: NISTCurvePrivateKeyImpl @@ -1173,17 +1146,15 @@ extension P521 { } } // MARK: - P521 + KeyAgreement -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P521 { /// A mechanism used to create a shared secret between two users by /// performing NIST P-521 elliptic curve Diffie Hellman (ECDH) key /// exchange. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + @nonexhaustive public enum KeyAgreement: Sendable { /// A P-521 public key used for key agreement. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PublicKey: NISTECPublicKey, Sendable { var impl: NISTCurvePublicKeyImpl @@ -1287,7 +1258,6 @@ extension P521 { } /// A P-521 private key used for key agreement. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PrivateKey: NISTECPrivateKey, Sendable { let impl: NISTCurvePrivateKeyImpl @@ -1401,7 +1371,6 @@ extension P521 { } // MARK: - P256 + DH -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P256.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement { /// Computes a shared secret with the provided public key from another party. /// @@ -1410,15 +1379,10 @@ extension P256.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement { /// key from this user to create the shared secret. /// - Returns: The computed shared secret. public func sharedSecretFromKeyAgreement(with publicKeyShare: P256.KeyAgreement.PublicKey) throws(CryptoKitMetaError) -> SharedSecret { - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - return try self.coreCryptoSharedSecretFromKeyAgreement(with: publicKeyShare) - #else return try self.openSSLSharedSecretFromKeyAgreement(with: publicKeyShare) - #endif } } // MARK: - P384 + DH -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P384.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement { /// Computes a shared secret with the provided public key from another party. /// @@ -1427,15 +1391,10 @@ extension P384.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement { /// key from this user to create the shared secret. /// - Returns: The computed shared secret. public func sharedSecretFromKeyAgreement(with publicKeyShare: P384.KeyAgreement.PublicKey) throws(CryptoKitMetaError) -> SharedSecret { - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - return try self.coreCryptoSharedSecretFromKeyAgreement(with: publicKeyShare) - #else return try self.openSSLSharedSecretFromKeyAgreement(with: publicKeyShare) - #endif } } // MARK: - P521 + DH -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P521.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement { /// Computes a shared secret with the provided public key from another party. /// @@ -1444,11 +1403,7 @@ extension P521.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement { /// key from this user to create the shared secret. /// - Returns: The computed shared secret. public func sharedSecretFromKeyAgreement(with publicKeyShare: P521.KeyAgreement.PublicKey) throws(CryptoKitMetaError) -> SharedSecret { - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - return try self.coreCryptoSharedSecretFromKeyAgreement(with: publicKeyShare) - #else return try self.openSSLSharedSecretFromKeyAgreement(with: publicKeyShare) - #endif } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Key Agreement/ECDH.swift.gyb b/Sources/Crypto/Key Agreement/ECDH.swift.gyb deleted file mode 100644 index aa815c92..00000000 --- a/Sources/Crypto/Key Agreement/ECDH.swift.gyb +++ /dev/null @@ -1,305 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the SwiftCrypto open source project -// -// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@_exported import CryptoKit -#else -#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -typealias NISTCurvePublicKeyImpl = CoreCryptoNISTCurvePublicKeyImpl -typealias NISTCurvePrivateKeyImpl = CoreCryptoNISTCurvePrivateKeyImpl -#else -typealias NISTCurvePublicKeyImpl = OpenSSLNISTCurvePublicKeyImpl -typealias NISTCurvePrivateKeyImpl = OpenSSLNISTCurvePrivateKeyImpl -#endif - -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else -#if canImport(FoundationEssentials) -public import FoundationEssentials -#else -public import Foundation -#endif -#endif - -// MARK: - Generated file, do NOT edit -// any edits of this file WILL be overwritten and thus discarded -// see section `gyb` in `README` for details. - -%{ - NIST_CURVES = ["P256", "P384", "P521"] - CURVES_FUNC = ["Signing", "KeyAgreement"] -}% -% for CURVE in NIST_CURVES: -%{ DISPLAY_CURVE = CURVE[:1] + "-" + CURVE[1:] }% -% for FUNC in CURVES_FUNC: -// MARK: - ${CURVE} + ${FUNC} -extension ${CURVE} { - - % if FUNC == "Signing": - /// A mechanism used to create or verify a cryptographic signature using - /// the NIST ${DISPLAY_CURVE} elliptic curve digital signature algorithm (ECDSA). - % else: - /// A mechanism used to create a shared secret between two users by - /// performing NIST ${DISPLAY_CURVE} elliptic curve Diffie Hellman (ECDH) key - /// exchange. - % end - public enum ${FUNC}: Sendable { - - % if FUNC == "Signing": - %{ READABLE_FUNC = "signing" }% - /// A ${DISPLAY_CURVE} public key used to verify cryptographic signatures. - % else: - %{ READABLE_FUNC = "key agreement" }% - /// A ${DISPLAY_CURVE} public key used for key agreement. - % end - public struct PublicKey: NISTECPublicKey, Sendable { - var impl: NISTCurvePublicKeyImpl<${CURVE}> - - /// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a collection of bytes. - /// - /// - Parameters: - /// - rawRepresentation: A raw representation of the key as a collection of - /// contiguous bytes. - public init(rawRepresentation: D) throws(CryptoKitMetaError) { - impl = try NISTCurvePublicKeyImpl(rawRepresentation: rawRepresentation) - } - - /// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a compact - /// representation of the key. - /// - /// - Parameters: - /// - compactRepresentation: A compact representation of the key - /// as a collection of contiguous bytes. - public init(compactRepresentation: Bytes) throws(CryptoKitMetaError) { - impl = try NISTCurvePublicKeyImpl(compactRepresentation: compactRepresentation) - } - - /// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from an ANSI x9.63 - /// representation. - /// - /// - Parameters: - /// - x963Representation: An ANSI x9.63 representation of the key. - public init(x963Representation: Bytes) throws(CryptoKitMetaError) { - impl = try NISTCurvePublicKeyImpl(x963Representation: x963Representation) - } - - /// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a compressed representation of - /// the key. - /// - /// - Parameters: - /// - compressedRepresentation: A compressed representation of the key as a collection - /// of contiguous bytes. - public init(compressedRepresentation: Bytes) throws(CryptoKitMetaError) { - impl = try NISTCurvePublicKeyImpl(compressedRepresentation: compressedRepresentation) - } - -#if !hasFeature(Embedded) - /// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a Privacy-Enhanced Mail - /// (PEM) representation. - /// - /// - Parameters: - /// - pemRepresentation: A PEM representation of the key. - public init(pemRepresentation: String) throws(CryptoKitMetaError) { - let pem = try ASN1.PEMDocument(pemString: pemRepresentation) - guard pem.type == "PUBLIC KEY" else { - throw CryptoKitASN1Error.invalidPEMDocument - } - self = try .init(derRepresentation: pem.derBytes) - } -#endif - - /// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a Distinguished Encoding - /// Rules (DER) encoded representation. - /// - /// - Parameters: - /// - derRepresentation: A DER-encoded representation of the key. - public init(derRepresentation: Bytes) throws(CryptoKitMetaError) where Bytes.Element == UInt8 { - let bytes = Array(derRepresentation) - let parsed = try ASN1.SubjectPublicKeyInfo(asn1Encoded: bytes) - self = try .init(x963Representation: parsed.key) - } - - init(impl: NISTCurvePublicKeyImpl<${CURVE}>) { - self.impl = impl - } - - /// A compact representation of the public key. - public var compactRepresentation: Data? { impl.compactRepresentation } - - /// A full representation of the public key. - public var rawRepresentation: Data { impl.rawRepresentation } - - /// An ANSI x9.63 representation of the public key. - public var x963Representation: Data { impl.x963Representation } - - /// A compressed representation of the public key. - public var compressedRepresentation: Data { impl.compressedRepresentation } - - /// A Distinguished Encoding Rules (DER) encoded representation of the public key. - public var derRepresentation: Data { - let spki = ASN1.SubjectPublicKeyInfo(algorithmIdentifier: .ecdsa${CURVE}, key: Array(self.x963Representation)) - var serializer = ASN1.Serializer() - - // Serializing these keys can't throw - try! serializer.serialize(spki) - return Data(serializer.serializedBytes) - } - -#if !hasFeature(Embedded) - /// A Privacy-Enhanced Mail (PEM) representation of the public key. - public var pemRepresentation: String { - let pemDocument = ASN1.PEMDocument(type: "PUBLIC KEY", derBytes: self.derRepresentation) - return pemDocument.pemString - } -#endif - } - - % if FUNC == "Signing": - /// A ${DISPLAY_CURVE} private key used to create cryptographic signatures. - % else: - /// A ${DISPLAY_CURVE} private key used for key agreement. - % end - public struct PrivateKey: NISTECPrivateKey, Sendable { - let impl: NISTCurvePrivateKeyImpl<${CURVE}> - - /// Creates a random ${DISPLAY_CURVE} private key for ${READABLE_FUNC}. - /// - /// Keys that use a compact point encoding enable shorter public keys, but aren’t - /// compliant with FIPS certification. If your app requires FIPS certification, - /// create a key with ``init(rawRepresentation:)``. - /// - /// - Parameters: - /// - compactRepresentable: A Boolean value that indicates whether CryptoKit - /// creates the key with the structure to enable compact point encoding. - public init(compactRepresentable: Bool = true) { - impl = NISTCurvePrivateKeyImpl(compactRepresentable: compactRepresentable) - } - - /// Creates a ${DISPLAY_CURVE} private key for ${READABLE_FUNC} from an ANSI x9.63 - /// representation. - /// - /// - Parameters: - /// - x963Representation: An ANSI x9.63 representation of the key. - public init(x963Representation: Bytes) throws(CryptoKitMetaError) { - impl = try NISTCurvePrivateKeyImpl(x963: x963Representation) - } - - /// Creates a ${DISPLAY_CURVE} private key for ${READABLE_FUNC} from a collection of bytes. - /// - /// - Parameters: - /// - rawRepresentation: A raw representation of the key as a collection of - /// contiguous bytes. - public init(rawRepresentation: Bytes) throws(CryptoKitMetaError) { - impl = try NISTCurvePrivateKeyImpl(data: rawRepresentation) - } - -#if !hasFeature(Embedded) - /// Creates a ${DISPLAY_CURVE} private key for ${READABLE_FUNC} from a Privacy-Enhanced Mail - /// PEM) representation. - /// - /// - Parameters: - /// - pemRepresentation: A PEM representation of the key. - public init(pemRepresentation: String) throws(CryptoKitMetaError) { - let pem = try ASN1.PEMDocument(pemString: pemRepresentation) - - switch pem.type { - case "EC PRIVATE KEY": - let parsed = try ASN1.SEC1PrivateKey(asn1Encoded: Array(pem.derBytes)) - self = try .init(rawRepresentation: parsed.privateKey) - case "PRIVATE KEY": - let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes)) - self = try .init(rawRepresentation: parsed.privateKey.privateKey) - default: - throw CryptoKitASN1Error.invalidPEMDocument - } - } -#endif - - /// Creates a ${DISPLAY_CURVE} private key for ${READABLE_FUNC} from a Distinguished Encoding - /// Rules (DER) encoded representation. - /// - /// - Parameters: - /// - derRepresentation: A DER-encoded representation of the key. - public init(derRepresentation: Bytes) throws(CryptoKitMetaError) where Bytes.Element == UInt8 { - let bytes = Array(derRepresentation) - - // We have to try to parse this twice because we have no information about what kind of key this is. - // We try with PKCS#8 first, and then fall back to SEC.1. - - do { - let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes) - self = try .init(rawRepresentation: key.privateKey.privateKey) - } catch { - let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes) - self = try .init(rawRepresentation: key.privateKey) - } - } - - init(impl: NISTCurvePrivateKeyImpl<${CURVE}>) { - self.impl = impl - } - - /// The corresponding public key. - public var publicKey: ${CURVE}.${FUNC}.PublicKey { - return PublicKey(impl: impl.publicKey()) - } - - /// A data representation of the private key. - public var rawRepresentation: Data { impl.rawRepresentation } - - /// An ANSI x9.63 representation of the private key. - public var x963Representation: Data { impl.x963Representation } - - /// A Distinguished Encoding Rules (DER) encoded representation of the private key. - public var derRepresentation: Data { - let pkey = ASN1.PKCS8PrivateKey(algorithm: .ecdsa${CURVE}, privateKey: Array(self.rawRepresentation), publicKey: Array(self.publicKey.x963Representation)) - var serializer = ASN1.Serializer() - - // Serializing these keys can't throw - try! serializer.serialize(pkey) - return Data(serializer.serializedBytes) - } - -#if !hasFeature(Embedded) - /// A Privacy-Enhanced Mail (PEM) representation of the private key. - public var pemRepresentation: String { - let pemDocument = ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: self.derRepresentation) - return pemDocument.pemString - } -#endif - } - } -} -% end -% end - -% for CURVE in NIST_CURVES: -// MARK: - ${CURVE} + DH -extension ${CURVE}.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement { - /// Computes a shared secret with the provided public key from another party. - /// - /// - Parameters: - /// - publicKeyShare: The public key from another party to be combined with the private - /// key from this user to create the shared secret. - /// - Returns: The computed shared secret. - public func sharedSecretFromKeyAgreement(with publicKeyShare: ${CURVE}.KeyAgreement.PublicKey) throws(CryptoKitMetaError) -> SharedSecret { - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - return try self.coreCryptoSharedSecretFromKeyAgreement(with: publicKeyShare) - #else - return try self.openSSLSharedSecretFromKeyAgreement(with: publicKeyShare) - #endif - } -} -% end -#endif // Linux or !SwiftPM diff --git a/Sources/Crypto/Key Derivation/ANSIx963.swift b/Sources/Crypto/Key Derivation/ANSIx963.swift index 6c0357d3..081069d7 100644 --- a/Sources/Crypto/Key Derivation/ANSIx963.swift +++ b/Sources/Crypto/Key Derivation/ANSIx963.swift @@ -11,23 +11,18 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) -public import FoundationEssentials +import FoundationEssentials #else -public import Foundation -#endif +import Foundation #endif -@_spi(ANSIKDF) -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -public struct ANSIKDFx963: Sendable { +internal struct ANSIKDFx963: Sendable { public static func deriveKey(inputKeyMaterial: SymmetricKey, info: Info, outputByteCount: Int) -> SymmetricKey { guard UInt64(outputByteCount) < (UInt64(H.Digest.byteCount) * UInt64(UInt32.max)) else { @@ -44,7 +39,11 @@ public struct ANSIKDFx963: Sendable { // 1. Compute: Ki = Hash(Z || Counter || [SharedInfo]). var hasher = H() inputKeyMaterial.withUnsafeBytes { ikmBytes in + #if CRYPTOKIT_URBP_LACKS_CONFORMANCE + hasher.update(bufferPointer: ikmBytes) + #else hasher.update(data: ikmBytes) + #endif } hasher.update(counter.bigEndian) hasher.update(data: info) @@ -56,7 +55,7 @@ public struct ANSIKDFx963: Sendable { // Append the bytes of the digest. We don't want to append more than the remaining number of bytes. let bytesToAppend = min(remainingBytes, H.Digest.byteCount) digest.withUnsafeBytes { digestPtr in - key.append(digestPtr.prefix(bytesToAppend)) + key.append(digestPtr.bytes.extracting(first: bytesToAppend)) } remainingBytes -= bytesToAppend } diff --git a/Sources/Crypto/Key Derivation/HKDF.swift b/Sources/Crypto/Key Derivation/HKDF.swift index 8d66b74d..5b09d42d 100644 --- a/Sources/Crypto/Key Derivation/HKDF.swift +++ b/Sources/Crypto/Key Derivation/HKDF.swift @@ -11,19 +11,16 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif /// A standards-based implementation of an HMAC-based Key Derivation Function /// (HKDF). @@ -40,8 +37,34 @@ public import Foundation /// material in the form of a hashed authentication code, then call /// ``expand(pseudoRandomKey:info:outputByteCount:)`` using that key material to /// generate a symmetric key of the length you specify. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct HKDF: Sendable { + /// Derives a symmetric encryption key from a main key or passcode using + /// HKDF key derivation with information and salt you specify. + /// + /// - Parameters: + /// - inputKeyMaterial: The main key or passcode the derivation function + /// uses to derive a key. + /// - salt: The salt to use for key derivation. + /// - info: The shared information to use for key derivation. + /// - outputKey: An output span that will be populated with the derived + /// symmetric key. + #if swift(<6.3) + @_lifetime(outputKey: copy outputKey) + #endif + public static func deriveKey(inputKeyMaterial: SymmetricKey, + salt: RawSpan? = nil, + info: RawSpan? = nil, + output outputKey: inout OutputRawSpan) { + let code = extract(inputKeyMaterial: inputKeyMaterial, salt: salt) + code.withUnsafeBytes { codeBytes in + expand( + pseudoRandomKey: codeBytes.bytes, + info: info, + into: &outputKey + ) + } + } + /// Derives a symmetric encryption key from a main key or passcode using /// HKDF key derivation with information and salt you specify. /// @@ -53,11 +76,38 @@ public struct HKDF: Sendable { /// - outputByteCount: The length in bytes of the resulting symmetric key. /// /// - Returns: The derived symmetric key. - public static func deriveKey(inputKeyMaterial: SymmetricKey, - salt: Salt, - info: Info, - outputByteCount: Int) -> SymmetricKey { - return expand(pseudoRandomKey: extract(inputKeyMaterial: inputKeyMaterial, salt: salt), info: info, outputByteCount: outputByteCount) + public static func deriveKey( + inputKeyMaterial: SymmetricKey, + salt: Salt, + info: Info, + outputByteCount: Int + ) -> SymmetricKey { + // Fast path: Both salt and info have a single contiguous region, so + // go directly to the span. + if salt.regions.count == 1 && info.regions.count == 1 { + return salt.regions.first!.withUnsafeBytes { saltBytes in + info.regions.first!.withUnsafeBytes { infoBytes in + SymmetricKey(size: SymmetricKeySize(bitCount: outputByteCount * 8)) { output in + deriveKey( + inputKeyMaterial: inputKeyMaterial, + salt: saltBytes.bytes, + info: infoBytes.bytes, + output: &output + ) + } + } + } + } + + // Turn salt and info into contiguous regions, then recurse. + let contiguousSalt = Array(salt) + let contiguousInfo = Array(info) + return deriveKey( + inputKeyMaterial: inputKeyMaterial, + salt: contiguousSalt, + info: contiguousInfo, + outputByteCount: outputByteCount + ) } /// Derives a symmetric encryption key from a main key or passcode using @@ -133,9 +183,31 @@ public struct HKDF: Sendable { key = SymmetricKey(data: [UInt8]()) } - return inputKeyMaterial.withUnsafeBytes { ikmBytes in - return HMAC.authenticationCode(for: ikmBytes, using: key) + return HMAC.authenticationCode(for: inputKeyMaterial.bytes, using: key) + } + + /// Creates cryptographically strong key material from a main key or + /// passcode that you specify. + /// + /// Generate a derived symmetric key from the cryptographically strong key + /// material this function creates by calling + /// ``expand(pseudoRandomKey:info:outputByteCount:)``. + /// + /// - Parameters: + /// - inputKeyMaterial: The main key or passcode the derivation function + /// uses to derive a key. + /// - salt: The salt to use for key derivation. + /// + /// - Returns: A pseudorandom, cryptographically strong key in the form of a + /// hashed authentication code. + public static func extract(inputKeyMaterial: SymmetricKey, salt: RawSpan?) -> HashedAuthenticationCode { + let key = if let salt { + SymmetricKey(bytes: salt) + } else { + SymmetricKey(data: SecureBytes()) } + + return HMAC.authenticationCode(for: inputKeyMaterial.bytes, using: key) } /// Expands cryptographically strong key material into a derived symmetric @@ -152,27 +224,66 @@ public struct HKDF: Sendable { /// /// - Returns: The derived symmetric key. public static func expand(pseudoRandomKey prk: PRK, info: Info?, outputByteCount: Int) -> SymmetricKey { - - let iterations: UInt8 = UInt8((Double(outputByteCount) / Double(H.Digest.byteCount)).rounded(.up)) - - var output = SecureBytes() - let key = SymmetricKey(data: prk) - var TMinusOne = SecureBytes() - for i in 1...iterations { - var hmac = HMAC(key: key) - hmac.update(data: TMinusOne) - if let info { - hmac.update(data: info) + SymmetricKey(capacity: outputByteCount) { output in + prk.withUnsafeBytes { prkBuffer in + guard let info else { + self.expand(pseudoRandomKey: prkBuffer.bytes, info: nil, into: &output) + return + } + + if info.regions.count == 1 { + info.regions.first!.withUnsafeBytes { infoBuffer in + self.expand(pseudoRandomKey: prkBuffer.bytes, info: infoBuffer.bytes, into: &output) + } + } else { + let contiguous = ContiguousArray(info) + self.expand(pseudoRandomKey: prkBuffer.bytes, info: contiguous.span.bytes, into: &output) + } } - withUnsafeBytes(of: i) { counter in - hmac.update(bufferPointer: counter) - } - TMinusOne = SecureBytes(bytes: hmac.finalize()) - output.append(TMinusOne) } - return SymmetricKey(data: output.prefix(outputByteCount)) + } + + /// Expands cryptographically strong key material into a derived symmetric + /// key. + /// + /// Generate cryptographically strong key material to use with this function + /// by calling ``extract(inputKeyMaterial:salt:)``. + /// + /// - Parameters: + /// - prk: A pseudorandom, cryptographically strong key generated from the + /// ``extract(inputKeyMaterial:salt:)`` function. + /// - info: The shared information to use for key derivation. + /// - outputByteCount: The length in bytes of the resulting symmetric key. + /// + /// - Returns: The derived symmetric key. + #if swift(<6.3) + @_lifetime(output: copy output) + #endif + public static func expand(pseudoRandomKey prk: RawSpan, info: RawSpan?, into output: inout OutputRawSpan) { + let iterations: UInt8 = UInt8((Double(output.freeCapacity) / Double(H.Digest.byteCount)).rounded(.up)) + + let key = SymmetricKey(bytes: prk) + var lastIterationBytes = 0 + for i in 1...iterations { + var hmac = HMAC(key: key) + hmac.update(bytes: output.bytes.extracting(last: lastIterationBytes)) + if let info { + hmac.update(bytes: info) + } + + var buf = i + withUnsafeBytes(of: &buf) { rawBuffer in + let span = RawSpan(_unsafeBytes: rawBuffer) + hmac.update(bytes: span) + } + hmac.finalize().withUnsafeBytes { + let bytesToAppend = $0.bytes.extracting(first: output.freeCapacity) + output.append(contentsOf: bytesToAppend) + lastIterationBytes = bytesToAppend.byteCount + } + } } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Key Wrapping/AESWrap.swift b/Sources/Crypto/Key Wrapping/AESWrap.swift index 69ab6833..da99412a 100644 --- a/Sources/Crypto/Key Wrapping/AESWrap.swift +++ b/Sources/Crypto/Key Wrapping/AESWrap.swift @@ -11,33 +11,23 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif -#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -typealias AESWRAPImpl = CoreCryptoAESWRAPImpl -#else -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) typealias AESWRAPImpl = BoringSSLAESWRAPImpl -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension AES { /// An implementation of AES Key Wrapping in accordance with the IETF RFC /// 3394 specification. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + @nonexhaustive public enum KeyWrap: Sendable { /// Wraps a key using the AES wrap algorithm. /// @@ -70,4 +60,4 @@ extension AES { } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Key Wrapping/BoringSSL/AESWrap_boring.swift b/Sources/Crypto/Key Wrapping/BoringSSL/AESWrap_boring.swift index f493b865..29b74c42 100644 --- a/Sources/Crypto/Key Wrapping/BoringSSL/AESWrap_boring.swift +++ b/Sources/Crypto/Key Wrapping/BoringSSL/AESWrap_boring.swift @@ -11,10 +11,14 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL +#endif #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -29,12 +33,8 @@ enum BoringSSLAESWRAPImpl { let rc = try key.withUnsafeAESKEY(mode: .encrypting) { aesKey in output.withUnsafeMutableBytes { outputPtr -> CInt in - // Memory bind is safe: we cannot alias the pointer here. - let outputPtr = outputPtr.bindMemory(to: UInt8.self) - return keyToWrap.withUnsafeBytes { keyToWrapPtr -> CInt in - // Memory bind is safe: we cannot alias the pointer here. - let keyToWrapPtr = keyToWrapPtr.bindMemory(to: UInt8.self) - return CCryptoBoringSSL_AES_wrap_key( + keyToWrap.withUnsafeBytes { keyToWrapPtr -> CInt in + CCryptoBoringSSL_AES_wrap_key( aesKey, nil, outputPtr.baseAddress, @@ -74,8 +74,6 @@ enum BoringSSLAESWRAPImpl { ) throws -> SymmetricKey { let unwrapped = try contiguousWrappedKey.withUnsafeBytes { inPtr in try [UInt8](unsafeUninitializedCapacity: inPtr.count) { outputPtr, count in - // Bind is safe: we cannot violate the aliasing rules here as we never call to arbitrary code. - let inPtr = inPtr.bindMemory(to: UInt8.self) let rc = try key.withUnsafeAESKEY(mode: .decrypting) { aesKey in CCryptoBoringSSL_AES_unwrap_key( aesKey, @@ -113,8 +111,6 @@ extension SymmetricKey { _ body: (UnsafePointer) throws -> ResultType ) throws -> ResultType { try self.withUnsafeBytes { bytesPointer in - // Bind is safe: cannot alias the pointer here. - let bytesPointer = bytesPointer.bindMemory(to: UInt8.self) var aesKey = AES_KEY() let bitsInKey = UInt32(bytesPointer.count * 8) @@ -146,4 +142,4 @@ extension SymmetricKey { } } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Keys/EC/BoringSSL/Ed25519_boring.swift b/Sources/Crypto/Keys/EC/BoringSSL/Ed25519_boring.swift index 037de26f..504ba903 100644 --- a/Sources/Crypto/Keys/EC/BoringSSL/Ed25519_boring.swift +++ b/Sources/Crypto/Keys/EC/BoringSSL/Ed25519_boring.swift @@ -11,11 +11,14 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL -@_implementationOnly import CCryptoBoringSSLShims +#endif #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -41,7 +44,7 @@ extension Curve25519.Signing { privateKeyBytes in privateKeyBytes = 64 publicKey.withUnsafeMutableBytes { publicKeyPtr in - CCryptoBoringSSLShims_ED25519_keypair( + CCryptoBoringSSL_ED25519_keypair( publicKeyPtr.baseAddress, privateKeyPtr.baseAddress ) @@ -75,7 +78,7 @@ extension Curve25519.Signing { privateKeyBytes in privateKeyBytes = 64 publicKey.withUnsafeMutableBytes { publicKeyPtr in - CCryptoBoringSSLShims_ED25519_keypair_from_seed( + CCryptoBoringSSL_ED25519_keypair_from_seed( publicKeyPtr.baseAddress, privateKeyPtr.baseAddress, seedPtr.baseAddress @@ -123,4 +126,4 @@ extension Curve25519.Signing { } } } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Keys/EC/BoringSSL/NISTCurvesKeys_boring.swift b/Sources/Crypto/Keys/EC/BoringSSL/NISTCurvesKeys_boring.swift index 4130b2b3..84a5c07e 100644 --- a/Sources/Crypto/Keys/EC/BoringSSL/NISTCurvesKeys_boring.swift +++ b/Sources/Crypto/Keys/EC/BoringSSL/NISTCurvesKeys_boring.swift @@ -11,11 +11,14 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL -@_implementationOnly import CCryptoBoringSSLShims +#endif import CryptoBoringWrapper #if canImport(FoundationEssentials) import FoundationEssentials @@ -74,6 +77,10 @@ struct OpenSSLNISTCurvePrivateKeyImpl: Sendabl self.key = try BoringSSLECPrivateKeyWrapper(rawRepresentation: data) } + init(seed: Data, compactRepresentable: Bool) throws { + fatalError("unimplemented on this platform") + } + func publicKey() -> OpenSSLNISTCurvePublicKeyImpl { OpenSSLNISTCurvePublicKeyImpl(wrapping: self.key.publicKey) } @@ -139,7 +146,7 @@ struct OpenSSLNISTCurvePublicKeyImpl: Sendable /// allows some helper operations. @usableFromInline @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -class BoringSSLECPrivateKeyWrapper: @unchecked Sendable { +final class BoringSSLECPrivateKeyWrapper: @unchecked Sendable { @usableFromInline let key: OpaquePointer @@ -326,7 +333,7 @@ class BoringSSLECPrivateKeyWrapper: @unchecked func sign(digest: D) throws -> ECDSASignature { let optionalRawSignature: UnsafeMutablePointer? = digest.withUnsafeBytes { digestPtr in - CCryptoBoringSSLShims_ECDSA_do_sign(digestPtr.baseAddress, digestPtr.count, self.key) + CCryptoBoringSSL_ECDSA_do_sign(digestPtr.baseAddress, digestPtr.count, self.key) } guard let rawSignature = optionalRawSignature else { throw CryptoKitError.internalBoringSSLError() @@ -344,7 +351,7 @@ class BoringSSLECPrivateKeyWrapper: @unchecked /// allows some helper operations. @usableFromInline @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -class BoringSSLECPublicKeyWrapper: @unchecked Sendable { +final class BoringSSLECPublicKeyWrapper: @unchecked Sendable { @usableFromInline let key: OpaquePointer @@ -566,7 +573,7 @@ class BoringSSLECPublicKeyWrapper: @unchecked func isValidSignature(_ signature: ECDSASignature, for digest: D) -> Bool { let rc: CInt = signature.withUnsafeSignaturePointer { signaturePointer in digest.withUnsafeBytes { digestPointer in - CCryptoBoringSSLShims_ECDSA_do_verify( + CCryptoBoringSSL_ECDSA_do_verify( digestPointer.baseAddress, digestPointer.count, signaturePointer, @@ -697,4 +704,4 @@ func _isCompactRepresentable( // The point is compact representable if y is less than or equal to newY. return y <= newY } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Keys/EC/BoringSSL/X25519Keys_boring.swift b/Sources/Crypto/Keys/EC/BoringSSL/X25519Keys_boring.swift index df7807cd..91c8ffc7 100644 --- a/Sources/Crypto/Keys/EC/BoringSSL/X25519Keys_boring.swift +++ b/Sources/Crypto/Keys/EC/BoringSSL/X25519Keys_boring.swift @@ -11,11 +11,14 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL -@_implementationOnly import CCryptoBoringSSLShims +#endif #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -72,7 +75,7 @@ extension Curve25519.KeyAgreement { publicKey.withUnsafeMutableBytes { publicKeyBytes in precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes) precondition(privateKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes) - CCryptoBoringSSLShims_X25519_keypair( + CCryptoBoringSSL_X25519_keypair( publicKeyBytes.baseAddress, privateKeyBytes.baseAddress ) @@ -100,7 +103,7 @@ extension Curve25519.KeyAgreement { publicKeyBytes, publicKeySize in precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes) - CCryptoBoringSSLShims_X25519_public_from_private( + CCryptoBoringSSL_X25519_public_from_private( publicKeyBytes.baseAddress, privatePointer.baseAddress ) @@ -135,7 +138,7 @@ extension Curve25519.KeyAgreement { // politely describe as a "lack of consensus" as to whether crypto libraries should reject this secret. CryptoKit on Apple // platforms currently does not, so for the sake of conformance with our peer implementation I will also refuse to check it. // We may elect to revisit this decision if the security best-practice thinking changes. - CCryptoBoringSSLShims_X25519( + CCryptoBoringSSL_X25519( secretPointer.baseAddress, privateKeyPointer.baseAddress, publicKeyShare.keyBytes @@ -162,4 +165,4 @@ extension Curve25519.KeyAgreement { } } } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Keys/EC/Curve25519.swift b/Sources/Crypto/Keys/EC/Curve25519.swift index 83d6a608..df79153e 100644 --- a/Sources/Crypto/Keys/EC/Curve25519.swift +++ b/Sources/Crypto/Keys/EC/Curve25519.swift @@ -11,10 +11,11 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else /// An elliptic curve that enables X25519 key agreement and Ed25519 signatures. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +@nonexhaustive public enum Curve25519: Sendable {} -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Keys/EC/Ed25519Keys.swift b/Sources/Crypto/Keys/EC/Ed25519Keys.swift index 3ca56763..ad1781b5 100644 --- a/Sources/Crypto/Keys/EC/Ed25519Keys.swift +++ b/Sources/Crypto/Keys/EC/Ed25519Keys.swift @@ -11,42 +11,31 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Curve25519.Signing { static var keyByteCount: Int { return 32 } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Curve25519 { /// A mechanism used to create or verify a cryptographic signature using /// Ed25519. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + @nonexhaustive public enum Signing: Sendable { - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - typealias Curve25519PrivateKeyImpl = Curve25519.Signing.CoreCryptoCurve25519PrivateKeyImpl - typealias Curve25519PublicKeyImpl = Curve25519.Signing.CoreCryptoCurve25519PublicKeyImpl - #else typealias Curve25519PrivateKeyImpl = Curve25519.Signing.OpenSSLCurve25519PrivateKeyImpl typealias Curve25519PublicKeyImpl = Curve25519.Signing.OpenSSLCurve25519PublicKeyImpl - #endif /// A Curve25519 private key used to create cryptographic signatures. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PrivateKey: ECPrivateKey, Sendable { private var baseKey: Curve25519.Signing.Curve25519PrivateKeyImpl @@ -82,7 +71,6 @@ extension Curve25519 { } /// A Curve25519 public key used to verify cryptographic signatures. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PublicKey: Sendable { private var baseKey: Curve25519.Signing.Curve25519PublicKeyImpl @@ -110,4 +98,4 @@ extension Curve25519 { } } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Keys/EC/NISTCurvesKeys.swift b/Sources/Crypto/Keys/EC/NISTCurvesKeys.swift index 319e556c..6a4bdcc0 100644 --- a/Sources/Crypto/Keys/EC/NISTCurvesKeys.swift +++ b/Sources/Crypto/Keys/EC/NISTCurvesKeys.swift @@ -11,64 +11,51 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else + #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -typealias SupportedCurveDetailsImpl = CorecryptoSupportedNISTCurve -#else -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) typealias SupportedCurveDetailsImpl = OpenSSLSupportedNISTCurve -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol ECPublicKey { - init (rawRepresentation: Bytes) throws + init (rawRepresentation: Bytes) throws(CryptoKitMetaError) var rawRepresentation: Data { get } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol ECPrivateKey { associatedtype PK var publicKey: PK { get } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol NISTECPublicKey: ECPublicKey { - init(compactRepresentation: Bytes) throws - init(compressedRepresentation: Bytes) throws - init(x963Representation: Bytes) throws + init(compactRepresentation: Bytes) throws(CryptoKitMetaError) + init(compressedRepresentation: Bytes) throws(CryptoKitMetaError) + init(x963Representation: Bytes) throws(CryptoKitMetaError) var compactRepresentation: Data? { get } var x963Representation: Data { get } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol NISTECPrivateKey: ECPrivateKey where PK: NISTECPublicKey { - init (rawRepresentation: Bytes) throws + init (rawRepresentation: Bytes) throws(CryptoKitMetaError) var rawRepresentation: Data { get } } /// An elliptic curve that enables NIST P-256 signatures and key agreement. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +@nonexhaustive public enum P256: Sendable { } /// An elliptic curve that enables NIST P-384 signatures and key agreement. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +@nonexhaustive public enum P384: Sendable { } /// An elliptic curve that enables NIST P-521 signatures and key agreement. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +@nonexhaustive public enum P521: Sendable { } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Keys/EC/X25519Keys.swift b/Sources/Crypto/Keys/EC/X25519Keys.swift index a34299ba..c6eca27c 100644 --- a/Sources/Crypto/Keys/EC/X25519Keys.swift +++ b/Sources/Crypto/Keys/EC/X25519Keys.swift @@ -11,42 +11,31 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Curve25519.KeyAgreement { static var keyByteCount: Int { return 32 } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Curve25519 { /// A mechanism used to create a shared secret between two users by /// performing X25519 key agreement. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + @nonexhaustive public enum KeyAgreement: Sendable { - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - typealias Curve25519PrivateKeyImpl = Curve25519.KeyAgreement.CoreCryptoCurve25519PrivateKeyImpl - typealias Curve25519PublicKeyImpl = Curve25519.KeyAgreement.CoreCryptoCurve25519PublicKeyImpl - #else typealias Curve25519PrivateKeyImpl = Curve25519.KeyAgreement.OpenSSLCurve25519PrivateKeyImpl typealias Curve25519PublicKeyImpl = Curve25519.KeyAgreement.OpenSSLCurve25519PublicKeyImpl - #endif /// A Curve25519 public key used for key agreement. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PublicKey: ECPublicKey, Sendable { fileprivate var baseKey: Curve25519PublicKeyImpl @@ -86,7 +75,6 @@ extension Curve25519 { } /// A Curve25519 private key used for key agreement. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PrivateKey: DiffieHellmanKeyAgreement, Sendable { fileprivate var baseKey: Curve25519PrivateKeyImpl @@ -135,4 +123,4 @@ extension Curve25519 { } } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Keys/Symmetric/SymmetricKeys.swift b/Sources/Crypto/Keys/Symmetric/SymmetricKeys.swift index 0e46873f..94d3fe0c 100644 --- a/Sources/Crypto/Keys/Symmetric/SymmetricKeys.swift +++ b/Sources/Crypto/Keys/Symmetric/SymmetricKeys.swift @@ -11,19 +11,16 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif /// The sizes that a symmetric cryptographic key can take. /// @@ -32,7 +29,6 @@ public import Foundation /// standard key sizes, like ``bits128``, ``bits192``, or ``bits256``. When you /// need a key with a non-standard length, use the ``init(bitCount:)`` /// initializer to create a `SymmetricKeySize` instance with a custom bit count. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SymmetricKeySize: Sendable { /// The number of bits in the key. public let bitCount: Int @@ -73,7 +69,6 @@ public struct SymmetricKeySize: Sendable { /// symmetric key to compute a message authentication code like ``HMAC``, or to /// open and close a sealed box (``ChaChaPoly/SealedBox`` or /// ``AES/GCM/SealedBox``) using a cipher like ``ChaChaPoly`` or ``AES``. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct SymmetricKey: ContiguousBytes, Sendable { let sb: SecureBytes @@ -95,6 +90,11 @@ public struct SymmetricKey: ContiguousBytes, Sendable { } #endif + /// Access the raw bytes of the key. + public var bytes: RawSpan { + sb.bytes + } + /// Creates a key from the given data. /// /// - Parameters: @@ -103,6 +103,35 @@ public struct SymmetricKey: ContiguousBytes, Sendable { self.init(key: SecureBytes(bytes: data)) } + /// Creates a key from the given data. + /// + /// - Parameters: + /// - bytes: The span of bytes from which to create the key. + /// + /// Note: historical version of init(copying:) below, SPI only. + @inlinable + internal init(bytes: RawSpan) { + self = bytes.withUnsafeBytes { SymmetricKey(data: $0) } + } + + /// Creates a key from the given data. + /// + /// - Parameters: + /// - bytes: The span of bytes from which to create the key. + @inlinable + public init(copying bytes: RawSpan) { + self = bytes.withUnsafeBytes { SymmetricKey(data: $0) } + } + + /// Creates a key from the given data, zeroing out the bytes afterward. + /// + /// - Parameters: + /// - byte: The span of bytes from which to create the key. + public init(copyingWithZeroing bytes: inout MutableRawSpan) { + self = bytes.withUnsafeBytes { SymmetricKey(data: $0) } + bytes.withUnsafeMutableBytes { $0.zeroize() } + } + /// Generates a new random key of the given size. /// /// - Parameters: @@ -124,6 +153,25 @@ public struct SymmetricKey: ContiguousBytes, Sendable { } #endif + /// Create a symmetric key with a closure that will initialize the memory. + internal init(capacity: Int, initializingWith callback: (inout OutputRawSpan) throws(E) -> Void) throws(E) { + self.init(key: try SecureBytes(capacity: capacity, initializingWith: callback)) + } + + /// Creates a new key of the given size where the key contents are initialized via a callback. + /// + /// - Parameters: + /// - size: The size of the key to generate. You can use one of the standard + /// sizes, like ``SymmetricKeySize/bits256``, or you can create a key of + /// custom length by initializing a ``SymmetricKeySize`` instance with a + /// non-standard value. + /// - callback: A callback that will be invoked to initialize the contents + /// of the key. It must initialize the full set of size.bitCount / 8 bytes + /// in the provided output span. + public init(size: SymmetricKeySize, initializingWith callback: (inout OutputRawSpan) throws(E) -> Void) throws(E) { + try self.init(capacity: Int(size.bitCount / 8), initializingWith: callback) + } + // Fast-path alias for cases whe know we have a SecureBytes object. internal init(data: SecureBytes) { self.init(key: data) @@ -145,11 +193,10 @@ public struct SymmetricKey: ContiguousBytes, Sendable { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SymmetricKey: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { return safeCompare(lhs, rhs) } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Message Authentication Codes/HMAC/HMAC.swift b/Sources/Crypto/Message Authentication Codes/HMAC/HMAC.swift index a60def59..27acd40a 100644 --- a/Sources/Crypto/Message Authentication Codes/HMAC/HMAC.swift +++ b/Sources/Crypto/Message Authentication Codes/HMAC/HMAC.swift @@ -11,31 +11,15 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) -#if os(Windows) -import ucrt -#elseif canImport(Darwin) -import Darwin -#elseif canImport(Glibc) -import Glibc -#elseif canImport(Musl) -import Musl -#elseif canImport(Android) -import Android -#elseif canImport(WASILibc) -import WASILibc -#endif public import FoundationEssentials #else public import Foundation #endif -#endif /// A hash-based message authentication algorithm. /// @@ -50,7 +34,6 @@ public import Foundation /// need to encrypt the data as well as authenticate it, use a cipher like /// ``AES`` or ``ChaChaPoly`` to put the data into a sealed box (an instance of /// ``AES/GCM/SealedBox`` or ``ChaChaPoly/SealedBox``). -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct HMAC: MACAlgorithm, Sendable { /// An alias for the symmetric key type used to compute or verify a message /// authentication code. @@ -82,39 +65,32 @@ public struct HMAC: MACAlgorithm, Sendable { #if os(iOS) && (arch(arm) || arch(i386)) fatalError("Unsupported architecture") #else - var K: SymmetricKey - if key.byteCount == H.blockByteCount { - K = key - } else if key.byteCount > H.blockByteCount { - var array = Array(repeating: UInt8(0), count: H.blockByteCount) - - K = key.withUnsafeBytes { (keyBytes) in - let hash = H.hash(bufferPointer: keyBytes) - - return SymmetricKey(data: hash.withUnsafeBytes({ (hashBytes) in - memcpy(&array, hashBytes.baseAddress!, hashBytes.count) - return array - })) + var innerKey = SecureBytes(capacity: H.blockByteCount) { keyOutput in + if key.byteCount <= keyOutput.freeCapacity { + keyOutput.append(contentsOf: key.bytes) + } else if key.byteCount > H.blockByteCount { + let hash = H.hash(bytes: key.bytes) + hash.withUnsafeBytes { + keyOutput.append(contentsOf: $0.bytes) + } } - } else { - var keyArray = Array(repeating: UInt8(0), count: H.blockByteCount) - key.withUnsafeBytes { keyArray.replaceSubrange(0..<$0.count, with: $0) } - K = SymmetricKey(data: keyArray) + keyOutput.append(repeating: 0, count: keyOutput.freeCapacity, as: UInt8.self) } + var outerKey = innerKey self.innerHasher = H() - let innerKey = K.withUnsafeBytes { - return $0.map({ (keyByte) in - keyByte ^ 0x36 - }) + innerKey.withUnsafeMutableBytes { + for i in 0 ..< $0.count { + $0[i] ^= 0x36 + } } - innerHasher.update(data: innerKey) + innerHasher.update(bytes: innerKey.bytes) self.outerHasher = H() - let outerKey = K.withUnsafeBytes { - return $0.map({ (keyByte) in - keyByte ^ 0x5c - }) + outerKey.withUnsafeMutableBytes { + for i in 0 ..< $0.count { + $0[i] ^= 0x5c + } } outerHasher.update(data: outerKey) #endif @@ -133,6 +109,19 @@ public struct HMAC: MACAlgorithm, Sendable { return authenticator.finalize() } + /// Computes a message authentication code for the given data. + /// + /// - Parameters: + /// - data: The data for which to compute the authentication code. + /// - key: The symmetric key used to secure the computation. + /// + /// - Returns: The message authentication code. + public static func authenticationCode(for data: RawSpan, using key: SymmetricKey) -> MAC { + var authenticator = Self(key: key) + authenticator.update(bytes: data) + return authenticator.finalize() + } + /// Returns a Boolean value indicating whether the given message /// authentication code is valid for a block of data. /// @@ -177,6 +166,10 @@ public struct HMAC: MACAlgorithm, Sendable { } } + public mutating func update(bytes: RawSpan) { + innerHasher.update(bytes: bytes) + } + /// Finalizes the message authentication computation and returns the /// computed code. /// @@ -211,10 +204,18 @@ public struct HMAC: MACAlgorithm, Sendable { let computedMac = authenticator.finalize() return safeCompare(authenticationCodeBytes, computedMac) } + + private static func isValidAuthenticationCode(authenticationCodeBytes: C, + authenticatedData: UnsafeRawBufferPointer, + key: SymmetricKey) -> Bool { + var authenticator = Self(key: key) + authenticator.update(bufferPointer: authenticatedData) + let computedMac = authenticator.finalize() + return safeCompare(authenticationCodeBytes, computedMac) + } } /// A hash-based message authentication code. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct HashedAuthenticationCode: MessageAuthenticationCode, Sendable { let digest: H.Digest @@ -248,4 +249,4 @@ public struct HashedAuthenticationCode: MessageAuthenticationCo } #endif } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Message Authentication Codes/MACFunctions.swift b/Sources/Crypto/Message Authentication Codes/MACFunctions.swift index 118bc388..66ea3f6b 100644 --- a/Sources/Crypto/Message Authentication Codes/MACFunctions.swift +++ b/Sources/Crypto/Message Authentication Codes/MACFunctions.swift @@ -11,27 +11,19 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol MACAlgorithm { associatedtype Key - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - associatedtype MAC: CryptoKit.MessageAuthenticationCode - #else associatedtype MAC: Crypto.MessageAuthenticationCode - #endif /// Initializes the MAC Algorithm /// @@ -49,7 +41,6 @@ protocol MACAlgorithm { func finalize() -> MAC } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension MACAlgorithm { /// Computes a Message Authentication Code. /// @@ -76,4 +67,4 @@ extension MACAlgorithm { return mac == Self.authenticationCode(bufferPointer: bufferPointer, using: key) } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Message Authentication Codes/MessageAuthenticationCode.swift b/Sources/Crypto/Message Authentication Codes/MessageAuthenticationCode.swift index 13d31f04..15605ad4 100644 --- a/Sources/Crypto/Message Authentication Codes/MessageAuthenticationCode.swift +++ b/Sources/Crypto/Message Authentication Codes/MessageAuthenticationCode.swift @@ -11,23 +11,19 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif #if hasFeature(Embedded) /// A type that represents a message authentication code. @preconcurrency -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public protocol MessageAuthenticationCode: Hashable, ContiguousBytes, Sendable, Sequence where Element == UInt8 { /// The number of bytes in the message authentication code. var byteCount: Int { get } @@ -35,14 +31,12 @@ public protocol MessageAuthenticationCode: Hashable, ContiguousBytes, Sendable, #else /// A type that represents a message authentication code. @preconcurrency -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public protocol MessageAuthenticationCode: Hashable, ContiguousBytes, Sendable, CustomStringConvertible, Sequence where Element == UInt8 { /// The number of bytes in the message authentication code. var byteCount: Int { get } } #endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension MessageAuthenticationCode { /// Returns a Boolean value indicating whether two message authentication /// codes are equal. @@ -77,7 +71,7 @@ extension MessageAuthenticationCode { public func makeIterator() -> Array.Iterator { self.withUnsafeBytes({ (buffPtr) in - return Array(buffPtr.bindMemory(to: UInt8.self)).makeIterator() + return Array(buffPtr).makeIterator() }) } @@ -87,4 +81,4 @@ extension MessageAuthenticationCode { } #endif } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/PRF/AES.swift b/Sources/Crypto/PRF/AES.swift index bd58060f..623ba98d 100644 --- a/Sources/Crypto/PRF/AES.swift +++ b/Sources/Crypto/PRF/AES.swift @@ -11,16 +11,16 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else /// A container for Advanced Encryption Standard (AES) ciphers. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +@nonexhaustive public enum AES: Sendable { static let blockSizeByteCount = 16 } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension AES { static func isValidKey(_ key: SymmetricKey) -> Bool { switch key.bitCount { @@ -35,4 +35,4 @@ extension AES { } } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Signatures/BoringSSL/ECDSASignature_boring.swift b/Sources/Crypto/Signatures/BoringSSL/ECDSASignature_boring.swift index d33110d3..644409e5 100644 --- a/Sources/Crypto/Signatures/BoringSSL/ECDSASignature_boring.swift +++ b/Sources/Crypto/Signatures/BoringSSL/ECDSASignature_boring.swift @@ -11,11 +11,14 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL -@_implementationOnly import CCryptoBoringSSLShims +#endif import CryptoBoringWrapper #if canImport(FoundationEssentials) import FoundationEssentials @@ -25,13 +28,13 @@ import Foundation /// A wrapper around BoringSSL's ECDSA_SIG with some lifetime management. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -class ECDSASignature { +final class ECDSASignature { private var _baseSig: UnsafeMutablePointer init(contiguousDERBytes derBytes: ContiguousBuffer) throws { self._baseSig = try derBytes.withUnsafeBytes { bytesPtr in guard - let sig = CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(bytesPtr.baseAddress, bytesPtr.count) + let sig = CCryptoBoringSSL_ECDSA_SIG_from_bytes(bytesPtr.baseAddress, bytesPtr.count) else { throw CryptoKitError.internalBoringSSLError() } @@ -96,21 +99,6 @@ class ECDSASignature { ) } - @usableFromInline - var derBytes: Data { - var dataPtr: UnsafeMutablePointer? - 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( _ body: (UnsafeMutablePointer) throws -> T ) @@ -119,4 +107,4 @@ class ECDSASignature { try body(self._baseSig) } } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Signatures/BoringSSL/ECDSA_boring.swift b/Sources/Crypto/Signatures/BoringSSL/ECDSA_boring.swift index 0842eada..517d24e1 100644 --- a/Sources/Crypto/Signatures/BoringSSL/ECDSA_boring.swift +++ b/Sources/Crypto/Signatures/BoringSSL/ECDSA_boring.swift @@ -11,10 +11,14 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL +#endif import CryptoBoringWrapper #if canImport(FoundationEssentials) import FoundationEssentials @@ -63,17 +67,6 @@ extension Data { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -extension P256.Signing.ECDSASignature { - init(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(for digest: D) throws -> P256.Signing.ECDSASignature { @@ -100,17 +93,6 @@ extension P256.Signing.PublicKey { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -extension P384.Signing.ECDSASignature { - init(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(for digest: D) throws -> P384.Signing.ECDSASignature { @@ -137,17 +119,6 @@ extension P384.Signing.PublicKey { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -extension P521.Signing.ECDSASignature { - init(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(for digest: D) throws -> P521.Signing.ECDSASignature { @@ -173,4 +144,4 @@ extension P521.Signing.PublicKey { return self.impl.key.isValidSignature(baseSignature, for: digest) } } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Signatures/BoringSSL/EdDSA_boring.swift b/Sources/Crypto/Signatures/BoringSSL/EdDSA_boring.swift index 9c3e39c0..ed012236 100644 --- a/Sources/Crypto/Signatures/BoringSSL/EdDSA_boring.swift +++ b/Sources/Crypto/Signatures/BoringSSL/EdDSA_boring.swift @@ -11,11 +11,14 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL -@_implementationOnly import CCryptoBoringSSLShims +#endif #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -89,7 +92,7 @@ extension Curve25519.Signing.PublicKey { precondition(signaturePointer.count == Curve25519.Signing.PublicKey.signatureByteCount) precondition(self.keyBytes.count == 32) let rc: CInt = self.keyBytes.withUnsafeBytes { keyBytesPtr in - CCryptoBoringSSLShims_ED25519_verify( + CCryptoBoringSSL_ED25519_verify( dataPointer.baseAddress, dataPointer.count, signaturePointer.baseAddress, @@ -128,7 +131,7 @@ extension Curve25519.Signing.PrivateKey { precondition(signaturePointer.count == Curve25519.Signing.PublicKey.signatureByteCount) precondition(keyPointer.count == ED25519_PRIVATE_KEY_LEN) - return CCryptoBoringSSLShims_ED25519_sign( + return CCryptoBoringSSL_ED25519_sign( signaturePointer.baseAddress, dataPointer.baseAddress, dataPointer.count, @@ -144,4 +147,4 @@ extension Curve25519.Signing.PrivateKey { return signature } } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Signatures/BoringSSL/MLDSA_boring.swift b/Sources/Crypto/Signatures/BoringSSL/MLDSA_boring.swift index 05150b49..412ed1ac 100644 --- a/Sources/Crypto/Signatures/BoringSSL/MLDSA_boring.swift +++ b/Sources/Crypto/Signatures/BoringSSL/MLDSA_boring.swift @@ -12,21 +12,18 @@ // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@_exported import CryptoKit -#else -@_implementationOnly import CCryptoBoringSSL -#if canImport(FoundationEssentials) -import FoundationEssentials -#else -import Foundation -#endif - // MARK: - Generated file, do NOT edit // any edits of this file WILL be overwritten and thus discarded // see section `gyb` in `README` for details. +#if canImport(CryptoKit) +@_exported import CryptoKit +#else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL +#endif #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -642,4 +639,4 @@ enum MLDSA { static let seedByteCount = 32 } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Signatures/BoringSSL/MLDSA_boring.swift.gyb b/Sources/Crypto/Signatures/BoringSSL/MLDSA_boring.swift.gyb index 27aaa239..62891ac6 100644 --- a/Sources/Crypto/Signatures/BoringSSL/MLDSA_boring.swift.gyb +++ b/Sources/Crypto/Signatures/BoringSSL/MLDSA_boring.swift.gyb @@ -12,21 +12,18 @@ // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@_exported import CryptoKit -#else -@_implementationOnly import CCryptoBoringSSL -#if canImport(FoundationEssentials) -import FoundationEssentials -#else -import Foundation -#endif - // MARK: - Generated file, do NOT edit // any edits of this file WILL be overwritten and thus discarded // see section `gyb` in `README` for details. +#if canImport(CryptoKit) +@_exported import CryptoKit +#else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL +#endif #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -345,4 +342,4 @@ enum MLDSA { static let seedByteCount = 32 } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Signatures/BoringSSL/MLDSA_wrapper.swift b/Sources/Crypto/Signatures/BoringSSL/MLDSA_wrapper.swift index a02db507..24a6f9d2 100644 --- a/Sources/Crypto/Signatures/BoringSSL/MLDSA_wrapper.swift +++ b/Sources/Crypto/Signatures/BoringSSL/MLDSA_wrapper.swift @@ -12,10 +12,14 @@ // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL +#endif #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -171,4 +175,4 @@ struct OpenSSLMLDSAPublicKeyImpl { } } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Signatures/ECDSA.swift b/Sources/Crypto/Signatures/ECDSA.swift index 423aef1e..d27e9783 100644 --- a/Sources/Crypto/Signatures/ECDSA.swift +++ b/Sources/Crypto/Signatures/ECDSA.swift @@ -11,23 +11,21 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if !CRYPTOKIT_NO_ACCESS_TO_FOUNDATION + #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#else -public import SwiftSystem -#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. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol NISTECDSASignature { init(rawRepresentation: D) throws(CryptoKitMetaError) init(derRepresentation: D) throws(CryptoKitMetaError) @@ -35,7 +33,6 @@ protocol NISTECDSASignature { var rawRepresentation: Data { get } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol NISTSigning { associatedtype PublicKey: NISTECPublicKey & DataValidator & DigestValidator associatedtype PrivateKey: NISTECPrivateKey & Signer @@ -43,11 +40,9 @@ protocol NISTSigning { } // MARK: - P256 + Signing -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P256.Signing { /// A P-256 elliptic curve digital signature algorithm (ECDSA) signature. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct ECDSASignature: ContiguousBytes, NISTECDSASignature, Sendable { /// A raw data representation of a P-256 digital signature. @@ -145,11 +140,9 @@ extension P256.Signing { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P256.Signing: NISTSigning {} // MARK: - P256 + PrivateKey -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P256.Signing.PrivateKey: DigestSigner { /// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA) /// signature of the digest you provide over the P-256 elliptic curve. @@ -160,15 +153,10 @@ extension P256.Signing.PrivateKey: DigestSigner { /// algorithm employs randomization to generate a different signature on /// every call, even for the same data and key. public func signature(for digest: D) throws(CryptoKitMetaError) -> P256.Signing.ECDSASignature { - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - return try self.coreCryptoSignature(for: digest) - #else return try self.openSSLSignature(for: digest) - #endif } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P256.Signing.PrivateKey: Signer { /// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA) /// signature of the data you provide over the P-256 elliptic curve, @@ -184,7 +172,6 @@ extension P256.Signing.PrivateKey: Signer { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P256.Signing.PublicKey: DigestValidator { /// Verifies an elliptic curve digital signature algorithm (ECDSA) /// signature on a digest over the P-256 elliptic curve. @@ -195,15 +182,10 @@ extension P256.Signing.PublicKey: DigestValidator { /// - Returns: A Boolean value that’s `true` if the signature is valid for /// the given digest; otherwise, `false`. public func isValidSignature(_ signature: P256.Signing.ECDSASignature, for digest: D) -> Bool { - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - return self.coreCryptoIsValidSignature(signature, for: digest) - #else return self.openSSLIsValidSignature(signature, for: digest) - #endif } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P256.Signing.PublicKey: DataValidator { /// Verifies an elliptic curve digital signature algorithm (ECDSA) /// signature on a block of data over the P-256 elliptic curve. @@ -219,11 +201,9 @@ extension P256.Signing.PublicKey: DataValidator { } // MARK: - P384 + Signing -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P384.Signing { /// A P-384 elliptic curve digital signature algorithm (ECDSA) signature. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct ECDSASignature: ContiguousBytes, NISTECDSASignature, Sendable { /// A raw data representation of a P-384 digital signature. @@ -321,11 +301,9 @@ extension P384.Signing { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P384.Signing: NISTSigning {} // MARK: - P384 + PrivateKey -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P384.Signing.PrivateKey: DigestSigner { /// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA) /// signature of the digest you provide over the P-384 elliptic curve. @@ -336,15 +314,10 @@ extension P384.Signing.PrivateKey: DigestSigner { /// algorithm employs randomization to generate a different signature on /// every call, even for the same data and key. public func signature(for digest: D) throws(CryptoKitMetaError) -> P384.Signing.ECDSASignature { - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - return try self.coreCryptoSignature(for: digest) - #else return try self.openSSLSignature(for: digest) - #endif } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P384.Signing.PrivateKey: Signer { /// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA) /// signature of the data you provide over the P-384 elliptic curve, @@ -360,7 +333,6 @@ extension P384.Signing.PrivateKey: Signer { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P384.Signing.PublicKey: DigestValidator { /// Verifies an elliptic curve digital signature algorithm (ECDSA) /// signature on a digest over the P-384 elliptic curve. @@ -371,15 +343,10 @@ extension P384.Signing.PublicKey: DigestValidator { /// - Returns: A Boolean value that’s `true` if the signature is valid for /// the given digest; otherwise, `false`. public func isValidSignature(_ signature: P384.Signing.ECDSASignature, for digest: D) -> Bool { - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - return self.coreCryptoIsValidSignature(signature, for: digest) - #else return self.openSSLIsValidSignature(signature, for: digest) - #endif } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P384.Signing.PublicKey: DataValidator { /// Verifies an elliptic curve digital signature algorithm (ECDSA) /// signature on a block of data over the P-384 elliptic curve. @@ -395,11 +362,9 @@ extension P384.Signing.PublicKey: DataValidator { } // MARK: - P521 + Signing -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P521.Signing { /// A P-521 elliptic curve digital signature algorithm (ECDSA) signature. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct ECDSASignature: ContiguousBytes, NISTECDSASignature, Sendable { /// A raw data representation of a P-521 digital signature. @@ -497,11 +462,9 @@ extension P521.Signing { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P521.Signing: NISTSigning {} // MARK: - P521 + PrivateKey -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P521.Signing.PrivateKey: DigestSigner { /// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA) /// signature of the digest you provide over the P-521 elliptic curve. @@ -512,15 +475,10 @@ extension P521.Signing.PrivateKey: DigestSigner { /// algorithm employs randomization to generate a different signature on /// every call, even for the same data and key. public func signature(for digest: D) throws(CryptoKitMetaError) -> P521.Signing.ECDSASignature { - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - return try self.coreCryptoSignature(for: digest) - #else return try self.openSSLSignature(for: digest) - #endif } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P521.Signing.PrivateKey: Signer { /// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA) /// signature of the data you provide over the P-521 elliptic curve, @@ -536,7 +494,6 @@ extension P521.Signing.PrivateKey: Signer { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P521.Signing.PublicKey: DigestValidator { /// Verifies an elliptic curve digital signature algorithm (ECDSA) /// signature on a digest over the P-521 elliptic curve. @@ -547,15 +504,10 @@ extension P521.Signing.PublicKey: DigestValidator { /// - Returns: A Boolean value that’s `true` if the signature is valid for /// the given digest; otherwise, `false`. public func isValidSignature(_ signature: P521.Signing.ECDSASignature, for digest: D) -> Bool { - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - return self.coreCryptoIsValidSignature(signature, for: digest) - #else return self.openSSLIsValidSignature(signature, for: digest) - #endif } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension P521.Signing.PublicKey: DataValidator { /// Verifies an elliptic curve digital signature algorithm (ECDSA) /// signature on a block of data over the P-521 elliptic curve. @@ -571,4 +523,4 @@ extension P521.Signing.PublicKey: DataValidator { } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Signatures/ECDSA.swift.gyb b/Sources/Crypto/Signatures/ECDSA.swift.gyb deleted file mode 100644 index a4e6a701..00000000 --- a/Sources/Crypto/Signatures/ECDSA.swift.gyb +++ /dev/null @@ -1,224 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the SwiftCrypto open source project -// -// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@_exported import CryptoKit -#else -#if !CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -#if canImport(FoundationEssentials) -public import FoundationEssentials -#else -public import Foundation -#endif -#else -public import SwiftSystem -#endif -// MARK: - Generated file, do NOT edit -// any edits of this file WILL be overwritten and thus discarded -// see section `gyb` in `README` for details. -%{ - NIST_CURVES_AND_HF = [{"curve": "P256", "hf": "SHA256"},{"curve": "P384", "hf": "SHA384"},{"curve": "P521", "hf": "SHA512"}] -}% - -protocol NISTECDSASignature { - init(rawRepresentation: D) throws(CryptoKitMetaError) - init(derRepresentation: D) throws(CryptoKitMetaError) - var derRepresentation: Data { get } - var rawRepresentation: Data { get } -} - -protocol NISTSigning { - associatedtype PublicKey: NISTECPublicKey & DataValidator & DigestValidator - associatedtype PrivateKey: NISTECPrivateKey & Signer - associatedtype ECDSASignature: NISTECDSASignature -} - -% for CURVE_AND_HF in NIST_CURVES_AND_HF: -%{ - CURVE = CURVE_AND_HF["curve"] - HF = CURVE_AND_HF["hf"] - DISPLAY_CURVE = CURVE[:1] + "-" + CURVE[1:] - DISPLAY_HF = HF[:3] + "-" + HF[3:] -}% -// MARK: - ${CURVE} + Signing -extension ${CURVE}.Signing { - - /// A ${DISPLAY_CURVE} elliptic curve digital signature algorithm (ECDSA) signature. - public struct ECDSASignature: ContiguousBytes, NISTECDSASignature, Sendable { - - /// A raw data representation of a ${DISPLAY_CURVE} digital signature. - public var rawRepresentation: Data - - /// Creates a ${DISPLAY_CURVE} digital signature from a raw representation. - /// - /// - Parameters: - /// - rawRepresentation: A raw representation of the signature as a - /// collection of contiguous bytes. - public init(rawRepresentation: D) throws(CryptoKitMetaError) { - guard rawRepresentation.count == 2 * ${CURVE}.coordinateByteCount else { - throw error(CryptoKitError.incorrectParameterSize) - } - - self.rawRepresentation = Data(rawRepresentation) - } - - internal init(_ dataRepresentation: Data) throws(CryptoKitMetaError) { - guard dataRepresentation.count == 2 * ${CURVE}.coordinateByteCount else { - throw error(CryptoKitError.incorrectParameterSize) - } - - self.rawRepresentation = dataRepresentation - } - - var composite: (r: Data, s: Data) { - let combined = rawRepresentation - assert(combined.count % 2 == 0) - let half = combined.count / 2 - return (combined.prefix(half), combined.suffix(half)) - } - - /// Creates a ${DISPLAY_CURVE} digital signature from a Distinguished Encoding - /// Rules (DER) encoded representation. - /// - /// - Parameters: - /// - derRepresentation: The DER-encoded representation of the - /// signature. - public init(derRepresentation: D) throws(CryptoKitMetaError) { - #if os(iOS) && (arch(arm) || arch(i386)) - fatalError("Unsupported architecture") - #else - let parsed = try ASN1.parse(Array(derRepresentation)) - let signature = try ASN1.ECDSASignature>(asn1Encoded: parsed) - - let coordinateByteCount = ${CURVE}.coordinateByteCount - - guard signature.r.count <= coordinateByteCount && signature.s.count <= coordinateByteCount else { - throw error(CryptoKitError.incorrectParameterSize) - } - - // r and s must be padded out to the coordinate byte count. - var raw = Data() - raw.reserveCapacity(2 * ${CURVE}.coordinateByteCount) - - raw.append(contentsOf: repeatElement(0, count: ${CURVE}.coordinateByteCount - signature.r.count)) - raw.append(contentsOf: signature.r) - raw.append(contentsOf: repeatElement(0, count: ${CURVE}.coordinateByteCount - signature.s.count)) - raw.append(contentsOf: signature.s) - - self.rawRepresentation = raw - #endif - } - - /// Invokes the given closure with a buffer pointer covering the raw - /// bytes of the signature. -#if hasFeature(Embedded) - public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R { - try self.rawRepresentation.withUnsafeBytes(body) - } -#else - public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { - try self.rawRepresentation.withUnsafeBytes(body) - } -#endif - - /// A Distinguished Encoding Rules (DER) encoded representation of a - /// ${DISPLAY_CURVE} digital signature. - public var derRepresentation: Data { - #if os(iOS) && (arch(arm) || arch(i386)) - fatalError("Unsupported architecture") - #else - let raw = rawRepresentation - let half = raw.count / 2 - let r = Array(raw.prefix(half))[...] - let s = Array(raw.suffix(half))[...] - - let sig = ASN1.ECDSASignature(r: r, s: s) - var serializer = ASN1.Serializer() - try! serializer.serialize(sig) - return Data(serializer.serializedBytes) - #endif - } - } -} - -extension ${CURVE}.Signing: NISTSigning {} - -// MARK: - ${CURVE} + PrivateKey -extension ${CURVE}.Signing.PrivateKey: DigestSigner { - /// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA) - /// signature of the digest you provide over the ${DISPLAY_CURVE} elliptic curve. - /// - /// - Parameters: - /// - digest: The digest of the data to sign. - /// - Returns: The signature corresponding to the digest. The signing - /// algorithm employs randomization to generate a different signature on - /// every call, even for the same data and key. - public func signature(for digest: D) throws(CryptoKitMetaError) -> ${CURVE}.Signing.ECDSASignature { - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - return try self.coreCryptoSignature(for: digest) - #else - return try self.openSSLSignature(for: digest) - #endif - } - } - -extension ${CURVE}.Signing.PrivateKey: Signer { - /// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA) - /// signature of the data you provide over the ${DISPLAY_CURVE} elliptic curve, - /// using ${DISPLAY_HF} as the hash function. - /// - /// - Parameters: - /// - data: The data to sign. - /// - Returns: The signature corresponding to the data. The signing - /// algorithm employs randomization to generate a different signature on - /// every call, even for the same data and key. - public func signature(for data: D) throws(CryptoKitMetaError) -> ${CURVE}.Signing.ECDSASignature { - return try self.signature(for: ${HF}.hash(data: data)) - } -} - -extension ${CURVE}.Signing.PublicKey: DigestValidator { - /// Verifies an elliptic curve digital signature algorithm (ECDSA) - /// signature on a digest over the ${DISPLAY_CURVE} elliptic curve. - /// - /// - Parameters: - /// - signature: The signature to verify. - /// - digest: The signed digest. - /// - Returns: A Boolean value that’s `true` if the signature is valid for - /// the given digest; otherwise, `false`. - public func isValidSignature(_ signature: ${CURVE}.Signing.ECDSASignature, for digest: D) -> Bool { - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - return self.coreCryptoIsValidSignature(signature, for: digest) - #else - return self.openSSLIsValidSignature(signature, for: digest) - #endif - } -} - -extension ${CURVE}.Signing.PublicKey: DataValidator { - /// Verifies an elliptic curve digital signature algorithm (ECDSA) - /// signature on a block of data over the ${DISPLAY_CURVE} elliptic curve. - /// - /// - Parameters: - /// - signature: The signature to verify. - /// - data: The signed data. - /// - Returns: A Boolean value that’s `true` if the signature is valid for - /// the given data; otherwise, `false`. - public func isValidSignature(_ signature: ${CURVE}.Signing.ECDSASignature, for data: D) -> Bool { - return self.isValidSignature(signature, for: ${HF}.hash(data: data)) - } - } - -% end - -#endif // Linux or !SwiftPM diff --git a/Sources/Crypto/Signatures/Ed25519.swift b/Sources/Crypto/Signatures/Ed25519.swift index c82b85bc..ba377bb2 100644 --- a/Sources/Crypto/Signatures/Ed25519.swift +++ b/Sources/Crypto/Signatures/Ed25519.swift @@ -11,39 +11,32 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -public import SwiftSystem -#else #if canImport(FoundationEssentials) public import FoundationEssentials #else public import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol DigestValidator { associatedtype Signature func isValidSignature(_ signature: Signature, for digest: D) -> Bool } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol DataValidator { associatedtype Signature func isValidSignature(_ signature: Signature, for signedData: D) -> Bool } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Curve25519.Signing { static var signatureByteCount: Int { return 64 } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Curve25519.Signing.PublicKey: DataValidator { typealias Signature = Data @@ -56,15 +49,10 @@ extension Curve25519.Signing.PublicKey: DataValidator { /// - Returns: A Boolean value that’s `true` when the signature is valid for /// the given data. public func isValidSignature(_ signature: S, for data: D) -> Bool { - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - return self.coreCryptoIsValidSignature(signature, for: data) - #else return self.openSSLIsValidSignature(signature, for: data) - #endif } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Curve25519.Signing.PrivateKey: Signer { /// Generates an EdDSA signature over Curve25519. /// @@ -78,11 +66,7 @@ extension Curve25519.Signing.PrivateKey: Signer { /// different signature on every call, even for the same data and key, to /// guard against side-channel attacks. public func signature(for data: D) throws(CryptoKitMetaError) -> Data { - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - return try self.coreCryptoSignature(for: data) - #else return try self.openSSLSignature(for: data) - #endif } } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Signatures/MLDSA.swift b/Sources/Crypto/Signatures/MLDSA.swift index b3f2cce0..26e9c1fd 100644 --- a/Sources/Crypto/Signatures/MLDSA.swift +++ b/Sources/Crypto/Signatures/MLDSA.swift @@ -11,7 +11,8 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else #if canImport(FoundationEssentials) @@ -20,34 +21,23 @@ public import FoundationEssentials public import Foundation #endif -#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -typealias MLDSAPublicKeyImpl = CorecryptoMLDSAPublicKeyImpl -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -typealias MLDSAPrivateKeyImpl = CorecryptoMLDSAPrivateKeyImpl -#else -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) typealias MLDSAPublicKeyImpl = OpenSSLMLDSAPublicKeyImpl -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) typealias MLDSAPrivateKeyImpl = OpenSSLMLDSAPrivateKeyImpl -#endif /// The MLDSA65 Digital Signature Algorithm -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +@nonexhaustive public enum MLDSA65: Sendable {} -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension MLDSA65 { /// The public key for MLDSA65. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PublicKey: Sendable { var impl: MLDSAPublicKeyImpl internal init(_ impl: MLDSAPublicKeyImpl) { self.impl = impl } - + /// Parses a public key from a serialized representation. /// /// - Parameter rawRepresentation: The public key, in the FIPS 204 standard serialization format. @@ -55,7 +45,7 @@ extension MLDSA65 { public init(rawRepresentation: D) throws { self.impl = try MLDSAPublicKeyImpl(rawRepresentation: rawRepresentation) } - + /// A serialized representation of the public key. /// /// This property provides a representation of the public key in the FIPS 204 standard serialization format. @@ -86,15 +76,24 @@ extension MLDSA65 { } /// The private key for MLDSA65. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PrivateKey: Signer, Sendable { internal let impl: MLDSAPrivateKeyImpl - + internal init(_ impl: MLDSAPrivateKeyImpl) { self.impl = impl } - - /// Initializes a new random private key. + + /// Creates a random MLDSA65 private key. + /// + /// This initializer is marked `throws` to support use in generic contexts, + /// but key generation itself doesn't produce errors. + /// + /// When you call this initializer directly on a concrete type, rather than + /// through a generic type parameter, you can safely call `try!` to create the key: + /// + /// ```swift + /// let privateKey = try! MLDSA65.PrivateKey() + /// ``` public init() throws { let impl = try MLDSAPrivateKeyImpl() self = PrivateKey(impl) @@ -115,7 +114,7 @@ extension MLDSA65 { } self.impl = try MLDSAPrivateKeyImpl(seedRepresentation: seedRepresentation, publicKeyRawRepresentation: publicKeyRawRepresentation) } - + /// The seed representation of the private key. /// /// The seed representation is 32 bytes long, and is the parameter @@ -144,11 +143,11 @@ extension MLDSA65 { public func signature(for data: D, context: C) throws -> Data { return try impl.signature(for: data, context: context) } - + /// The associated public key. public var publicKey: PublicKey { get { - PublicKey(impl.publicKey) + return PublicKey(self.impl.publicKey) } } @@ -164,7 +163,7 @@ extension MLDSA65 { let seed = Data(integrityCheckedRepresentation).subdata(in: 0..(seedRepresentation: seed, publicKeyHash: publicKeyHash) } @@ -182,20 +181,18 @@ extension MLDSA65 { /// The MLDSA87 Digital Signature Algorithm -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +@nonexhaustive public enum MLDSA87: Sendable {} -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension MLDSA87 { /// The public key for MLDSA87. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PublicKey: Sendable { var impl: MLDSAPublicKeyImpl internal init(_ impl: MLDSAPublicKeyImpl) { self.impl = impl } - + /// Parses a public key from a serialized representation. /// /// - Parameter rawRepresentation: The public key, in the FIPS 204 standard serialization format. @@ -203,7 +200,7 @@ extension MLDSA87 { public init(rawRepresentation: D) throws { self.impl = try MLDSAPublicKeyImpl(rawRepresentation: rawRepresentation) } - + /// A serialized representation of the public key. /// /// This property provides a representation of the public key in the FIPS 204 standard serialization format. @@ -234,15 +231,24 @@ extension MLDSA87 { } /// The private key for MLDSA87. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public struct PrivateKey: Signer, Sendable { internal let impl: MLDSAPrivateKeyImpl - + internal init(_ impl: MLDSAPrivateKeyImpl) { self.impl = impl } - - /// Initializes a new random private key. + + /// Creates a random MLDSA87 private key. + /// + /// This initializer is marked `throws` to support use in generic contexts, + /// but key generation itself doesn't produce errors. + /// + /// When you call this initializer directly on a concrete type, rather than + /// through a generic type parameter, you can safely call `try!` to create the key: + /// + /// ```swift + /// let privateKey = try! MLDSA87.PrivateKey() + /// ``` public init() throws { let impl = try MLDSAPrivateKeyImpl() self = PrivateKey(impl) @@ -263,7 +269,7 @@ extension MLDSA87 { } self.impl = try MLDSAPrivateKeyImpl(seedRepresentation: seedRepresentation, publicKeyRawRepresentation: publicKeyRawRepresentation) } - + /// The seed representation of the private key. /// /// The seed representation is 32 bytes long, and is the parameter @@ -292,11 +298,11 @@ extension MLDSA87 { public func signature(for data: D, context: C) throws -> Data { return try impl.signature(for: data, context: context) } - + /// The associated public key. public var publicKey: PublicKey { get { - PublicKey(impl.publicKey) + return PublicKey(self.impl.publicKey) } } @@ -312,7 +318,7 @@ extension MLDSA87 { let seed = Data(integrityCheckedRepresentation).subdata(in: 0..(seedRepresentation: seed, publicKeyHash: publicKeyHash) } @@ -329,4 +335,4 @@ extension MLDSA87 { } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Signatures/MLDSA.swift.gyb b/Sources/Crypto/Signatures/MLDSA.swift.gyb deleted file mode 100644 index 5378503a..00000000 --- a/Sources/Crypto/Signatures/MLDSA.swift.gyb +++ /dev/null @@ -1,180 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the SwiftCrypto open source project -// -// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@_exported import CryptoKit -#else -#if canImport(FoundationEssentials) -public import FoundationEssentials -#else -public import Foundation -#endif -%{ - MLDSA_VARIANTS = [{"name": "MLDSA65"}, {"name": "MLDSA87"}] -}% - -#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -typealias MLDSAPublicKeyImpl = CorecryptoMLDSAPublicKeyImpl -typealias MLDSAPrivateKeyImpl = CorecryptoMLDSAPrivateKeyImpl -#else -typealias MLDSAPublicKeyImpl = OpenSSLMLDSAPublicKeyImpl -typealias MLDSAPrivateKeyImpl = OpenSSLMLDSAPrivateKeyImpl -#endif - -% for MLDSA_VARIANT in MLDSA_VARIANTS: -%{ - NAME = MLDSA_VARIANT["name"] -}% - -/// The ${NAME} Digital Signature Algorithm -public enum ${NAME}: Sendable {} - -extension ${NAME} { - /// The public key for ${NAME}. - public struct PublicKey: Sendable { - var impl: MLDSAPublicKeyImpl<${NAME}> - - /// Parses a public key from a serialized representation. - /// - /// - Parameter rawRepresentation: The public key, in the FIPS 204 standard serialization format. - /// - Returns: The deserialized public key. - public init(rawRepresentation: D) throws { - self.impl = try MLDSAPublicKeyImpl(rawRepresentation: rawRepresentation) - } - - /// A serialized representation of the public key. - /// - /// This property provides a representation of the public key in the FIPS 204 standard serialization format. - public var rawRepresentation: Data { - get { - return self.impl.rawRepresentation - } - } - - /// Verifies a ${NAME} signature. - /// - Parameters: - /// - signature: The ${NAME} signature to verify. - /// - data: The signed data. - /// - Returns: `true` if the signature is valid, `false` otherwise. - public func isValidSignature(_ signature: S, for data: D) -> Bool { - return self.impl.isValidSignature(signature, for: data) - } - - /// Verifies a ${NAME} signature, in a specific context. - /// - Parameters: - /// - signature: The ${NAME} signature to verify. - /// - data: The signed data. - /// - context: Context for the signature. - /// - Returns: `true` if the signature is valid in the specified context, `false` otherwise. - public func isValidSignature(_ signature: S, for data: D, context: C) -> Bool { - return self.impl.isValidSignature(signature, for: data, context: context) - } - } - - /// The private key for ${NAME}. - public struct PrivateKey: Signer, Sendable { - internal let impl: MLDSAPrivateKeyImpl<${NAME}> - - internal init(_ impl: MLDSAPrivateKeyImpl<${NAME}>) { - self.impl = impl - } - - /// Initializes a new random private key. - public init() throws { - let impl = try MLDSAPrivateKeyImpl<${NAME}>() - self = PrivateKey(impl) - } - - /// Initializes a private key from the seed representation. - /// - /// - Parameter seedRepresentation: The seed representation of the private key. This parameter needs to be 32 bytes long. - /// - Parameter publicKey: The public key associated with the secret key. - /// - /// This initializer implements the `ML-DSA.KeyGen_internal` algorithm (Algorithm 16) of FIPS 204. - /// - /// If a public key is provided, a consistency check is performed between it and the derived public key. - public init(seedRepresentation: D, publicKey: ${NAME}.PublicKey?) throws { - var publicKeyRawRepresentation: Data? = nil - if publicKey != nil { - publicKeyRawRepresentation = publicKey!.rawRepresentation - } - self.impl = try MLDSAPrivateKeyImpl<${NAME}>(seedRepresentation: seedRepresentation, publicKeyRawRepresentation: publicKeyRawRepresentation) - } - - /// The seed representation of the private key. - /// - /// The seed representation is 32 bytes long, and is the parameter - /// for the `ML-DSA.KeyGen_internal` algorithm (Algorithm 16) of FIPS 204. - public var seedRepresentation: Data { - get { - return self.impl.seedRepresentation - } - } - - /// Generates a ${NAME} signature. - /// - Parameters: - /// - data: The data to sign. - /// - Returns: The ${NAME} signature. - /// This method throws if CryptoKit encounters an error producing the signature. - public func signature(for data: D) throws -> Data { - return try impl.signature(for: data) - } - - /// Generates a ${NAME} signature, with context. - /// - Parameters: - /// - data: The data to sign. - /// - context: Context for the signature. - /// - Returns: The ${NAME} signature. - /// This method throws if CryptoKit encounters an error producing the signature. - public func signature(for data: D, context: C) throws -> Data { - return try impl.signature(for: data, context: context) - } - - /// The associated public key. - public var publicKey: PublicKey { - get { - PublicKey(impl.publicKey) - } - } - - /// Initializes a private key from an integrity-checked data representation. - /// - /// - Parameter integrityCheckedRepresentation: The integrity-checked data representation of the private key. - /// The parameter needs to be 64 bytes long, and contain the seed and a hash of the public key. - public init(integrityCheckedRepresentation: D) throws { - let seedSize = MLDSAPrivateKeyImpl<${NAME}>.seedSize - guard integrityCheckedRepresentation.count == seedSize + 32 else { - throw CryptoKitError.incorrectParameterSize - } - - let seed = Data(integrityCheckedRepresentation).subdata(in: 0..(seedRepresentation: seed, publicKeyHash: publicKeyHash) - } - - /// The integrity-checked data representation of the private key. - /// - /// This representation is 64 bytes long, and contains the seed and a hash of the public key. - public var integrityCheckedRepresentation: Data { - get { - return self.impl.integrityCheckedRepresentation - } - } - } -} - -% end - -#endif // Linux or !SwiftPM diff --git a/Sources/Crypto/Signatures/Signature.swift b/Sources/Crypto/Signatures/Signature.swift index ea9f9700..bfef886b 100644 --- a/Sources/Crypto/Signatures/Signature.swift +++ b/Sources/Crypto/Signatures/Signature.swift @@ -11,33 +11,27 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol SignatureVerification { func verifySignature(signature: Data, data: Data) throws(CryptoKitMetaError) -> Bool } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol DigestSigner { associatedtype Signature func signature(for digest: D) throws(CryptoKitMetaError) -> Signature } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) protocol Signer { associatedtype Signature func signature(for data: D) throws(CryptoKitMetaError) -> Signature } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Util/ArraySpanHelpers.swift b/Sources/Crypto/Util/ArraySpanHelpers.swift new file mode 100644 index 00000000..548fcb6d --- /dev/null +++ b/Sources/Crypto/Util/ArraySpanHelpers.swift @@ -0,0 +1,92 @@ +//===----------------------------------------------------------------------===// +// +// 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(CryptoKit) +@_exported import CryptoKit +#else + +extension InlineArray where Element == UInt8 { + /// Copy of the bytes of the given raw span into this array. The span + /// must have exactly count bytes in it. + init(copying bytes: RawSpan) { + precondition(count == bytes.byteCount) + self.init { outputSpan in + for i in 0.. { + /// Append the contents of the given raw span to this output span. + #if swift(<6.3) + @_lifetime(self: copy self) + #endif + mutating func append(contentsOf bytes: RawSpan) { + for i in 0..(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R { + try self.span.withUnsafeBytes(body) + } + + func withBytes(_ body: (RawSpan) throws(E) -> R) throws(E) -> R where R: ~Copyable { + try body(self.span.bytes) + } +} + +#endif diff --git a/Sources/Crypto/Util/BoringSSL/Optional+withUnsafeBytes_boring.swift b/Sources/Crypto/Util/BoringSSL/Optional+withUnsafeBytes_boring.swift index 8d8aabac..a57f5709 100644 --- a/Sources/Crypto/Util/BoringSSL/Optional+withUnsafeBytes_boring.swift +++ b/Sources/Crypto/Util/BoringSSL/Optional+withUnsafeBytes_boring.swift @@ -18,6 +18,7 @@ import FoundationEssentials import Foundation #endif +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Optional where Wrapped: DataProtocol { func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> ReturnValue) rethrows -> ReturnValue { if let self { diff --git a/Sources/Crypto/Util/BoringSSL/RNG_boring.swift b/Sources/Crypto/Util/BoringSSL/RNG_boring.swift index 674bdb9a..3a4b7373 100644 --- a/Sources/Crypto/Util/BoringSSL/RNG_boring.swift +++ b/Sources/Crypto/Util/BoringSSL/RNG_boring.swift @@ -11,7 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) @_exported import CryptoKit #else @@ -43,4 +43,28 @@ extension UnsafeMutableRawBufferPointer { } } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +extension MutableRawSpan { + #if swift(<6.3) + @_lifetime(self: copy self) + #endif + mutating func initializeWithRandomBytes(count: Int) { + self.withUnsafeMutableBytes { $0.initializeWithRandomBytes(count: count) } + } +} + +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +extension OutputRawSpan { + #if swift(<6.3) + @_lifetime(self: copy self) + #endif + mutating func appendingRandomBytes(count: Int) { + self.withUnsafeMutableBytes { buffer, initializedCount in + UnsafeMutableRawBufferPointer(rebasing: buffer[initializedCount..( + start: buffer.baseAddress!.assumingMemoryBound(to: UInt8.self), + count: buffer.count + ) + ) + } + } + } + + /// Append the contents of the given span to this Data instance. + mutating func append(contentsOf bytes: RawSpan) { + bytes.withUnsafeBytes { buffer in + self.append(contentsOf: buffer) + } + } +} + +extension InlineArray where Element == UInt8 { + init(copying data: D) { + self.init { outputSpan in + for region in data.regions { + region.withUnsafeBytes { bytes in + outputSpan.append(contentsOf: bytes.bytes) + } + } + } + } +} + +#endif diff --git a/Sources/Crypto/Util/PrettyBytes.swift b/Sources/Crypto/Util/PrettyBytes.swift index 82190c60..97e8ba33 100644 --- a/Sources/Crypto/Util/PrettyBytes.swift +++ b/Sources/Crypto/Util/PrettyBytes.swift @@ -11,33 +11,25 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else + #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) enum ByteHexEncodingErrors: Error { case incorrectHexValue case incorrectString } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) let charA = UInt8(97 /* "a" */) -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) let char0 = UInt8(48 /* "0" */) -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) private func itoh(_ value: UInt8) -> UInt8 { return (value > 9) ? (charA + value - 10) : (char0 + value) } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) private func htoi(_ value: UInt8) throws -> UInt8 { switch value { case char0...char0 + 9: @@ -50,7 +42,6 @@ private func htoi(_ value: UInt8) throws -> UInt8 { } #if !hasFeature(Embedded) -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension DataProtocol { var hexString: String { let hexLen = self.count * 2 @@ -70,15 +61,12 @@ extension DataProtocol { } #endif // !hasFeature(Embedded) -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension RangeReplaceableCollection where Element == UInt8 { mutating func appendByte(_ byte: UInt64) { withUnsafeBytes(of: byte.littleEndian, { self.append(contentsOf: $0) }) } } -#if !CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Data { init(hexString: String) throws { self.init() @@ -98,7 +86,6 @@ extension Data { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Array where Element == UInt8 { init(hexString: String) throws { self.init() @@ -118,4 +105,3 @@ extension Array where Element == UInt8 { } } -#endif diff --git a/Sources/Crypto/Util/SafeCompare.swift b/Sources/Crypto/Util/SafeCompare.swift index 25358f9a..8496f7b4 100644 --- a/Sources/Crypto/Util/SafeCompare.swift +++ b/Sources/Crypto/Util/SafeCompare.swift @@ -11,26 +11,18 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal func safeCompare(_ lhs: LHS, _ rhs: RHS) -> Bool { - #if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - return coreCryptoSafeCompare(lhs, rhs) - #else return openSSLSafeCompare(lhs, rhs) - #endif } -#endif // Linux or !SwiftPM +#endif // canImport(CryptoKit) diff --git a/Sources/Crypto/Util/SecureBytes.swift b/Sources/Crypto/Util/SecureBytes.swift index 86b7c88a..6824c52d 100644 --- a/Sources/Crypto/Util/SecureBytes.swift +++ b/Sources/Crypto/Util/SecureBytes.swift @@ -11,23 +11,18 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API + +#if canImport(CryptoKit) @_exported import CryptoKit #else -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) nonisolated(unsafe) private let emptyStorage:SecureBytes.Backing = SecureBytes.Backing.createEmpty() -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct SecureBytes: @unchecked Sendable { var backing: Backing @@ -43,11 +38,24 @@ struct SecureBytes: @unchecked Sendable { } } - init(bytes: D) { + init(bytes: RawSpan) { self.backing = Backing.create(bytes: bytes) } + init(bytes: D) { + self = bytes.withUnsafeBytes{ buffer in + SecureBytes(bytes: buffer.bytes) + } + } + + /// Create a SecureBytes object with a closure that will initialize the memory. + init(capacity: Int, initializingWith callback: (inout OutputRawSpan) throws(E) -> Void) throws(E) { + self.backing = try Backing.create(capacity: capacity, initializingWith: callback) + } + /// Allows initializing a SecureBytes object with a closure that will initialize the memory. + /// + /// Note: Please use the safe counterpart, `init(capacity:initializingWith:)`. #if hasFeature(Embedded) init(unsafeUninitializedCapacity: Int, initializingWith callback: (inout UnsafeMutableRawBufferPointer, inout Int) throws(E) -> Void) throws(E) { self.backing = Backing.create(capacity: unsafeUninitializedCapacity) @@ -75,17 +83,22 @@ struct SecureBytes: @unchecked Sendable { #endif } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SecureBytes { - mutating func append(_ data: C) where C.Element == UInt8 { - let requiredCapacity = self.count + data.count + mutating func append(_ bytes: RawSpan) { + let requiredCapacity = self.count + bytes.byteCount let backingCapacity = self.backing.allocatedCapacity if !isKnownUniquelyReferenced(&self.backing) || requiredCapacity > backingCapacity { let newBacking = Backing.create(capacity: requiredCapacity) newBacking._appendBytes(self.backing, inRange: 0..(_ bytes: D) { + bytes.withUnsafeBytes { bytesBuffer in + self.append(bytesBuffer.bytes) + } } mutating func reserveCapacity(_ n: Int) { @@ -101,7 +114,6 @@ extension SecureBytes { } // MARK: - Equatable conformance, constant-time -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SecureBytes: Equatable { public static func == (lhs: SecureBytes, rhs: SecureBytes) -> Bool { return safeCompare(lhs, rhs) @@ -109,9 +121,7 @@ extension SecureBytes: Equatable { } // MARK: - Collection conformance -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SecureBytes: Collection { - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct Index { fileprivate var offset: Int @@ -147,7 +157,6 @@ extension SecureBytes: Collection { } // MARK: - BidirectionalCollection conformance -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SecureBytes: BidirectionalCollection { func index(before index: Index) -> Index { return index.advanced(by: -1) @@ -155,15 +164,12 @@ extension SecureBytes: BidirectionalCollection { } // MARK: - RandomAccessCollection conformance -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SecureBytes: RandomAccessCollection { } // MARK: - MutableCollection conformance -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SecureBytes: MutableCollection { } // MARK: - RangeReplaceableCollection conformance -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SecureBytes: RangeReplaceableCollection { mutating func replaceSubrange(_ subrange: Range, with newElements: C) where C.Element == UInt8 { let requiredCapacity = self.backing.count - subrange.count + newElements.count @@ -192,7 +198,7 @@ extension SecureBytes: RangeReplaceableCollection { // The default implementation of this from RangeReplaceableCollection can't take advantage of `ContiguousBytes`, so we override it here mutating func append(contentsOf newElements: some Sequence) { let done:Void? = newElements.withContiguousStorageIfAvailable { - replaceSubrange(endIndex..(_ body: (UnsafeRawBufferPointer) throws(E) -> T) throws(E) -> T { return try self.backing.withUnsafeBytes(body) } - #else - func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> T) rethrows -> T { - return try self.backing.withUnsafeBytes(body) - } - #endif #if hasFeature(Embedded) mutating func withUnsafeMutableBytes(_ body: (UnsafeMutableRawBufferPointer) throws(E) -> T) throws(E) -> T { @@ -246,7 +264,6 @@ extension SecureBytes: ContiguousBytes { } // MARK: - DataProtocol conformance -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SecureBytes: DataProtocol { var regions: CollectionOfOne { return CollectionOfOne(self) @@ -254,21 +271,17 @@ extension SecureBytes: DataProtocol { } // MARK: - MutableDataProtocol conformance -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SecureBytes: MutableDataProtocol { } // MARK: - Index conformances -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SecureBytes.Index: Hashable { } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SecureBytes.Index: Comparable { static func <(lhs: SecureBytes.Index, rhs: SecureBytes.Index) -> Bool { return lhs.offset < rhs.offset } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SecureBytes.Index: Strideable { func advanced(by n: Int) -> SecureBytes.Index { return SecureBytes.Index(offset: self.offset + n) @@ -280,17 +293,14 @@ extension SecureBytes.Index: Strideable { } // MARK: - Heap allocated backing storage. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SecureBytes { #if !hasFeature(Embedded) - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal struct BackingHeader { internal var count: Int internal var capacity: Int } - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal class Backing: ManagedBuffer { class func createEmpty() -> Backing { @@ -302,29 +312,46 @@ extension SecureBytes { return Backing.create(minimumCapacity: capacity, makingHeaderWith: { _ in BackingHeader(count: 0, capacity: capacity) }) as! Backing } + /// Create a new backing buffer with the given capacity, initializing its contents by calling the `body` closure + /// with an output span. Clients should initialize the contents of the buffer via that output span. + class func create(capacity: Int, initializingWith body: (inout OutputRawSpan) throws(E) -> Void) throws(E) -> Backing { + let backing = create(capacity: capacity) + try backing._withVeryUnsafeMutableBytes { (overallocatedTargetPtr) throws(E) in + // As Array does, we only produce an output span that covers the requested capacity, + // not the over-allocated capacity. + let targetPtr = overallocatedTargetPtr[0.. Backing { return Backing.create(bytes: original) } - final class func create(bytes: D) -> Backing { - return bytes.withUnsafeBytes { bytesPtr in - let backing = Backing.create(capacity: bytesPtr.count) - backing._withVeryUnsafeMutableBytes { targetPtr in - targetPtr.copyMemory(from: bytesPtr) - } - backing.count = bytesPtr.count - precondition(backing.count <= backing.allocatedCapacity) - return backing + final class func create(bytes: RawSpan) -> Backing { + let backing = create(capacity: bytes.byteCount) { output in + output.append(contentsOf: bytes) } + precondition(backing.count <= backing.allocatedCapacity) + return backing + } + + final class func create(bytes: D) -> Backing { + return bytes.withUnsafeBytes { create(bytes: $0.bytes) } } class func create(randomBytes: Int) -> Backing { - let backing = Backing.create(capacity: randomBytes) - backing._withVeryUnsafeMutableBytes { targetPtr in - assert(targetPtr.count >= randomBytes) - targetPtr.initializeWithRandomBytes(count: randomBytes) + let backing = Backing.create(capacity: randomBytes) { output in + output.appendingRandomBytes(count: randomBytes) } - backing.count = randomBytes return backing } @@ -356,9 +383,47 @@ extension SecureBytes { return self.withUnsafeMutablePointerToElements { ($0 + offset).pointee = newValue } } } + + /// Access the bytes in the buffer. Note that this is only safe to use + /// when you can ensure that no other code has mutating access to the + /// buffer. + @unsafe + var bytes: RawSpan { + _read { + let buffer = self.withUnsafeMutablePointerToElements { pointer in + UnsafeMutableBufferPointer(start: pointer, count: self.count) + } + + yield buffer.span.bytes + } + } + + /// Provide mutating access to the bytes in the buffer. Note that this + /// is only safe to use when you can ensure that no other code has + /// access to the buffer. + @unsafe + var mutableBytes: MutableRawSpan { + _read { + let buffer = self.withUnsafeMutablePointerToElements { pointer in + UnsafeMutableBufferPointer(start: pointer, count: self.count) + } + + var span = buffer.mutableSpan + yield span.mutableBytes + } + + _modify { + let buffer = self.withUnsafeMutablePointerToElements { pointer in + UnsafeMutableBufferPointer(start: pointer, count: self.count) + } + + var span = buffer.mutableSpan + var rawSpan = span.mutableBytes + yield &rawSpan + } + } } #else - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal class Backing { private var storage: UnsafeMutableRawBufferPointer @@ -367,6 +432,27 @@ extension SecureBytes { storage.count } + var bytes: RawSpan { + @_lifetime(self) + _read { + yield storage.bytes.extracting(first: count) + } + } + + var mutableBytes: MutableRawSpan { + _read { + var mutableStorage = storage.mutableBytes + let mutableBytes = mutableStorage._mutatingExtracting(first: count) + yield mutableBytes + } + + _modify { + var mutableStorage = storage.mutableBytes + var mutableBytes = mutableStorage._mutatingExtracting(first: count) + yield &mutableBytes + } + } + private init(storage: UnsafeMutableRawBufferPointer, count: Int) { self.storage = storage self.count = count @@ -382,21 +468,43 @@ extension SecureBytes { return Backing.init(storage: buffer, count: 0) } + /// Create a new backing buffer with the given capacity, initializing its contents by calling the `body` closure + /// with an output span. Clients should initialize the contents of the buffer via that output span. + final class func create(capacity: Int, initializingWith body: (inout OutputRawSpan) throws(E) -> Void) throws(E) -> Backing { + let backing = create(capacity: capacity) + try backing._withVeryUnsafeMutableBytes { (overallocatedTargetPtr) throws(E) in + // As Array does, we only produce an output span that covers the requested capacity, + // not the over-allocated capacity. + let targetPtr = overallocatedTargetPtr[0.. Backing { let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: original.capacity, alignment: Int(CC_MAX_ALIGNMENT)) buffer.copyBytes(from: original.storage) return Backing.init(storage: buffer, count: original.count) } + final class func create(bytes: RawSpan) -> Backing { + let backing = create(capacity: bytes.byteCount) { output in + output.append(contentsOf: bytes) + } + precondition(backing.count <= backing.allocatedCapacity) + return backing + } + final class func create(bytes: D) -> Backing { return bytes.withUnsafeBytes { bytesPtr in - let backing = Backing.create(capacity: bytesPtr.count) - backing._withVeryUnsafeMutableBytes { targetPtr in - targetPtr.copyMemory(from: bytesPtr) - } - backing.count = bytesPtr.count - precondition(backing.count <= backing.capacity) - return backing + create(bytes: bytesPtr.bytes) } } @@ -412,7 +520,8 @@ extension SecureBytes { deinit { // We always clear the whole capacity, even if we don't think we used it all. - memset_s(storage.baseAddress, storage.count, 0, storage.count) + memset_s(storage.baseAddress!, storage.count, 0, storage.count) + storage.deallocate() } subscript(offset offset: Int) -> UInt8 { @@ -429,7 +538,6 @@ extension SecureBytes { #endif } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SecureBytes.Backing { var allocatedCapacity: Int { #if os(OpenBSD) @@ -481,23 +589,24 @@ extension SecureBytes.Backing { self.count += byteCount } + /// Appends the bytes of a collection to this storage, crashing if there is not enough room. + fileprivate func _appendBytes(_ bytes: RawSpan) { + let byteCount = bytes.byteCount + + precondition(self.allocatedCapacity - self.count - byteCount >= 0, "Insufficient space for byte copying, must have reallocated!") + + let lowerOffset = self.count + self._withVeryUnsafeMutableBytes { bytesPtr in + let innerPtrSlice = UnsafeMutableRawBufferPointer(rebasing: bytesPtr[lowerOffset...]) + innerPtrSlice.copyBytes(from: bytes) + } + self.count += byteCount + } + /// Appends the bytes of a slice of another backing buffer to this storage, crashing if there /// is not enough room. fileprivate func _appendBytes(_ backing: SecureBytes.Backing, inRange range: Range) { - precondition(range.lowerBound >= 0) - precondition(range.upperBound <= backing.allocatedCapacity) - precondition(self.allocatedCapacity - self.count - range.count >= 0, "Insufficient space for byte copying, must have reallocated!") - - backing.withUnsafeBytes { backingPtr in - let ptrSlice = UnsafeRawBufferPointer(rebasing: backingPtr[range]) - - let lowerOffset = self.count - self._withVeryUnsafeMutableBytes { bytesPtr in - let innerPtrSlice = UnsafeMutableRawBufferPointer(rebasing: bytesPtr[lowerOffset...]) - innerPtrSlice.copyMemory(from: ptrSlice) - } - self.count += ptrSlice.count - } + self._appendBytes(backing.bytes.extracting(range)) } /// Moves the range of bytes identified by the slice by the delta, crashing if the move would @@ -533,38 +642,32 @@ extension SecureBytes.Backing { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension SecureBytes.Backing: ContiguousBytes { -#if hasFeature(Embedded) func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws(E) -> T) throws(E) -> T { let count = self.count + +#if hasFeature(Embedded) return try storage.withUnsafeBytes { elementsPtr throws(E) in return try body(UnsafeRawBufferPointer(start: elementsPtr.baseAddress, count: count)) } - } #else - func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> T) rethrows -> T { - let count = self.count - return try self.withUnsafeMutablePointerToElements { elementsPtr in + return try self.withUnsafeMutablePointerToElements { elementsPtr throws(E) in return try body(UnsafeRawBufferPointer(start: elementsPtr, count: count)) } - } #endif - - #if hasFeature(Embedded) + } func withUnsafeMutableBytes(_ body: (UnsafeMutableRawBufferPointer) throws(E) -> T) throws(E) -> T { - return try body(storage) - } - #else - func withUnsafeMutableBytes(_ body: (UnsafeMutableRawBufferPointer) throws -> T) rethrows -> T { +#if hasFeature(Embedded) + return try body(UnsafeMutableRawBufferPointer(rebasing: storage[..(_ body: (UnsafeMutableRawBufferPointer) throws -> T) rethrows -> T { + func _withVeryUnsafeMutableBytes(_ body: (UnsafeMutableRawBufferPointer) throws(E) -> T) throws(E) -> T { let capacity = self.allocatedCapacity - return try self.withUnsafeMutablePointerToElements { elementsPtr in + return try self.withUnsafeMutablePointerToElements { (elementsPtr) throws(E) in return try body(UnsafeMutableRawBufferPointer(start: elementsPtr, count: capacity)) } } @@ -600,7 +703,6 @@ extension SecureBytes.Backing: ContiguousBytes { #endif } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension UInt32 { /// Returns the next power of two unless that would overflow, in which case UInt32.max (on 64-bit systems) or /// Int32.max (on 32-bit systems) is returned. The returned value is always safe to be cast to Int and passed @@ -634,18 +736,11 @@ extension UInt32 { } } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension Data { /// A custom initializer for Data that attempts to share the same storage as the current SecureBytes instance. /// This is our best-effort attempt to expose the data in an auto-zeroing fashion. Any mutating function called on /// the constructed `Data` object will cause the bytes to be copied out: we can't avoid that. init(_ secureBytes: SecureBytes) { - #if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - self = secureBytes.withUnsafeBytes { - // We make a mutable copy of this pointer here because we know Data won't write through it. - return Data($0) - } - #else // We need to escape into unmanaged land here in order to keep the backing storage alive. let unmanagedBacking = Unmanaged.passRetained(secureBytes.backing) @@ -655,7 +750,6 @@ extension Data { // We make a mutable copy of this pointer here because we know Data won't write through it. return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0.baseAddress!), count: $0.count, deallocator: .custom { (_: UnsafeMutableRawPointer, _: Int) in unmanagedBacking.release() }) } - #endif } /// A custom initializer for Data that attempts to share the same storage as the current SecureBytes instance. @@ -668,15 +762,6 @@ extension Data { let baseOffset = secureByteSlice.startIndex.offset let endOffset = secureByteSlice.endIndex.offset - #if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION - self = base.withUnsafeBytes { - // Slice the base pointer down to just the range we want. - let slicedPointer = UnsafeRawBufferPointer(rebasing: $0[baseOffset..(cipher: BoringSSLAEAD, key: Key) throws { @@ -47,7 +50,7 @@ extension BoringSSLAEAD { let rc: CInt = key.withUnsafeBytes { keyPointer in withUnsafeMutablePointer(to: &self.context) { contextPointer in // Create the AEAD context with a default tag length using the given key. - CCryptoBoringSSLShims_EVP_AEAD_CTX_init( + CCryptoBoringSSL_EVP_AEAD_CTX_init( contextPointer, cipher.boringSSLCipher, keyPointer.baseAddress, @@ -84,9 +87,7 @@ extension BoringSSLAEAD.AEADContext { message: Plaintext, nonce: Nonce, authenticatedData: AuthenticatedData - ) throws -> ( - ciphertext: Data, tag: Data - ) { + ) throws -> Data { // Seal is a somewhat awkward function. As it returns a Data, we are going to need to initialize a Data large enough to write into. Data does not provide us an // initializer that gives us access to its uninitialized memory, so the cost of creating this Data is the cost of allocating the data + the cost of initializing // it. For smaller plaintexts this isn't too big a deal, but for larger ones the initialization cost can really get hairy. @@ -136,72 +137,107 @@ extension BoringSSLAEAD.AEADContext { message: Plaintext, nonce: Nonce, authenticatedData: AuthenticatedData - ) throws -> ( - ciphertext: Data, tag: Data - ) { + ) throws -> Data { try message.withUnsafeBytes { messagePointer in try nonce.withUnsafeBytes { noncePointer in try authenticatedData.withUnsafeBytes { authenticatedDataPointer in try self._sealContiguous( - plaintext: messagePointer, - noncePointer: noncePointer, - authenticatedData: authenticatedDataPointer + plaintext: messagePointer.bytes, + nonce: noncePointer.bytes, + authenticatedData: authenticatedDataPointer.bytes ) } } } } - /// The unsafe base call: not inlinable so that it can touch private variables. - @usableFromInline - func _sealContiguous( - plaintext: UnsafeRawBufferPointer, - noncePointer: UnsafeRawBufferPointer, - authenticatedData: UnsafeRawBufferPointer - ) throws -> (ciphertext: Data, tag: Data) { + /// Lowest level seal operation that calls into BoringSSL directly and + /// operates on already-allocated memory. + #if swift(<6.3) + @_lifetime(tag: copy tag) + #endif + public func seal( + message: inout MutableRawSpan, + nonce: RawSpan, + authenticatedData: RawSpan, + tag: inout OutputRawSpan + ) throws { let tagByteCount = CCryptoBoringSSL_EVP_AEAD_max_overhead(self.context.aead) - - // We use malloc here because we are going to call free later. We force unwrap to trigger crashes if the allocation - // fails. - let outputBuffer = UnsafeMutableRawBufferPointer( - start: malloc(plaintext.count)!, - count: plaintext.count - ) - let tagBuffer = UnsafeMutableRawBufferPointer(start: malloc(tagByteCount)!, count: tagByteCount) - var actualTagSize = tagBuffer.count + precondition(tag.freeCapacity >= tagByteCount) + var actualTagSize = tagByteCount let rc = withUnsafeMutablePointer(to: &self.context) { contextPointer in - CCryptoBoringSSLShims_EVP_AEAD_CTX_seal_scatter( - contextPointer, - outputBuffer.baseAddress, - tagBuffer.baseAddress, - &actualTagSize, - tagBuffer.count, - noncePointer.baseAddress, - noncePointer.count, - plaintext.baseAddress, - plaintext.count, - nil, - 0, - authenticatedData.baseAddress, - authenticatedData.count - ) + message.withUnsafeMutableBytes { messageBuffer in + tag.withUnsafeMutableBytes { tagBuffer, tagInitializedCount in + defer { + tagInitializedCount += actualTagSize + } + + return authenticatedData.withUnsafeBytes { authenticatedDataBuffer in + nonce.withUnsafeBytes { nonceBuffer in + CCryptoBoringSSL_EVP_AEAD_CTX_seal_scatter( + contextPointer, + messageBuffer.baseAddress, + tagBuffer.baseAddress! + tagInitializedCount, + &actualTagSize, + tagBuffer.count - tagInitializedCount, + nonceBuffer.baseAddress, + nonceBuffer.count, + messageBuffer.baseAddress, + messageBuffer.count, + nil, + 0, + authenticatedDataBuffer.baseAddress, + authenticatedDataBuffer.count + ) + } + + } + } + } } guard rc == 1 else { - // Ooops, error. Free the memory we allocated before we throw. - free(outputBuffer.baseAddress) - free(tagBuffer.baseAddress) throw CryptoBoringWrapperError.internalBoringSSLError() } + } - let output = Data( - bytesNoCopy: outputBuffer.baseAddress!, - count: outputBuffer.count, - deallocator: .free - ) - let tag = Data(bytesNoCopy: tagBuffer.baseAddress!, count: actualTagSize, deallocator: .free) - return (ciphertext: output, tag: tag) + /// The unsafe base call: not inlinable so that it can touch private variables. + @usableFromInline + func _sealContiguous( + plaintext: RawSpan, + nonce: RawSpan, + authenticatedData: RawSpan + ) throws -> Data { + let tagByteCount = CCryptoBoringSSL_EVP_AEAD_max_overhead(self.context.aead) + + // Form the combined represention of a sealed box with nonce + plaintext + tag. + var combined = Data() + combined.reserveCapacity(nonce.byteCount + plaintext.byteCount + tagByteCount) + combined.append(contentsOf: nonce) + combined.append(contentsOf: plaintext) + combined.append(Data(count: tagByteCount)) + + try combined.withUnsafeMutableBytes { (combinedBuffer: UnsafeMutableRawBufferPointer) in + let messageRange = nonce.byteCount..<(nonce.byteCount + plaintext.byteCount) + let messageBuffer = UnsafeMutableRawBufferPointer(rebasing: combinedBuffer[messageRange]) + var messageSpan = messageBuffer.mutableBytes + + let tagBuffer = UnsafeMutableRawBufferPointer( + rebasing: combinedBuffer[(nonce.byteCount + plaintext.byteCount)...] + ) + var tagSpan = OutputRawSpan(buffer: tagBuffer, initializedCount: 0) + try seal( + message: &messageSpan, + nonce: nonce, + authenticatedData: authenticatedData, + tag: &tagSpan + ) + let tagBytesWritten = tagSpan.finalize(for: tagBuffer) + assert(tagBytesWritten == tagByteCount) + } + + return combined } } @@ -255,10 +291,10 @@ extension BoringSSLAEAD.AEADContext { try tag.withUnsafeBytes { tagBytes in try authenticatedData.withUnsafeBytes { authenticatedDataBytes in try self._openContiguous( - ciphertext: ciphertextPointer, - nonceBytes: nonceBytes, - tagBytes: tagBytes, - authenticatedData: authenticatedDataBytes + ciphertext: ciphertextPointer.bytes, + nonceBytes: nonceBytes.bytes, + tagBytes: tagBytes.bytes, + authenticatedData: authenticatedDataBytes.bytes ) } } @@ -266,47 +302,63 @@ extension BoringSSLAEAD.AEADContext { } } - /// The unsafe base call: not inlinable so that it can touch private variables. - @usableFromInline - func _openContiguous( - ciphertext: UnsafeRawBufferPointer, - nonceBytes: UnsafeRawBufferPointer, - tagBytes: UnsafeRawBufferPointer, - authenticatedData: UnsafeRawBufferPointer - ) throws -> Data { - // We use malloc here because we are going to call free later. We force unwrap to trigger crashes if the allocation - // fails. - let outputBuffer = UnsafeMutableRawBufferPointer( - start: malloc(ciphertext.count)!, - count: ciphertext.count - ) - + /// Lowest level call into BoringSSL that decrypts in place. + #if swift(<6.3) + @_lifetime(message: copy message) + #endif + public func open( + message: inout MutableRawSpan, + nonce: RawSpan, + tag: RawSpan, + authenticatedData: RawSpan + ) throws { let rc = withUnsafePointer(to: &self.context) { contextPointer in - CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather( - contextPointer, - outputBuffer.baseAddress, - nonceBytes.baseAddress, - nonceBytes.count, - ciphertext.baseAddress, - ciphertext.count, - tagBytes.baseAddress, - tagBytes.count, - authenticatedData.baseAddress, - authenticatedData.count - ) + message.withUnsafeMutableBytes { messageBuffer in + nonce.withUnsafeBytes { nonceBuffer in + tag.withUnsafeBytes { tagBuffer in + authenticatedData.withUnsafeBytes { adBuffer in + CCryptoBoringSSL_EVP_AEAD_CTX_open_gather( + contextPointer, + messageBuffer.baseAddress, + nonceBuffer.baseAddress, + nonceBuffer.count, + messageBuffer.baseAddress, + messageBuffer.count, + tagBuffer.baseAddress, + tagBuffer.count, + adBuffer.baseAddress, + adBuffer.count + ) + } + } + } + } } guard rc == 1 else { - // Ooops, error. Free the memory we allocated before we throw. - free(outputBuffer.baseAddress) throw CryptoBoringWrapperError.internalBoringSSLError() } + } - let output = Data( - bytesNoCopy: outputBuffer.baseAddress!, - count: outputBuffer.count, - deallocator: .free - ) + /// The unsafe base call: not inlinable so that it can touch private variables. + @usableFromInline + func _openContiguous( + ciphertext: RawSpan, + nonceBytes: RawSpan, + tagBytes: RawSpan, + authenticatedData: RawSpan + ) throws -> Data { + var output = Data(copying: ciphertext) + if #available(visionOS 1.1, *) { + var outputSpan = output.mutableBytes + try open(message: &outputSpan, nonce: nonceBytes, tag: tagBytes, authenticatedData: authenticatedData) + } else { + // For some reason `Data.mutableBytes` is not available on visionOS 1.0 so we'll bounce through wUSMB. + try output.withUnsafeMutableBytes { bytes in + var outputSpan = bytes.mutableBytes + try open(message: &outputSpan, nonce: nonceBytes, tag: tagBytes, authenticatedData: authenticatedData) + } + } return output } @@ -376,7 +428,7 @@ extension BoringSSLAEAD.AEADContext { var writtenBytes = 0 let rc = withUnsafePointer(to: &self.context) { contextPointer in - CCryptoBoringSSLShims_EVP_AEAD_CTX_open( + CCryptoBoringSSL_EVP_AEAD_CTX_open( contextPointer, outputBuffer.baseAddress, &writtenBytes, diff --git a/Sources/CryptoBoringWrapper/CMakeLists.txt b/Sources/CryptoBoringWrapper/CMakeLists.txt index 980f33c4..bd9b9129 100644 --- a/Sources/CryptoBoringWrapper/CMakeLists.txt +++ b/Sources/CryptoBoringWrapper/CMakeLists.txt @@ -18,18 +18,17 @@ add_library(CryptoBoringWrapper STATIC "EC/EllipticCurve.swift" "EC/EllipticCurvePoint.swift" "Util/ArbitraryPrecisionInteger.swift" + "Util/Data+Span.swift" "Util/FiniteFieldArithmeticContext.swift" "Util/RandomBytes.swift" ) target_include_directories(CryptoBoringWrapper PUBLIC - $ - $) + $) target_link_libraries(CryptoBoringWrapper PUBLIC $<$>:Foundation> - CCryptoBoringSSL - CCryptoBoringSSLShims) + CCryptoBoringSSL) target_compile_options(CryptoBoringWrapper PRIVATE ${SWIFT_CRYPTO_COMPILE_OPTIONS}) diff --git a/Sources/CryptoBoringWrapper/CryptoKitErrors_boring.swift b/Sources/CryptoBoringWrapper/CryptoKitErrors_boring.swift index bc3a5c25..7de92e25 100644 --- a/Sources/CryptoBoringWrapper/CryptoKitErrors_boring.swift +++ b/Sources/CryptoBoringWrapper/CryptoKitErrors_boring.swift @@ -12,7 +12,11 @@ // //===----------------------------------------------------------------------===// +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL +#endif @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) public enum CryptoBoringWrapperError: Error { diff --git a/Sources/CryptoBoringWrapper/EC/EllipticCurve.swift b/Sources/CryptoBoringWrapper/EC/EllipticCurve.swift index c333ecbd..01614506 100644 --- a/Sources/CryptoBoringWrapper/EC/EllipticCurve.swift +++ b/Sources/CryptoBoringWrapper/EC/EllipticCurve.swift @@ -11,7 +11,11 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL +#endif /// A wrapper around BoringSSL's EC_GROUP object that handles reference counting and /// liveness. diff --git a/Sources/CryptoBoringWrapper/EC/EllipticCurvePoint.swift b/Sources/CryptoBoringWrapper/EC/EllipticCurvePoint.swift index dc593879..98fbea01 100644 --- a/Sources/CryptoBoringWrapper/EC/EllipticCurvePoint.swift +++ b/Sources/CryptoBoringWrapper/EC/EllipticCurvePoint.swift @@ -11,8 +11,11 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL -@_implementationOnly import CCryptoBoringSSLShims +#endif #if canImport(FoundationEssentials) import protocol FoundationEssentials.ContiguousBytes @@ -489,29 +492,35 @@ extension EllipticCurvePoint { to group: BoringSSLEllipticCurveGroup, domainSeparationTag: DSTBytes ) throws { - let hashToCurveFunction = - switch group.curveName { - case .p256: CCryptoBoringSSLShims_EC_hash_to_curve_p256_xmd_sha256_sswu - case .p384: CCryptoBoringSSLShims_EC_hash_to_curve_p384_xmd_sha384_sswu - // BoringSSL has no P521 hash_to_curve API. - case .p521: throw CryptoBoringWrapperError.invalidParameter - case .none: throw CryptoBoringWrapperError.internalBoringSSLError() - } - try self.init(_pointAtInfinityOn: group) try msg.withUnsafeBytes { msgPtr in try group.withUnsafeGroupPointer { groupPtr in try domainSeparationTag.withUnsafeBytes { dstPtr in - guard - hashToCurveFunction( + let rc: CInt + switch group.curveName { + case .p256: + rc = CCryptoBoringSSL_EC_hash_to_curve_p256_xmd_sha256_sswu( groupPtr, self._basePoint, dstPtr.baseAddress, dstPtr.count, msgPtr.baseAddress, msgPtr.count - ) == 1 - else { throw CryptoBoringWrapperError.internalBoringSSLError() } + ) + case .p384: + rc = CCryptoBoringSSL_EC_hash_to_curve_p384_xmd_sha384_sswu( + groupPtr, + self._basePoint, + dstPtr.baseAddress, + dstPtr.count, + msgPtr.baseAddress, + msgPtr.count + ) + // BoringSSL has no P521 hash_to_curve API. + case .p521: throw CryptoBoringWrapperError.invalidParameter + case .none: throw CryptoBoringWrapperError.internalBoringSSLError() + } + guard rc == 1 else { throw CryptoBoringWrapperError.internalBoringSSLError() } } } } @@ -598,7 +607,7 @@ extension EllipticCurvePoint { let numBytesWritten = group.withUnsafeGroupPointer { groupPtr in buf.withUnsafeMutableBytes { bufPtr in - CCryptoBoringSSLShims_EC_POINT_point2oct( + CCryptoBoringSSL_EC_POINT_point2oct( groupPtr, self._basePoint, compressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED, diff --git a/Sources/CryptoBoringWrapper/Util/ArbitraryPrecisionInteger.swift b/Sources/CryptoBoringWrapper/Util/ArbitraryPrecisionInteger.swift index aaa2fd21..cf8673d4 100644 --- a/Sources/CryptoBoringWrapper/Util/ArbitraryPrecisionInteger.swift +++ b/Sources/CryptoBoringWrapper/Util/ArbitraryPrecisionInteger.swift @@ -11,11 +11,13 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@_exported import CryptoKit + +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL #else @_implementationOnly import CCryptoBoringSSL -@_implementationOnly import CCryptoBoringSSLShims +#endif + #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -119,7 +121,7 @@ extension ArbitraryPrecisionInteger.BackingStorage { self.init() let rc: UnsafeMutablePointer? = bytes.withUnsafeBytes { bytesPointer in - CCryptoBoringSSLShims_BN_bin2bn( + CCryptoBoringSSL_BN_bin2bn( bytesPointer.baseAddress, bytesPointer.count, &self._backing @@ -455,7 +457,8 @@ extension ArbitraryPrecisionInteger { if nonNegative { CCryptoBoringSSL_BN_nnmod(resultPtr, selfPtr, modPtr, bnCtx) } else { - CCryptoBoringSSLShims_BN_mod(resultPtr, selfPtr, modPtr, bnCtx) + // BN_mod is a C macro for BN_div with a nil quotient; call that directly. + CCryptoBoringSSL_BN_div(nil, resultPtr, selfPtr, modPtr, bnCtx) } } } @@ -714,7 +717,7 @@ extension Data { assert(bytesPtr.count == byteCount) return integer.withUnsafeBignumPointer { bnPtr in - CCryptoBoringSSLShims_BN_bn2bin(bnPtr, bytesPtr.baseAddress!) + CCryptoBoringSSL_BN_bn2bin(bnPtr, bytesPtr.baseAddress!) } } @@ -771,4 +774,3 @@ extension ArbitraryPrecisionInteger: CustomDebugStringConvertible { ) } } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API diff --git a/Sources/CryptoBoringWrapper/Util/Data+Span.swift b/Sources/CryptoBoringWrapper/Util/Data+Span.swift new file mode 100644 index 00000000..dac7249c --- /dev/null +++ b/Sources/CryptoBoringWrapper/Util/Data+Span.swift @@ -0,0 +1,45 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#if canImport(FoundationEssentials) +import FoundationEssentials +#else +import Foundation +#endif +extension Data { + /// Copy the raw bytes from the given span into a new Data instance. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + init(copying bytes: RawSpan) { + if bytes.byteCount == 0 { + self = Data() + } else { + self = bytes.withUnsafeBytes { buffer in + Data( + UnsafeBufferPointer( + start: buffer.baseAddress!.assumingMemoryBound(to: UInt8.self), + count: buffer.count + ) + ) + } + } + } + + /// Append the contents of the given span to this Data instance. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + mutating func append(contentsOf bytes: RawSpan) { + bytes.withUnsafeBytes { buffer in + self.append(contentsOf: buffer) + } + } +} diff --git a/Sources/CryptoBoringWrapper/Util/FiniteFieldArithmeticContext.swift b/Sources/CryptoBoringWrapper/Util/FiniteFieldArithmeticContext.swift index 82593238..d6cb7e9e 100644 --- a/Sources/CryptoBoringWrapper/Util/FiniteFieldArithmeticContext.swift +++ b/Sources/CryptoBoringWrapper/Util/FiniteFieldArithmeticContext.swift @@ -11,10 +11,13 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@_exported import CryptoKit + +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL #else @_implementationOnly import CCryptoBoringSSL +#endif + #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -34,7 +37,7 @@ import Foundation /// ourselves. @usableFromInline @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -package class FiniteFieldArithmeticContext: @unchecked Sendable { +package final class FiniteFieldArithmeticContext: @unchecked Sendable { private let fieldSize: ArbitraryPrecisionInteger package let bnCtx: OpaquePointer @@ -315,4 +318,3 @@ extension FiniteFieldArithmeticContext { } } } -#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API diff --git a/Sources/CryptoBoringWrapper/Util/RandomBytes.swift b/Sources/CryptoBoringWrapper/Util/RandomBytes.swift index c902b6a3..516e316d 100644 --- a/Sources/CryptoBoringWrapper/Util/RandomBytes.swift +++ b/Sources/CryptoBoringWrapper/Util/RandomBytes.swift @@ -45,6 +45,20 @@ extension UnsafeMutableRawBufferPointer { } } +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +extension OutputRawSpan { + #if swift(<6.3) + @_lifetime(self: copy self) + #endif + package mutating func appendingRandomBytes(count: Int) { + self.withUnsafeMutableBytes { buffer, initializedCount in + UnsafeMutableRawBufferPointer(rebasing: buffer[initializedCount.. (ciphertext: Data, tag: Data) { + ) throws -> Data { do { let context = try AEADContext(cipher: self, key: key) return try context.seal(message: message, nonce: nonce, authenticatedData: authenticatedData) @@ -75,17 +79,16 @@ enum OpenSSLAESGCMSIVImpl { let aead = try Self._backingAEAD(key: key) - let ciphertext: Data - let tag: Data + let combined: Data if let ad = authenticatedData { - (ciphertext, tag) = try aead.seal( + combined = try aead.seal( message: message, key: key, nonce: nonce, authenticatedData: ad ) } else { - (ciphertext, tag) = try aead.seal( + combined = try aead.seal( message: message, key: key, nonce: nonce, @@ -93,7 +96,7 @@ enum OpenSSLAESGCMSIVImpl { ) } - return try AES.GCM._SIV.SealedBox(nonce: nonce, ciphertext: ciphertext, tag: tag) + return AES.GCM._SIV.SealedBox(combined: combined, nonceByteCount: nonce.bytes.count) } @inlinable diff --git a/Sources/CryptoExtras/AES/CMAC.swift b/Sources/CryptoExtras/AES/CMAC.swift index c9629334..a5a4b201 100644 --- a/Sources/CryptoExtras/AES/CMAC.swift +++ b/Sources/CryptoExtras/AES/CMAC.swift @@ -11,9 +11,15 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -@_implementationOnly import CCryptoBoringSSL + import Crypto +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else +@_implementationOnly import CCryptoBoringSSL +#endif + #if canImport(FoundationEssentials) import FoundationEssentials #else diff --git a/Sources/CryptoExtras/CMakeLists.txt b/Sources/CryptoExtras/CMakeLists.txt index 9ae79fe0..1b4fdb93 100644 --- a/Sources/CryptoExtras/CMakeLists.txt +++ b/Sources/CryptoExtras/CMakeLists.txt @@ -86,20 +86,14 @@ add_library(CryptoExtras target_compile_options(CryptoExtras PRIVATE -DCRYPTO_IN_SWIFTPM) -if(NOT CMAKE_SYSTEM_NAME STREQUAL "Darwin") - target_compile_options(CryptoExtras PRIVATE -DCRYPTO_IN_SWIFTPM_FORCE_BUILD_API) -endif() - target_include_directories(CryptoExtras PRIVATE - $ - $) + $) target_link_libraries(CryptoExtras PUBLIC $<$>:Foundation> Crypto CryptoBoringWrapper - CCryptoBoringSSL - CCryptoBoringSSLShims) + CCryptoBoringSSL) target_compile_options(CryptoExtras PRIVATE ${SWIFT_CRYPTO_COMPILE_OPTIONS}) diff --git a/Sources/CryptoExtras/ChaCha20CTR/BoringSSL/ChaCha20CTR_boring.swift b/Sources/CryptoExtras/ChaCha20CTR/BoringSSL/ChaCha20CTR_boring.swift index 701bf8d8..fa96b54c 100644 --- a/Sources/CryptoExtras/ChaCha20CTR/BoringSSL/ChaCha20CTR_boring.swift +++ b/Sources/CryptoExtras/ChaCha20CTR/BoringSSL/ChaCha20CTR_boring.swift @@ -12,11 +12,15 @@ // //===----------------------------------------------------------------------===// -@_implementationOnly import CCryptoBoringSSL -@_implementationOnly import CCryptoBoringSSLShims import Crypto import CryptoBoringWrapper +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else +@_implementationOnly import CCryptoBoringSSL +#endif + #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -66,22 +70,15 @@ enum OpenSSLChaCha20CTRImpl { key.withUnsafeBytes { keyPtr in nonce.withUnsafeBytes { noncePtr in message.withUnsafeBytes { plaintextPtr in - // We bind all three pointers here. These binds are not technically safe, but because we - // know the pointers don't persist they can't violate the aliasing rules. We really - // want a "with memory rebound" function but we don't have it yet. - let keyBytes = keyPtr.bindMemory(to: UInt8.self) - let nonceBytes = noncePtr.bindMemory(to: UInt8.self) - let plaintext = plaintextPtr.bindMemory(to: UInt8.self) - - var ciphertext = Data(repeating: 0, count: plaintext.count) + var ciphertext = Data(repeating: 0, count: plaintextPtr.count) ciphertext.withUnsafeMutableBytes { ciphertext in CCryptoBoringSSL_CRYPTO_chacha_20( ciphertext.baseAddress, - plaintext.baseAddress, - plaintext.count, - keyBytes.baseAddress, - nonceBytes.baseAddress, + plaintextPtr.baseAddress, + plaintextPtr.count, + keyPtr.baseAddress, + noncePtr.baseAddress, counter ) } diff --git a/Sources/CryptoExtras/ChaCha20CTR/ChaCha20CTR.swift b/Sources/CryptoExtras/ChaCha20CTR/ChaCha20CTR.swift index 385fa6e6..4551189b 100644 --- a/Sources/CryptoExtras/ChaCha20CTR/ChaCha20CTR.swift +++ b/Sources/CryptoExtras/ChaCha20CTR/ChaCha20CTR.swift @@ -12,8 +12,11 @@ // //===----------------------------------------------------------------------===// +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL -@_implementationOnly import CCryptoBoringSSLShims +#endif import Crypto import CryptoBoringWrapper #if canImport(FoundationEssentials) diff --git a/Sources/CryptoExtras/Digests/BoringSSL/BoringSSLSHA512256Context.swift b/Sources/CryptoExtras/Digests/BoringSSL/BoringSSLSHA512256Context.swift index c091bc3f..8fe33e1c 100644 --- a/Sources/CryptoExtras/Digests/BoringSSL/BoringSSLSHA512256Context.swift +++ b/Sources/CryptoExtras/Digests/BoringSSL/BoringSSLSHA512256Context.swift @@ -12,9 +12,14 @@ // //===----------------------------------------------------------------------===// -@_implementationOnly import CCryptoBoringSSL import Crypto +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else +@_implementationOnly import CCryptoBoringSSL +#endif + #if canImport(Darwin) import Darwin #endif diff --git a/Sources/CryptoExtras/Digests/BoringSSL/BoringSSLSHA512256HashFunction.swift b/Sources/CryptoExtras/Digests/BoringSSL/BoringSSLSHA512256HashFunction.swift index d97a2369..5b7151fb 100644 --- a/Sources/CryptoExtras/Digests/BoringSSL/BoringSSLSHA512256HashFunction.swift +++ b/Sources/CryptoExtras/Digests/BoringSSL/BoringSSLSHA512256HashFunction.swift @@ -12,9 +12,10 @@ // //===----------------------------------------------------------------------===// -@_implementationOnly import CCryptoBoringSSL import Crypto +@_implementationOnly import CCryptoBoringSSL + struct BoringSSLSHA512256HashFunction { static var digestSize: Int { Int(SHA256_DIGEST_LENGTH) diff --git a/Sources/CryptoExtras/ECToolbox/ECToolbox.swift b/Sources/CryptoExtras/ECToolbox/ECToolbox.swift index a1eb80e9..b6c9ddda 100644 --- a/Sources/CryptoExtras/ECToolbox/ECToolbox.swift +++ b/Sources/CryptoExtras/ECToolbox/ECToolbox.swift @@ -18,21 +18,12 @@ import FoundationEssentials import Foundation #endif -#if canImport(Darwin) && !CRYPTO_IN_SWIFTPM -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -typealias SupportedCurveDetailsImpl = CorecryptoSupportedNISTCurve -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -typealias GroupImpl = CoreCryptoGroup -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) -typealias HashToCurveImpl = CoreCryptoHashToCurve -#else @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) typealias SupportedCurveDetailsImpl = OpenSSLSupportedNISTCurve @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) typealias GroupImpl = OpenSSLGroup @available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, macCatalyst 13.2, visionOS 1.2, *) typealias HashToCurveImpl = OpenSSLHashToCurve -#endif /// A prime-order group @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) diff --git a/Sources/CryptoExtras/Key Derivation/PBKDF2/BoringSSL/PBKDF2_boring.swift b/Sources/CryptoExtras/Key Derivation/PBKDF2/BoringSSL/PBKDF2_boring.swift index 6bfbad71..2fce41a0 100644 --- a/Sources/CryptoExtras/Key Derivation/PBKDF2/BoringSSL/PBKDF2_boring.swift +++ b/Sources/CryptoExtras/Key Derivation/PBKDF2/BoringSSL/PBKDF2_boring.swift @@ -20,8 +20,11 @@ import Foundation #endif #if !canImport(CommonCrypto) +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL -@_implementationOnly import CCryptoBoringSSLShims +#endif @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) internal struct BoringSSLPBKDF2 { diff --git a/Sources/CryptoExtras/Key Derivation/Scrypt/BoringSSL/Scrypt_boring.swift b/Sources/CryptoExtras/Key Derivation/Scrypt/BoringSSL/Scrypt_boring.swift index b89c9bd1..ce7cbca0 100644 --- a/Sources/CryptoExtras/Key Derivation/Scrypt/BoringSSL/Scrypt_boring.swift +++ b/Sources/CryptoExtras/Key Derivation/Scrypt/BoringSSL/Scrypt_boring.swift @@ -12,10 +12,14 @@ // //===----------------------------------------------------------------------===// -@_implementationOnly import CCryptoBoringSSL -@_implementationOnly import CCryptoBoringSSLShims import Crypto +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else +@_implementationOnly import CCryptoBoringSSL +#endif + #if canImport(FoundationEssentials) #if os(Windows) import ucrt diff --git a/Sources/CryptoExtras/RSA/RSA_boring.swift b/Sources/CryptoExtras/RSA/RSA_boring.swift index 839e2b60..247ef548 100644 --- a/Sources/CryptoExtras/RSA/RSA_boring.swift +++ b/Sources/CryptoExtras/RSA/RSA_boring.swift @@ -12,12 +12,16 @@ // //===----------------------------------------------------------------------===// -// NOTE: This file is unconditionally compiled because RSABSSA is implemented using BoringSSL on all platforms. -@_implementationOnly import CCryptoBoringSSL -@_implementationOnly import CCryptoBoringSSLShims import Crypto 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 +#else +@_implementationOnly import CCryptoBoringSSL +#endif + #if canImport(FoundationEssentials) #if os(Windows) import ucrt @@ -369,7 +373,7 @@ extension BoringSSLRSAPublicKey { let rc: CInt = digest.withUnsafeBytes { digestPtr in switch padding.backing { case .pkcs1v1_5: - return CCryptoBoringSSLShims_RSA_verify( + return CCryptoBoringSSL_RSA_verify( hashDigestType.nid, digestPtr.baseAddress, digestPtr.count, @@ -378,7 +382,7 @@ extension BoringSSLRSAPublicKey { rsaPublicKey ) case .pss: - return CCryptoBoringSSLShims_RSA_verify_pss_mgf1( + return CCryptoBoringSSL_RSA_verify_pss_mgf1( rsaPublicKey, digestPtr.baseAddress, digestPtr.count, @@ -389,7 +393,7 @@ extension BoringSSLRSAPublicKey { signaturePtr.count ) case .pssZero: - return CCryptoBoringSSLShims_RSA_verify_pss_mgf1( + return CCryptoBoringSSL_RSA_verify_pss_mgf1( rsaPublicKey, digestPtr.baseAddress, digestPtr.count, @@ -441,7 +445,7 @@ extension BoringSSLRSAPublicKey { } var writtenLength = bufferPtr.count - let rc = CCryptoBoringSSLShims_EVP_PKEY_encrypt( + let rc = CCryptoBoringSSL_EVP_PKEY_encrypt( ctx, bufferPtr.baseAddress, &writtenLength, @@ -854,10 +858,10 @@ extension BoringSSLRSAPrivateKey { switch padding.backing { case .pkcs1v1_5: var writtenLength = CUnsignedInt(0) - let rc = CCryptoBoringSSLShims_RSA_sign( + let rc = CCryptoBoringSSL_RSA_sign( hashDigestType.nid, digestPtr.baseAddress, - CUnsignedInt(digestPtr.count), + digestPtr.count, bufferPtr.baseAddress, &writtenLength, rsaPrivateKey @@ -865,7 +869,7 @@ extension BoringSSLRSAPrivateKey { outputLength = Int(writtenLength) return rc case .pss: - return CCryptoBoringSSLShims_RSA_sign_pss_mgf1( + return CCryptoBoringSSL_RSA_sign_pss_mgf1( rsaPrivateKey, &outputLength, bufferPtr.baseAddress, @@ -877,7 +881,7 @@ extension BoringSSLRSAPrivateKey { CInt(hashDigestType.digestLength) ) case .pssZero: - return CCryptoBoringSSLShims_RSA_sign_pss_mgf1( + return CCryptoBoringSSL_RSA_sign_pss_mgf1( rsaPrivateKey, &outputLength, bufferPtr.baseAddress, @@ -934,7 +938,7 @@ extension BoringSSLRSAPrivateKey { var writtenLength = bufferPtr.count - let rc = CCryptoBoringSSLShims_EVP_PKEY_decrypt( + let rc = CCryptoBoringSSL_EVP_PKEY_decrypt( ctx, bufferPtr.baseAddress, &writtenLength, diff --git a/Sources/CryptoExtras/Util/BoringSSL/Zeroization_boring.swift b/Sources/CryptoExtras/Util/BoringSSL/Zeroization_boring.swift index 1991f2f6..3a268aa2 100644 --- a/Sources/CryptoExtras/Util/BoringSSL/Zeroization_boring.swift +++ b/Sources/CryptoExtras/Util/BoringSSL/Zeroization_boring.swift @@ -12,7 +12,11 @@ // //===----------------------------------------------------------------------===// #if !canImport(Darwin) +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else @_implementationOnly import CCryptoBoringSSL +#endif @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) typealias errno_t = CInt diff --git a/Sources/CryptoExtras/Util/BoringSSLHelpers.swift b/Sources/CryptoExtras/Util/BoringSSLHelpers.swift index b560330c..ddab8c82 100644 --- a/Sources/CryptoExtras/Util/BoringSSLHelpers.swift +++ b/Sources/CryptoExtras/Util/BoringSSLHelpers.swift @@ -13,8 +13,11 @@ //===----------------------------------------------------------------------===// // 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 +#else @_implementationOnly import CCryptoBoringSSL -@_implementationOnly import CCryptoBoringSSLShims +#endif #if canImport(FoundationEssentials) import FoundationEssentials #else diff --git a/Sources/CryptoExtras/Util/CryptoKitErrors_boring.swift b/Sources/CryptoExtras/Util/CryptoKitErrors_boring.swift index 21d5da6f..cf3528dc 100644 --- a/Sources/CryptoExtras/Util/CryptoKitErrors_boring.swift +++ b/Sources/CryptoExtras/Util/CryptoKitErrors_boring.swift @@ -12,9 +12,14 @@ // //===----------------------------------------------------------------------===// -@_implementationOnly import CCryptoBoringSSL import Crypto +#if hasFeature(SourceWarningControl) +@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL +#else +@_implementationOnly import CCryptoBoringSSL +#endif + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension CryptoKitError { /// A helper function that packs the value of `ERR_get_error` into the internal error field. diff --git a/Sources/CryptoExtras/Util/DigestType.swift b/Sources/CryptoExtras/Util/DigestType.swift index 469c5687..171caf47 100644 --- a/Sources/CryptoExtras/Util/DigestType.swift +++ b/Sources/CryptoExtras/Util/DigestType.swift @@ -13,7 +13,11 @@ //===----------------------------------------------------------------------===// // 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 +#else @_implementationOnly import CCryptoBoringSSL +#endif import Crypto @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) diff --git a/Sources/CryptoExtras/Util/ThreadSpecific/ThreadSpecific.swift b/Sources/CryptoExtras/Util/ThreadSpecific/ThreadSpecific.swift index 96eb7100..1cc21fc6 100644 --- a/Sources/CryptoExtras/Util/ThreadSpecific/ThreadSpecific.swift +++ b/Sources/CryptoExtras/Util/ThreadSpecific/ThreadSpecific.swift @@ -29,7 +29,7 @@ final class ThreadSpecificVariable { // the actual type in there is `Box<(ThreadSpecificVariable, T)>` but we can't use that as C functions can't capture (even types) private typealias BoxedType = Box<(AnyObject, AnyObject)> - private class Key { + private final class Key { private var underlyingKey: ThreadOpsSystem.ThreadSpecificKey internal init(destructor: @escaping ThreadOpsSystem.ThreadSpecificKeyDestructor) { diff --git a/Tests/CXKCPTests/CXKCPTests.swift b/Tests/CXKCPTests/CXKCPTests.swift index 652467ec..b9b1f432 100644 --- a/Tests/CXKCPTests/CXKCPTests.swift +++ b/Tests/CXKCPTests/CXKCPTests.swift @@ -24,7 +24,7 @@ final class CXKCPTests: XCTestCase { var output = [UInt8](repeating: 0, count: 32) let result = input.withUnsafeBytes { inputBytes in - SHA3_256(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count) + SHA3_256(&output, inputBytes.baseAddress, inputBytes.count) } // Should return 0 on success @@ -43,7 +43,7 @@ final class CXKCPTests: XCTestCase { var output = [UInt8](repeating: 0, count: 28) let result = input.withUnsafeBytes { inputBytes in - SHA3_224(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count) + SHA3_224(&output, inputBytes.baseAddress, inputBytes.count) } // Should return 0 on success @@ -62,7 +62,7 @@ final class CXKCPTests: XCTestCase { var output = [UInt8](repeating: 0, count: 48) let result = input.withUnsafeBytes { inputBytes in - SHA3_384(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count) + SHA3_384(&output, inputBytes.baseAddress, inputBytes.count) } // Should return 0 on success @@ -82,7 +82,7 @@ final class CXKCPTests: XCTestCase { var output = [UInt8](repeating: 0, count: 64) let result = input.withUnsafeBytes { inputBytes in - SHA3_512(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count) + SHA3_512(&output, inputBytes.baseAddress, inputBytes.count) } // Should return 0 on success @@ -102,7 +102,7 @@ final class CXKCPTests: XCTestCase { var output = [UInt8](repeating: 0, count: 32) // 256 bits output let result = input.withUnsafeBytes { inputBytes in - SHAKE128(&output, output.count, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count) + SHAKE128(&output, output.count, inputBytes.baseAddress, inputBytes.count) } // Should return 0 on success @@ -121,7 +121,7 @@ final class CXKCPTests: XCTestCase { var output = [UInt8](repeating: 0, count: 32) // 256 bits output let result = input.withUnsafeBytes { inputBytes in - SHAKE256(&output, output.count, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count) + SHAKE256(&output, output.count, inputBytes.baseAddress, inputBytes.count) } // Should return 0 on success diff --git a/Tests/CryptoExtrasTests/AES_CFBTests.swift b/Tests/CryptoExtrasTests/AES_CFBTests.swift index 207a4d33..1de46022 100644 --- a/Tests/CryptoExtrasTests/AES_CFBTests.swift +++ b/Tests/CryptoExtrasTests/AES_CFBTests.swift @@ -45,7 +45,7 @@ final class AES_CFBTests: XCTestCase { func testVector(_ vector: TestVector) throws { let (contiguousPlaintextData, discontiguousPlaintextData) = vector.plaintext.asDataProtocols() - for plaintextData in [contiguousPlaintextData as DataProtocol, discontiguousPlaintextData as DataProtocol] { + for plaintextData in [contiguousPlaintextData as (any DataProtocol), discontiguousPlaintextData as (any DataProtocol)] { let key = SymmetricKey(data: Data(vector.key)) let iv = try AES._CFB.IV(ivBytes: vector.iv) let ciphertext = try AES._CFB.encrypt(plaintextData, using: key, iv: iv) diff --git a/Tests/CryptoExtrasTests/Curve25519DERTests.swift b/Tests/CryptoExtrasTests/Curve25519DERTests.swift index 084a6c73..749292c3 100644 --- a/Tests/CryptoExtrasTests/Curve25519DERTests.swift +++ b/Tests/CryptoExtrasTests/Curve25519DERTests.swift @@ -15,6 +15,7 @@ import CryptoExtras import XCTest +@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *) final class Curve25519DERTests: XCTestCase { func testSigningPrivateKeyDERRoundTrip() throws { let privateKey = Curve25519.Signing.PrivateKey() diff --git a/Tests/CryptoExtrasTests/Curve25519PEMTests.swift b/Tests/CryptoExtrasTests/Curve25519PEMTests.swift index 02cf6d92..ec286cb9 100644 --- a/Tests/CryptoExtrasTests/Curve25519PEMTests.swift +++ b/Tests/CryptoExtrasTests/Curve25519PEMTests.swift @@ -15,6 +15,7 @@ import CryptoExtras import XCTest +@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *) final class Curve25519PEMTests: XCTestCase { func testSigningPrivateKeyPEMRoundTrip() throws { let privateKey = Curve25519.Signing.PrivateKey() diff --git a/Tests/CryptoExtrasTests/OPRFs/VOPRFAPITests.swift b/Tests/CryptoExtrasTests/OPRFs/VOPRFAPITests.swift index 9a34599b..be0e50c6 100644 --- a/Tests/CryptoExtrasTests/OPRFs/VOPRFAPITests.swift +++ b/Tests/CryptoExtrasTests/OPRFs/VOPRFAPITests.swift @@ -32,7 +32,7 @@ extension OPRFSuite { } } -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, visionOS 2.0, *) final class VOPRFAPITests: XCTestCase { func testVectors() throws { try testVectorsVOPRF(suite: .P384_SHA384_VORPF) diff --git a/Tests/CryptoExtrasTests/OPRFs/VOPRFPublicAPITests.swift b/Tests/CryptoExtrasTests/OPRFs/VOPRFPublicAPITests.swift index 0fae0be6..2a446541 100644 --- a/Tests/CryptoExtrasTests/OPRFs/VOPRFPublicAPITests.swift +++ b/Tests/CryptoExtrasTests/OPRFs/VOPRFPublicAPITests.swift @@ -15,7 +15,7 @@ import Crypto import CryptoExtras // NOTE: No @testable import, because we want to test the public API. import XCTest -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, visionOS 2.0, *) final class VOPRFPublicAPITests: XCTestCase { func testEndToEndVOPRF() throws { diff --git a/Tests/CryptoExtrasTests/PKCS8DERRepresentationTests.swift b/Tests/CryptoExtrasTests/PKCS8DERRepresentationTests.swift index 41bf3271..98743d9c 100644 --- a/Tests/CryptoExtrasTests/PKCS8DERRepresentationTests.swift +++ b/Tests/CryptoExtrasTests/PKCS8DERRepresentationTests.swift @@ -23,6 +23,7 @@ import FoundationEssentials import Foundation #endif +@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *) final class PKCS8DERRepresentationTests: XCTestCase { func test_RSA() { let rsaPrivateKeyPEM = """ diff --git a/Tests/CryptoTests/ASN1/ASN1Tests.swift b/Tests/CryptoTests/ASN1/ASN1Tests.swift index a2941a93..33272c4d 100644 --- a/Tests/CryptoTests/ASN1/ASN1Tests.swift +++ b/Tests/CryptoTests/ASN1/ASN1Tests.swift @@ -11,16 +11,13 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif class ASN1Tests: XCTestCase { func testSimpleASN1P256SPKI() throws { @@ -635,939 +632,6 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA== XCTAssertThrowsError(try ASN1.PKCS8PrivateKey(asn1Encoded: parsed), error: CryptoKitASN1Error.invalidASN1Object) } - func testSimplePEMP256SPKI() throws { - let pemPublicKey = """ ------BEGIN PUBLIC KEY----- -MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEb4nB0k8CBVnKCHVHkxuXAkSlZuO5 -Nsev1rzcRv5QHiJuWUKomFGadQlMSGwoDOHEDdW3ujcA6t0ADteHw6KrZg== ------END PUBLIC KEY----- -""" - - // Test the working public keys. - let signingKey = try orFail { try P256.Signing.PublicKey(pemRepresentation: pemPublicKey) } - let keyAgreementKey = try orFail { try P256.KeyAgreement.PublicKey(pemRepresentation: pemPublicKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching public keys. - XCTAssertThrowsError(try P384.Signing.PublicKey(pemRepresentation: pemPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(pemRepresentation: pemPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P521.Signing.PublicKey(pemRepresentation: pemPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(pemRepresentation: pemPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - - // Now the private keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.Signing.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.Signing.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - - // Validate we can reserialize. - let firstReserialization = signingKey.pemRepresentation - let secondReserialization = keyAgreementKey.pemRepresentation - XCTAssertEqual(firstReserialization, pemPublicKey) - XCTAssertEqual(secondReserialization, pemPublicKey) - } - - func testSimplePEMP384SPKI() throws { - let pemPublicKey = """ ------BEGIN PUBLIC KEY----- -MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEBwY0l7mq7hSBEZRld5ISWfSoFsYN3wwM -hdD3cMU95DmYXzbqVHB4dCfsy7bexm4h9c0zs4CyTPzy3DV3vfmv1akQJIQv7l08 -lx/YXNeGXTN4Gr9r4rwA5GvRl1p6plPL ------END PUBLIC KEY----- -""" - - // Test the working public keys. - let signingKey = try orFail { try P384.Signing.PublicKey(pemRepresentation: pemPublicKey) } - let keyAgreementKey = try orFail { try P384.KeyAgreement.PublicKey(pemRepresentation: pemPublicKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching public keys. - XCTAssertThrowsError(try P256.Signing.PublicKey(pemRepresentation: pemPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(pemRepresentation: pemPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P521.Signing.PublicKey(pemRepresentation: pemPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(pemRepresentation: pemPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - - // Now the private keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.Signing.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.Signing.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - - // Validate we can reserialize. - let firstReserialization = signingKey.pemRepresentation - let secondReserialization = keyAgreementKey.pemRepresentation - XCTAssertEqual(firstReserialization, pemPublicKey) - XCTAssertEqual(secondReserialization, pemPublicKey) - } - - func testSimplePEMP521SPKI() throws { - let pemPublicKey = """ ------BEGIN PUBLIC KEY----- -MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQAp3v1UQWvSyQnkAUEBu+x/7ZrPtNJ -SCUk9kMvuZMyGP1idwvspALuJjzrSFFlXObjlOjxucSbWhTYF/o3nc0XzpAA3dxA -BYiMqH9vrVePoJMpv+DMdkUiUJ/WqHSOu9bJEi1h4fdqh5HHx4QZJY/iX/59VAi1 -uSbAhALvbdGFbVpkcOs= ------END PUBLIC KEY----- -""" - - // Test the working public keys. - let signingKey = try orFail { try P521.Signing.PublicKey(pemRepresentation: pemPublicKey) } - let keyAgreementKey = try orFail { try P521.KeyAgreement.PublicKey(pemRepresentation: pemPublicKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching public keys. - XCTAssertThrowsError(try P256.Signing.PublicKey(pemRepresentation: pemPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(pemRepresentation: pemPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P384.Signing.PublicKey(pemRepresentation: pemPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(pemRepresentation: pemPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - - // Now the private keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.Signing.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.Signing.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(pemRepresentation: pemPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - - // Validate we can reserialize. - let firstReserialization = signingKey.pemRepresentation - let secondReserialization = keyAgreementKey.pemRepresentation - XCTAssertEqual(firstReserialization, pemPublicKey) - XCTAssertEqual(secondReserialization, pemPublicKey) - } - - func testSimplePEMP256PKCS8() throws { - let pemPrivateKey = """ ------BEGIN PRIVATE KEY----- -MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgZjQLlzempZx7YF1F -+MK1HWZTNgLcC1MAufb/2/YZYk6hRANCAAQwgn0PfkIHiZ/K+3zA//CoDqU2PqDc -aA3U5R68jmlZQITvMyBlMJl9Mjh0biIe88dAfRKeUm9FVMD2ErJ/006V ------END PRIVATE KEY----- -""" - - // Test the working private keys. - let signingKey = try orFail { try P256.Signing.PrivateKey(pemRepresentation: pemPrivateKey) } - let keyAgreementKey = try orFail { try P256.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching private keys. - XCTAssertThrowsError(try P384.Signing.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P521.Signing.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey)) - - // Now the public keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - - // Validate we can reserialize. - let firstReserialization = signingKey.pemRepresentation - let secondReserialization = keyAgreementKey.pemRepresentation - XCTAssertEqual(firstReserialization, pemPrivateKey) - XCTAssertEqual(secondReserialization, pemPrivateKey) - } - - func testSimplePEMP384PKCS8() throws { - let pemPrivateKey = """ ------BEGIN PRIVATE KEY----- -MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDB7ERKhMR+mvz1NQ+oL -i6ZJMACOcwbUetWcNnB4Mnx3j4XuhpkkHEW8E1+rXyjZ3UmhZANiAASYH+emlyXM -kBSFJl0BiopDVuIIR47M4pLl00YNnuu/Rp5VHeVAHrP67i2Q92u5fk34eOSwQvkO -VvktWsgtzAomIam4SHqE9bhvrHy6kW6QzxlERHTL+YkXEX8c6t8VOxk= ------END PRIVATE KEY----- -""" - - // Test the working private keys. - let signingKey = try orFail { try P384.Signing.PrivateKey(pemRepresentation: pemPrivateKey) } - let keyAgreementKey = try orFail { try P384.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching private keys. - XCTAssertThrowsError(try P256.Signing.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P521.Signing.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey)) - - // Now the public keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - - // Validate we can reserialize. - let firstReserialization = signingKey.pemRepresentation - let secondReserialization = keyAgreementKey.pemRepresentation - XCTAssertEqual(firstReserialization, pemPrivateKey) - XCTAssertEqual(secondReserialization, pemPrivateKey) - } - - func testSimplePEMP521PKCS8() throws { - let pemPrivateKey = """ ------BEGIN PRIVATE KEY----- -MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIAmMp6YYRfT6uA+DFi -VB/V7FGAgjjuin1GcF8eujBZTcNB8jyzyXfG7Ak80jd3yhrHhAg7rOOZYV72Ekz5 -o05NKM2hgYkDgYYABAEIOePr9DPc9lGHqSYrGHX0ICvZxy3DLTjPcl7jgAcUU9NT -1DBvJ7aAAmzTImz9mKOJk14f1fxc1BsWjsf1hU4QOwFu1l+dIDcNYFUxjzsGMc5e -LsSxRn35ts4qogmz3kmerOc0smI8NIFiK/EuinK5Bs8PfPMW3ZOCIpvXbqyksLk0 -rg== ------END PRIVATE KEY----- -""" - - // Test the working private keys. - let signingKey = try orFail { try P521.Signing.PrivateKey(pemRepresentation: pemPrivateKey) } - let keyAgreementKey = try orFail { try P521.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching private keys. - XCTAssertThrowsError(try P256.Signing.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P384.Signing.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey)) - - // Now the public keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - - // Validate we can reserialize. - let firstReserialization = signingKey.pemRepresentation - let secondReserialization = keyAgreementKey.pemRepresentation - XCTAssertEqual(firstReserialization, pemPrivateKey) - XCTAssertEqual(secondReserialization, pemPrivateKey) - } - - func testSimplePEMP256SEC1PrivateKey() throws { - let pemPrivateKey = """ ------BEGIN EC PRIVATE KEY----- -MHcCAQEEIHwS3r7tdBfDPSOaT/x6A2qvXFFXlGmnaYkxzrj1CQUHoAoGCCqGSM49 -AwEHoUQDQgAE79HvsMQC9IyhZ7yCCYKmgz9zewM4KziWoVMXKN+7Cd5Ds+jK8V5q -hD6YVbbo/v1udmM5DfhHJiUW3Ww5++suRg== ------END EC PRIVATE KEY----- -""" - - // Test the working private keys. - let signingKey = try orFail { try P256.Signing.PrivateKey(pemRepresentation: pemPrivateKey) } - let keyAgreementKey = try orFail { try P256.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching private keys. - XCTAssertThrowsError(try P384.Signing.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P521.Signing.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey)) - - // Now the public keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - - // We can't reserialize the SEC1 keys, we don't emit them. - } - - func testSimplePEMP384SEC1PrivateKey() throws { - let pemPrivateKey = """ ------BEGIN EC PRIVATE KEY----- -MIGkAgEBBDDrN+qjvW7TqcXrKlTFbSP8AdbsIdqvRAgWHlaBicP7dkx+HKQidSiS -B2RLWyjSrs6gBwYFK4EEACKhZANiAAQrRiaztGpInYo1XqMnNokWY6g1TcgMuzgq -Ug6LzFQbCAqCrcnM9+c9Z4/63dC06ulL/KbLQgThjSiqRzgbzvmOvB0OzlpX1weK -usFrF4Pi0B9pKPmVCAlSzaxVEmRsbmw= ------END EC PRIVATE KEY----- -""" - - // Test the working private keys. - let signingKey = try orFail { try P384.Signing.PrivateKey(pemRepresentation: pemPrivateKey) } - let keyAgreementKey = try orFail { try P384.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching private keys. - XCTAssertThrowsError(try P256.Signing.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P521.Signing.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey)) - - // Now the public keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - - // We can't reserialize the SEC1 keys, we don't emit them. - } - - func testSimplePEMP521SEC1PrivateKey() throws { - let pemPrivateKey = """ ------BEGIN EC PRIVATE KEY----- -MIHcAgEBBEIBf4tGkyicrFEadZv7iWnmCGsDk7S18CTCUD7n4+XOG6GbVNLwpBsE -naUP5eXHm5Bxuiir0BIsKATXx0ZwEjULpfCgBwYFK4EEACOhgYkDgYYABAEiHfCR -mQtxxjthsfQ987aSYGgxcCLxBaj8/fW4U7jufPcqxz27x9wi1qB2rZmOKaSsh1JZ -wF5yOAMX4/acIK1OdgGzbafukRZjqF3wKVP8UFH0DzdNaZ8aSplgUu8gV2TjJyQB -1sCKaVuecBtTRiIwvnapv5PgQIgstPQmRhqVOLriDA== ------END EC PRIVATE KEY----- -""" - - // Test the working private keys. - let signingKey = try orFail { try P521.Signing.PrivateKey(pemRepresentation: pemPrivateKey) } - let keyAgreementKey = try orFail { try P521.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching private keys. - XCTAssertThrowsError(try P256.Signing.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P384.Signing.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey)) - - // Now the public keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.Signing.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(pemRepresentation: pemPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .invalidPEMDocument) - } - - // We can't reserialize the SEC1 keys, we don't emit them. - } - - func testSimpleDERP256SPKI() throws { - let b64PublicKey = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEIq+Qd2HviOb1JAkvKInCCec/gbZRnEZ6H9gO29wJ1H/a8Mmmog7b8nj+xEgo7Rh5dKlNgRaKvVjlLDllq+bPAA==" - let derPublicKey = Data(base64Encoded: b64PublicKey)! - - // Test the working public keys. - let signingKey = try orFail { try P256.Signing.PublicKey(derRepresentation: derPublicKey) } - let keyAgreementKey = try orFail { try P256.KeyAgreement.PublicKey(derRepresentation: derPublicKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching public keys. - XCTAssertThrowsError(try P384.Signing.PublicKey(derRepresentation: derPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(derRepresentation: derPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P521.Signing.PublicKey(derRepresentation: derPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(derRepresentation: derPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - - // Now the private keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.Signing.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.Signing.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - - // Validate we can reserialize. - let firstReserialization = signingKey.derRepresentation - let secondReserialization = keyAgreementKey.derRepresentation - XCTAssertEqual(firstReserialization, derPublicKey) - XCTAssertEqual(secondReserialization, derPublicKey) - } - - func testSimpleDERP384SPKI() throws { - let b64PublicKey = "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEvt9xABn4WAo0EQsp3BMEd26f3qrXJ5RrhU1i2wp0G29oK2cdNareBirnyjlsQEg/OQ+ZQyKmMrxm5OrbhvJf/+97dc6phzb2R/blH62I65BiUSBAsGaXU69ObTPOwDKT" - let derPublicKey = Data(base64Encoded: b64PublicKey)! - - // Test the working public keys. - let signingKey = try orFail { try P384.Signing.PublicKey(derRepresentation: derPublicKey) } - let keyAgreementKey = try orFail { try P384.KeyAgreement.PublicKey(derRepresentation: derPublicKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching public keys. - XCTAssertThrowsError(try P256.Signing.PublicKey(derRepresentation: derPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(derRepresentation: derPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P521.Signing.PublicKey(derRepresentation: derPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(derRepresentation: derPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - - // Now the private keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.Signing.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.Signing.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - - // Validate we can reserialize. - let firstReserialization = signingKey.derRepresentation - let secondReserialization = keyAgreementKey.derRepresentation - XCTAssertEqual(firstReserialization, derPublicKey) - XCTAssertEqual(secondReserialization, derPublicKey) - } - - func testSimpleDERP521SPKI() throws { - let b64PublicKey = "MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQAfH9fsVM7MdTe88+kvkZmFq9nPLMAPvCyAf5PYnJ7qV3W0rtVC2R3c0Aw21QxeN4XAIFcElO9NQ+ErT/m4o6+1YgBlLfBTnHKTq/WTNjQWxQk8i1PzHMsplT41OMAm0LaHwi9s+mWUIGlbfcP+MmVKY5dMkskPsU2YBlLZI81xk+z2X4=" - let derPublicKey = Data(base64Encoded: b64PublicKey)! - - // Test the working public keys. - let signingKey = try orFail { try P521.Signing.PublicKey(derRepresentation: derPublicKey) } - let keyAgreementKey = try orFail { try P521.KeyAgreement.PublicKey(derRepresentation: derPublicKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching public keys. - XCTAssertThrowsError(try P256.Signing.PublicKey(derRepresentation: derPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(derRepresentation: derPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P384.Signing.PublicKey(derRepresentation: derPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(derRepresentation: derPublicKey)) { error in - guard case .incorrectParameterSize = error as? CryptoKitError else { - XCTFail("Unexpected error: \(error)") - return - } - } - - // Now the private keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.Signing.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.Signing.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(derRepresentation: derPublicKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - - // Validate we can reserialize. - let firstReserialization = signingKey.derRepresentation - let secondReserialization = keyAgreementKey.derRepresentation - XCTAssertEqual(firstReserialization, derPublicKey) - XCTAssertEqual(secondReserialization, derPublicKey) - } - - func testSimpleDERP256PKCS8() throws { - let b64PrivateKey = "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgxWaWfbbhHsTjtEwkANo6ZDeJ2CARYhjOSt2auAW7xNOhRANCAAQsAL3hTMCCbh1kVCSJa8V22WLNDriEpVOLEJXiVFEwAFjWd1BufewuT69tYa0hyB1Q3pt12HPK2c1KGwjOpScW" - let derPrivateKey = Data(base64Encoded: b64PrivateKey)! - - // Test the working private keys. - let signingKey = try orFail { try P256.Signing.PrivateKey(derRepresentation: derPrivateKey) } - let keyAgreementKey = try orFail { try P256.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching private keys. - XCTAssertThrowsError(try P384.Signing.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P521.Signing.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey)) - - // Now the public keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - - // Validate we can reserialize. - let firstReserialization = signingKey.derRepresentation - let secondReserialization = keyAgreementKey.derRepresentation - XCTAssertEqual(firstReserialization, derPrivateKey) - XCTAssertEqual(secondReserialization, derPrivateKey) - } - - func testSimpleDERP384PKCS8() throws { - let b64PrivateKey = "MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDAsdACCJGneotN0y5zQjZxImZuH3TuvHeKWXKi2m6d3fYsGOufibIqaxfCLVZGvxb2hZANiAARL6IhECKbw5UCSqGaaZ3H5FNbXuk/4y4QTJLhdQRBkibr6YjEzFGDgd1yjU0msBOMBvx3oCZ5rPgVaogQXPdZbx8PnTt2I+2x2BuoRibA+/yCAyJSluVm/005p0EcAmuI=" - let derPrivateKey = Data(base64Encoded: b64PrivateKey)! - - // Test the working private keys. - let signingKey = try orFail { try P384.Signing.PrivateKey(derRepresentation: derPrivateKey) } - let keyAgreementKey = try orFail { try P384.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching private keys. - XCTAssertThrowsError(try P256.Signing.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P521.Signing.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey)) - - // Now the public keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - - // Validate we can reserialize. - let firstReserialization = signingKey.derRepresentation - let secondReserialization = keyAgreementKey.derRepresentation - XCTAssertEqual(firstReserialization, derPrivateKey) - XCTAssertEqual(secondReserialization, derPrivateKey) - } - - func testSimpleDERP521PKCS8() throws { - let b64PrivateKey = "MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIA2u5+KHPk/vVrYI53Khh3WrFmxUCQ5YeK6HAi+GyebeRM3w1KoQuD4oHocp2aKffjjWKVkEfLRfjraJgh1jH+GPihgYkDgYYABAC4M0cSEZ+hKwn65PQtdFu+L1ZdBt4kjrGJ2ggNG+tQ3z4S11KV9b+R+CyUajajhU2nJ4UkHQO5bEaTPmaWySFSVQEZilLlYtnQZSKGLS2DR4zBsny0O2+D5DpFSYKsDPN23MdOBdTam2Gqtm/WAirVmXMqs8v5VSjmh3i/EG6EDPEtXw==" - let derPrivateKey = Data(base64Encoded: b64PrivateKey)! - - // Test the working private keys. - let signingKey = try orFail { try P521.Signing.PrivateKey(derRepresentation: derPrivateKey) } - let keyAgreementKey = try orFail { try P521.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching private keys. - XCTAssertThrowsError(try P256.Signing.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P384.Signing.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey)) - - // Now the public keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - - // Validate we can reserialize. - let firstReserialization = signingKey.derRepresentation - let secondReserialization = keyAgreementKey.derRepresentation - XCTAssertEqual(firstReserialization, derPrivateKey) - XCTAssertEqual(secondReserialization, derPrivateKey) - } - - func testSimpleDERP256SEC1PrivateKey() throws { - let b64PrivateKey = "MHcCAQEEIKzmkxtADyr8LymuVMqpLFVlx27bdgT0+un4I2a3DE1KoAoGCCqGSM49AwEHoUQDQgAEZp2q8QP4shIBZIHS1b1ZBUeLbrpnTA6CB17iFzF8udyYmcRkDAPSBamFXf4IthinYkfnru/PymZl+tpeM56BOw==" - let derPrivateKey = Data(base64Encoded: b64PrivateKey)! - - // Test the working private keys. - let signingKey = try orFail { try P256.Signing.PrivateKey(derRepresentation: derPrivateKey) } - let keyAgreementKey = try orFail { try P256.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching private keys. - XCTAssertThrowsError(try P384.Signing.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P521.Signing.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey)) - - // Now the public keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - - // We can't reserialize the SEC1 keys, we don't emit them. - } - - func testSimpleDERP384SEC1PrivateKey() throws { - let b64PrivateKey = "MIGkAgEBBDAF5FSBF7Se55zRtIyMRcKgFWAEx0ixHqeevUFerPVtvZC7U2LfGOx9GMR5V+Nj7uagBwYFK4EEACKhZANiAAQCXRQ9B+RYv6zvQVdP2xZ0/8U3nzcOdWuAMb0BvjqkE/xDhHp7DYNGEv4pWhj1hkl9Tv5jum0eqAGgzq1hLpeY2aWnwk8fqnrDVDcnWrZe/9QpmHGaOP1YJXuyaJRnBWo=" - let derPrivateKey = Data(base64Encoded: b64PrivateKey)! - - // Test the working private keys. - let signingKey = try orFail { try P384.Signing.PrivateKey(derRepresentation: derPrivateKey) } - let keyAgreementKey = try orFail { try P384.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching private keys. - XCTAssertThrowsError(try P256.Signing.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P521.Signing.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey)) - - // Now the public keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - - // We can't reserialize the SEC1 keys, we don't emit them. - } - - func testSimpleDERP521SEC1PrivateKey() throws { - let b64PrivateKey = "MIHcAgEBBEIBFQwJ2Spw90Sn7oOnBKU6ob5Zoq9qBo6YiarvTok4jurO2VSQTyrmk02KK8EmZ/ZQqXRl/mZm0hLXwKBdUe+MPfSgBwYFK4EEACOhgYkDgYYABAEFYqZABFf2NBxxLb7rUV/pKAO8IF/ddIs2BY9dU/Ru6sQBOT6lzr5pGZC4a0o30ZGWNOvMq503Ev7/XDjW8fdPCQBGm4JGOOI/Pr008wsASEQOvloAUEQ+HOTZ94Dk3OTHqqahtgjp2BLGvMWHf1PwMsXv98nLE+LEYTQ8fzTgbUJwxg==" - let derPrivateKey = Data(base64Encoded: b64PrivateKey)! - - // Test the working private keys. - let signingKey = try orFail { try P521.Signing.PrivateKey(derRepresentation: derPrivateKey) } - let keyAgreementKey = try orFail { try P521.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey) } - XCTAssertEqual(signingKey.rawRepresentation, keyAgreementKey.rawRepresentation) - - // Now the non-matching private keys. - XCTAssertThrowsError(try P256.Signing.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P384.Signing.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey)) - - // Now the public keys, which all fail. - XCTAssertThrowsError(try P256.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.Signing.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(derRepresentation: derPrivateKey)) { error in - XCTAssertEqual(error as? CryptoKitASN1Error, .unexpectedFieldType) - } - - // We can't reserialize the SEC1 keys, we don't emit them. - } - - func testInvalidPEMP521PKCS8() throws { - // This key is generated by an older OpenSSL or LibreSSL, which forgets to zero-pad the - // private key. We want to validate that we correctly reject this. - let pemPrivateKey = """ ------BEGIN PRIVATE KEY----- -MIHtAgEAMBAGByqGSM49AgEGBSuBBAAjBIHVMIHSAgEBBEFtmqAvS3jccVAam+Yn -y3iiwMi6q8roJeAtxqdOkZUCdZ3Rf6lD0nehiH4QN7xOrhHrAIeZWe0ld2XUawGF -H0ltO6GBiQOBhgAEAJHKKLTdXvL1DyZX4TI0kEi63I9cwtg09CQZ/Bp+K9MWsx9S -bjIEBcr3yEKlUmRW+TKNoXo50ycbl4DlLknN2VbGAXE22e2sz8RQ1omvDE6lLBvB -A5UvlNrk6ioTg2tumXD3Co06r1Hn+7lkkcjfT5mZO4jy7vP9ItvprJrIa6ySzVQ8 ------END PRIVATE KEY----- -""" - - // This is not a valid private key for P521. - XCTAssertThrowsError(try P521.Signing.PrivateKey(pemRepresentation: pemPrivateKey)) - XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(pemRepresentation: pemPrivateKey)) - } - - func testInvalidDERP521PKCS8() throws { - // This key is generated by an older OpenSSL or LibreSSL, which forgets to zero-pad the - // private key. We want to validate that we correctly reject this. - let b64PrivateKey = "MIHtAgEAMBAGByqGSM49AgEGBSuBBAAjBIHVMIHSAgEBBEG1erZ/O4JMc11uT3SLJPQ4ICWbEdM0e8d1mI/uUhbZ6nE90jq38FZYkvKf6q3d1DUWJj8aWjktq2+gfCSD+XFulaGBiQOBhgAEAYKbRHQpjqaS17SwXAQzpUct9i+TyVUdDtQVpwxVTVhuklvTEWqypvSAyhqo9nPf/aKHl4fQD94Fd3RTzOmW8x+nAGnWGO6ZG1OQ72NCmT9fyB8dG2ifeDpICKuEq6reVIBDSQvi5F98C/lEIgu2r+MGYWj+S7pjEmSqksSjsJ3Oxo9U" - let derPrivateKey = Data(base64Encoded: b64PrivateKey)! - - // This is not a valid private key for P521. - XCTAssertThrowsError(try P521.Signing.PrivateKey(derRepresentation: derPrivateKey)) - XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey)) - } - func testExcessiveDepth() throws { // This is an ASN1 document that has a deeply nested structure: Sequences within // Sequences, for eleven levels. diff --git a/Tests/CryptoTests/ASN1/GeneralizedTimeTests.swift b/Tests/CryptoTests/ASN1/GeneralizedTimeTests.swift index 0878c36a..4abf820c 100644 --- a/Tests/CryptoTests/ASN1/GeneralizedTimeTests.swift +++ b/Tests/CryptoTests/ASN1/GeneralizedTimeTests.swift @@ -11,16 +11,13 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif final class GeneralizedTimeTests: XCTestCase { private func assertRoundTrips(_ value: ASN1Object) throws { diff --git a/Tests/CryptoTests/Authenticated Encryption/AES-GCM-Runner.swift b/Tests/CryptoTests/Authenticated Encryption/AES-GCM-Runner.swift index 0a1890a7..166a5120 100644 --- a/Tests/CryptoTests/Authenticated Encryption/AES-GCM-Runner.swift +++ b/Tests/CryptoTests/Authenticated Encryption/AES-GCM-Runner.swift @@ -11,20 +11,12 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if canImport(FoundationEssentials) -import FoundationEssentials -#else -import Foundation -#endif import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -import Crypto -#elseif !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -import CryptoKit +#if canImport(CryptoKit) +// Skip tests that require @testable imports of CryptoKit. #else -import Crypto -#endif +@testable import Crypto struct AEADTestGroup: Codable { let ivSize: Int @@ -44,7 +36,6 @@ struct AESGCMTestVector: Codable { let result: String } -@available(iOS 17.4, macOS 14.4, watchOS 10.4, tvOS 17.4, macCatalyst 17.4, *) class AESGCMTests: XCTestCase { func testPropertiesStayTheSameAfterFailedOpening() throws { let message = Data("this is a message".utf8) @@ -94,6 +85,51 @@ class AESGCMTests: XCTestCase { XCTAssertEqual(recoveredPlaintext, plaintext) XCTAssertEqual(recoveredPlaintextWithoutAAD, plaintext) + XCTAssertEqual(recoveredPlaintext.startIndex, 0) + XCTAssertEqual(recoveredPlaintextWithoutAAD.startIndex, 0) + } + + func testEncryptDecryptSpan() throws { + let plaintext: [UInt8] = Array("Some Super Secret Message".utf8) + + let key = SymmetricKey(size: .bits256) + let nonce = AES.GCM.Nonce() + + var ciphertext = plaintext + var ciphertextTag: [16 of UInt8] = .init(repeating: 0) + + try orFail { + var ciphertextSpan = ciphertext.mutableSpan + var ciphertextRawSpan = ciphertextSpan.mutableBytes + var tagSpan = ciphertextTag.mutableSpan + + try tagSpan.withUnsafeMutableBytes { (tagBytesBuffer) throws(CryptoKitMetaError) in + var outputTagBytes = OutputRawSpan(buffer: tagBytesBuffer, initializedCount: 0) + try AES.GCM + .seal(inPlace: &ciphertextRawSpan, using: key, nonce: nonce, authenticating: [UInt8]().span.bytes, tag: &outputTagBytes) + _ = outputTagBytes.finalize(for: tagBytesBuffer) + } + + } + + // Make sure we actually ended up with different contents. + XCTAssertNotEqual(ciphertext, plaintext) + + do { + var ciphertextSpan = ciphertext.mutableSpan + var ciphertextRawSpan = ciphertextSpan.mutableBytes + try orFail { + try AES.GCM + .open( + inPlace: &ciphertextRawSpan, + using: key, + nonce: nonce, + tag: ciphertextTag.span.bytes + ) + } + } + + XCTAssertEqual(ciphertext, plaintext) } func testExtractingBytesFromNonce() throws { @@ -115,7 +151,7 @@ class AESGCMTests: XCTestCase { let ciphertext = Array("This pretty clearly isn't ciphertext, but sure why not".utf8) let (contiguousCiphertext, discontiguousCiphertext) = ciphertext.asDataProtocols() - let contiguousSB = try orFail { try AES.GCM.SealedBox(combined: contiguousCiphertext) } + let contiguousSB = try orFail { AES.GCM.SealedBox(combined: contiguousCiphertext) } let discontiguousSB = try orFail { try AES.GCM.SealedBox(combined: discontiguousCiphertext) } XCTAssertEqual(contiguousSB.combined, discontiguousSB.combined) XCTAssertEqual(Array(contiguousSB.nonce), Array(discontiguousSB.nonce)) @@ -247,3 +283,4 @@ class AESGCMTests: XCTestCase { } } } +#endif diff --git a/Tests/CryptoTests/Authenticated Encryption/ChaChaPoly-Runner.swift b/Tests/CryptoTests/Authenticated Encryption/ChaChaPoly-Runner.swift index f0ccb430..c743faf5 100644 --- a/Tests/CryptoTests/Authenticated Encryption/ChaChaPoly-Runner.swift +++ b/Tests/CryptoTests/Authenticated Encryption/ChaChaPoly-Runner.swift @@ -11,22 +11,13 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if canImport(FoundationEssentials) -import FoundationEssentials -#else -import Foundation -#endif import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -import Crypto -#elseif !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -import CryptoKit +#if canImport(CryptoKit) +// Skip tests that require @testable imports of CryptoKit. #else -import Crypto -#endif +@testable import Crypto -@available(iOS 17.4, macOS 14.4, watchOS 10.4, tvOS 17.4, macCatalyst 17.4, *) class ChaChaPolyTests: XCTestCase { func testIncorrectKeySize() throws { let plaintext: Data = "Some Super Secret Message".data(using: String.Encoding.utf8)! @@ -67,6 +58,49 @@ class ChaChaPolyTests: XCTestCase { let recoveredPlaintext = try orFail { try ChaChaPoly.open(ciphertext, using: key, authenticating: Data()) } XCTAssertEqual(recoveredPlaintext, plaintext) + + XCTAssertEqual(recoveredPlaintext.startIndex, 0) + } + + func testEncryptDecryptSpans() throws { + let plaintext: [UInt8] = Array("Some Super Secret Message".utf8) + + let key = SymmetricKey(size: .bits256) + let nonce = ChaChaPoly.Nonce() + + var ciphertext = plaintext + var ciphertextTag: [16 of UInt8] = .init(repeating: 0) + + try orFail { + var ciphertextSpan = ciphertext.mutableSpan + var ciphertextRawSpan = ciphertextSpan.mutableBytes + var tagSpan = ciphertextTag.mutableSpan + try tagSpan.withUnsafeMutableBytes { (tagBytes) throws(CryptoKitMetaError) in + var tagOutputSpan = OutputRawSpan(buffer: tagBytes, initializedCount: 0) + try ChaChaPoly + .seal(inPlace: &ciphertextRawSpan, using: key, nonce: nonce, authenticating: [UInt8]().span.bytes, tag: &tagOutputSpan) + _ = tagOutputSpan.finalize(for: tagBytes) + } + } + + // Make sure we actually ended up with different contents. + XCTAssertNotEqual(ciphertext, plaintext) + + do { + var ciphertextSpan = ciphertext.mutableSpan + var ciphertextRawSpan = ciphertextSpan.mutableBytes + try orFail { + try ChaChaPoly + .open( + inPlace: &ciphertextRawSpan, + using: key, + nonce: nonce, + tag: ciphertextTag.span.bytes + ) + } + } + + XCTAssertEqual(ciphertext, plaintext) } func testUserConstructedSealedBoxesCombined() throws { @@ -210,3 +244,5 @@ class ChaChaPolyTests: XCTestCase { } } } + +#endif diff --git a/Tests/CryptoTests/Digests/DigestsTests.swift b/Tests/CryptoTests/Digests/DigestsTests.swift index bc9e03d1..f8b5cfd4 100644 --- a/Tests/CryptoTests/Digests/DigestsTests.swift +++ b/Tests/CryptoTests/Digests/DigestsTests.swift @@ -11,12 +11,11 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) import Crypto -#elseif !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -import CryptoKit #else import Crypto #endif @@ -27,7 +26,7 @@ enum TestError: Error { func nullTestVectorForAlgorithm(hashFunction: H.Type) throws -> String { #if !CRYPTOKIT_IN_SEP -#if !CRYPTO_IN_SWIFTPM || canImport(CryptoKit, _version: 324.0.4) +#if canImport(CryptoKit, _version: 324.0.4) if #available(iOS 19.0, macOS 16.0, watchOS 12.0, tvOS 19.0, macCatalyst 19.0, visionOS 2.0, *) { switch H.self { case is SHA3_256.Type: return "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a" @@ -37,7 +36,7 @@ func nullTestVectorForAlgorithm(hashFunction: H.Type) throws -> break } } -#endif // !CRYPTO_IN_SWIFTPM || canImport(CryptoKit, _version: 324.0.4) +#endif // canImport(CryptoKit, _version: 324.0.4) #endif // !CRYPTOKIT_IN_SEP switch H.self { @@ -53,7 +52,7 @@ func nullTestVectorForAlgorithm(hashFunction: H.Type) throws -> func testVectorForAlgorithm(hashFunction: H.Type) throws -> String { #if !CRYPTOKIT_IN_SEP -#if !CRYPTO_IN_SWIFTPM || canImport(CryptoKit, _version: 324.0.4) +#if canImport(CryptoKit, _version: 324.0.4) if #available(iOS 19.0, macOS 16.0, watchOS 12.0, tvOS 19.0, macCatalyst 19.0, visionOS 2.0, *) { switch H.self { case is SHA3_256.Type: return "916f6061fe879741ca6469b43971dfdb28b1a32dc36cb3254e812be27aad1d18" @@ -63,7 +62,7 @@ func testVectorForAlgorithm(hashFunction: H.Type) throws -> Str break } } -#endif // !CRYPTO_IN_SWIFTPM || canImport(CryptoKit, _version: 324.0.4) +#endif // canImport(CryptoKit, _version: 324.0.4) #endif // !CRYPTOKIT_IN_SEP switch H.self { @@ -118,13 +117,13 @@ class DigestsTests: XCTestCase { try orFail { try testHashFunction(hf: SHA384.self) } try orFail { try testHashFunction(hf: SHA512.self) } #if !CRYPTOKIT_IN_SEP -#if !CRYPTO_IN_SWIFTPM || canImport(CryptoKit, _version: 324.0.4) +#if canImport(CryptoKit, _version: 324.0.4) if #available(iOS 19.0, macOS 16.0, watchOS 12.0, tvOS 19.0, macCatalyst 19.0, visionOS 2.0, *) { try orFail { try testHashFunction(hf: SHA3_256.self) } try orFail { try testHashFunction(hf: SHA3_384.self) } try orFail { try testHashFunction(hf: SHA3_512.self) } } -#endif // !CRYPTO_IN_SWIFTPM || canImport(CryptoKit, _version: 324.0.4) +#endif // canImport(CryptoKit, _version: 324.0.4) #endif // !CRYPTOKIT_IN_SEP } @@ -149,13 +148,13 @@ class DigestsTests: XCTestCase { try orFail { try testHashFunctionImplementsCoW(hf: SHA384.self) } try orFail { try testHashFunctionImplementsCoW(hf: SHA512.self) } #if !CRYPTOKIT_IN_SEP -#if !CRYPTO_IN_SWIFTPM || canImport(CryptoKit, _version: 324.0.4) +#if canImport(CryptoKit, _version: 324.0.4) if #available(iOS 19.0, macOS 16.0, watchOS 12.0, tvOS 19.0, macCatalyst 19.0, visionOS 2.0, *) { try orFail { try testHashFunctionImplementsCoW(hf: SHA3_256.self) } try orFail { try testHashFunctionImplementsCoW(hf: SHA3_384.self) } try orFail { try testHashFunctionImplementsCoW(hf: SHA3_512.self) } } -#endif // !CRYPTO_IN_SWIFTPM || canImport(CryptoKit, _version: 324.0.4) +#endif // canImport(CryptoKit, _version: 324.0.4) #endif // !CRYPTOKIT_IN_SEP } @@ -168,13 +167,13 @@ class DigestsTests: XCTestCase { XCTAssertEqual(SHA512.blockByteCount, 128) #if !CRYPTOKIT_IN_SEP -#if !CRYPTO_IN_SWIFTPM || canImport(CryptoKit, _version: 324.0.4) +#if canImport(CryptoKit, _version: 324.0.4) if #available(iOS 19.0, macOS 16.0, watchOS 12.0, tvOS 19.0, macCatalyst 19.0, visionOS 2.0, *) { XCTAssertEqual(SHA3_256.blockByteCount, 136) XCTAssertEqual(SHA3_384.blockByteCount, 104) XCTAssertEqual(SHA3_512.blockByteCount, 72) } -#endif // !CRYPTO_IN_SWIFTPM || canImport(CryptoKit, _version: 324.0.4) +#endif // canImport(CryptoKit, _version: 324.0.4) #endif // !CRYPTOKIT_IN_SEP } } diff --git a/Tests/CryptoTests/ECDH/BoringSSL/ASN1.swift b/Tests/CryptoTests/ECDH/BoringSSL/ASN1.swift index 1a3716f3..839bfc2b 100644 --- a/Tests/CryptoTests/ECDH/BoringSSL/ASN1.swift +++ b/Tests/CryptoTests/ECDH/BoringSSL/ASN1.swift @@ -13,21 +13,16 @@ //===----------------------------------------------------------------------===// import XCTest +#if canImport(CryptoKit) +// Skip tests that require @testable imports of CryptoKit. +#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif - -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -// Skip tests that require @testable imports of CryptoKit. -#else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @_implementationOnly import CCryptoBoringSSL @testable import Crypto -#endif // This module implements "just enough" ASN.1. Specifically, we implement exactly enough ASN.1 DER parsing to handle // taking the Wycheproof input of EC public keys and to turn them into the x963 representation of the key. This is not @@ -342,4 +337,4 @@ extension UInt { } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/ECDH/BoringSSL/secpECDH_Runner_boring.swift b/Tests/CryptoTests/ECDH/BoringSSL/secpECDH_Runner_boring.swift index d1d82af0..28177f54 100644 --- a/Tests/CryptoTests/ECDH/BoringSSL/secpECDH_Runner_boring.swift +++ b/Tests/CryptoTests/ECDH/BoringSSL/secpECDH_Runner_boring.swift @@ -13,21 +13,16 @@ //===----------------------------------------------------------------------===// import XCTest +#if canImport(CryptoKit) +// Skip tests that require @testable imports of CryptoKit. +#else #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif - -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -// Skip tests that require @testable imports of CryptoKit. -#else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @_implementationOnly import CCryptoBoringSSL @testable import Crypto -#endif extension NISTECDHTests { func testGroupOpenSSL< @@ -185,4 +180,4 @@ extension NISTECPublicKey { } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/ECDH/X25519-Runner.swift b/Tests/CryptoTests/ECDH/X25519-Runner.swift index 41deb870..9f5c55f3 100644 --- a/Tests/CryptoTests/ECDH/X25519-Runner.swift +++ b/Tests/CryptoTests/ECDH/X25519-Runner.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -18,14 +19,10 @@ import Foundation #endif import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif struct ECDHTestGroup: Codable { let curve: String @@ -206,4 +203,4 @@ class X25519Tests: XCTestCase { } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/ECDH/secpECDH_Runner.swift b/Tests/CryptoTests/ECDH/secpECDH_Runner.swift index e03efa1d..e8d07ade 100644 --- a/Tests/CryptoTests/ECDH/secpECDH_Runner.swift +++ b/Tests/CryptoTests/ECDH/secpECDH_Runner.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -18,14 +19,10 @@ import Foundation #endif import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif enum ECDHTestErrors: Error { case PublicKeyFailure @@ -113,19 +110,11 @@ class NISTECDHTests: XCTestCase { } func testGroup(group: ECDHTestGroup, privateKeys: PrivKey.Type, onCurve curve: Curve.Type) { - #if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API - self.testGroupCC(group: group, privateKeys: privateKeys, onCurve: curve) - #else self.testGroupOpenSSL(group: group, privateKeys: privateKeys, onCurve: curve) - #endif } func testGroupPoint(group: ECDHTestGroup, privateKeys: PrivKey.Type, onCurve curve: Curve.Type) { - #if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API - self.testGroupPointCC(group: group, privateKeys: privateKeys, onCurve: curve) - #else self.testGroupPointOpenSSL(group: group, privateKeys: privateKeys, onCurve: curve) - #endif } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/Encodings/BoringSSL/DERTests_boring.swift b/Tests/CryptoTests/Encodings/BoringSSL/DERTests_boring.swift index f0a8896c..8320cd8d 100644 --- a/Tests/CryptoTests/Encodings/BoringSSL/DERTests_boring.swift +++ b/Tests/CryptoTests/Encodings/BoringSSL/DERTests_boring.swift @@ -13,14 +13,10 @@ //===----------------------------------------------------------------------===// import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif extension DERTests { func openSSLCoordinateSizeForCurve(_: Curve.Type) -> Int { @@ -28,4 +24,4 @@ extension DERTests { } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/Encodings/DERTests.swift b/Tests/CryptoTests/Encodings/DERTests.swift index 02ce6bbd..88e025ba 100644 --- a/Tests/CryptoTests/Encodings/DERTests.swift +++ b/Tests/CryptoTests/Encodings/DERTests.swift @@ -11,16 +11,13 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif class DERTests: XCTestCase { func testEncodeDecodeECDSASignature() throws { @@ -41,15 +38,11 @@ class DERTests: XCTestCase { } func coordinateSizeForCurve(_ curve: Curve.Type) -> Int { - #if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API - return self.coreCryptoCoordinateSizeForCurve(curve) - #else return self.openSSLCoordinateSizeForCurve(curve) - #endif } func randomBytes(count: Int) -> [UInt8] { - #if canImport(Darwin) || os(Linux) || os(Android) || os(Windows) || os(FreeBSD) + #if os(Linux) || os(Android) || os(Windows) var rng = SystemRandomNumberGenerator() return (0.. HPKE.AEAD? { return aeadValues.first } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/HPKE/HPKETests.swift b/Tests/CryptoTests/HPKE/HPKETests.swift index e0e9e888..c78da04e 100644 --- a/Tests/CryptoTests/HPKE/HPKETests.swift +++ b/Tests/CryptoTests/HPKE/HPKETests.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -18,15 +19,10 @@ import Foundation #endif import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable @_spi(HPKEAlgID) import CryptoKit -@testable import CryptoKit -#else -@testable @_spi(HPKEAlgID) import Crypto -#endif +@testable import Crypto class HPKETests: XCTestCase { func testCases() throws { @@ -43,7 +39,7 @@ class HPKETests: XCTestCase { try testCiphersuite(ciphersuite) } } - + func testMismatchedKEM() { let skR = P256.KeyAgreement.PrivateKey() XCTAssertThrowsError(try HPKE.Sender(recipientKey: skR.publicKey, ciphersuite: .P384_SHA384_AES_GCM_256, info: Data())) @@ -176,4 +172,4 @@ class HPKETests: XCTestCase { } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/KEM/Boring/XWingTests_boring.swift b/Tests/CryptoTests/KEM/Boring/XWingTests_boring.swift index ea3890f7..5876c6a6 100644 --- a/Tests/CryptoTests/KEM/Boring/XWingTests_boring.swift +++ b/Tests/CryptoTests/KEM/Boring/XWingTests_boring.swift @@ -12,14 +12,10 @@ // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif extension XWingMLKEM768X25519.PrivateKey { static func generateWithRng(rngState: SequenceDrbg) throws -> Self { @@ -49,4 +45,4 @@ extension XWingMLKEM768X25519.PublicKey { } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/KEM/MLKEMKeyGenTests.swift b/Tests/CryptoTests/KEM/MLKEMKeyGenTests.swift index 6eec1c6f..7441798e 100644 --- a/Tests/CryptoTests/KEM/MLKEMKeyGenTests.swift +++ b/Tests/CryptoTests/KEM/MLKEMKeyGenTests.swift @@ -11,23 +11,16 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif final class MLKEMKeyGenTests: XCTestCase { func processKeyGenKATFile(filename: String) throws -> [MLKEMKeyGenKAT] { - #if CRYPTO_IN_SWIFTPM let bundle = Bundle.module - #else - let bundle = Bundle(for: type(of: self)) - #endif let fileURL = bundle.url(forResource: filename, withExtension: "json") let json = try Data(contentsOf: fileURL!) let stringInput = String(data: json, encoding: .ascii)! @@ -98,4 +91,4 @@ struct MLKEMKeyGenKAT { } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/KEM/MLKEMTests.swift b/Tests/CryptoTests/KEM/MLKEMTests.swift index 4126a05d..b5899a9d 100644 --- a/Tests/CryptoTests/KEM/MLKEMTests.swift +++ b/Tests/CryptoTests/KEM/MLKEMTests.swift @@ -11,17 +11,42 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif final class MLKEMTests: XCTestCase { + /// Decapsulates with the regular private key and also with a one-time private key built from the + /// same key material, asserting that both paths recover the same shared secret. Returns the shared + /// secret so callers can run their own assertions (e.g. against a known-answer value), guaranteeing + /// the one-time and regular decapsulation functions are tested identically everywhere. + private func decapsulate( + with privateKey: MLKEM768.PrivateKey, + _ encapsulated: Data, + file: StaticString = #filePath, + line: UInt = #line + ) throws -> SymmetricKey { + let sharedSecret = try privateKey.decapsulate(encapsulated) + let oneTimeSharedSecret = try MLKEM768.OneTimePrivateKey(reusingForTestingOnly: privateKey).decapsulate(encapsulated) + XCTAssertEqual(sharedSecret, oneTimeSharedSecret, "one-time decapsulation diverged from regular decapsulation", file: file, line: line) + return sharedSecret + } + + private func decapsulate( + with privateKey: MLKEM1024.PrivateKey, + _ encapsulated: Data, + file: StaticString = #filePath, + line: UInt = #line + ) throws -> SymmetricKey { + let sharedSecret = try privateKey.decapsulate(encapsulated) + let oneTimeSharedSecret = try MLKEM1024.OneTimePrivateKey(reusingForTestingOnly: privateKey).decapsulate(encapsulated) + XCTAssertEqual(sharedSecret, oneTimeSharedSecret, "one-time decapsulation diverged from regular decapsulation", file: file, line: line) + return sharedSecret + } + func testMLKEM768() throws { let privateKey = try MLKEM768.PrivateKey.generate() let publicKey = privateKey.publicKey @@ -34,7 +59,7 @@ final class MLKEMTests: XCTestCase { try XCTAssert(privateKey.integrityCheckedRepresentation == MLKEM768.PrivateKey(integrityCheckedRepresentation: privateKey.integrityCheckedRepresentation).integrityCheckedRepresentation) let er = try publicKey.encapsulate() - let ss = try privateKey.decapsulate(er.encapsulated) + let ss = try decapsulate(with: privateKey, er.encapsulated) XCTAssert(er.sharedSecret == ss) } @@ -51,17 +76,22 @@ final class MLKEMTests: XCTestCase { try XCTAssert(privateKey.integrityCheckedRepresentation == MLKEM1024.PrivateKey(integrityCheckedRepresentation: privateKey.integrityCheckedRepresentation).integrityCheckedRepresentation) let er = try publicKey.encapsulate() - let ss = try privateKey.decapsulate(er.encapsulated) + let ss = try decapsulate(with: privateKey, er.encapsulated) XCTAssert(er.sharedSecret == ss) } + // Test that the private key API function throws on an invalid seed + func testPrivateKeyInitThrowsOnInvalidSeedLength768() { + XCTAssertThrowsError(try MLKEM768.PrivateKey(seedRepresentation: Data(count: 1), publicKey: nil)) + } + + func testPrivateKeyInitThrowsOnInvalidSeedLength1024() { + XCTAssertThrowsError(try MLKEM1024.PrivateKey(seedRepresentation: Data(count: 1), publicKey: nil)) + } + func processKATFile(filename: String) throws -> [MLKEMKAT] { - #if CRYPTO_IN_SWIFTPM let bundle = Bundle.module - #else - let bundle = Bundle(for: type(of: self)) - #endif let fileURL = bundle.url(forResource: filename, withExtension: "json") let json = try Data(contentsOf: fileURL!) let stringInput = String(data: json, encoding: .ascii)! @@ -70,65 +100,13 @@ final class MLKEMTests: XCTestCase { } func test768KAT() throws { - #if CRYPTO_IN_SWIFTPM // No support for encapsulateWithSeed in BoringSSL. throw XCTSkip() - #else - let katTests = try processKATFile(filename:"MLKEM768KAT") - for katTest in katTests { - let rndGen = try Drbg(katTest.rngSeed) - - var keyGenSeed = Data(count: 64) - try keyGenSeed.withUnsafeMutableBytes { buffer in - try buffer.initializeWithRandomBytes(count: buffer.count, rngState: rndGen) - } - var encapSeed = Data(count: 32) - try encapSeed.withUnsafeMutableBytes { buffer in - try buffer.initializeWithRandomBytes(count: buffer.count, rngState: rndGen) - } - - let privateKey = try MLKEM768.PrivateKey.generateWithSeed(keyGenSeed) // 2 * 32 bytes - XCTAssert(privateKey.publicKey.rawRepresentation == katTest.pk) - - let encapsulatedKey = try privateKey.publicKey.encapsulateWithSeed(encapSeed: encapSeed) // 32 bytes - XCTAssert(encapsulatedKey.encapsulated == katTest.ek) - XCTAssert(encapsulatedKey.sharedSecret == katTest.k) - - let retrievedSharedSecret = try privateKey.decapsulate(encapsulatedKey.encapsulated) - XCTAssert(retrievedSharedSecret.dataRepresentation == katTest.k) - } - #endif } func test1024KAT() throws { - #if CRYPTO_IN_SWIFTPM // No support for encapsulateWithSeed in BoringSSL. throw XCTSkip() - #else - let katTests = try processKATFile(filename:"MLKEM1024KAT") - for katTest in katTests { - let rndGen = try Drbg(katTest.rngSeed) - - var keyGenSeed = Data(count: 64) - try keyGenSeed.withUnsafeMutableBytes { buffer in - try buffer.initializeWithRandomBytes(count: buffer.count, rngState: rndGen) - } - var encapSeed = Data(count: 32) - try encapSeed.withUnsafeMutableBytes { buffer in - try buffer.initializeWithRandomBytes(count: buffer.count, rngState: rndGen) - } - - let privateKey = try MLKEM1024.PrivateKey.generateWithSeed(keyGenSeed) - XCTAssert(privateKey.publicKey.rawRepresentation == katTest.pk) - - let encapsulatedKey = try privateKey.publicKey.encapsulateWithSeed(encapSeed: encapSeed) - XCTAssert(encapsulatedKey.encapsulated == katTest.ek) - XCTAssert(encapsulatedKey.sharedSecret == katTest.k) - - let retrievedSharedSecret = try privateKey.decapsulate(encapsulatedKey.encapsulated) - XCTAssert(retrievedSharedSecret.dataRepresentation == katTest.k) - } - #endif } } @@ -157,4 +135,4 @@ struct MLKEMKAT { } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/KEM/XWingTests.swift b/Tests/CryptoTests/KEM/XWingTests.swift index e55c8c39..f7255f79 100644 --- a/Tests/CryptoTests/KEM/XWingTests.swift +++ b/Tests/CryptoTests/KEM/XWingTests.swift @@ -11,17 +11,30 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif final class XWingTests: XCTestCase { + /// Decapsulates with the regular private key and also with a one-time private key built from the + /// same key material, asserting that both paths recover the same shared secret. Returns the shared + /// secret so callers can run their own assertions (e.g. against a known-answer value), guaranteeing + /// the one-time and regular decapsulation functions are tested identically everywhere. + private func decapsulate( + with privateKey: XWingMLKEM768X25519.PrivateKey, + _ encapsulated: Data, + file: StaticString = #filePath, + line: UInt = #line + ) throws -> SymmetricKey { + let sharedSecret = try privateKey.decapsulate(encapsulated) + let oneTimeSharedSecret = try XWingMLKEM768X25519.OneTimePrivateKey(reusingForTestingOnly: privateKey).decapsulate(encapsulated) + XCTAssertEqual(sharedSecret, oneTimeSharedSecret, "one-time decapsulation diverged from regular decapsulation", file: file, line: line) + return sharedSecret + } + func testKEM() throws { let privateKey = try XWingMLKEM768X25519.PrivateKey.generate() @@ -33,17 +46,13 @@ final class XWingTests: XCTestCase { try XCTAssert(privateKey.integrityCheckedRepresentation == XWingMLKEM768X25519.PrivateKey(integrityCheckedRepresentation: privateKey.integrityCheckedRepresentation).integrityCheckedRepresentation) let er = try privateKey.publicKey.encapsulate() - let ss = try privateKey.decapsulate(er.encapsulated) + let ss = try decapsulate(with: privateKey, er.encapsulated) XCTAssert(er.sharedSecret == ss) } func processKATFile(filename: String) throws -> [XWingKAT] { - #if CRYPTO_IN_SWIFTPM let bundle = Bundle.module - #else - let bundle = Bundle(for: type(of: self)) - #endif let fileURL = bundle.url(forResource: filename, withExtension: "json") let json = try Data(contentsOf: fileURL!) let stringInput = String(data: json, encoding: .ascii)! @@ -62,7 +71,7 @@ final class XWingTests: XCTestCase { let encapsulatedKey = try privateKey.publicKey.encapsulateWithRng(rngState: encapDrbg) XCTAssertEqual(encapsulatedKey.encapsulated, katTest.ct) XCTAssertEqual(encapsulatedKey.sharedSecret.dataRepresentation, katTest.ss) - let retrievedSharedSecret = try privateKey.decapsulate(encapsulatedKey.encapsulated) + let retrievedSharedSecret = try decapsulate(with: privateKey, encapsulatedKey.encapsulated) XCTAssertEqual(retrievedSharedSecret.dataRepresentation, katTest.ss) } } @@ -97,8 +106,7 @@ final class XWingTests: XCTestCase { ciphersuite: ciphersuite, info: Data(), encapsulatedKey: corretlySizedKey - ), - error: CryptoKitError.underlyingCoreCryptoError(error: 0) + ) ) // Keys with the wrong size fail input validation. @@ -112,7 +120,6 @@ final class XWingTests: XCTestCase { info: Data(), encapsulatedKey: wronglySizedKey ), - error: CryptoKitError.incorrectParameterSize, "Unexpectedly returned from malformed decapsulation path for keySize \(keySize)" ) } @@ -147,4 +154,4 @@ struct XWingKAT { } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/Key Derivation/HKDFTests.swift b/Tests/CryptoTests/Key Derivation/HKDFTests.swift index a93b9506..09063c93 100644 --- a/Tests/CryptoTests/Key Derivation/HKDFTests.swift +++ b/Tests/CryptoTests/Key Derivation/HKDFTests.swift @@ -11,16 +11,13 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif // Test Vectors are coming from https://tools.ietf.org/html/rfc5869 class HKDFTests: XCTestCase { @@ -144,4 +141,4 @@ class HKDFTests: XCTestCase { } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/Key Derivation/SharedSecretTests.swift b/Tests/CryptoTests/Key Derivation/SharedSecretTests.swift index 910fade7..8dbc9755 100644 --- a/Tests/CryptoTests/Key Derivation/SharedSecretTests.swift +++ b/Tests/CryptoTests/Key Derivation/SharedSecretTests.swift @@ -11,16 +11,13 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif class SharedSecretTests: XCTestCase { func testEqualityWithDataProtocol() throws { @@ -34,4 +31,4 @@ class SharedSecretTests: XCTestCase { } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/Key Derivation/X963KDFTests.swift b/Tests/CryptoTests/Key Derivation/X963KDFTests.swift index 3a335cb3..67076188 100644 --- a/Tests/CryptoTests/Key Derivation/X963KDFTests.swift +++ b/Tests/CryptoTests/Key Derivation/X963KDFTests.swift @@ -11,16 +11,13 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif // Test Vectors are coming from ANSI X9.63-2001. class X963KDFTests: XCTestCase { @@ -91,4 +88,4 @@ class X963KDFTests: XCTestCase { } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/Key Wrapping/KeyWrapping.swift b/Tests/CryptoTests/Key Wrapping/KeyWrapping.swift index 8bf166c8..079ca98a 100644 --- a/Tests/CryptoTests/Key Wrapping/KeyWrapping.swift +++ b/Tests/CryptoTests/Key Wrapping/KeyWrapping.swift @@ -11,16 +11,13 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif class KeyWrappingTests: XCTestCase { func testAESWrapTestVectors() throws { @@ -95,4 +92,4 @@ class KeyWrappingTests: XCTestCase { } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/MAC/HMACTests.swift b/Tests/CryptoTests/MAC/HMACTests.swift index df36bb11..5343266c 100644 --- a/Tests/CryptoTests/MAC/HMACTests.swift +++ b/Tests/CryptoTests/MAC/HMACTests.swift @@ -11,16 +11,13 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif // Test Vectors are coming from https://tools.ietf.org/html/rfc4231 class HMACTests: XCTestCase { @@ -233,4 +230,4 @@ class HMACTests: XCTestCase { XCTAssertFalse(mac == DispatchData.empty) } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/SecureBytes/SecureBytesTests.swift b/Tests/CryptoTests/SecureBytes/SecureBytesTests.swift index 5be78cb3..04cbfe6e 100644 --- a/Tests/CryptoTests/SecureBytes/SecureBytesTests.swift +++ b/Tests/CryptoTests/SecureBytes/SecureBytesTests.swift @@ -11,16 +11,13 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif final class SecureBytesTests: XCTestCase { func testBasicSoundness() { @@ -148,6 +145,8 @@ final class SecureBytesTests: XCTestCase { base.withUnsafeBytes { XCTAssertEqual($0.count, 10) } base.withUnsafeMutableBytes { XCTAssertEqual($0.count, 10) } base.backing._withVeryUnsafeMutableBytes { XCTAssertGreaterThanOrEqual($0.count, 16) } + XCTAssertEqual(base.bytes.byteCount, 10) + XCTAssertEqual(base.mutableBytes.byteCount, 10) } func testTheresOnlyOneRegion() { @@ -179,7 +178,7 @@ final class SecureBytesTests: XCTestCase { var base = SecureBytes(repeating: 0, count: 10) let copy = base - base.append("Hello, world".utf8) + base.append(Array("Hello, world".utf8).span.bytes) XCTAssertEqual(base.count, 22) XCTAssertEqual(copy.count, 10) @@ -202,7 +201,7 @@ final class SecureBytesTests: XCTestCase { let copy = Data(base) XCTAssertEqual(base.count, copy.count) - base.append("Hello, world".utf8) + base.append(Array("Hello, world".utf8).span.bytes) XCTAssertEqual(base.count, 22) XCTAssertEqual(copy.count, 10) @@ -213,11 +212,11 @@ final class SecureBytesTests: XCTestCase { let copy = Data(base.prefix(5)) XCTAssertEqual(Array(copy), [0, 1, 2, 3, 4]) - base.append("Hello, world".utf8) + base.append(Array("Hello, world".utf8).span.bytes) XCTAssertEqual(base.count, 22) XCTAssertEqual(Array(copy), [0, 1, 2, 3, 4]) } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/Signatures/ECDSA/ECDSASignatureTests.swift b/Tests/CryptoTests/Signatures/ECDSA/ECDSASignatureTests.swift index fc72e4c5..4f8d1cda 100644 --- a/Tests/CryptoTests/Signatures/ECDSA/ECDSASignatureTests.swift +++ b/Tests/CryptoTests/Signatures/ECDSA/ECDSASignatureTests.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -18,14 +19,10 @@ import Foundation #endif import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif struct ECDSATestGroup: Codable { let tests: [SignatureTestVector] @@ -390,4 +387,4 @@ class SignatureTests: XCTestCase { } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/Signatures/ECDSA/RawECDSASignaturesTests.swift b/Tests/CryptoTests/Signatures/ECDSA/RawECDSASignaturesTests.swift index a085be4e..1947978f 100644 --- a/Tests/CryptoTests/Signatures/ECDSA/RawECDSASignaturesTests.swift +++ b/Tests/CryptoTests/Signatures/ECDSA/RawECDSASignaturesTests.swift @@ -11,16 +11,13 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif typealias TestVector = (publicKey: Data, privateKey: Data, rs: rAndS) typealias rAndS = (r: Data, s: Data) @@ -86,4 +83,4 @@ class RawECDSASignaturesTests: XCTestCase { try orFail { try testForCurve(curve: P521.Signing.self) } } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/Signatures/EdDSA/Ed25519-Runner.swift b/Tests/CryptoTests/Signatures/EdDSA/Ed25519-Runner.swift index c025e04c..64c36cbe 100644 --- a/Tests/CryptoTests/Signatures/EdDSA/Ed25519-Runner.swift +++ b/Tests/CryptoTests/Signatures/EdDSA/Ed25519-Runner.swift @@ -11,15 +11,14 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -import Crypto -#elseif !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -import CryptoKit +import XCTest +#if canImport(CryptoKit) +// Skip tests that require @testable imports of CryptoKit. #else -import Crypto -#endif +@testable import Crypto struct Ed25519TestGroup: Codable { let tests: [Ed25519TestVector] @@ -57,9 +56,7 @@ class Ed25519Tests: XCTestCase { let signatureOnContiguous = try orFail { try privateKey.signature(for: someContiguousData) } let signatureOnDiscontiguous = try orFail { try privateKey.signature(for: someDiscontiguousData) } - #if !canImport(Darwin) XCTAssertEqual(signatureOnContiguous, signatureOnDiscontiguous) - #endif // This tests the 4 combinations. let (contiguousSignature, discontiguousSignature) = Array(signatureOnContiguous).asDataProtocols() @@ -140,3 +137,5 @@ class Ed25519Tests: XCTestCase { } } } + +#endif diff --git a/Tests/CryptoTests/Signatures/MLDSA/MLDSAKeyGenTests.swift b/Tests/CryptoTests/Signatures/MLDSA/MLDSAKeyGenTests.swift index 6d0add31..a14aa4bd 100644 --- a/Tests/CryptoTests/Signatures/MLDSA/MLDSAKeyGenTests.swift +++ b/Tests/CryptoTests/Signatures/MLDSA/MLDSAKeyGenTests.swift @@ -11,23 +11,16 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif final class MLDSAKeyGenTests: XCTestCase { func processKeyGenKATFile(filename: String) throws -> [MLDSAKeyGenKAT] { - #if CRYPTO_IN_SWIFTPM let bundle = Bundle.module - #else - let bundle = Bundle(for: type(of: self)) - #endif let fileURL = bundle.url(forResource: filename, withExtension: "json") let json = try Data(contentsOf: fileURL!) let stringInput = String(data: json, encoding: .ascii)! @@ -97,4 +90,4 @@ struct MLDSAKeyGenKAT { } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/Signatures/MLDSA/MLDSATests.swift b/Tests/CryptoTests/Signatures/MLDSA/MLDSATests.swift index 443981da..c6a3bd52 100644 --- a/Tests/CryptoTests/Signatures/MLDSA/MLDSATests.swift +++ b/Tests/CryptoTests/Signatures/MLDSA/MLDSATests.swift @@ -11,15 +11,12 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) // Skip tests that require @testable imports of CryptoKit. #else -#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API -@testable import CryptoKit -#else @testable import Crypto -#endif final class MLDSATests: XCTestCase { func testMLDSA65() throws { @@ -81,4 +78,4 @@ final class MLDSATests: XCTestCase { } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/SymmetricKeyTests/SymmetricKeyTests.swift b/Tests/CryptoTests/SymmetricKeyTests/SymmetricKeyTests.swift new file mode 100644 index 00000000..6db318e5 --- /dev/null +++ b/Tests/CryptoTests/SymmetricKeyTests/SymmetricKeyTests.swift @@ -0,0 +1,50 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +import XCTest + +#if canImport(CryptoKit) +// Skip tests that require @testable imports of CryptoKit. +#else +@testable import Crypto + +class SymmetricKeyTests: XCTestCase { + func testBytesZeroing() throws { + var myData: [UInt8] = [1, 2, 3, 4, 5, 6, 7, 8] + + let simpleKey = myData.withUnsafeBytes { buffer in + SymmetricKey(data: buffer) + } + + do { + var span = myData.mutableSpan + var rawSpan = span.mutableBytes + let key = SymmetricKey(copyingWithZeroing: &rawSpan) + assert(key.bytes == simpleKey.bytes) + } + + assert(myData == [0, 0, 0, 0, 0, 0, 0, 0]) + } +} + +extension RawSpan { + static func ==(lhs: RawSpan, rhs: RawSpan) -> Bool { + lhs.withUnsafeBytes { lhsBuffer in + rhs.withUnsafeBytes { rhsBuffer in + lhsBuffer.elementsEqual(rhsBuffer) + } + } + } +} +#endif diff --git a/Tests/CryptoTests/Utils/Boring/CTRDRBG.swift b/Tests/CryptoTests/Utils/Boring/CTRDRBG.swift index aff625d8..8d7cfee1 100644 --- a/Tests/CryptoTests/Utils/Boring/CTRDRBG.swift +++ b/Tests/CryptoTests/Utils/Boring/CTRDRBG.swift @@ -11,7 +11,9 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) +@_exported import CryptoKit +#else #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -73,4 +75,4 @@ extension SymmetricKey { } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/Utils/Boring/SequenceDRBG.swift b/Tests/CryptoTests/Utils/Boring/SequenceDRBG.swift index 89c32f62..98e4df9d 100644 --- a/Tests/CryptoTests/Utils/Boring/SequenceDRBG.swift +++ b/Tests/CryptoTests/Utils/Boring/SequenceDRBG.swift @@ -11,7 +11,9 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTO_IN_SWIFTPM && CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +#if canImport(CryptoKit) +@_exported import CryptoKit +#else #if canImport(FoundationEssentials) import FoundationEssentials #else @@ -31,4 +33,4 @@ final class SequenceDrbg { var detRngPtr: Self { self } } -#endif // CRYPTO_IN_SWIFTPM +#endif // canImport(CryptoKit) diff --git a/Tests/CryptoTests/Utils/PrettyBytes.swift b/Tests/CryptoTests/Utils/PrettyBytes.swift index 8a8ef78c..97e8ba33 100644 --- a/Tests/CryptoTests/Utils/PrettyBytes.swift +++ b/Tests/CryptoTests/Utils/PrettyBytes.swift @@ -11,15 +11,12 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION -import SwiftSystem -#else + #if canImport(FoundationEssentials) import FoundationEssentials #else import Foundation #endif -#endif enum ByteHexEncodingErrors: Error { case incorrectHexValue @@ -70,7 +67,6 @@ extension RangeReplaceableCollection where Element == UInt8 { } } -#if !CRYPTOKIT_NO_ACCESS_TO_FOUNDATION extension Data { init(hexString: String) throws { self.init() @@ -109,4 +105,3 @@ extension Array where Element == UInt8 { } } -#endif diff --git a/Tests/CryptoTests/Utils/RFCVector.swift b/Tests/CryptoTests/Utils/RFCVector.swift index a4a7d77b..6bbe4aaf 100644 --- a/Tests/CryptoTests/Utils/RFCVector.swift +++ b/Tests/CryptoTests/Utils/RFCVector.swift @@ -11,7 +11,12 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + +#if canImport(FoundationEssentials) +import FoundationEssentials +#else import Foundation +#endif /// This is a not-very-performant decoder of the RFC formatted test vectors. /// @@ -25,14 +30,11 @@ struct RFCVectorDecoder { private var index: Int? init(bundleType: AnyObject, fileName: String) throws { - #if !CRYPTO_IN_SWIFTPM - let bundle = Bundle(for: type(of: bundleType)) - let fileURL = bundle.url(forResource: fileName, withExtension: "txt") - #else var fileURL: URL? = URL(fileURLWithPath: "\(#filePath)") 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) @@ -40,6 +42,9 @@ 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!) @@ -279,14 +284,14 @@ extension ArraySlice where Element == Substring { // or begin with whitespace (these are used in some cases and we don't want them). This is a brute // force comparison, but it's test code, don't worry about it. let elements: [(String, String)] = self[.. 0 && + return (string.trimmingWhitespace.count > 0 && !string.hasPrefix("#") && !string.hasPrefix("[") && !string.first!.isWhitespace) }.map { string in let split = string.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false) assert(split.count == 2) - return (String(split.first!.trimmingCharacters(in: .whitespaces)), String(split.last!).trimmingCharacters(in: .whitespaces)) + return (String(split.first!.trimmingWhitespace), String(split.last!).trimmingWhitespace) } // Slice off the section we've parsed. @@ -301,3 +306,16 @@ extension ArraySlice where Element == Substring { } } } + +fileprivate extension StringProtocol { + /// Returns the string with leading and trailing whitespace removed. + var trimmingWhitespace: String { self.trimming { $0.isWhitespace } } + + /// Returns a new string by removing leading and trailing characters + /// that satisfy the given predicate. + func trimming(while predicate: (Character) -> Bool) -> String { + guard let start = self.firstIndex(where: { !predicate($0) }) else { return "" } + let end = self.lastIndex(where: { !predicate($0) })! + return String(self[start...end]) + } +} diff --git a/Tests/CryptoTests/Utils/SplitData.swift b/Tests/CryptoTests/Utils/SplitData.swift index 37283d85..d4e72f5e 100644 --- a/Tests/CryptoTests/Utils/SplitData.swift +++ b/Tests/CryptoTests/Utils/SplitData.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + #if canImport(FoundationEssentials) import FoundationEssentials #else diff --git a/Tests/CryptoTests/Utils/Wycheproof.swift b/Tests/CryptoTests/Utils/Wycheproof.swift index 6bd9f5f3..a4bb46cd 100644 --- a/Tests/CryptoTests/Utils/Wycheproof.swift +++ b/Tests/CryptoTests/Utils/Wycheproof.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest struct WycheproofTest: Codable { @@ -21,14 +22,11 @@ struct WycheproofTest: Codable { extension XCTestCase { func wycheproofTest(bundleType: AnyObject, jsonName: String, file: StaticString = #filePath, line: UInt = #line, testFunction: (T) throws -> Void) throws { - #if !CRYPTO_IN_SWIFTPM - let bundle = Bundle(for: type(of: bundleType)) - let fileURL = bundle.url(forResource: jsonName, withExtension: "json") - #else var fileURL = URL(fileURLWithPath: "\(#filePath)") 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) @@ -36,6 +34,9 @@ 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)) } diff --git a/Tests/CryptoTests/Utils/XCTestUtils.swift b/Tests/CryptoTests/Utils/XCTestUtils.swift index 87e8dbe6..79922111 100644 --- a/Tests/CryptoTests/Utils/XCTestUtils.swift +++ b/Tests/CryptoTests/Utils/XCTestUtils.swift @@ -11,8 +11,8 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import XCTest -import Crypto // Xcode 11.4 catches errors thrown during tests and reports them on the // correct line. But Linux and older Xcodes do not, so we need to use this