Catch-up merge main into wwdc25 branch (#403)

Co-authored-by: YourMJK <37852512+YourMJK@users.noreply.github.com>
Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
Co-authored-by: Raphael <josephnoir@users.noreply.github.com>
Co-authored-by: Si Beaumont <beaumont@apple.com>
Co-authored-by: Evan Wilde <ewilde@apple.com>
Co-authored-by: Tim Condon <0xTim@users.noreply.github.com>
Co-authored-by: Gus Cairo <gus.cairo@apple.com>
Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Fabrice de Gans <Steelskin@users.noreply.github.com>
Co-authored-by: Wojciech Nagrodzki <278594+wnagrodzki@users.noreply.github.com>
Co-authored-by: Jesse L. Zamora <xtremekforever@gmail.com>
Co-authored-by: aryan-25 <aryan_shah@apple.com>
This commit is contained in:
58 files changed
+5547 -766

No files matched your search

+2 -2
View File
@@ -9,7 +9,7 @@ _[One line description of your change]_
- [ ] I've updated the documentation if necessary
#### If you've made changes to `gyb` files
- [ ] I've run `.script/generate_boilerplate_files_with_gyb` and included updated generated files in a commit of this pull request
- [ ] I've run `./scripts/generate_boilerplate_files_with_gyb.sh` and included updated generated files in a commit of this pull request
### Motivation:
@@ -21,4 +21,4 @@ _[Describe the modifications you've done.]_
### Result:
_[After your change, what will change.]_
_[After your change, what will change.]_
+21
View File
@@ -16,11 +16,32 @@ jobs:
linux_6_1_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_0_enabled: true
windows_6_1_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
windows_6_0_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_1_arguments_override: "--explicit-target-dependency-import-check error"
windows_nightly_next_arguments_override: "--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_0_enabled: true
windows_6_1_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
cxx-interop:
name: Cxx interop
uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main
static-sdk:
name: Static SDK
uses: apple/swift-nio/.github/workflows/static_sdk.yml@main
macos-tests:
name: macOS tests
uses: apple/swift-nio/.github/workflows/macos_tests.yml@main
+13
View File
@@ -30,6 +30,15 @@ jobs:
windows_nightly_next_arguments_override: "--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_0_enabled: true
windows_6_1_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
cxx-interop:
name: Cxx interop
uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main
@@ -58,3 +67,7 @@ jobs:
with:
runner_pool: general
build_scheme: swift-crypto-Package
static-sdk:
name: Static SDK
uses: apple/swift-nio/.github/workflows/static_sdk.yml@main
-1
View File
@@ -100,7 +100,6 @@ Sources/_CryptoExtras/OPRFs/VOPRFClient.swift
Sources/_CryptoExtras/OPRFs/VOPRFServer.swift
Sources/_CryptoExtras/RSA/RSA+BlindSigning.swift
Sources/_CryptoExtras/RSA/RSA.swift
Sources/_CryptoExtras/RSA/RSA_security.swift
Sources/_CryptoExtras/Util/BoringSSLHelpers.swift
Sources/_CryptoExtras/Util/DigestType.swift
Sources/_CryptoExtras/Util/Error.swift
+104
View File
@@ -24,6 +24,65 @@ import Foundation
let benchmarks = {
let defaultMetrics: [BenchmarkMetric] = [.mallocCountTotal, .cpuTotal]
Benchmark(
"arc-issue-p256",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .kilo,
maxDuration: .seconds(10_000_000),
maxIterations: 3
)
) { benchmark in
let privateKey = P256._ARCV1.PrivateKey()
let publicKey = privateKey.publicKey
let requestContext = Data("shared request context".utf8)
let precredential = try publicKey.prepareCredentialRequest(requestContext: requestContext)
let credentialRequest = precredential.credentialRequest
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(try privateKey.issue(credentialRequest))
}
}
Benchmark(
"arc-verify-p256",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .kilo,
maxDuration: .seconds(10_000_000),
maxIterations: 10
)
) { benchmark in
let privateKey = P256._ARCV1.PrivateKey()
let publicKey = privateKey.publicKey
let requestContext = Data("shared request context".utf8)
let (presentationContext, presentationLimit) = (Data("shared presentation context".utf8), 2)
let precredential = try publicKey.prepareCredentialRequest(requestContext: requestContext)
let credentialRequest = precredential.credentialRequest
let credentialResponse = try privateKey.issue(credentialRequest)
var credential = try publicKey.finalize(credentialResponse, for: precredential)
let (presentation, nonce) = try credential.makePresentation(
context: presentationContext,
presentationLimit: presentationLimit
)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(
try privateKey.verify(
presentation,
requestContext: requestContext,
presentationContext: presentationContext,
presentationLimit: presentationLimit,
nonce: nonce
)
)
}
}
Benchmark(
"arc-issue-p384",
configuration: Benchmark.Configuration(
@@ -104,4 +163,49 @@ let benchmarks = {
blackHole(try privateKey.evaluate(blindedElement))
}
}
Benchmark(
"key-exchange-p256",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .kilo,
maxDuration: .seconds(10_000_000),
maxIterations: 10
)
) { benchmark in
for _ in benchmark.scaledIterations {
let (key1, key2) = (P256.KeyAgreement.PrivateKey(), P256.KeyAgreement.PrivateKey())
blackHole(try key1.sharedSecretFromKeyAgreement(with: key2.publicKey))
}
}
Benchmark(
"key-exchange-p384",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .kilo,
maxDuration: .seconds(10_000_000),
maxIterations: 10
)
) { benchmark in
for _ in benchmark.scaledIterations {
let (key1, key2) = (P384.KeyAgreement.PrivateKey(), P384.KeyAgreement.PrivateKey())
blackHole(try key1.sharedSecretFromKeyAgreement(with: key2.publicKey))
}
}
Benchmark(
"key-exchange-p521",
configuration: Benchmark.Configuration(
metrics: defaultMetrics,
scalingFactor: .kilo,
maxDuration: .seconds(10_000_000),
maxIterations: 10
)
) { benchmark in
for _ in benchmark.scaledIterations {
let (key1, key2) = (P521.KeyAgreement.PrivateKey(), P521.KeyAgreement.PrivateKey())
blackHole(try key1.sharedSecretFromKeyAgreement(with: key2.publicKey))
}
}
}
+16
View File
@@ -14,6 +14,10 @@
cmake_minimum_required(VERSION 3.15.1)
if(POLICY CMP0157)
cmake_policy(SET CMP0157 NEW)
endif()
project(SwiftCrypto
LANGUAGES ASM C CXX Swift)
@@ -47,6 +51,18 @@ if(CMAKE_SYSTEM_NAME STREQUAL Darwin AND NOT CMAKE_CROSSCOMPILING)
set(CMAKE_RANLIB "/usr/bin/ranlib")
endif()
set(CMAKE_CXX_STANDARD 17)
if(CMAKE_SYSTEM_NAME STREQUAL Windows)
# We need to ensure that we don't include the min/max macros from the Windows SDK.
add_compile_definitions(NOMINMAX)
# We can only link against the DLL version of the MSVC runtime library for now.
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreadedDLL")
if(CMAKE_Swift_COMPILER_VERSION VERSION_EQUAL 0.0.0 OR CMAKE_Swift_COMPILER_VERSION VERSION_GREATER_EQUAL 6.2)
# We need to set the static library prefix to "lib" so that we can link against the static libraries.
set(CMAKE_STATIC_LIBRARY_PREFIX_Swift "lib")
endif()
endif()
if(NOT CMAKE_SYSTEM_NAME STREQUAL Darwin)
find_package(dispatch CONFIG)
find_package(Foundation CONFIG)
+1 -1
View File
@@ -34,7 +34,7 @@ This product contains test vectors from Google's wycheproof project.
---
This product contains a derivation of various scripts from SwiftNIO.
This product contains a derivation of various files from SwiftNIO.
* LICENSE (Apache License 2.0):
* https://www.apache.org/licenses/LICENSE-2.0
-1
View File
@@ -102,7 +102,6 @@ let package = Package(
name: "CCryptoBoringSSL",
exclude: privacyManifestExclude + [
"hash.txt",
"include/boringssl_prefix_symbols_nasm.inc",
"CMakeLists.txt",
/*
* These files are excluded to support WASI libc which doesn't provide <netdb.h>.
+3 -3
View File
@@ -1,6 +1,6 @@
# Swift Crypto
Swift Crypto is an open-source implementation of a substantial portion of the API of [Apple CryptoKit](https://developer.apple.com/documentation/cryptokit) suitable for use on Linux platforms. It enables cross-platform or server applications with the advantages of CryptoKit.
Swift Crypto is an open-source implementation of a substantial portion of the API of [Apple CryptoKit](https://developer.apple.com/documentation/cryptokit) suitable for use on Linux and ARM64 Windows platforms. It enables cross-platform or server applications with the advantages of CryptoKit.
## Using Swift Crypto
@@ -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, Swift Crypto builds substantially more code. In particular, we build:
When building Swift Crypto for use on Linux or Windows, Swift Crypto builds substantially more code. In particular, we build:
1. A vendored copy of BoringSSL's libcrypto.
2. The common API of Swift Crypto and CryptoKit.
@@ -129,7 +129,7 @@ What this means for you is that you should depend on Swift Crypto with a version
In SwiftPM that can be easily done specifying for example `from: "1.0.0"` meaning that you support Swift Crypto in every version starting from 1.0.0 up to (excluding) 2.0.0.
SemVer and Swift Crypto's Public API guarantees should result in a working program without having to worry about testing every single version for compatibility.
Swift Crypto 2.0.0 was released in September 2021. The only breaking change between Swift Crypto 2.0.0 and 1.0.0 was the addition of new cases in the `CryptoKitError` enumeration. For most users, then, it's safe to depend on either the 1.0.0 _or_ 2.0.0 series of releases.
Swift Crypto 2.0.0 was released in September 2021. The only breaking change between Swift Crypto 2.0.0 and 1.0.0 was the addition of new cases in the `CryptoError` enumeration. For most users, then, it's safe to depend on either the 1.0.0 _or_ 2.0.0 series of releases.
To do so, please use the following dependency in your `Package.swift`:
+20 -1
View File
@@ -342,8 +342,27 @@ elseif(CMAKE_SYSTEM_NAME MATCHES "Linux|Android|FreeBSD|OpenBSD" AND CMAKE_SYSTE
gen/bcm/vpaes-armv8-linux.S
gen/crypto/chacha-armv8-linux.S
gen/crypto/chacha20_poly1305_armv8-linux.S)
elseif(CMAKE_SYSTEM_NAME MATCHES "Windows" AND CMAKE_SYSTEM_PROCESSOR MATCHES "AMD64|amd64|x86_64")
target_sources(CCryptoBoringSSL PRIVATE
)
elseif(CMAKE_SYSTEM_NAME MATCHES "Windows" AND CMAKE_SYSTEM_PROCESSOR MATCHES "ARM64|arm64|aarch64")
target_sources(CCryptoBoringSSL PRIVATE
gen/bcm/aesv8-armv8-win.S
gen/bcm/aesv8-gcm-armv8-win.S
gen/bcm/armv8-mont-win.S
gen/bcm/bn-armv8-win.S
gen/bcm/ghash-neon-armv8-win.S
gen/bcm/ghashv8-armv8-win.S
gen/bcm/p256-armv8-asm-win.S
gen/bcm/p256_beeu-armv8-asm-win.S
gen/bcm/sha1-armv8-win.S
gen/bcm/sha256-armv8-win.S
gen/bcm/sha512-armv8-win.S
gen/bcm/vpaes-armv8-win.S
gen/crypto/chacha-armv8-win.S
gen/crypto/chacha20_poly1305_armv8-win.S)
else()
message(FATAL_ERROR "platform sources are not defined here")
message(FATAL_ERROR "platform sources are not defined here for ${CMAKE_SYSTEM_NAME} on ${CMAKE_SYSTEM_PROCESSOR}")
endif()
target_include_directories(CCryptoBoringSSL PUBLIC
@@ -640,6 +640,8 @@
#define bn_mul4x_mont_capable BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, bn_mul4x_mont_capable)
#define bn_mul4x_mont_gather5 BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, bn_mul4x_mont_gather5)
#define bn_mul4x_mont_gather5_capable BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, bn_mul4x_mont_gather5_capable)
#define bn_mul8x_mont_neon BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, bn_mul8x_mont_neon)
#define bn_mul8x_mont_neon_capable BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, bn_mul8x_mont_neon_capable)
#define bn_mulx_adx_capable BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, bn_mulx_adx_capable)
#define bn_mulx4x_mont BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, bn_mulx4x_mont)
#define bn_mulx4x_mont_capable BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, bn_mulx4x_mont_capable)
@@ -735,6 +737,7 @@
#define boringssl_self_test_slhdsa BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, boringssl_self_test_slhdsa)
#define bsaes_capable BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, bsaes_capable)
#define bsaes_cbc_encrypt BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, bsaes_cbc_encrypt)
#define bsaes_ctr32_encrypt_blocks BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, bsaes_ctr32_encrypt_blocks)
#define BUF_MEM_append BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, BUF_MEM_append)
#define BUF_MEM_free BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, BUF_MEM_free)
#define BUF_MEM_grow BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, BUF_MEM_grow)
@@ -931,6 +934,7 @@
#define CRYPTO_get_thread_local BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_get_thread_local)
#define CRYPTO_ghash_init BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_ghash_init)
#define CRYPTO_has_asm BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_has_asm)
#define CRYPTO_has_broken_NEON BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_has_broken_NEON)
#define CRYPTO_hchacha20 BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_hchacha20)
#define CRYPTO_init_sysrand BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_init_sysrand)
#define CRYPTO_is_ADX_capable BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_is_ADX_capable)
@@ -967,13 +971,17 @@
#define CRYPTO_MUTEX_lock_write BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_MUTEX_lock_write)
#define CRYPTO_MUTEX_unlock_read BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_MUTEX_unlock_read)
#define CRYPTO_MUTEX_unlock_write BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_MUTEX_unlock_write)
#define CRYPTO_needs_hwcap2_workaround BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_needs_hwcap2_workaround)
#define CRYPTO_new_ex_data BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_new_ex_data)
#define CRYPTO_num_locks BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_num_locks)
#define CRYPTO_ofb128_encrypt BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_ofb128_encrypt)
#define CRYPTO_once BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_once)
#define CRYPTO_poly1305_finish BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_poly1305_finish)
#define CRYPTO_poly1305_finish_neon BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_poly1305_finish_neon)
#define CRYPTO_poly1305_init BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_poly1305_init)
#define CRYPTO_poly1305_init_neon BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_poly1305_init_neon)
#define CRYPTO_poly1305_update BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_poly1305_update)
#define CRYPTO_poly1305_update_neon BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_poly1305_update_neon)
#define CRYPTO_pre_sandbox_init BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_pre_sandbox_init)
#define CRYPTO_rdrand BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_rdrand)
#define CRYPTO_rdrand_multiple8_buf BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, CRYPTO_rdrand_multiple8_buf)
@@ -2240,6 +2248,8 @@
#define OPENSSL_malloc_init BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, OPENSSL_malloc_init)
#define OPENSSL_memdup BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, OPENSSL_memdup)
#define OPENSSL_no_config BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, OPENSSL_no_config)
#define openssl_poly1305_neon2_addmulmod BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, openssl_poly1305_neon2_addmulmod)
#define openssl_poly1305_neon2_blocks BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, openssl_poly1305_neon2_blocks)
#define OPENSSL_posix_to_tm BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, OPENSSL_posix_to_tm)
#define OPENSSL_realloc BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, OPENSSL_realloc)
#define OPENSSL_secure_clear_free BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, OPENSSL_secure_clear_free)
@@ -2578,6 +2588,7 @@
#define sha1_block_data_order_avx BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha1_block_data_order_avx)
#define sha1_block_data_order_avx2 BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha1_block_data_order_avx2)
#define sha1_block_data_order_hw BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha1_block_data_order_hw)
#define sha1_block_data_order_neon BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha1_block_data_order_neon)
#define sha1_block_data_order_nohw BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha1_block_data_order_nohw)
#define sha1_block_data_order_ssse3 BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha1_block_data_order_ssse3)
#define SHA1_Final BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, SHA1_Final)
@@ -2594,6 +2605,7 @@
#define sha256_avx_capable BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha256_avx_capable)
#define sha256_block_data_order_avx BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha256_block_data_order_avx)
#define sha256_block_data_order_hw BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha256_block_data_order_hw)
#define sha256_block_data_order_neon BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha256_block_data_order_neon)
#define sha256_block_data_order_nohw BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha256_block_data_order_nohw)
#define sha256_block_data_order_ssse3 BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha256_block_data_order_ssse3)
#define SHA256_Final BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, SHA256_Final)
@@ -2615,6 +2627,7 @@
#define sha512_avx_capable BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha512_avx_capable)
#define sha512_block_data_order_avx BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha512_block_data_order_avx)
#define sha512_block_data_order_hw BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha512_block_data_order_hw)
#define sha512_block_data_order_neon BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha512_block_data_order_neon)
#define sha512_block_data_order_nohw BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha512_block_data_order_nohw)
#define SHA512_Final BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, SHA512_Final)
#define sha512_hw_capable BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, sha512_hw_capable)
@@ -2955,9 +2968,11 @@
#define vpaes_capable BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, vpaes_capable)
#define vpaes_cbc_encrypt BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, vpaes_cbc_encrypt)
#define vpaes_ctr32_encrypt_blocks BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, vpaes_ctr32_encrypt_blocks)
#define vpaes_ctr32_encrypt_blocks_with_bsaes BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, vpaes_ctr32_encrypt_blocks_with_bsaes)
#define vpaes_decrypt BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, vpaes_decrypt)
#define vpaes_decrypt_key_to_bsaes BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, vpaes_decrypt_key_to_bsaes)
#define vpaes_encrypt BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, vpaes_encrypt)
#define vpaes_encrypt_key_to_bsaes BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, vpaes_encrypt_key_to_bsaes)
#define vpaes_set_decrypt_key BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, vpaes_set_decrypt_key)
#define vpaes_set_encrypt_key BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, vpaes_set_encrypt_key)
#define X25519 BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X25519)
@@ -2974,6 +2989,7 @@
#define x25519_ge_sub BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, x25519_ge_sub)
#define x25519_ge_tobytes BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, x25519_ge_tobytes)
#define X25519_keypair BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X25519_keypair)
#define x25519_NEON BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, x25519_NEON)
#define x25519_pkey_meth BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, x25519_pkey_meth)
#define X25519_public_from_private BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X25519_public_from_private)
#define x25519_sc_reduce BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, x25519_sc_reduce)
@@ -645,6 +645,8 @@
#define _bn_mul4x_mont_capable BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, bn_mul4x_mont_capable)
#define _bn_mul4x_mont_gather5 BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, bn_mul4x_mont_gather5)
#define _bn_mul4x_mont_gather5_capable BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, bn_mul4x_mont_gather5_capable)
#define _bn_mul8x_mont_neon BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, bn_mul8x_mont_neon)
#define _bn_mul8x_mont_neon_capable BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, bn_mul8x_mont_neon_capable)
#define _bn_mulx_adx_capable BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, bn_mulx_adx_capable)
#define _bn_mulx4x_mont BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, bn_mulx4x_mont)
#define _bn_mulx4x_mont_capable BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, bn_mulx4x_mont_capable)
@@ -740,6 +742,7 @@
#define _boringssl_self_test_slhdsa BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, boringssl_self_test_slhdsa)
#define _bsaes_capable BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, bsaes_capable)
#define _bsaes_cbc_encrypt BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, bsaes_cbc_encrypt)
#define _bsaes_ctr32_encrypt_blocks BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, bsaes_ctr32_encrypt_blocks)
#define _BUF_MEM_append BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, BUF_MEM_append)
#define _BUF_MEM_free BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, BUF_MEM_free)
#define _BUF_MEM_grow BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, BUF_MEM_grow)
@@ -936,6 +939,7 @@
#define _CRYPTO_get_thread_local BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_get_thread_local)
#define _CRYPTO_ghash_init BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_ghash_init)
#define _CRYPTO_has_asm BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_has_asm)
#define _CRYPTO_has_broken_NEON BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_has_broken_NEON)
#define _CRYPTO_hchacha20 BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_hchacha20)
#define _CRYPTO_init_sysrand BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_init_sysrand)
#define _CRYPTO_is_ADX_capable BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_is_ADX_capable)
@@ -972,13 +976,17 @@
#define _CRYPTO_MUTEX_lock_write BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_MUTEX_lock_write)
#define _CRYPTO_MUTEX_unlock_read BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_MUTEX_unlock_read)
#define _CRYPTO_MUTEX_unlock_write BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_MUTEX_unlock_write)
#define _CRYPTO_needs_hwcap2_workaround BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_needs_hwcap2_workaround)
#define _CRYPTO_new_ex_data BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_new_ex_data)
#define _CRYPTO_num_locks BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_num_locks)
#define _CRYPTO_ofb128_encrypt BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_ofb128_encrypt)
#define _CRYPTO_once BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_once)
#define _CRYPTO_poly1305_finish BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_poly1305_finish)
#define _CRYPTO_poly1305_finish_neon BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_poly1305_finish_neon)
#define _CRYPTO_poly1305_init BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_poly1305_init)
#define _CRYPTO_poly1305_init_neon BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_poly1305_init_neon)
#define _CRYPTO_poly1305_update BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_poly1305_update)
#define _CRYPTO_poly1305_update_neon BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_poly1305_update_neon)
#define _CRYPTO_pre_sandbox_init BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_pre_sandbox_init)
#define _CRYPTO_rdrand BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_rdrand)
#define _CRYPTO_rdrand_multiple8_buf BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, CRYPTO_rdrand_multiple8_buf)
@@ -2245,6 +2253,8 @@
#define _OPENSSL_malloc_init BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, OPENSSL_malloc_init)
#define _OPENSSL_memdup BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, OPENSSL_memdup)
#define _OPENSSL_no_config BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, OPENSSL_no_config)
#define _openssl_poly1305_neon2_addmulmod BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, openssl_poly1305_neon2_addmulmod)
#define _openssl_poly1305_neon2_blocks BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, openssl_poly1305_neon2_blocks)
#define _OPENSSL_posix_to_tm BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, OPENSSL_posix_to_tm)
#define _OPENSSL_realloc BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, OPENSSL_realloc)
#define _OPENSSL_secure_clear_free BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, OPENSSL_secure_clear_free)
@@ -2583,6 +2593,7 @@
#define _sha1_block_data_order_avx BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha1_block_data_order_avx)
#define _sha1_block_data_order_avx2 BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha1_block_data_order_avx2)
#define _sha1_block_data_order_hw BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha1_block_data_order_hw)
#define _sha1_block_data_order_neon BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha1_block_data_order_neon)
#define _sha1_block_data_order_nohw BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha1_block_data_order_nohw)
#define _sha1_block_data_order_ssse3 BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha1_block_data_order_ssse3)
#define _SHA1_Final BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, SHA1_Final)
@@ -2599,6 +2610,7 @@
#define _sha256_avx_capable BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha256_avx_capable)
#define _sha256_block_data_order_avx BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha256_block_data_order_avx)
#define _sha256_block_data_order_hw BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha256_block_data_order_hw)
#define _sha256_block_data_order_neon BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha256_block_data_order_neon)
#define _sha256_block_data_order_nohw BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha256_block_data_order_nohw)
#define _sha256_block_data_order_ssse3 BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha256_block_data_order_ssse3)
#define _SHA256_Final BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, SHA256_Final)
@@ -2620,6 +2632,7 @@
#define _sha512_avx_capable BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha512_avx_capable)
#define _sha512_block_data_order_avx BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha512_block_data_order_avx)
#define _sha512_block_data_order_hw BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha512_block_data_order_hw)
#define _sha512_block_data_order_neon BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha512_block_data_order_neon)
#define _sha512_block_data_order_nohw BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha512_block_data_order_nohw)
#define _SHA512_Final BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, SHA512_Final)
#define _sha512_hw_capable BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, sha512_hw_capable)
@@ -2960,9 +2973,11 @@
#define _vpaes_capable BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, vpaes_capable)
#define _vpaes_cbc_encrypt BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, vpaes_cbc_encrypt)
#define _vpaes_ctr32_encrypt_blocks BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, vpaes_ctr32_encrypt_blocks)
#define _vpaes_ctr32_encrypt_blocks_with_bsaes BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, vpaes_ctr32_encrypt_blocks_with_bsaes)
#define _vpaes_decrypt BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, vpaes_decrypt)
#define _vpaes_decrypt_key_to_bsaes BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, vpaes_decrypt_key_to_bsaes)
#define _vpaes_encrypt BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, vpaes_encrypt)
#define _vpaes_encrypt_key_to_bsaes BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, vpaes_encrypt_key_to_bsaes)
#define _vpaes_set_decrypt_key BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, vpaes_set_decrypt_key)
#define _vpaes_set_encrypt_key BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, vpaes_set_encrypt_key)
#define _X25519 BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X25519)
@@ -2979,6 +2994,7 @@
#define _x25519_ge_sub BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, x25519_ge_sub)
#define _x25519_ge_tobytes BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, x25519_ge_tobytes)
#define _X25519_keypair BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X25519_keypair)
#define _x25519_NEON BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, x25519_NEON)
#define _x25519_pkey_meth BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, x25519_pkey_meth)
#define _X25519_public_from_private BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X25519_public_from_private)
#define _x25519_sc_reduce BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, x25519_sc_reduce)
@@ -637,6 +637,8 @@
%xdefine _bn_mul4x_mont_capable _ %+ BORINGSSL_PREFIX %+ _bn_mul4x_mont_capable
%xdefine _bn_mul4x_mont_gather5 _ %+ BORINGSSL_PREFIX %+ _bn_mul4x_mont_gather5
%xdefine _bn_mul4x_mont_gather5_capable _ %+ BORINGSSL_PREFIX %+ _bn_mul4x_mont_gather5_capable
%xdefine _bn_mul8x_mont_neon _ %+ BORINGSSL_PREFIX %+ _bn_mul8x_mont_neon
%xdefine _bn_mul8x_mont_neon_capable _ %+ BORINGSSL_PREFIX %+ _bn_mul8x_mont_neon_capable
%xdefine _bn_mulx_adx_capable _ %+ BORINGSSL_PREFIX %+ _bn_mulx_adx_capable
%xdefine _bn_mulx4x_mont _ %+ BORINGSSL_PREFIX %+ _bn_mulx4x_mont
%xdefine _bn_mulx4x_mont_capable _ %+ BORINGSSL_PREFIX %+ _bn_mulx4x_mont_capable
@@ -732,6 +734,7 @@
%xdefine _boringssl_self_test_slhdsa _ %+ BORINGSSL_PREFIX %+ _boringssl_self_test_slhdsa
%xdefine _bsaes_capable _ %+ BORINGSSL_PREFIX %+ _bsaes_capable
%xdefine _bsaes_cbc_encrypt _ %+ BORINGSSL_PREFIX %+ _bsaes_cbc_encrypt
%xdefine _bsaes_ctr32_encrypt_blocks _ %+ BORINGSSL_PREFIX %+ _bsaes_ctr32_encrypt_blocks
%xdefine _BUF_MEM_append _ %+ BORINGSSL_PREFIX %+ _BUF_MEM_append
%xdefine _BUF_MEM_free _ %+ BORINGSSL_PREFIX %+ _BUF_MEM_free
%xdefine _BUF_MEM_grow _ %+ BORINGSSL_PREFIX %+ _BUF_MEM_grow
@@ -928,6 +931,7 @@
%xdefine _CRYPTO_get_thread_local _ %+ BORINGSSL_PREFIX %+ _CRYPTO_get_thread_local
%xdefine _CRYPTO_ghash_init _ %+ BORINGSSL_PREFIX %+ _CRYPTO_ghash_init
%xdefine _CRYPTO_has_asm _ %+ BORINGSSL_PREFIX %+ _CRYPTO_has_asm
%xdefine _CRYPTO_has_broken_NEON _ %+ BORINGSSL_PREFIX %+ _CRYPTO_has_broken_NEON
%xdefine _CRYPTO_hchacha20 _ %+ BORINGSSL_PREFIX %+ _CRYPTO_hchacha20
%xdefine _CRYPTO_init_sysrand _ %+ BORINGSSL_PREFIX %+ _CRYPTO_init_sysrand
%xdefine _CRYPTO_is_ADX_capable _ %+ BORINGSSL_PREFIX %+ _CRYPTO_is_ADX_capable
@@ -964,13 +968,17 @@
%xdefine _CRYPTO_MUTEX_lock_write _ %+ BORINGSSL_PREFIX %+ _CRYPTO_MUTEX_lock_write
%xdefine _CRYPTO_MUTEX_unlock_read _ %+ BORINGSSL_PREFIX %+ _CRYPTO_MUTEX_unlock_read
%xdefine _CRYPTO_MUTEX_unlock_write _ %+ BORINGSSL_PREFIX %+ _CRYPTO_MUTEX_unlock_write
%xdefine _CRYPTO_needs_hwcap2_workaround _ %+ BORINGSSL_PREFIX %+ _CRYPTO_needs_hwcap2_workaround
%xdefine _CRYPTO_new_ex_data _ %+ BORINGSSL_PREFIX %+ _CRYPTO_new_ex_data
%xdefine _CRYPTO_num_locks _ %+ BORINGSSL_PREFIX %+ _CRYPTO_num_locks
%xdefine _CRYPTO_ofb128_encrypt _ %+ BORINGSSL_PREFIX %+ _CRYPTO_ofb128_encrypt
%xdefine _CRYPTO_once _ %+ BORINGSSL_PREFIX %+ _CRYPTO_once
%xdefine _CRYPTO_poly1305_finish _ %+ BORINGSSL_PREFIX %+ _CRYPTO_poly1305_finish
%xdefine _CRYPTO_poly1305_finish_neon _ %+ BORINGSSL_PREFIX %+ _CRYPTO_poly1305_finish_neon
%xdefine _CRYPTO_poly1305_init _ %+ BORINGSSL_PREFIX %+ _CRYPTO_poly1305_init
%xdefine _CRYPTO_poly1305_init_neon _ %+ BORINGSSL_PREFIX %+ _CRYPTO_poly1305_init_neon
%xdefine _CRYPTO_poly1305_update _ %+ BORINGSSL_PREFIX %+ _CRYPTO_poly1305_update
%xdefine _CRYPTO_poly1305_update_neon _ %+ BORINGSSL_PREFIX %+ _CRYPTO_poly1305_update_neon
%xdefine _CRYPTO_pre_sandbox_init _ %+ BORINGSSL_PREFIX %+ _CRYPTO_pre_sandbox_init
%xdefine _CRYPTO_rdrand _ %+ BORINGSSL_PREFIX %+ _CRYPTO_rdrand
%xdefine _CRYPTO_rdrand_multiple8_buf _ %+ BORINGSSL_PREFIX %+ _CRYPTO_rdrand_multiple8_buf
@@ -2237,6 +2245,8 @@
%xdefine _OPENSSL_malloc_init _ %+ BORINGSSL_PREFIX %+ _OPENSSL_malloc_init
%xdefine _OPENSSL_memdup _ %+ BORINGSSL_PREFIX %+ _OPENSSL_memdup
%xdefine _OPENSSL_no_config _ %+ BORINGSSL_PREFIX %+ _OPENSSL_no_config
%xdefine _openssl_poly1305_neon2_addmulmod _ %+ BORINGSSL_PREFIX %+ _openssl_poly1305_neon2_addmulmod
%xdefine _openssl_poly1305_neon2_blocks _ %+ BORINGSSL_PREFIX %+ _openssl_poly1305_neon2_blocks
%xdefine _OPENSSL_posix_to_tm _ %+ BORINGSSL_PREFIX %+ _OPENSSL_posix_to_tm
%xdefine _OPENSSL_realloc _ %+ BORINGSSL_PREFIX %+ _OPENSSL_realloc
%xdefine _OPENSSL_secure_clear_free _ %+ BORINGSSL_PREFIX %+ _OPENSSL_secure_clear_free
@@ -2575,6 +2585,7 @@
%xdefine _sha1_block_data_order_avx _ %+ BORINGSSL_PREFIX %+ _sha1_block_data_order_avx
%xdefine _sha1_block_data_order_avx2 _ %+ BORINGSSL_PREFIX %+ _sha1_block_data_order_avx2
%xdefine _sha1_block_data_order_hw _ %+ BORINGSSL_PREFIX %+ _sha1_block_data_order_hw
%xdefine _sha1_block_data_order_neon _ %+ BORINGSSL_PREFIX %+ _sha1_block_data_order_neon
%xdefine _sha1_block_data_order_nohw _ %+ BORINGSSL_PREFIX %+ _sha1_block_data_order_nohw
%xdefine _sha1_block_data_order_ssse3 _ %+ BORINGSSL_PREFIX %+ _sha1_block_data_order_ssse3
%xdefine _SHA1_Final _ %+ BORINGSSL_PREFIX %+ _SHA1_Final
@@ -2591,6 +2602,7 @@
%xdefine _sha256_avx_capable _ %+ BORINGSSL_PREFIX %+ _sha256_avx_capable
%xdefine _sha256_block_data_order_avx _ %+ BORINGSSL_PREFIX %+ _sha256_block_data_order_avx
%xdefine _sha256_block_data_order_hw _ %+ BORINGSSL_PREFIX %+ _sha256_block_data_order_hw
%xdefine _sha256_block_data_order_neon _ %+ BORINGSSL_PREFIX %+ _sha256_block_data_order_neon
%xdefine _sha256_block_data_order_nohw _ %+ BORINGSSL_PREFIX %+ _sha256_block_data_order_nohw
%xdefine _sha256_block_data_order_ssse3 _ %+ BORINGSSL_PREFIX %+ _sha256_block_data_order_ssse3
%xdefine _SHA256_Final _ %+ BORINGSSL_PREFIX %+ _SHA256_Final
@@ -2612,6 +2624,7 @@
%xdefine _sha512_avx_capable _ %+ BORINGSSL_PREFIX %+ _sha512_avx_capable
%xdefine _sha512_block_data_order_avx _ %+ BORINGSSL_PREFIX %+ _sha512_block_data_order_avx
%xdefine _sha512_block_data_order_hw _ %+ BORINGSSL_PREFIX %+ _sha512_block_data_order_hw
%xdefine _sha512_block_data_order_neon _ %+ BORINGSSL_PREFIX %+ _sha512_block_data_order_neon
%xdefine _sha512_block_data_order_nohw _ %+ BORINGSSL_PREFIX %+ _sha512_block_data_order_nohw
%xdefine _SHA512_Final _ %+ BORINGSSL_PREFIX %+ _SHA512_Final
%xdefine _sha512_hw_capable _ %+ BORINGSSL_PREFIX %+ _sha512_hw_capable
@@ -2952,9 +2965,11 @@
%xdefine _vpaes_capable _ %+ BORINGSSL_PREFIX %+ _vpaes_capable
%xdefine _vpaes_cbc_encrypt _ %+ BORINGSSL_PREFIX %+ _vpaes_cbc_encrypt
%xdefine _vpaes_ctr32_encrypt_blocks _ %+ BORINGSSL_PREFIX %+ _vpaes_ctr32_encrypt_blocks
%xdefine _vpaes_ctr32_encrypt_blocks_with_bsaes _ %+ BORINGSSL_PREFIX %+ _vpaes_ctr32_encrypt_blocks_with_bsaes
%xdefine _vpaes_decrypt _ %+ BORINGSSL_PREFIX %+ _vpaes_decrypt
%xdefine _vpaes_decrypt_key_to_bsaes _ %+ BORINGSSL_PREFIX %+ _vpaes_decrypt_key_to_bsaes
%xdefine _vpaes_encrypt _ %+ BORINGSSL_PREFIX %+ _vpaes_encrypt
%xdefine _vpaes_encrypt_key_to_bsaes _ %+ BORINGSSL_PREFIX %+ _vpaes_encrypt_key_to_bsaes
%xdefine _vpaes_set_decrypt_key _ %+ BORINGSSL_PREFIX %+ _vpaes_set_decrypt_key
%xdefine _vpaes_set_encrypt_key _ %+ BORINGSSL_PREFIX %+ _vpaes_set_encrypt_key
%xdefine _X25519 _ %+ BORINGSSL_PREFIX %+ _X25519
@@ -2971,6 +2986,7 @@
%xdefine _x25519_ge_sub _ %+ BORINGSSL_PREFIX %+ _x25519_ge_sub
%xdefine _x25519_ge_tobytes _ %+ BORINGSSL_PREFIX %+ _x25519_ge_tobytes
%xdefine _X25519_keypair _ %+ BORINGSSL_PREFIX %+ _X25519_keypair
%xdefine _x25519_NEON _ %+ BORINGSSL_PREFIX %+ _x25519_NEON
%xdefine _x25519_pkey_meth _ %+ BORINGSSL_PREFIX %+ _x25519_pkey_meth
%xdefine _X25519_public_from_private _ %+ BORINGSSL_PREFIX %+ _X25519_public_from_private
%xdefine _x25519_sc_reduce _ %+ BORINGSSL_PREFIX %+ _x25519_sc_reduce
@@ -4068,6 +4084,8 @@
%xdefine bn_mul4x_mont_capable BORINGSSL_PREFIX %+ _bn_mul4x_mont_capable
%xdefine bn_mul4x_mont_gather5 BORINGSSL_PREFIX %+ _bn_mul4x_mont_gather5
%xdefine bn_mul4x_mont_gather5_capable BORINGSSL_PREFIX %+ _bn_mul4x_mont_gather5_capable
%xdefine bn_mul8x_mont_neon BORINGSSL_PREFIX %+ _bn_mul8x_mont_neon
%xdefine bn_mul8x_mont_neon_capable BORINGSSL_PREFIX %+ _bn_mul8x_mont_neon_capable
%xdefine bn_mulx_adx_capable BORINGSSL_PREFIX %+ _bn_mulx_adx_capable
%xdefine bn_mulx4x_mont BORINGSSL_PREFIX %+ _bn_mulx4x_mont
%xdefine bn_mulx4x_mont_capable BORINGSSL_PREFIX %+ _bn_mulx4x_mont_capable
@@ -4163,6 +4181,7 @@
%xdefine boringssl_self_test_slhdsa BORINGSSL_PREFIX %+ _boringssl_self_test_slhdsa
%xdefine bsaes_capable BORINGSSL_PREFIX %+ _bsaes_capable
%xdefine bsaes_cbc_encrypt BORINGSSL_PREFIX %+ _bsaes_cbc_encrypt
%xdefine bsaes_ctr32_encrypt_blocks BORINGSSL_PREFIX %+ _bsaes_ctr32_encrypt_blocks
%xdefine BUF_MEM_append BORINGSSL_PREFIX %+ _BUF_MEM_append
%xdefine BUF_MEM_free BORINGSSL_PREFIX %+ _BUF_MEM_free
%xdefine BUF_MEM_grow BORINGSSL_PREFIX %+ _BUF_MEM_grow
@@ -4359,6 +4378,7 @@
%xdefine CRYPTO_get_thread_local BORINGSSL_PREFIX %+ _CRYPTO_get_thread_local
%xdefine CRYPTO_ghash_init BORINGSSL_PREFIX %+ _CRYPTO_ghash_init
%xdefine CRYPTO_has_asm BORINGSSL_PREFIX %+ _CRYPTO_has_asm
%xdefine CRYPTO_has_broken_NEON BORINGSSL_PREFIX %+ _CRYPTO_has_broken_NEON
%xdefine CRYPTO_hchacha20 BORINGSSL_PREFIX %+ _CRYPTO_hchacha20
%xdefine CRYPTO_init_sysrand BORINGSSL_PREFIX %+ _CRYPTO_init_sysrand
%xdefine CRYPTO_is_ADX_capable BORINGSSL_PREFIX %+ _CRYPTO_is_ADX_capable
@@ -4395,13 +4415,17 @@
%xdefine CRYPTO_MUTEX_lock_write BORINGSSL_PREFIX %+ _CRYPTO_MUTEX_lock_write
%xdefine CRYPTO_MUTEX_unlock_read BORINGSSL_PREFIX %+ _CRYPTO_MUTEX_unlock_read
%xdefine CRYPTO_MUTEX_unlock_write BORINGSSL_PREFIX %+ _CRYPTO_MUTEX_unlock_write
%xdefine CRYPTO_needs_hwcap2_workaround BORINGSSL_PREFIX %+ _CRYPTO_needs_hwcap2_workaround
%xdefine CRYPTO_new_ex_data BORINGSSL_PREFIX %+ _CRYPTO_new_ex_data
%xdefine CRYPTO_num_locks BORINGSSL_PREFIX %+ _CRYPTO_num_locks
%xdefine CRYPTO_ofb128_encrypt BORINGSSL_PREFIX %+ _CRYPTO_ofb128_encrypt
%xdefine CRYPTO_once BORINGSSL_PREFIX %+ _CRYPTO_once
%xdefine CRYPTO_poly1305_finish BORINGSSL_PREFIX %+ _CRYPTO_poly1305_finish
%xdefine CRYPTO_poly1305_finish_neon BORINGSSL_PREFIX %+ _CRYPTO_poly1305_finish_neon
%xdefine CRYPTO_poly1305_init BORINGSSL_PREFIX %+ _CRYPTO_poly1305_init
%xdefine CRYPTO_poly1305_init_neon BORINGSSL_PREFIX %+ _CRYPTO_poly1305_init_neon
%xdefine CRYPTO_poly1305_update BORINGSSL_PREFIX %+ _CRYPTO_poly1305_update
%xdefine CRYPTO_poly1305_update_neon BORINGSSL_PREFIX %+ _CRYPTO_poly1305_update_neon
%xdefine CRYPTO_pre_sandbox_init BORINGSSL_PREFIX %+ _CRYPTO_pre_sandbox_init
%xdefine CRYPTO_rdrand BORINGSSL_PREFIX %+ _CRYPTO_rdrand
%xdefine CRYPTO_rdrand_multiple8_buf BORINGSSL_PREFIX %+ _CRYPTO_rdrand_multiple8_buf
@@ -5668,6 +5692,8 @@
%xdefine OPENSSL_malloc_init BORINGSSL_PREFIX %+ _OPENSSL_malloc_init
%xdefine OPENSSL_memdup BORINGSSL_PREFIX %+ _OPENSSL_memdup
%xdefine OPENSSL_no_config BORINGSSL_PREFIX %+ _OPENSSL_no_config
%xdefine openssl_poly1305_neon2_addmulmod BORINGSSL_PREFIX %+ _openssl_poly1305_neon2_addmulmod
%xdefine openssl_poly1305_neon2_blocks BORINGSSL_PREFIX %+ _openssl_poly1305_neon2_blocks
%xdefine OPENSSL_posix_to_tm BORINGSSL_PREFIX %+ _OPENSSL_posix_to_tm
%xdefine OPENSSL_realloc BORINGSSL_PREFIX %+ _OPENSSL_realloc
%xdefine OPENSSL_secure_clear_free BORINGSSL_PREFIX %+ _OPENSSL_secure_clear_free
@@ -6006,6 +6032,7 @@
%xdefine sha1_block_data_order_avx BORINGSSL_PREFIX %+ _sha1_block_data_order_avx
%xdefine sha1_block_data_order_avx2 BORINGSSL_PREFIX %+ _sha1_block_data_order_avx2
%xdefine sha1_block_data_order_hw BORINGSSL_PREFIX %+ _sha1_block_data_order_hw
%xdefine sha1_block_data_order_neon BORINGSSL_PREFIX %+ _sha1_block_data_order_neon
%xdefine sha1_block_data_order_nohw BORINGSSL_PREFIX %+ _sha1_block_data_order_nohw
%xdefine sha1_block_data_order_ssse3 BORINGSSL_PREFIX %+ _sha1_block_data_order_ssse3
%xdefine SHA1_Final BORINGSSL_PREFIX %+ _SHA1_Final
@@ -6022,6 +6049,7 @@
%xdefine sha256_avx_capable BORINGSSL_PREFIX %+ _sha256_avx_capable
%xdefine sha256_block_data_order_avx BORINGSSL_PREFIX %+ _sha256_block_data_order_avx
%xdefine sha256_block_data_order_hw BORINGSSL_PREFIX %+ _sha256_block_data_order_hw
%xdefine sha256_block_data_order_neon BORINGSSL_PREFIX %+ _sha256_block_data_order_neon
%xdefine sha256_block_data_order_nohw BORINGSSL_PREFIX %+ _sha256_block_data_order_nohw
%xdefine sha256_block_data_order_ssse3 BORINGSSL_PREFIX %+ _sha256_block_data_order_ssse3
%xdefine SHA256_Final BORINGSSL_PREFIX %+ _SHA256_Final
@@ -6043,6 +6071,7 @@
%xdefine sha512_avx_capable BORINGSSL_PREFIX %+ _sha512_avx_capable
%xdefine sha512_block_data_order_avx BORINGSSL_PREFIX %+ _sha512_block_data_order_avx
%xdefine sha512_block_data_order_hw BORINGSSL_PREFIX %+ _sha512_block_data_order_hw
%xdefine sha512_block_data_order_neon BORINGSSL_PREFIX %+ _sha512_block_data_order_neon
%xdefine sha512_block_data_order_nohw BORINGSSL_PREFIX %+ _sha512_block_data_order_nohw
%xdefine SHA512_Final BORINGSSL_PREFIX %+ _SHA512_Final
%xdefine sha512_hw_capable BORINGSSL_PREFIX %+ _sha512_hw_capable
@@ -6383,9 +6412,11 @@
%xdefine vpaes_capable BORINGSSL_PREFIX %+ _vpaes_capable
%xdefine vpaes_cbc_encrypt BORINGSSL_PREFIX %+ _vpaes_cbc_encrypt
%xdefine vpaes_ctr32_encrypt_blocks BORINGSSL_PREFIX %+ _vpaes_ctr32_encrypt_blocks
%xdefine vpaes_ctr32_encrypt_blocks_with_bsaes BORINGSSL_PREFIX %+ _vpaes_ctr32_encrypt_blocks_with_bsaes
%xdefine vpaes_decrypt BORINGSSL_PREFIX %+ _vpaes_decrypt
%xdefine vpaes_decrypt_key_to_bsaes BORINGSSL_PREFIX %+ _vpaes_decrypt_key_to_bsaes
%xdefine vpaes_encrypt BORINGSSL_PREFIX %+ _vpaes_encrypt
%xdefine vpaes_encrypt_key_to_bsaes BORINGSSL_PREFIX %+ _vpaes_encrypt_key_to_bsaes
%xdefine vpaes_set_decrypt_key BORINGSSL_PREFIX %+ _vpaes_set_decrypt_key
%xdefine vpaes_set_encrypt_key BORINGSSL_PREFIX %+ _vpaes_set_encrypt_key
%xdefine X25519 BORINGSSL_PREFIX %+ _X25519
@@ -6402,6 +6433,7 @@
%xdefine x25519_ge_sub BORINGSSL_PREFIX %+ _x25519_ge_sub
%xdefine x25519_ge_tobytes BORINGSSL_PREFIX %+ _x25519_ge_tobytes
%xdefine X25519_keypair BORINGSSL_PREFIX %+ _X25519_keypair
%xdefine x25519_NEON BORINGSSL_PREFIX %+ _x25519_NEON
%xdefine x25519_pkey_meth BORINGSSL_PREFIX %+ _x25519_pkey_meth
%xdefine X25519_public_from_private BORINGSSL_PREFIX %+ _X25519_public_from_private
%xdefine x25519_sc_reduce BORINGSSL_PREFIX %+ _x25519_sc_reduce
+1
View File
@@ -36,6 +36,7 @@ add_library(Crypto
"ASN1/PKCS8PrivateKey.swift"
"ASN1/SEC1PrivateKey.swift"
"ASN1/SubjectPublicKeyInfo.swift"
"CryptoError_boring.swift"
"CryptoKitErrors.swift"
"Digests/BoringSSL/Digest_boring.swift"
"Digests/Digest.swift"
+18
View File
@@ -0,0 +1,18 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2025 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
//
//===----------------------------------------------------------------------===//
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, *)
public typealias CryptoError = CryptoKitError
@available(iOS 14, macOS 11, tvOS 14, watchOS 7, *)
public typealias CryptoASN1Error = CryptoKitASN1Error
@@ -40,26 +40,20 @@ extension OpenSSLSupportedNISTCurve {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P256: OpenSSLSupportedNISTCurve {
@inlinable
static var group: BoringSSLEllipticCurveGroup {
try! BoringSSLEllipticCurveGroup(.p256)
}
@usableFromInline
static let group = try! BoringSSLEllipticCurveGroup(.p256)
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P384: OpenSSLSupportedNISTCurve {
@inlinable
static var group: BoringSSLEllipticCurveGroup {
try! BoringSSLEllipticCurveGroup(.p384)
}
@usableFromInline
static let group = try! BoringSSLEllipticCurveGroup(.p384)
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension P521: OpenSSLSupportedNISTCurve {
@inlinable
static var group: BoringSSLEllipticCurveGroup {
try! BoringSSLEllipticCurveGroup(.p521)
}
@usableFromInline
static let group = try! BoringSSLEllipticCurveGroup(.p521)
}
@usableFromInline
@@ -69,6 +69,10 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.multiply(by: rhs, on: group, context: context)
}
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package consuming func multiplying(
by rhs: ArbitraryPrecisionInteger,
@@ -78,6 +82,18 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.multiply(by: rhs, on: group, context: context)
return self
}
#else
@usableFromInline
package func multiplying(
by rhs: ArbitraryPrecisionInteger,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var `self` = self
try self.multiply(by: rhs, on: group, context: context)
return self
}
#endif
@usableFromInline
package static func multiplying(
@@ -110,6 +126,10 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.add(rhs, on: group, context: context)
}
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package consuming func adding(
_ rhs: consuming EllipticCurvePoint,
@@ -119,7 +139,23 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.add(rhs, on: group, context: context)
return self
}
#else
@usableFromInline
package func adding(
_ rhs: consuming EllipticCurvePoint,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var `self` = self
try self.add(rhs, on: group, context: context)
return self
}
#endif
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package static func adding(
_ lhs: consuming EllipticCurvePoint,
@@ -130,6 +166,19 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try lhs.add(rhs, on: group, context: context)
return lhs
}
#else
@usableFromInline
package static func adding(
_ lhs: EllipticCurvePoint,
_ rhs: EllipticCurvePoint,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var lhs = lhs
try lhs.add(rhs, on: group, context: context)
return lhs
}
#endif
@usableFromInline
package mutating func invert(
@@ -150,6 +199,10 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.invert(on: group, context: context)
}
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package consuming func inverting(
on group: BoringSSLEllipticCurveGroup,
@@ -158,7 +211,22 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.invert(on: group, context: context)
return self
}
#else
@usableFromInline
package func inverting(
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var `self` = self
try self.invert(on: group, context: context)
return self
}
#endif
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package static func inverting(
_ point: consuming EllipticCurvePoint,
@@ -168,6 +236,18 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try point.invert(on: group, context: context)
return point
}
#else
@usableFromInline
package static func inverting(
_ point: EllipticCurvePoint,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var point = point
try point.invert(on: group, context: context)
return point
}
#endif
@usableFromInline
package mutating func subtract(
@@ -190,6 +270,10 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.subtract(rhs, on: group, context: context)
}
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package consuming func subtracting(
_ rhs: consuming EllipticCurvePoint,
@@ -199,7 +283,23 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try self.subtract(rhs, on: group, context: context)
return self
}
#else
@usableFromInline
package func subtracting(
_ rhs: EllipticCurvePoint,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var `self` = self
try self.subtract(rhs, on: group, context: context)
return self
}
#endif
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
@usableFromInline
package static func subtracting(
_ rhs: consuming EllipticCurvePoint,
@@ -210,6 +310,19 @@ package struct EllipticCurvePoint: @unchecked Sendable {
try lhs.subtract(rhs, on: group, context: context)
return lhs
}
#else
@usableFromInline
package static func subtracting(
_ rhs: EllipticCurvePoint,
from lhs: EllipticCurvePoint,
on group: BoringSSLEllipticCurveGroup,
context: FiniteFieldArithmeticContext? = nil
) throws -> EllipticCurvePoint {
var lhs = lhs
try lhs.subtract(rhs, on: group, context: context)
return lhs
}
#endif
@usableFromInline
package init<MessageBytes: ContiguousBytes, DSTBytes: ContiguousBytes>(
+9 -1
View File
@@ -151,8 +151,9 @@ extension AES {
extension AES._CBC {
/// An initialization vector.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
public struct IV: Sendable {
public struct IV: Sendable, Sequence {
// AES CBC uses a 128-bit IV.
@usableFromInline
var ivBytes: (
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8
@@ -197,6 +198,13 @@ extension AES._CBC {
bytesPtr.copyBytes(from: ivBytes)
}
}
@inlinable
public func makeIterator() -> some IteratorProtocol<UInt8> {
withUnsafeBytes(of: ivBytes) { unsafeRawBufferPointer in
Array(unsafeRawBufferPointer).makeIterator()
}
}
}
}
+214
View File
@@ -0,0 +1,214 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2025 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
//
//===----------------------------------------------------------------------===//
@_implementationOnly import CCryptoBoringSSL
import Crypto
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, *)
extension AES {
/// A cipher-based message authentication code.
///
/// CMAC uses AES to implement a MAC. CMAC is useful in contexts where access to
/// a hash function is not guaranteed, but a block cipher will be available.
public struct CMAC: @unchecked Sendable {
// Unchecked sendable because this is CoW.
fileprivate var backing: Backing
/// Creates a message authentication code generator.
///
/// Defaults the output size to 128 bits.
///
/// - Parameters:
/// - key: The symmetric key used to secure the computation.
public init(key: SymmetricKey) throws {
try self.init(key: key, outputSize: 16)
}
/// Creates a message authentication code generator.
///
/// - Parameters:
/// - key: The symmetric key used to secure the computation.
/// - outputSize: The number of bytes of MAC to generate. Must be in the range 0 to 16 inclusive.
public init(key: SymmetricKey, outputSize: Int) throws {
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoError.incorrectKeySize
}
guard (0...16).contains(outputSize) else {
throw CryptoKitError.incorrectParameterSize
}
self.backing = Backing(key: key, outputSize: outputSize)
}
/// Adds data to be authenticated by MAC function. This can be called one or more times to append additional data.
///
/// - Parameters:
/// - bufferPointer: The data to be authenticated.
public mutating func update(bufferPointer: UnsafeRawBufferPointer) {
self.cowIfNeeded()
self.backing.update(bufferPointer)
}
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
/// Finalizes the message authentication computation and returns the
/// computed code.
///
/// - Returns: The message authentication code.
public consuming func finalize() -> AES.CMAC.MAC {
// The combination of "consuming" and "cowifneeded" should
// produce an environment where, if users may choose to
// keep using the MAC, they can, but if they aren't we'll
// avoid an unnecessary CoW.
self.cowIfNeeded()
return self.backing.finalize()
}
#else
/// Finalizes the message authentication computation and returns the
/// computed code.
///
/// - Returns: The message authentication code.
public func finalize() -> AES.CMAC.MAC {
var `self` = self
return self.backing.finalize()
}
#endif
/// Updates the MAC with data.
///
/// - Parameter data: The data to update the MAC
public mutating func update<D: DataProtocol>(data: D) {
for memoryRegion in data.regions {
memoryRegion.withUnsafeBytes { bp in
self.update(bufferPointer: bp)
}
}
}
private mutating func cowIfNeeded() {
if !isKnownUniquelyReferenced(&self.backing) {
self.backing = Backing(copying: self.backing)
}
}
}
}
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, *)
extension AES.CMAC {
/// A cipher-based message authentication code.
public struct MAC: MessageAuthenticationCode {
fileprivate let underlyingData: Data
init(underlyingData: Data) {
self.underlyingData = underlyingData
}
/// The number of bytes in the message authentication code.
public var byteCount: Int {
self.underlyingData.count
}
/// Invokes the given closure with a buffer pointer covering the raw bytes
/// of the code.
///
/// - Parameters:
/// - body: A closure that takes a raw buffer pointer to the bytes of the
/// code.
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
try self.underlyingData.withUnsafeBytes(body)
}
}
}
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, *)
extension AES.CMAC {
fileprivate final class Backing {
private let key: SymmetricKey
private let context: OpaquePointer
private let outputSize: Int
init(key: SymmetricKey, outputSize: Int) {
self.key = key
self.context = CCryptoBoringSSL_CMAC_CTX_new()
self.outputSize = outputSize
let rc = self.key.withUnsafeBytes { keyPtr in
CCryptoBoringSSL_CMAC_Init(
self.context,
keyPtr.baseAddress,
keyPtr.count,
key.aesEVP,
nil
)
}
precondition(rc == 1)
}
init(copying other: Backing) {
self.key = other.key
self.context = CCryptoBoringSSL_CMAC_CTX_new()
self.outputSize = other.outputSize
let rc = CCryptoBoringSSL_CMAC_CTX_copy(self.context, other.context)
precondition(rc == 1)
// Ensure we don't lose `other` at this time.
withExtendedLifetime(other) {}
}
deinit {
CCryptoBoringSSL_CMAC_CTX_free(self.context)
}
func update(_ bytes: UnsafeRawBufferPointer) {
let rc = CCryptoBoringSSL_CMAC_Update(self.context, bytes.baseAddress, bytes.count)
precondition(rc == 1)
}
func finalize() -> AES.CMAC.MAC {
let bytes = withUnsafeTemporaryAllocation(byteCount: 16, alignment: 1) { bytes in
precondition(bytes.count >= 16)
var count = 16
let rc = CCryptoBoringSSL_CMAC_Final(self.context, bytes.baseAddress, &count)
precondition(count == 16)
precondition(rc == 1)
return Data(UnsafeRawBufferPointer(rebasing: bytes.prefix(self.outputSize)))
}
return AES.CMAC.MAC(underlyingData: bytes)
}
}
}
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, *)
extension SymmetricKey {
fileprivate var aesEVP: OpaquePointer {
switch self.bitCount {
case 128:
CCryptoBoringSSL_EVP_aes_128_cbc()
case 192:
CCryptoBoringSSL_EVP_aes_192_cbc()
case 256:
CCryptoBoringSSL_EVP_aes_256_cbc()
default:
fatalError("Should be unreachable")
}
}
}
+394 -8
View File
@@ -18,8 +18,388 @@ import FoundationEssentials
import Foundation
#endif
// MARK: - P256 + ARC(P-256)
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P256 {
/// Anonymous Rate-Limited Credentials (ARC).
///
/// A specialization of keyed-verification anonymous credentials with support for rate limiting.
///
/// - Seealso: [IETF Internet Draft: draft-yun-cfrg-arc-00](https://datatracker.ietf.org/doc/draft-yun-cfrg-arc).
public enum _ARCV1 {
internal typealias H2G = HashToCurveImpl<P256>
internal typealias Ciphersuite = ARC.Ciphersuite<H2G>
fileprivate typealias Server = ARC.Server<H2G>
internal static let ciphersuite = Ciphersuite(H2G.self)
}
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P256._ARCV1 {
/// The server secrets used to issue and verify credentials.
public struct PrivateKey: Sendable {
fileprivate var backing: ARC.Server<H2G>
/// Creates a random private key for ARC(P-256).
public init() {
self.backing = ARC.Server(ciphersuite: P256._ARCV1.ciphersuite)
}
// The spec does not define a serialization of the private key since, unlike the public key, it is not an
// interop concern.
//
// This initializer expects a concatenation of the binary representations of the private scalars:
//
// struct {
// uint8 x0[Ne];
// uint8 x1[Ne];
// uint8 x2[Ne];
// uint8 x0Blinding[Ne];
// } ServerPrivateKey;
//
public init<D: DataProtocol>(rawRepresentation: D) throws {
guard rawRepresentation.count == 4 * P256.orderByteCount else {
throw ARC.Errors.incorrectPrivateKeyDataSize
}
var bytes = Data(rawRepresentation)[...]
let x0 = try H2G.G.Scalar(bytes: bytes[..<bytes.startIndex.advanced(by: P256.orderByteCount)])
bytes.removeFirst(P256.orderByteCount)
let x1 = try H2G.G.Scalar(bytes: bytes[..<bytes.startIndex.advanced(by: P256.orderByteCount)])
bytes.removeFirst(P256.orderByteCount)
let x2 = try H2G.G.Scalar(bytes: bytes[..<bytes.startIndex.advanced(by: P256.orderByteCount)])
bytes.removeFirst(P256.orderByteCount)
let x0Blinding = try H2G.G.Scalar(bytes: bytes[..<bytes.startIndex.advanced(by: P256.orderByteCount)])
bytes.removeFirst(P256.orderByteCount)
assert(bytes.isEmpty)
self.backing = ARC.Server(ciphersuite: P256._ARCV1.ciphersuite, x0: x0, x1: x1, x2: x2, x0Blinding: x0Blinding)
}
// The spec does not define a serialization of the private key since, unlike the public key, it is not an
// interop concern.
//
// This initializer expects a concatenation of the binary representations of the private scalars:
//
// struct {
// uint8 x0[Ns];
// uint8 x1[Ns];
// uint8 x2[Ns];
// uint8 x0Blinding[Ns];
// } ServerPrivateKey;
//
public var rawRepresentation: Data {
let serializedByteCount = 4 * P256.orderByteCount
var result = Data(capacity: serializedByteCount)
result.append(self.backing.serverPrivateKey.x0.rawRepresentation)
result.append(self.backing.serverPrivateKey.x1.rawRepresentation)
result.append(self.backing.serverPrivateKey.x2.rawRepresentation)
result.append(self.backing.serverPrivateKey.x0Blinding.rawRepresentation)
assert(result.count == serializedByteCount)
return result
}
public var publicKey: P256._ARCV1.PublicKey {
P256._ARCV1.PublicKey(backing: self.backing.serverPublicKey)
}
}
/// The server public key, used by clients to create anonymous credentials in conjunction with the server.
public struct PublicKey: Sendable {
fileprivate var backing: ARC.ServerPublicKey<H2G>
fileprivate init(backing: ARC.ServerPublicKey<H2G>) {
self.backing = backing
}
fileprivate static var serializedByteCount: Int { 3 * P256.compressedx962PointByteCount }
// The spec defines this serialization of the public key:
//
// struct {
// uint8 X0[Ne];
// uint8 X1[Ne];
// uint8 X2[Ne];
// } ServerPublicKey;
//
public init<D: DataProtocol>(rawRepresentation: D) throws {
guard rawRepresentation.count == Self.serializedByteCount else { throw ARC.Errors.incorrectPublicKeyDataSize }
var bytes = Data(rawRepresentation)[...]
let X0 = try H2G.G.Element(oprfRepresentation: bytes[..<bytes.startIndex.advanced(by: P256.compressedx962PointByteCount)])
bytes.removeFirst(P256.compressedx962PointByteCount)
let X1 = try H2G.G.Element(oprfRepresentation: bytes[..<bytes.startIndex.advanced(by: P256.compressedx962PointByteCount)])
bytes.removeFirst(P256.compressedx962PointByteCount)
let X2 = try H2G.G.Element(oprfRepresentation: bytes[..<bytes.startIndex.advanced(by: P256.compressedx962PointByteCount)])
bytes.removeFirst(P256.compressedx962PointByteCount)
assert(bytes.isEmpty)
self.backing = ARC.ServerPublicKey(X0: X0, X1: X1, X2: X2)
}
// The spec defines this serialization of the public key:
//
// struct {
// uint8 X0[Ne];
// uint8 X1[Ne];
// uint8 X2[Ne];
// } ServerPublicKey;
//
public var rawRepresentation: Data {
var result = Data(capacity: Self.serializedByteCount)
result.append(self.backing.X0.oprfRepresentation)
result.append(self.backing.X1.oprfRepresentation)
result.append(self.backing.X2.oprfRepresentation)
assert(result.count == Self.serializedByteCount)
return result
}
}
/// A credential request, created by the client, to be sent to the server.
///
/// Clients should not create values of this type manually; they should use the prepare method on the public key.
///
/// Servers should reconstruct values of this type from the serialized bytes sent by the client.
public struct CredentialRequest: Sendable {
var backing: ARC.CredentialRequest<H2G>
fileprivate init(backing: ARC.CredentialRequest<H2G>) {
self.backing = backing
}
public init<D: DataProtocol>(rawRepresentation: D) throws {
self.backing = try ARC.CredentialRequest.deserialize(requestData: rawRepresentation, ciphersuite: P256._ARCV1.ciphersuite)
}
public var rawRepresentation: Data {
self.backing.serialize(ciphersuite: P256._ARCV1.ciphersuite)
}
}
/// A credential request to be sent to the server, and associated client secrets.
///
/// Users cannot create values of this type manually; they are created using the prepare method on the public key.
public struct Precredential: Sendable {
/// This backing type binds many things together, including the server commitments, client secrets, credential
/// request, and presentation limit.
internal var backing: ARC.Precredential<H2G>
/// The credential request to be sent to the server.
public var credentialRequest: CredentialRequest {
CredentialRequest(backing: self.backing.credentialRequest)
}
}
/// A credential response, created by the server, to be sent to the client.
///
/// Servers should not create values of this type manually; they should use the issue method on the private key.
///
/// Clients should reconstruct values of this type from the serialized bytes sent by the server.
public struct CredentialResponse: Sendable {
var backing: ARC.CredentialResponse<H2G>
fileprivate init(backing: ARC.CredentialResponse<H2G>) {
self.backing = backing
}
public init<D: DataProtocol>(rawRepresentation: D) throws {
self.backing = try ARC.CredentialResponse.deserialize(responseData: rawRepresentation, ciphersuite: P256._ARCV1.ciphersuite)
}
public var rawRepresentation: Data {
self.backing.serialize(ciphersuite: P256._ARCV1.ciphersuite)
}
}
/// A credential, created by the client using the response from the server.
///
/// Users cannot create values of this type manually; they are created using the issue method on the public key.
public struct Credential: Sendable {
var backing: ARC.Credential<H2G>
fileprivate init(backing: ARC.Credential<H2G>) {
self.backing = backing
}
}
/// A presentation, created by the client from a credential, to be sent to the server to verify.
///
/// Users cannot create values of this type manually; they are created using the present method on the credential.
public struct Presentation: Sendable {
internal var backing: ARC.Presentation<H2G>
fileprivate init(backing: ARC.Presentation<H2G>) {
self.backing = backing
}
public init<D: DataProtocol>(rawRepresentation: D) throws {
self.backing = try ARC.Presentation.deserialize(presentationData: rawRepresentation, ciphersuite: P256._ARCV1.ciphersuite)
}
public var rawRepresentation: Data {
self.backing.serialize(ciphersuite: P256._ARCV1.ciphersuite)
}
public var tag: Data {
self.backing.tag.compressedRepresentation
}
}
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P256._ARCV1.PublicKey {
internal func prepareCredentialRequest<D: DataProtocol>(
requestContext: D,
m1: P256._ARCV1.H2G.G.Scalar,
r1: P256._ARCV1.H2G.G.Scalar,
r2: P256._ARCV1.H2G.G.Scalar
) throws -> P256._ARCV1.Precredential {
let precedential = try ARC.Precredential(
ciphersuite: P256._ARCV1.ciphersuite,
m1: m1,
requestContext: Data(requestContext),
r1: r1,
r2: r2,
serverPublicKey: self.backing
)
return P256._ARCV1.Precredential(backing: precedential)
}
/// Prepare a credential request for a given request context.
///
/// - Parameters:
/// - requestContext: Request context, agreed with the server.
///
/// - Returns: A precredential containing the client secrets, and request to be sent to the server.
public func prepareCredentialRequest<D: DataProtocol>(
requestContext: D
) throws -> P256._ARCV1.Precredential {
try self.prepareCredentialRequest(
requestContext: requestContext,
m1: .random,
r1: .random,
r2: .random
)
}
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P256._ARCV1.PrivateKey {
internal func issue(
_ credentialRequest: P256._ARCV1.CredentialRequest,
b: P256._ARCV1.H2G.G.Scalar
) throws -> P256._ARCV1.CredentialResponse {
let response = try self.backing.respond(credentialRequest: credentialRequest.backing, b: b)
return P256._ARCV1.CredentialResponse(backing: response)
}
/// Generate a credential response from a credential request.
public func issue(_ credentialRequest: P256._ARCV1.CredentialRequest) throws -> P256._ARCV1.CredentialResponse {
try self.issue(credentialRequest, b: .random)
}
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P256._ARCV1.PublicKey {
/// Create a credential from the issuer response.
public func finalize(
_ credentialResponse: P256._ARCV1.CredentialResponse,
for precredential: P256._ARCV1.Precredential
) throws -> P256._ARCV1.Credential {
let credential = try precredential.backing.makeCredential(credentialResponse: credentialResponse.backing)
return P256._ARCV1.Credential(backing: credential)
}
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P256._ARCV1.Credential {
internal mutating func makePresentation<D: DataProtocol>(
context: D,
presentationLimit: Int,
fixedNonce: Int?,
a: P256._ARCV1.H2G.G.Scalar,
r: P256._ARCV1.H2G.G.Scalar,
z: P256._ARCV1.H2G.G.Scalar
) throws -> (presentation: P256._ARCV1.Presentation, nonce: Int) {
let (presentation, nonce) = try self.backing.makePresentation(
presentationContext: Data(context),
presentationLimit: presentationLimit,
a: a,
r: r,
z: z,
optionalNonce: fixedNonce
)
return (P256._ARCV1.Presentation(backing: presentation), nonce)
}
/// Create a presentation to provide to a verifier.
///
/// - Parameters:
/// - context: The presentation context agreed with the verifier.
/// - presentationLimit: The presentation limit to enforce.
///
/// - Returns: A presentation of this credential.
///
/// - Throws: An error if the presentation limit for this credential has been exceeded.
public mutating func makePresentation<D: DataProtocol>(
context: D,
presentationLimit: Int
) throws -> (presentation: P256._ARCV1.Presentation, nonce: Int) {
try self.makePresentation(
context: context,
presentationLimit: presentationLimit,
fixedNonce: nil,
a: .random,
r: .random,
z: .random
)
}
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P256._ARCV1.PrivateKey {
/// Verify a presentation is valid for a given attribute.
///
/// Presentation verification includes checking that:
/// 1. The presentation is for the expected request context.
/// 2. The presentation is for the expected presentation context.
/// 3. The presentation nonce is appropriate for the presentation limit.
/// 4. The presentation proof is valid.
///
/// - Parameters:
/// - presentation: The presentation to verify.
/// - requestContext: The expected request context encoded within the presentation.
/// - presentationContext: The expected presentation context encoded within the presentation.
/// - presentationLimit: The presentation limit to enforce.
/// - nonce: The expected nonce encoded within the presentation.
///
/// - Returns: True if the presentation is valid, false otherwise.
public func verify<D1: DataProtocol, D2: DataProtocol>(
_ presentation: P256._ARCV1.Presentation,
requestContext: D1,
presentationContext: D2,
presentationLimit: Int,
nonce: Int
) throws -> Bool {
try self.backing.verify(
presentation: presentation.backing,
requestContext: Data(requestContext),
presentationContext: Data(presentationContext),
presentationLimit: presentationLimit,
nonce: nonce
)
}
}
// MARK: - P384 + ARC(P-384)
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
extension P384 {
/// Anonymous Rate-Limited Credentials (ARC).
///
@@ -28,14 +408,15 @@ extension P384 {
/// - Seealso: [IETF Internet Draft: draft-yun-cfrg-arc-00](https://datatracker.ietf.org/doc/draft-yun-cfrg-arc).
public enum _ARCV1 {
internal typealias H2G = HashToCurveImpl<P384>
fileprivate typealias Ciphersuite = ARC.Ciphersuite<H2G>
internal typealias Ciphersuite = ARC.Ciphersuite<H2G>
fileprivate typealias Server = ARC.Server<H2G>
fileprivate static var ciphersuite: Ciphersuite { Ciphersuite(H2G.self) }
internal static let ciphersuite = Ciphersuite(H2G.self)
}
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
extension P384._ARCV1 {
/// The server secrets used to issue and verify credentials.
public struct PrivateKey: Sendable {
@@ -173,11 +554,11 @@ extension P384._ARCV1 {
}
public init<D: DataProtocol>(rawRepresentation: D) throws {
self.backing = try ARC.CredentialRequest.deserialize(requestData: rawRepresentation)
self.backing = try ARC.CredentialRequest.deserialize(requestData: rawRepresentation, ciphersuite: P384._ARCV1.ciphersuite)
}
public var rawRepresentation: Data {
self.backing.serialize()
self.backing.serialize(ciphersuite: P384._ARCV1.ciphersuite)
}
}
@@ -208,11 +589,11 @@ extension P384._ARCV1 {
}
public init<D: DataProtocol>(rawRepresentation: D) throws {
self.backing = try ARC.CredentialResponse.deserialize(responseData: rawRepresentation)
self.backing = try ARC.CredentialResponse.deserialize(responseData: rawRepresentation, ciphersuite: P384._ARCV1.ciphersuite)
}
public var rawRepresentation: Data {
self.backing.serialize()
self.backing.serialize(ciphersuite: P384._ARCV1.ciphersuite)
}
}
@@ -239,11 +620,11 @@ extension P384._ARCV1 {
}
public init<D: DataProtocol>(rawRepresentation: D) throws {
self.backing = try ARC.Presentation.deserialize(presentationData: rawRepresentation)
self.backing = try ARC.Presentation.deserialize(presentationData: rawRepresentation, ciphersuite: P384._ARCV1.ciphersuite)
}
public var rawRepresentation: Data {
self.backing.serialize()
self.backing.serialize(ciphersuite: P384._ARCV1.ciphersuite)
}
public var tag: Data {
@@ -253,6 +634,7 @@ extension P384._ARCV1 {
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
extension P384._ARCV1.PublicKey {
internal func prepareCredentialRequest<D: DataProtocol>(
requestContext: D,
@@ -290,6 +672,7 @@ extension P384._ARCV1.PublicKey {
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
extension P384._ARCV1.PrivateKey {
internal func issue(
_ credentialRequest: P384._ARCV1.CredentialRequest,
@@ -306,6 +689,7 @@ extension P384._ARCV1.PrivateKey {
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
extension P384._ARCV1.PublicKey {
/// Create a credential from the issuer response.
public func finalize(
@@ -318,6 +702,7 @@ extension P384._ARCV1.PublicKey {
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
extension P384._ARCV1.Credential {
internal mutating func makePresentation<D: DataProtocol>(
context: D,
@@ -363,6 +748,7 @@ extension P384._ARCV1.Credential {
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
extension P384._ARCV1.PrivateKey {
/// Verify a presentation is valid for a given attribute.
///
+11 -6
View File
@@ -25,8 +25,6 @@ enum ARC {}
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, macCatalyst 13.2, visionOS 1.2, *)
extension ARC {
static let domain = "ARCV1-P384"
enum Errors: Error {
case invalidProof
case invalidPresentationLimit
@@ -44,26 +42,33 @@ extension ARC {
/// Ciphersuites for Anonymous Rate-Limited Credentials (ARC)
struct Ciphersuite<H2G: HashToGroup> {
let suiteID: Int
let domain: String
let scalarByteCount: Int
let pointByteCount: Int
init(_ h2g: H2G.Type) {
switch h2g.self {
case is HashToCurveImpl<P256>.Type:
self.suiteID = 3
self.domain = "ARCV1-P256"
self.scalarByteCount = P256.orderByteCount
self.pointByteCount = P256.compressedx962PointByteCount
case is HashToCurveImpl<P384>.Type:
self.suiteID = 4
case is HashToCurveImpl<P521>.Type:
self.suiteID = 5
self.domain = "ARCV1-P384"
self.scalarByteCount = P384.orderByteCount
self.pointByteCount = P384.compressedx962PointByteCount
default:
fatalError("Anonymous Rate-Limited Credentials (ARC) only support corecrypto H2G.")
}
}
}
static func getGenerators<H2G: HashToGroup>(suite _: Ciphersuite<H2G>) -> (
static func getGenerators<H2G: HashToGroup>(suite: Ciphersuite<H2G>) -> (
generatorG: H2G.G.Element, generatorH: H2G.G.Element
) {
let generatorG = H2G.G.Element.generator
let generatorH = H2G.hashToGroup(generatorG.oprfRepresentation, domainSeparationString: Data(("HashToGroup-" + ARC.domain + "generatorH").utf8))
let generatorH = H2G.hashToGroup(generatorG.oprfRepresentation, domainSeparationString: Data(("HashToGroup-" + suite.domain + "generatorH").utf8))
return (generatorG, generatorH)
}
}
@@ -34,7 +34,7 @@ extension ARC {
init(credentialResponse: CredentialResponse<H2G>, credentialRequest: CredentialRequest<H2G>, clientSecrets: ClientSecrets<Group.Scalar>, serverPublicKey: ServerPublicKey<H2G>, ciphersuite: Ciphersuite<H2G>, generatorG: Group.Element, generatorH: Group.Element) throws {
// Verify credential response proof
guard
try credentialResponse.verify(request: credentialRequest, serverPublicKey: serverPublicKey, generatorG: generatorG, generatorH: generatorH)
try credentialResponse.verify(request: credentialRequest, serverPublicKey: serverPublicKey, generatorG: generatorG, generatorH: generatorH, ciphersuite: ciphersuite)
else {
throw ARC.Errors.invalidProof
}
+105 -98
View File
@@ -18,148 +18,155 @@ import Foundation
#endif
import Crypto
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
typealias ARCCurve = P384
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, macCatalyst 13.2, visionOS 1.2, *)
typealias ARCH2G = HashToCurveImpl<ARCCurve>
typealias ARCP256 = HashToCurveImpl<P256>
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, macCatalyst 13.2, visionOS 1.2, *)
typealias ARCP384 = HashToCurveImpl<P384>
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, macCatalyst 13.2, visionOS 1.2, *)
extension ARC.CredentialRequest where H2G == ARCH2G {
static let scalarCount = 5
static let serializedByteCount = 2 * ARCCurve.compressedx962PointByteCount + Self.scalarCount * ARCCurve.orderByteCount
extension ARC.CredentialRequest {
static func getScalarCount() -> Int { return 5 }
static func getSerializedByteCount(_ ciphersuite: ARC.Ciphersuite<H2G>) -> Int {
return 2 * ciphersuite.pointByteCount + Self.getScalarCount() * ciphersuite.scalarByteCount
}
func serialize() -> Data {
var result = Data(capacity: Self.serializedByteCount)
result.append(self.m1Enc.compressedRepresentation)
result.append(self.m2Enc.compressedRepresentation)
result.append(self.proof.serialize())
func serialize(ciphersuite: ARC.Ciphersuite<H2G>) -> Data {
var result = Data(capacity: Self.getSerializedByteCount(ciphersuite))
result.append(self.m1Enc.oprfRepresentation)
result.append(self.m2Enc.oprfRepresentation)
result.append(self.proof.serialize(ciphersuite: ciphersuite))
return result
}
static func deserialize<D: DataProtocol>(requestData: D) throws -> ARC.CredentialRequest<ARCH2G> {
guard requestData.count == Self.serializedByteCount else {
static func deserialize<D: DataProtocol>(requestData: D, ciphersuite: ARC.Ciphersuite<H2G>) throws -> ARC.CredentialRequest<H2G> {
guard requestData.count == Self.getSerializedByteCount(ciphersuite) else {
throw ARC.Errors.incorrectRequestDataSize
}
var bytes = Data(requestData)
let m1Enc = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let m2Enc = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let proof = try Proof.deserialize(proofData: bytes, scalarCount: Self.scalarCount)
let m1Enc = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let m2Enc = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let proof = try Proof<H2G>.deserialize(proofData: bytes, scalarCount: Self.getScalarCount(), ciphersuite: ciphersuite)
return ARC.CredentialRequest(m1Enc: m1Enc, m2Enc: m2Enc, proof: proof)
}
}
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, macCatalyst 13.2, visionOS 1.2, *)
extension ARC.CredentialResponse where H2G == ARCH2G {
static let scalarCount = 8
static let serializedByteCount = 6 * ARCCurve.compressedx962PointByteCount + Self.scalarCount * ARCCurve.orderByteCount
extension ARC.CredentialResponse {
static func getScalarCount() -> Int { return 8 }
static func getSerializedByteCount(_ ciphersuite: ARC.Ciphersuite<H2G>) -> Int {
return 6 * ciphersuite.pointByteCount + Self.getScalarCount() * ciphersuite.scalarByteCount
}
func serialize() -> Data {
var result = Data(capacity: Self.serializedByteCount)
func serialize(ciphersuite: ARC.Ciphersuite<H2G>) -> Data {
var result = Data(capacity: Self.getSerializedByteCount(ciphersuite))
result.append(self.U.compressedRepresentation)
result.append(self.encUPrime.compressedRepresentation)
result.append(self.X0Aux.compressedRepresentation)
result.append(self.X1Aux.compressedRepresentation)
result.append(self.X2Aux.compressedRepresentation)
result.append(self.HAux.compressedRepresentation)
result.append(self.proof.serialize())
result.append(self.U.oprfRepresentation)
result.append(self.encUPrime.oprfRepresentation)
result.append(self.X0Aux.oprfRepresentation)
result.append(self.X1Aux.oprfRepresentation)
result.append(self.X2Aux.oprfRepresentation)
result.append(self.HAux.oprfRepresentation)
result.append(self.proof.serialize(ciphersuite: ciphersuite))
return result
}
static func deserialize<D: DataProtocol>(responseData: D) throws -> ARC.CredentialResponse<ARCH2G> {
guard responseData.count == self.serializedByteCount else {
static func deserialize<D: DataProtocol>(responseData: D, ciphersuite: ARC.Ciphersuite<H2G>) throws -> ARC.CredentialResponse<H2G> {
guard responseData.count == self.getSerializedByteCount(ciphersuite) else {
throw ARC.Errors.incorrectResponseDataSize
}
var bytes = Data(responseData)
let U = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let encUPrime = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X0Aux = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X1Aux = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X2Aux = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let HAux = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let U = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let encUPrime = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let X0Aux = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let X1Aux = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let X2Aux = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let HAux = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let proof = try Proof.deserialize(proofData: bytes, scalarCount: self.scalarCount)
let proof = try Proof<H2G>.deserialize(proofData: bytes, scalarCount: Self.getScalarCount(), ciphersuite: ciphersuite)
return ARC.CredentialResponse(U: U, encUPrime: encUPrime, X0Aux: X0Aux, X1Aux: X1Aux, X2Aux: X2Aux, HAux: HAux, proof: proof)
}
}
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, macCatalyst 13.2, visionOS 1.2, *)
extension ARC.Presentation where H2G == ARCH2G {
static let scalarCount = 5
static let pointCount = 4
static let serializedByteCount = pointCount * ARCCurve.compressedx962PointByteCount + scalarCount * ARCCurve.orderByteCount
extension ARC.Presentation {
static func getScalarCount() -> Int { return 5 }
static func getPointCount() -> Int { return 4 }
static func getSerializedByteCount(_ ciphersuite: ARC.Ciphersuite<H2G>) -> Int {
return Self.getPointCount() * ciphersuite.pointByteCount + Self.getScalarCount() * ciphersuite.scalarByteCount
}
func serialize() -> Data {
var result = Data(capacity: Self.serializedByteCount)
func serialize(ciphersuite: ARC.Ciphersuite<H2G>) -> Data {
var result = Data(capacity: Self.getSerializedByteCount(ciphersuite))
result.append(self.U.compressedRepresentation)
result.append(self.UPrimeCommit.compressedRepresentation)
result.append(self.m1Commit.compressedRepresentation)
result.append(self.tag.compressedRepresentation)
result.append(self.proof.serialize())
result.append(self.U.oprfRepresentation)
result.append(self.UPrimeCommit.oprfRepresentation)
result.append(self.m1Commit.oprfRepresentation)
result.append(self.tag.oprfRepresentation)
result.append(self.proof.serialize(ciphersuite: ciphersuite))
return result
}
static func deserialize<D: DataProtocol>(presentationData: D) throws -> ARC.Presentation<ARCH2G> {
guard presentationData.count == self.serializedByteCount else {
static func deserialize<D: DataProtocol>(presentationData: D, ciphersuite: ARC.Ciphersuite<H2G>) throws -> ARC.Presentation<H2G> {
guard presentationData.count == self.getSerializedByteCount(ciphersuite) else {
throw ARC.Errors.incorrectPresentationDataSize
}
var bytes = Data(presentationData)
let U = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let UPrimeCommit = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let m1Commit = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let tag = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let presentationProof = try Proof.deserialize(proofData: bytes, scalarCount: Self.scalarCount)
let U = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let UPrimeCommit = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let m1Commit = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let tag = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let presentationProof = try Proof<H2G>.deserialize(proofData: bytes, scalarCount: Self.getScalarCount(), ciphersuite: ciphersuite)
return ARC.Presentation(U: U, UPrimeCommit: UPrimeCommit, m1Commit: m1Commit, tag: tag, proof: presentationProof)
}
}
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, macCatalyst 13.2, visionOS 1.2, *)
extension ARC.ServerPublicKey where H2G == ARCH2G {
static let serializedByteCount = 3 * ARCCurve.compressedx962PointByteCount
static let pointCount = 3 // TODO: delete
extension ARC.ServerPublicKey {
static func getSerializedByteCount(_ ciphersuite: ARC.Ciphersuite<H2G>) -> Int {
return 3 * ciphersuite.pointByteCount
}
func serialize() -> Data {
var result = Data(capacity: Self.serializedByteCount)
func serialize(ciphersuite: ARC.Ciphersuite<H2G>) -> Data {
var result = Data(capacity: Self.getSerializedByteCount(ciphersuite))
result.append(self.X0.compressedRepresentation)
result.append(self.X1.compressedRepresentation)
result.append(self.X2.compressedRepresentation)
result.append(self.X0.oprfRepresentation)
result.append(self.X1.oprfRepresentation)
result.append(self.X2.oprfRepresentation)
return result
}
static func deserialize<D: DataProtocol>(serverPublicKeyData: D) throws -> ARC.ServerPublicKey<ARCH2G> {
guard serverPublicKeyData.count == self.pointCount * ARCCurve.compressedx962PointByteCount else {
static func deserialize<D: DataProtocol>(serverPublicKeyData: D, ciphersuite: ARC.Ciphersuite<H2G>) throws -> ARC.ServerPublicKey<H2G> {
guard serverPublicKeyData.count == self.getSerializedByteCount(ciphersuite) else {
throw ARC.Errors.incorrectServerCommitmentsSize
}
var bytes = Data(serverPublicKeyData)
let X0 = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X1 = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X2 = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X0 = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let X1 = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let X2 = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
return ARC.ServerPublicKey(X0: X0, X1: X1, X2: X2)
}
}
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, macCatalyst 13.2, visionOS 1.2, *)
extension Proof where H2G == ARCH2G {
func serialize() -> Data {
extension Proof {
func serialize(ciphersuite: ARC.Ciphersuite<H2G>) -> Data {
let scalarCount = self.responses.count + 1
var result = Data(capacity: scalarCount * ARCCurve.orderByteCount)
var result = Data(capacity: scalarCount * ciphersuite.scalarByteCount)
// Serialize challenge
result.append(self.challenge.rawRepresentation)
@@ -170,21 +177,21 @@ extension Proof where H2G == ARCH2G {
return result
}
static func deserialize<D: DataProtocol>(proofData: D, scalarCount: Int) throws -> Proof<ARCH2G> {
guard proofData.count == scalarCount * ARCCurve.orderByteCount else {
static func deserialize<D: DataProtocol>(proofData: D, scalarCount: Int, ciphersuite: ARC.Ciphersuite<H2G>) throws -> Proof<H2G> {
guard proofData.count == scalarCount * ciphersuite.scalarByteCount else {
throw ARC.Errors.incorrectProofDataSize
}
var bytes = Data(proofData)
// Deserialize challenge
let challenge = try ARCH2G.G.Scalar(bytes: bytes.popFirst(ARCCurve.orderByteCount))
let challenge = try H2G.G.Scalar(bytes: bytes.popFirst(ciphersuite.scalarByteCount), reductionIsModOrder: true)
// Deserialize responses
var responses: [GroupImpl<ARCCurve>.Scalar] = []
var responses: [H2G.G.Scalar] = []
responses.reserveCapacity(scalarCount - 1)
for _ in (0..<scalarCount-1) {
let response = try ARCH2G.G.Scalar(bytes: bytes.popFirst(ARCCurve.orderByteCount))
let response = try H2G.G.Scalar(bytes: bytes.popFirst(ciphersuite.scalarByteCount), reductionIsModOrder: true)
responses.append(response)
}
@@ -195,47 +202,47 @@ extension Proof where H2G == ARCH2G {
// Serialize a ARC credential, to save and restore client state.
// This will only be called client-side, and never be sent over the wire.
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, macCatalyst 13.2, visionOS 1.2, *)
extension ARC.Credential where H2G == ARCH2G {
static let scalarCount = 1
static let pointCount = 5
extension ARC.Credential {
static func getScalarCount() -> Int { return 1 }
static func getPointCount() -> Int { return 5 }
static func getSerializedByteCountExcludingPresentationState(_ ciphersuite: ARC.Ciphersuite<H2G>) -> Int {
return Self.getPointCount() * ciphersuite.pointByteCount + Self.getScalarCount() * ciphersuite.scalarByteCount
}
static let serializedByteCountExcludingPresentationState = 1 * ARCCurve.orderByteCount + 5 * ARCCurve.compressedx962PointByteCount
func serialize() throws -> Data {
func serialize(ciphersuite: ARC.Ciphersuite<H2G>) throws -> Data {
let presentationStateBytes = try self.presentationState.serialize()
var result = Data(capacity: Self.serializedByteCountExcludingPresentationState + presentationStateBytes.count)
var result = Data(capacity: Self.getSerializedByteCountExcludingPresentationState(ciphersuite) + presentationStateBytes.count)
result.append(self.m1.rawRepresentation)
result.append(self.U.compressedRepresentation)
result.append(self.UPrime.compressedRepresentation)
result.append(self.X1.compressedRepresentation)
result.append(self.generatorG.compressedRepresentation)
result.append(self.generatorH.compressedRepresentation)
result.append(self.U.oprfRepresentation)
result.append(self.UPrime.oprfRepresentation)
result.append(self.X1.oprfRepresentation)
result.append(self.generatorG.oprfRepresentation)
result.append(self.generatorH.oprfRepresentation)
result.append(presentationStateBytes)
return result
}
static func deserialize<D: DataProtocol>(credentialData: D) throws -> ARC.Credential<ARCH2G> {
guard credentialData.count - Self.serializedByteCountExcludingPresentationState >= 0 else {
static func deserialize<D: DataProtocol>(credentialData: D, ciphersuite: ARC.Ciphersuite<H2G>) throws -> ARC.Credential<H2G> {
guard credentialData.count - Self.getSerializedByteCountExcludingPresentationState(ciphersuite) >= 0 else {
throw ARC.Errors.incorrectCredentialDataSize
}
let credentialData = Data(credentialData)
var bytes = Data(credentialData)
let m1 = try ARCH2G.G.Scalar(bytes: bytes.popFirst(ARCCurve.orderByteCount))
let U = try ARCH2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let UPrime = try ARCH2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X1 = try ARCH2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let genG = try ARCH2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let genH = try ARCH2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let m1 = try H2G.G.Scalar(bytes: bytes.popFirst(ciphersuite.scalarByteCount), reductionIsModOrder: true)
let U = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let UPrime = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let X1 = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let genG = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
let genH = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ciphersuite.pointByteCount))
// Deserialize presentationState from remaining bytes.
let presentationState = try ARC.PresentationState.deserialize(presentationStateData: bytes)
let ciphersuite = ARC.Ciphersuite(ARCH2G.self)
let ciphersuite = ARC.Ciphersuite(H2G.self)
return ARC.Credential(m1: m1, U: U, UPrime: UPrime, X1: X1, ciphersuite: ciphersuite, generatorG: genG, generatorH: genH, presentationState: presentationState)
}
}
@@ -44,12 +44,12 @@ extension ARC {
let credentialRequest: CredentialRequest<H2G>
init(ciphersuite: Ciphersuite<H2G>, m1: Group.Scalar = Group.Scalar.random, requestContext: Data, r1: Group.Scalar = Group.Scalar.random, r2: Group.Scalar = Group.Scalar.random, serverPublicKey: ServerPublicKey<H2G>) throws {
let m2 = try H2G.hashToScalar(requestContext, domainSeparationString: Data((ARC.domain + "requestContext").utf8))
let m2 = try H2G.hashToScalar(requestContext, domainSeparationString: Data((ciphersuite.domain + "requestContext").utf8))
self.clientSecrets = ClientSecrets(m1: m1, m2: m2, r1: r1, r2: r2)
self.serverPublicKey = serverPublicKey
self.ciphersuite = ciphersuite
(self.generatorG, self.generatorH) = ARC.getGenerators(suite: ciphersuite)
self.credentialRequest = try CredentialRequest(clientSecrets: self.clientSecrets, generatorG: generatorG, generatorH: generatorH)
self.credentialRequest = try CredentialRequest(clientSecrets: self.clientSecrets, generatorG: generatorG, generatorH: generatorH, ciphersuite: ciphersuite)
}
func makeCredential(credentialResponse: CredentialResponse<H2G>) throws -> Credential<H2G> {
@@ -49,9 +49,9 @@ extension ARC {
let V = z * credential.X1 - r * generatorG
// Create tag: (m1 + nonce)^(-1) * H2G(presentationContext)
let nonceScalar = try Group.Scalar(bytes: I2OSP(value: nonce, outputByteCount: ARCCurve.orderByteCount), reductionIsModOrder: true)
let nonceScalar = try Group.Scalar(bytes: I2OSP(value: nonce, outputByteCount: credential.ciphersuite.scalarByteCount), reductionIsModOrder: true)
let inverse = (nonceScalar + credential.m1) ^ (-1)
let T = H2G.hashToGroup(presentationContext, domainSeparationString: Data(("HashToGroup-" + ARC.domain + "Tag").utf8))
let T = H2G.hashToGroup(presentationContext, domainSeparationString: Data(("HashToGroup-" + credential.ciphersuite.domain + "Tag").utf8))
let tag = inverse * T
// m1Tag is a helper element in the ZKP, and is needed to ensure the
@@ -59,7 +59,7 @@ extension ARC {
let m1Tag = credential.m1 * tag
// Create a prover, and allocate variables for the constrained scalars.
var prover = Prover<H2G>(label: ARC.domain + ARC.domain + "CredentialPresentation")
var prover = Prover<H2G>(label: credential.ciphersuite.domain + credential.ciphersuite.domain + "CredentialPresentation")
let m1Var = prover.appendScalar(label: "m1", assignment: credential.m1)
let zVar = prover.appendScalar(label: "z", assignment: z)
let rNegVar = prover.appendScalar(label: "-r", assignment: -r)
@@ -90,12 +90,10 @@ extension ARC {
- nonce: Integer which is used for rate limiting, which should be in `[0, presentationLimit)`.
- generatorG: Public generator G
- generatorH: Public generator H
- ciphersuite: The ciphersuite for ARC
- Returns: a boolean for if the tag is valid and the tag proof verifies correctly.
*/
func verify(
serverPrivateKey: ServerPrivateKey<Group.Scalar>, X1: Group.Element, m2: Group.Scalar, presentationContext: Data, presentationLimit: Int, nonce: Int,
generatorG: Group.Element, generatorH: Group.Element
) throws -> Bool {
func verify(serverPrivateKey: ServerPrivateKey<Group.Scalar>, X1: Group.Element, m2: Group.Scalar, presentationContext: Data, presentationLimit: Int, nonce: Int, generatorG: Group.Element, generatorH: Group.Element, ciphersuite: Ciphersuite<H2G>) throws -> Bool {
if nonce < 0 || nonce >= presentationLimit {
return false // nonce is outside of the presentationLimit
}
@@ -107,14 +105,14 @@ extension ARC {
let V = serverPrivateKey.x0 * self.U + serverPrivateKey.x1 * self.m1Commit + serverPrivateKey.x2 * m2 * self.U - self.UPrimeCommit
// Recompute T = H2G(presentationContext)
let T = H2G.hashToGroup(presentationContext, domainSeparationString: Data(("HashToGroup-" + ARC.domain + "Tag").utf8))
let T = H2G.hashToGroup(presentationContext, domainSeparationString: Data(("HashToGroup-" + ciphersuite.domain + "Tag").utf8))
// Recompute m1Tag = H2G(presentationContext) - nonce * tag
var m1Tag = T
for _ in 0..<nonce { m1Tag = m1Tag - self.tag }
// Create a verifier, and allocate variables for the constrained scalars.
var verifier = Verifier<H2G>(label: ARC.domain + ARC.domain + "CredentialPresentation")
var verifier = Verifier<H2G>(label: ciphersuite.domain + ciphersuite.domain + "CredentialPresentation")
let m1Var = verifier.appendScalar(label: "m1")
let zVar = verifier.appendScalar(label: "z")
let rNegVar = verifier.appendScalar(label: "-r")
+4 -4
View File
@@ -30,12 +30,12 @@ extension ARC {
let m2Enc: Group.Element
let proof: Proof<H2G>
init(clientSecrets: ClientSecrets<Group.Scalar>, generatorG: Group.Element, generatorH: Group.Element) throws {
init(clientSecrets: ClientSecrets<Group.Scalar>, generatorG: Group.Element, generatorH: Group.Element, ciphersuite: Ciphersuite<H2G>) throws {
let m1Enc = clientSecrets.m1 * generatorG + clientSecrets.r1 * generatorH
let m2Enc = clientSecrets.m2 * generatorG + clientSecrets.r2 * generatorH
// Create a prover, and allocate variables for the constrained scalars.
var prover = Prover<H2G>(label: ARC.domain + ARC.domain + "CredentialRequest")
var prover = Prover<H2G>(label: ciphersuite.domain + ciphersuite.domain + "CredentialRequest")
let m1Var = prover.appendScalar(label: "m1", assignment: clientSecrets.m1)
let m2Var = prover.appendScalar(label: "m2", assignment: clientSecrets.m2)
let r1Var = prover.appendScalar(label: "r1", assignment: clientSecrets.r1)
@@ -54,7 +54,7 @@ extension ARC {
self.proof = proof
}
func verify(generatorG: Group.Element, generatorH: Group.Element) throws -> Bool {
func verify(generatorG: Group.Element, generatorH: Group.Element, ciphersuite: Ciphersuite<H2G>) throws -> Bool {
// Check that the encrypted attributes were generated with nonzero `m` and `r` values.
if (self.m1Enc == generatorG || self.m1Enc == generatorH || self.m1Enc == self.m1Enc + self.m1Enc) ||
(self.m2Enc == generatorG || self.m2Enc == generatorH || self.m2Enc == self.m2Enc + self.m2Enc) {
@@ -62,7 +62,7 @@ extension ARC {
}
// Create a verifier, and allocate variables for the constrained scalars.
var verifier = Verifier<H2G>(label: ARC.domain + ARC.domain + "CredentialRequest")
var verifier = Verifier<H2G>(label: ciphersuite.domain + ciphersuite.domain + "CredentialRequest")
let m1Var = verifier.appendScalar(label: "m1")
let m2Var = verifier.appendScalar(label: "m2")
let r1Var = verifier.appendScalar(label: "r1")
+5 -5
View File
@@ -52,7 +52,8 @@ extension ARC {
serverPublicKey: ServerPublicKey<H2G>,
generatorG: Group.Element,
generatorH: Group.Element,
b: Group.Scalar = Group.Scalar.random
b: Group.Scalar = Group.Scalar.random,
ciphersuite: Ciphersuite<H2G>
) throws {
let U = b * generatorG
let X0Aux = b * serverPrivateKey.x0Blinding * generatorH
@@ -65,7 +66,7 @@ extension ARC {
let encUPrime = b * (serverPublicKey.X0 + serverPrivateKey.x1 * request.m1Enc + serverPrivateKey.x2 * request.m2Enc)
// Create a prover, and allocate variables for the constrained scalars.
var prover = Prover<H2G>(label: ARC.domain + ARC.domain + "CredentialResponse")
var prover = Prover<H2G>(label: ciphersuite.domain + ciphersuite.domain + "CredentialResponse")
let x0Var = prover.appendScalar(label: "x0", assignment: serverPrivateKey.x0)
let x1Var = prover.appendScalar(label: "x1", assignment: serverPrivateKey.x1)
let x2Var = prover.appendScalar(label: "x2", assignment: serverPrivateKey.x2)
@@ -99,15 +100,14 @@ extension ARC {
self.proof = proof
}
func verify(request: CredentialRequest<H2G>, serverPublicKey: ServerPublicKey<H2G>, generatorG: Group.Element, generatorH: Group.Element
) throws -> Bool {
func verify(request: CredentialRequest<H2G>, serverPublicKey: ServerPublicKey<H2G>, generatorG: Group.Element, generatorH: Group.Element, ciphersuite: Ciphersuite<H2G>) throws -> Bool {
// Check that U, encUPrime are not 0
if (self.U == self.U + self.U) || (self.encUPrime == self.encUPrime + self.encUPrime) {
return false
}
// Create a verifier, and allocate variables for the constrained scalars.
var verifier = Verifier<H2G>(label: ARC.domain + ARC.domain + "CredentialResponse")
var verifier = Verifier<H2G>(label: ciphersuite.domain + ciphersuite.domain + "CredentialResponse")
let x0Var = verifier.appendScalar(label: "x0")
let x1Var = verifier.appendScalar(label: "x1")
let x2Var = verifier.appendScalar(label: "x2")
+6 -4
View File
@@ -72,7 +72,7 @@ extension ARC {
func respond(credentialRequest: CredentialRequest<H2G>, b: Group.Scalar = Group.Scalar.random) throws -> CredentialResponse<H2G> {
guard
try credentialRequest.verify(generatorG: generatorG, generatorH: generatorH)
try credentialRequest.verify(generatorG: generatorG, generatorH: generatorH, ciphersuite: self.ciphersuite)
else {
throw ARC.Errors.invalidProof
}
@@ -82,12 +82,13 @@ extension ARC {
serverPublicKey: self.serverPublicKey,
generatorG: generatorG,
generatorH: generatorH,
b: b
b: b,
ciphersuite: self.ciphersuite
)
}
func verify(presentation: Presentation<H2G>, requestContext: Data, presentationContext: Data, presentationLimit: Int, nonce: Int) throws -> Bool {
let m2 = try H2G.hashToScalar(requestContext, domainSeparationString: Data((ARC.domain + "requestContext").utf8))
let m2 = try H2G.hashToScalar(requestContext, domainSeparationString: Data((self.ciphersuite.domain + "requestContext").utf8))
return try presentation.verify(
serverPrivateKey: self.serverPrivateKey,
X1: self.serverPublicKey.X1,
@@ -96,7 +97,8 @@ extension ARC {
presentationLimit: presentationLimit,
nonce: nonce,
generatorG: generatorG,
generatorH: generatorH
generatorH: generatorH,
ciphersuite: self.ciphersuite
)
}
}
+9 -1
View File
@@ -21,6 +21,7 @@ add_library(_CryptoExtras
"AES/BoringSSL/AES_CFB_boring.swift"
"AES/BoringSSL/AES_CTR_boring.swift"
"AES/BoringSSL/AES_GCM_SIV_boring.swift"
"AES/CMAC.swift"
"ARC/ARC+API.swift"
"ARC/ARC.swift"
"ARC/ARCCredential.swift"
@@ -32,6 +33,10 @@ add_library(_CryptoExtras
"ARC/ARCServer.swift"
"ChaCha20CTR/BoringSSL/ChaCha20CTR_boring.swift"
"ChaCha20CTR/ChaCha20CTR.swift"
"EC/ObjectIdentifier.swift"
"EC/PKCS8DERRepresentation.swift"
"EC/PKCS8PrivateKey.swift"
"EC/RFC8410AlgorithmIdentifier.swift"
"ECToolbox/BoringSSL/ECToolbox_boring.swift"
"ECToolbox/ECToolbox.swift"
"H2G/HashToField.swift"
@@ -50,7 +55,6 @@ add_library(_CryptoExtras
"RSA/RSA+BlindSigning.swift"
"RSA/RSA.swift"
"RSA/RSA_boring.swift"
"RSA/RSA_security.swift"
"Reexport.swift"
"Util/BoringSSLHelpers.swift"
"Util/CryptoKitErrors_boring.swift"
@@ -62,6 +66,10 @@ add_library(_CryptoExtras
"Util/PEMDocument.swift"
"Util/PrettyBytes.swift"
"Util/SubjectPublicKeyInfo.swift"
"Util/ThreadSpecific/ThreadOps.swift"
"Util/ThreadSpecific/ThreadPosix.swift"
"Util/ThreadSpecific/ThreadSpecific.swift"
"Util/ThreadSpecific/ThreadWindows.swift"
"ZKPs/DLEQ.swift"
"ZKPs/Prover.swift"
"ZKPs/Verifier.swift"
-4
View File
@@ -15,10 +15,6 @@ Provides additional cryptographic APIs that are not available in CryptoKit (and
### Public key cryptography
- ``_RSA``
- ``MLKEM768``
- ``MLKEM1024``
- ``MLDSA65``
- ``MLDSA87``
### Key derivation functions
@@ -0,0 +1,37 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2025 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 SwiftASN1
extension ASN1ObjectIdentifier.AlgorithmIdentifier {
// Identifies the key agreement algorithm X25519.
//
// This identifier is defined in RFC 8410
static let idX25519: ASN1ObjectIdentifier = [1, 3, 101, 110]
// Identifies the key agreement algorithm X448.
//
// This identifier is defined in RFC 8410
static let idX448: ASN1ObjectIdentifier = [1, 3, 101, 111]
// Identifies the signature algorithm Ed25519.
//
// This identifier is defined in RFC 8410
static let idEd25519: ASN1ObjectIdentifier = [1, 3, 101, 112]
// Identifies the signature algorithm Ed448.
//
// This identifier is defined in RFC 8410
static let idEd448: ASN1ObjectIdentifier = [1, 3, 101, 113]
}
@@ -0,0 +1,76 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Crypto
import Foundation
import SwiftASN1
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *)
extension Curve25519.Signing.PrivateKey {
/// A Distinguished Encoding Rules (DER) encoded representation of the private key in PKCS#8 format.
public var pkcs8DERRepresentation: Data {
let pkey = ASN1.PKCS8PrivateKey(algorithm: .ed25519, privateKey: Array(self.rawRepresentation))
var serializer = DER.Serializer()
// Serializing this key can't throw
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
}
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *)
extension Curve25519.KeyAgreement.PrivateKey {
/// A Distinguished Encoding Rules (DER) encoded representation of the private key in PKCS#8 format.
public var pkcs8DERRepresentation: Data {
let pkey = ASN1.PKCS8PrivateKey(algorithm: .x25519, privateKey: Array(self.rawRepresentation))
var serializer = DER.Serializer()
// Serializing this key can't throw
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
}
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *)
extension P256.Signing.PrivateKey {
/// A Distinguished Encoding Rules (DER) encoded representation of the private key in PKCS#8 format.
///
/// This property provides the same output as the existing `derRepresentation` property,
/// which already conforms to the PKCS#8 standard.
public var pkcs8DERRepresentation: Data {
self.derRepresentation
}
}
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *)
extension P384.Signing.PrivateKey {
/// A Distinguished Encoding Rules (DER) encoded representation of the private key in PKCS#8 format.
///
/// This property provides the same output as the existing `derRepresentation` property,
/// which already conforms to the PKCS#8 standard.
public var pkcs8DERRepresentation: Data {
self.derRepresentation
}
}
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *)
extension P521.Signing.PrivateKey {
/// A Distinguished Encoding Rules (DER) encoded representation of the private key in PKCS#8 format.
///
/// This property provides the same output as the existing `derRepresentation` property,
/// which already conforms to the PKCS#8 standard.
public var pkcs8DERRepresentation: Data {
self.derRepresentation
}
}
@@ -0,0 +1,93 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Crypto
import SwiftASN1
@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:
//
// For PKCS#8 we need the following for the private key:
//
// PrivateKeyInfo ::= SEQUENCE {
// version Version,
// privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
// privateKey PrivateKey,
// attributes [0] IMPLICIT Attributes OPTIONAL }
//
// Version ::= INTEGER
//
// PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
//
// PrivateKey ::= OCTET STRING
//
// Attributes ::= SET OF Attribute
//
// We disregard the attributes because we don't support them anyway.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
struct PKCS8PrivateKey: DERImplicitlyTaggable {
static var defaultIdentifier: ASN1Identifier {
.sequence
}
var algorithm: RFC8410AlgorithmIdentifier
var privateKey: ASN1OctetString
init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
self = try DER.sequence(rootNode, identifier: identifier) { nodes in
let version = try Int(derEncoded: &nodes)
guard version == 0 || version == 1 else {
throw ASN1Error.invalidASN1Object(reason: "Version number mismatch")
}
let algorithm = try ASN1.RFC8410AlgorithmIdentifier(derEncoded: &nodes)
let privateKeyBytes = try ASN1OctetString(derEncoded: &nodes)
// We ignore the attributes
_ = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { _ in }
let privateKeyNode = try DER.parse(privateKeyBytes.bytes)
let privateKey = try ASN1OctetString(derEncoded: privateKeyNode)
return try .init(algorithm: algorithm, privateKey: privateKey)
}
}
private init(algorithm: ASN1.RFC8410AlgorithmIdentifier, privateKey: ASN1OctetString) throws {
self.privateKey = privateKey
self.algorithm = algorithm
}
init(algorithm: ASN1.RFC8410AlgorithmIdentifier, privateKey: [UInt8]) {
self.algorithm = algorithm
self.privateKey = ASN1OctetString(contentBytes: privateKey[...])
}
func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws {
try coder.appendConstructedNode(identifier: identifier) { coder in
try coder.serialize(0)
try coder.serialize(self.algorithm)
// Here's a weird one: we recursively serialize the private key, and then turn the bytes into an octet string.
var subCoder = DER.Serializer()
try subCoder.serialize(self.privateKey)
let serializedKey = ASN1OctetString(contentBytes: subCoder.serializedBytes[...])
try coder.serialize(serializedKey)
}
}
}
}
@@ -0,0 +1,74 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2025 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 SwiftASN1
@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 RFC8410AlgorithmIdentifier: DERImplicitlyTaggable, Hashable {
static var defaultIdentifier: ASN1Identifier {
.sequence
}
var algorithm: ASN1ObjectIdentifier
// RFC 8410: For all of these OIDs, the parameters MUST be absent.
// They are still part of the identifer block.
var parameters: ASN1Any?
init(algorithm: ASN1ObjectIdentifier, parameters: ASN1Any?) {
self.algorithm = algorithm
self.parameters = parameters
}
init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
// The AlgorithmIdentifier block looks like this.
//
// AlgorithmIdentifier ::= SEQUENCE {
// algorithm OBJECT IDENTIFIER,
// parameters ANY DEFINED BY algorithm OPTIONAL
// }
//
// We don't bother with helpers: we just try to decode it directly.
self = try DER.sequence(rootNode, identifier: identifier) { nodes in
let algorithmOID = try ASN1ObjectIdentifier(berEncoded: &nodes)
let parameters = nodes.next().map { ASN1Any(berEncoded: $0) }
return .init(algorithm: algorithmOID, parameters: parameters)
}
}
func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws {
try coder.appendConstructedNode(identifier: identifier) { coder in
try coder.serialize(self.algorithm)
if let parameters = self.parameters {
try coder.serialize(parameters)
}
}
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension ASN1.RFC8410AlgorithmIdentifier {
static let x25519 = ASN1.RFC8410AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idX25519, parameters: nil)
static let x448 = ASN1.RFC8410AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idX448, parameters: nil)
static let ed25519 = ASN1.RFC8410AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEd25519, parameters: nil)
static let ed448 = ASN1.RFC8410AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEd448, parameters: nil)
}
@@ -70,10 +70,17 @@ extension P256: OpenSSLSupportedNISTCurve {
@inlinable
static var hashToFieldByteCount: Int { 48 }
@TaskLocal
private static let __ffacTSV = ThreadSpecificVariable<FiniteFieldArithmeticContext>()
@usableFromInline
// NOTE: This could be a let when Swift 6.0 is the minimum supported version.
static var __ffac = try! FiniteFieldArithmeticContext(fieldSize: P256.group.order)
static var __ffac: FiniteFieldArithmeticContext {
if let value = Self.__ffacTSV.currentValue {
return value
}
let value = try! FiniteFieldArithmeticContext(fieldSize: P256.group.order)
Self.__ffacTSV.currentValue = value
return value
}
}
/// NOTE: This conformance applies to this type from the Crypto module even if it comes from the SDK.
@@ -97,10 +104,17 @@ extension P384: OpenSSLSupportedNISTCurve {
@inlinable
static var hashToFieldByteCount: Int { 72 }
@TaskLocal
private static let __ffacTSV = ThreadSpecificVariable<FiniteFieldArithmeticContext>()
@usableFromInline
// NOTE: This could be a let when Swift 6.0 is the minimum supported version.
static var __ffac = try! FiniteFieldArithmeticContext(fieldSize: P384.group.order)
static var __ffac: FiniteFieldArithmeticContext {
if let value = Self.__ffacTSV.currentValue {
return value
}
let value = try! FiniteFieldArithmeticContext(fieldSize: P384.group.order)
Self.__ffacTSV.currentValue = value
return value
}
}
/// NOTE: This conformance applies to this type from the Crypto module even if it comes from the SDK.
@@ -124,10 +138,17 @@ extension P521: OpenSSLSupportedNISTCurve {
@inlinable
static var hashToFieldByteCount: Int { 98 }
@TaskLocal
private static let __ffacTSV = ThreadSpecificVariable<FiniteFieldArithmeticContext>()
@usableFromInline
// NOTE: This could be a let when Swift 6.0 is the minimum supported version.
static var __ffac = try! FiniteFieldArithmeticContext(fieldSize: P521.group.order)
static var __ffac: FiniteFieldArithmeticContext {
if let value = Self.__ffacTSV.currentValue {
return value
}
let value = try! FiniteFieldArithmeticContext(fieldSize: P521.group.order)
Self.__ffacTSV.currentValue = value
return value
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
@@ -499,7 +499,7 @@ extension _RSA.BlindSigning.PublicKey {
extension _RSA.BlindSigning {
/// Errors defined in the RSA Blind Signatures protocol.
///
/// - NOTE: This type does not conform to `Swift.Error`, it is used to construct a `CryptoKitError`.
/// - NOTE: This type does not conform to `Swift.Error`, it is used to construct a `CryptoError`.
///
/// - Seealso: [RFC 9474: Errors](https://www.rfc-editor.org/rfc/rfc9474.html#name-errors).
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
@@ -516,7 +516,7 @@ extension _RSA.BlindSigning {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension CryptoKitError {
/// Map an error from the RSA Blind Signatures protocol to a CryptoKitError.
/// Map an error from the RSA Blind Signatures protocol to a CryptoError.
init(_ error: _RSA.BlindSigning.ProtocolError) {
switch error {
case .messageTooLong:
+9 -35
View File
@@ -20,17 +20,10 @@ import Crypto
import CryptoBoringWrapper
import SwiftASN1
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
fileprivate typealias BackingPublicKey = SecurityRSAPublicKey
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
fileprivate typealias BackingPrivateKey = SecurityRSAPrivateKey
#else
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
fileprivate typealias BackingPublicKey = BoringSSLRSAPublicKey
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
fileprivate typealias BackingPrivateKey = BoringSSLRSAPrivateKey
#endif
/// Types associated with the RSA algorithm
///
@@ -124,14 +117,8 @@ extension _RSA.Signing {
}
/// Construct an RSA public key with the specified parameters.
///
/// Only the BoringSSL backend provides APIs to create a key from its parameters so we first create a BoringSSL
/// key, and then pass it to the platform-specific initializer that accepts a BoringSSL key.
///
/// On Darwin platforms, this will serialize it to PEM format, and then construct a platform-specific key from
/// the PEM representation.
public init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.backing = try BackingPublicKey(BoringSSLRSAPublicKey(n: n, e: e))
self.backing = try BackingPublicKey(n: n, e: e)
}
public var pkcs1DERRepresentation: Data {
@@ -222,14 +209,8 @@ extension _RSA.Signing {
}
/// Construct an RSA private key with the specified parameters.
///
/// Only the BoringSSL backend provides APIs to create a key from its parameters so we first create a BoringSSL
/// key, and then pass it to the platform-specific initializer that accepts a BoringSSL key.
///
/// On Darwin platforms, this will serialize it to DER format, and then construct a platform-specific key from
/// the DER representation.
public init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes) throws {
self.backing = try BackingPrivateKey(BoringSSLRSAPrivateKey(n: n, e: e, d: d, p: p, q: q))
self.backing = try BackingPrivateKey(n: n, e: e, d: d, p: p, q: q)
}
/// Randomly generate a new RSA private key of a given size.
@@ -263,6 +244,11 @@ extension _RSA.Signing {
self.backing.pemRepresentation
}
/// A Distinguished Encoding Rules (DER) encoded representation of the private key in PKCS#8 format.
public var pkcs8DERRepresentation: Data {
self.backing.pkcs8DERRepresentation
}
public var pkcs8PEMRepresentation: String {
self.backing.pkcs8PEMRepresentation
}
@@ -545,14 +531,8 @@ extension _RSA.Encryption {
}
/// Construct an RSA public key with the specified parameters.
///
/// Only the BoringSSL backend provides APIs to create a key from its parameters so we first create a BoringSSL
/// key, and then pass it to the platform-specific initializer that accepts a BoringSSL key.
///
/// On Darwin platforms, this will serialize it to DER format, and then construct a platform-specific key from
/// the DER representation.
public init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.backing = try BackingPublicKey(BoringSSLRSAPublicKey(n: n, e: e))
self.backing = try BackingPublicKey(n: n, e: e)
}
public var pkcs1DERRepresentation: Data { self.backing.pkcs1DERRepresentation }
@@ -613,14 +593,8 @@ extension _RSA.Encryption {
/// Construct an RSA private key with the specified parameters.
///
/// Only the BoringSSL backend provides APIs to create a key from its parameters so we first create a BoringSSL
/// key, and then pass it to the platform-specific initializer that accepts a BoringSSL key.
///
/// On Darwin platforms, this will serialize it to PEM format, and then construct a platform-specific key from
/// the PEM representation.
public init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes) throws {
self.backing = try BackingPrivateKey(BoringSSLRSAPrivateKey(n: n, e: e, d: d, p: p, q: q))
self.backing = try BackingPrivateKey(n: n, e: e, d: d, p: p, q: q)
}
/// Randomly generate a new RSA private key of a given size.
@@ -124,6 +124,10 @@ internal struct BoringSSLRSAPrivateKey: Sendable {
self.backing.pemRepresentation
}
var pkcs8DERRepresentation: Data {
self.backing.pkcs8DERRepresentation
}
var pkcs8PEMRepresentation: String {
self.backing.pkcs8PEMRepresentation
}
@@ -755,6 +759,15 @@ extension BoringSSLRSAPrivateKey {
}
}
fileprivate var pkcs8DERRepresentation: Data {
BIOHelper.withWritableMemoryBIO { bio in
let rc = CCryptoBoringSSL_i2d_PKCS8PrivateKeyInfo_bio(bio, self.pointer)
precondition(rc == 1, "Exporting PKCS8 DER key failed")
return try! Data(copyingMemoryBIO: bio)
}
}
fileprivate var pkcs8PEMRepresentation: String {
BIOHelper.withWritableMemoryBIO { bio in
let evp = CCryptoBoringSSL_EVP_PKEY_new()
@@ -1,482 +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
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import Crypto
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_implementationOnly import Security
// unchecked sendable until `SecKey` gets sendable annotations
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
internal struct SecurityRSAPublicKey: @unchecked Sendable {
private var backing: SecKey
init(pemRepresentation: String) throws {
let document = try ASN1.PEMDocument(pemString: pemRepresentation)
self = try .init(derRepresentation: document.derBytes)
}
init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
let keyAttributes: [CFString: Any] = [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPublic,
]
let data = Data(derRepresentation)
var error: Unmanaged<CFError>? = nil
let key = SecKeyCreateWithData(data as CFData, keyAttributes as CFDictionary, &error)
guard let unwrappedKey = key else {
// If this returns nil, error must be set.
throw error!.takeRetainedValue() as Error
}
self.backing = unwrappedKey
}
init(_ boringSSLKey: BoringSSLRSAPublicKey) throws {
try self.init(derRepresentation: boringSSLKey.derRepresentation)
}
var pkcs1DERRepresentation: Data {
var error: Unmanaged<CFError>? = nil
let representation = SecKeyCopyExternalRepresentation(self.backing, &error)
return representation! as Data
}
var pkcs1PEMRepresentation: String {
return ASN1.PEMDocument(type: _RSA.PKCS1PublicKeyType, derBytes: self.pkcs1DERRepresentation).pemString
}
var derRepresentation: Data {
return Data(spkiBytesForPKCS1Bytes: self.pkcs1DERRepresentation)
}
var pemRepresentation: String {
return ASN1.PEMDocument(type: _RSA.SPKIPublicKeyType, derBytes: self.derRepresentation).pemString
}
var keySizeInBits: Int {
SecKeyGetBlockSize(self.backing) * 8
}
fileprivate init(_ backing: SecKey) {
self.backing = backing
}
func getKeyPrimitives() throws -> (n: Data, e: Data) {
try BoringSSLRSAPublicKey(derRepresentation: self.derRepresentation).getKeyPrimitives()
}
}
// unchecked sendable until `SecKey` gets sendable annotations
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
internal struct SecurityRSAPrivateKey: @unchecked Sendable {
private var backing: SecKey
init(pemRepresentation: String) throws {
let document = try ASN1.PEMDocument(pemString: pemRepresentation)
switch document.type {
case _RSA.PKCS1KeyType:
// This is what is expected by Security.framework
self = try .init(derRepresentation: document.derBytes)
case _RSA.PKCS8KeyType:
guard let pkcs8Bytes = document.derBytes.pkcs8RSAKeyBytes else {
throw _CryptoRSAError.invalidPEMDocument
}
self = try .init(derRepresentation: pkcs8Bytes)
default:
throw _CryptoRSAError.invalidPEMDocument
}
}
init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
let keyAttributes: [CFString: Any] = [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
]
let data = Data(derRepresentation)
var error: Unmanaged<CFError>? = nil
// We can't know in DER if this is PKCS8 or PKCS1 without just trying to decode it.
let keyData: Data
if let pkcs8Data = data.pkcs8RSAKeyBytes {
keyData = pkcs8Data
} else {
keyData = data
}
let key = SecKeyCreateWithData(keyData as CFData, keyAttributes as CFDictionary, &error)
guard let unwrappedKey = key else {
// If this returns nil, error must be set.
throw error!.takeRetainedValue() as Error
}
self.backing = unwrappedKey
}
init(keySize: _RSA.Signing.KeySize) throws {
let keyAttributes: [CFString: Any] = [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
kSecAttrKeySizeInBits: keySize.bitCount
]
var error: Unmanaged<CFError>? = nil
let key = SecKeyCreateRandomKey(keyAttributes as CFDictionary, &error)
guard let unwrappedKey = key else {
// If this returns nil, error must be set.
throw error!.takeRetainedValue() as Error
}
self.backing = unwrappedKey
}
init(_ boringSSLKey: BoringSSLRSAPrivateKey) throws {
try self.init(derRepresentation: boringSSLKey.derRepresentation)
}
var derRepresentation: Data {
var error: Unmanaged<CFError>? = nil
let representation = SecKeyCopyExternalRepresentation(self.backing, &error)
return representation! as Data
}
var pemRepresentation: String {
return ASN1.PEMDocument(type: _RSA.PKCS1KeyType, derBytes: self.derRepresentation).pemString
}
var pkcs8PEMRepresentation: String {
let pkcs1Bytes = self.derRepresentation
let pkcs8Bytes = Data(privateKeyPKCS8BytesForPKCS1Bytes: pkcs1Bytes)
let pemString = ASN1.PEMDocument(type: _RSA.PKCS8KeyType, derBytes: pkcs8Bytes).pemString
// The BoringSSL implementation returns this string with a trailing newline. For consistency,
// we'll do the same here.
return pemString.appending("\n")
}
var keySizeInBits: Int {
SecKeyGetBlockSize(self.backing) * 8
}
var publicKey: SecurityRSAPublicKey {
SecurityRSAPublicKey(SecKeyCopyPublicKey(self.backing)!)
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension SecurityRSAPrivateKey {
internal func signature<D: Digest>(for digest: D, padding: _RSA.Signing.Padding) throws -> _RSA.Signing.RSASignature {
let algorithm = try SecKeyAlgorithm(digestType: D.self, padding: padding)
let digestToSign = Data(digest)
var error: Unmanaged<CFError>? = nil
let sig = SecKeyCreateSignature(self.backing, algorithm, digestToSign as CFData, &error)
guard let signature = sig else {
// If this returns nil, error must be set.
throw error!.takeRetainedValue() as Error
}
return _RSA.Signing.RSASignature(rawRepresentation: signature as Data)
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension SecurityRSAPrivateKey {
internal func decrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
let algorithm = try SecKeyAlgorithm(padding: padding)
let dataToDecrypt = Data(data)
var error: Unmanaged<CFError>? = nil
let dec = SecKeyCreateDecryptedData(self.backing, algorithm, dataToDecrypt as CFData, &error)
guard let decrypted = dec else {
throw error!.takeRetainedValue() as Error
}
return decrypted as Data
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension SecurityRSAPublicKey {
func isValidSignature<D: Digest>(_ signature: _RSA.Signing.RSASignature, for digest: D, padding: _RSA.Signing.Padding) -> Bool {
do {
let algorithm = try SecKeyAlgorithm(digestType: D.self, padding: padding)
let digestToValidate = Data(digest)
var error: Unmanaged<CFError>? = nil
let result = SecKeyVerifySignature(self.backing,
algorithm,
digestToValidate as CFData,
signature.rawRepresentation as CFData,
&error)
return result
} catch {
return false
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension SecurityRSAPublicKey {
internal func encrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
let algorithm = try SecKeyAlgorithm(padding: padding)
let dataToEncrypt = Data(data)
var error: Unmanaged<CFError>? = nil
let enc = SecKeyCreateEncryptedData(self.backing, algorithm, dataToEncrypt as CFData, &error)
guard let encrypted = enc else {
throw error!.takeRetainedValue() as Error
}
return encrypted as Data
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension SecKeyAlgorithm {
fileprivate init<D: Digest>(digestType: D.Type = D.self, padding: _RSA.Signing.Padding) throws {
switch (digestType, padding.backing) {
case (is Insecure.SHA1.Digest.Type, .pss):
self = .rsaSignatureDigestPSSSHA1
case (is Insecure.SHA1.Digest.Type, .pkcs1v1_5):
self = .rsaSignatureDigestPKCS1v15SHA1
case (is SHA256.Digest.Type, .pss):
self = .rsaSignatureDigestPSSSHA256
case (is SHA256.Digest.Type, .pkcs1v1_5):
self = .rsaSignatureDigestPKCS1v15SHA256
case (is SHA384.Digest.Type, .pss):
self = .rsaSignatureDigestPSSSHA384
case (is SHA384.Digest.Type, .pkcs1v1_5):
self = .rsaSignatureDigestPKCS1v15SHA384
case (is SHA512.Digest.Type, .pss):
self = .rsaSignatureDigestPSSSHA512
case (is SHA512.Digest.Type, .pkcs1v1_5):
self = .rsaSignatureDigestPKCS1v15SHA512
case (_, .pssZero):
// Explicitly unsupported: only used in RSABSSA, which is implemented using BoringSSL on all platforms.
throw CryptoKitError.incorrectParameterSize
default:
throw CryptoKitError.incorrectParameterSize
}
}
fileprivate init(padding: _RSA.Encryption.Padding) throws {
switch padding.backing {
case .pkcs1_oaep(let digest):
switch digest {
case .sha1:
self = .rsaEncryptionOAEPSHA1
case .sha256:
self = .rsaEncryptionOAEPSHA256
}
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension Data {
init<D: Digest>(_ digest: D) {
self = digest.withUnsafeBytes { Data($0) }
}
/// A partial PKCS8 DER prefix. This specifically is the version and private key algorithm identifier.
private static let partialPKCS8Prefix = Data(
[
0x02, 0x01, 0x00, // Version, INTEGER 0
0x30, 0x0d, // SEQUENCE, length 13
0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, // rsaEncryption OID
0x05, 0x00 // NULL
]
)
var pkcs8RSAKeyBytes: Data? {
// This is PKCS8. A bit awkward now. Rather than bring over the fully-fledged ASN.1 code from
// the main module and all its dependencies, we have a little hand-rolled verifier. To be a proper
// PKCS8 key, this should match:
//
// PrivateKeyInfo ::= SEQUENCE {
// version Version,
// privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
// privateKey PrivateKey,
// attributes [0] IMPLICIT Attributes OPTIONAL }
//
// Version ::= INTEGER
//
// PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
//
// PrivateKey ::= OCTET STRING
//
// Attributes ::= SET OF Attribute
//
// We know the version and algorithm identifier, so we can just strip the bytes we'd expect to see here. We do validate
// them though.
precondition(self.startIndex == 0)
guard self.count >= 4 + Data.partialPKCS8Prefix.count + 4 else {
return nil
}
// First byte will be the tag for sequence, 0x30.
guard self[0] == 0x30 else {
return nil
}
// The next few bytes will be a length. We'll expect it to be 3 bytes long, with the first byte telling us
// that it's 3 bytes long.
let lengthLength = Int(self[1])
guard lengthLength == 0x82 else {
return nil
}
let length = Int(self[2]) << 8 | Int(self[3])
guard length == self.count - 4 else {
return nil
}
// Now we can check the version through the algorithm identifier against the hardcoded values.
guard self.dropFirst(4).prefix(Data.partialPKCS8Prefix.count) == Data.partialPKCS8Prefix else {
return nil
}
// Ok, the last check are the next 4 bytes, which should now be the tag for OCTET STRING followed by another length.
guard self[4 + Data.partialPKCS8Prefix.count] == 0x04,
self[4 + Data.partialPKCS8Prefix.count + 1] == 0x82 else {
return nil
}
let octetStringLength = Int(self[4 + Data.partialPKCS8Prefix.count + 2]) << 8 |
Int(self[4 + Data.partialPKCS8Prefix.count + 3])
guard octetStringLength == self.count - 4 - Data.partialPKCS8Prefix.count - 4 else {
return nil
}
return self.dropFirst(4 + Data.partialPKCS8Prefix.count + 4)
}
// Corresponds to the ASN.1 encoding of the RSA AlgorithmIdentifier:
//
// SEQUENCE of OID (:rsaEncryption) and NULL.
static let rsaAlgorithmIdentifierBytes = Data([
0x30, 0x0D, // SEQUENCE, Length 13
0x06, 0x09, // OID, length 9
0x2A, 0x86 , 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, // 1.2.840.113549.1.1.1 :rsaEncryption
0x05, 0x00, // NULL, length 0
])
fileprivate init(spkiBytesForPKCS1Bytes pkcs1Bytes: Data) {
// This does an ad-hoc SPKI encode. Ideally we'd bring over the entire ASN.1 stack, but it's not worth doing
// for just this one use-case.
let keyLength = (pkcs1Bytes.count + 1)
let bitStringOverhead = 1 + keyLength._bytesNeededToEncodeASN1Length // 1 byte for tag.
let totalLengthOfSequencePayload = Self.rsaAlgorithmIdentifierBytes.count + bitStringOverhead + keyLength
var bytes = Data()
bytes.reserveCapacity(1 + totalLengthOfSequencePayload._bytesNeededToEncodeASN1Length + totalLengthOfSequencePayload)
bytes.append(0x30) // SEQUENCE marker.
bytes.appendAsASN1NodeLength(totalLengthOfSequencePayload)
bytes.append(Self.rsaAlgorithmIdentifierBytes)
bytes.append(0x03) // BITSTRING marker
bytes.appendAsASN1NodeLength(keyLength)
bytes.append(UInt8(0)) // No padding bits
bytes.append(contentsOf: pkcs1Bytes)
self = bytes
}
static let pkcs8versionIdentifierBytes = Data([
0x02, 0x01, 0x00, // Version, INTEGER 0
])
fileprivate init(privateKeyPKCS8BytesForPKCS1Bytes pkcs1Bytes: Data) {
// The PKCS8 encoding of a private key is very similar to the
// SPKI encoding of a public key, as implemented in `Data(spkiBytesForPKCS1Bytes:)` above.
// The difference is that PKCS 8 includes a VERSION field, and
// uses an OCTET STREAM instead of a BIT STREAM.
let versionLength = Self.pkcs8versionIdentifierBytes.count
let keyLength = (pkcs1Bytes.count)
let octetStringOverhead = keyLength._bytesNeededToEncodeASN1Length + 1
let totalLengthOfSequencePayload = versionLength + Self.rsaAlgorithmIdentifierBytes.count + octetStringOverhead + keyLength
var bytes = Data()
bytes.reserveCapacity(1 + totalLengthOfSequencePayload._bytesNeededToEncodeASN1Length + totalLengthOfSequencePayload)
bytes.append(0x30) // SEQUENCE marker.
bytes.appendAsASN1NodeLength(totalLengthOfSequencePayload)
bytes.append(Self.pkcs8versionIdentifierBytes)
bytes.append(Self.rsaAlgorithmIdentifierBytes)
bytes.append(0x04) // OCTET STRING marker
bytes.appendAsASN1NodeLength(keyLength)
bytes.append(contentsOf: pkcs1Bytes)
self = bytes
}
fileprivate mutating func appendAsASN1NodeLength(_ length: Int) {
let bytesNeeded = length._bytesNeededToEncodeASN1Length
if bytesNeeded == 1 {
self.append(UInt8(length))
} else {
// We first write the number of length bytes
// we need, setting the high bit. Then we write the bytes of the length.
self.append(0x80 | UInt8(bytesNeeded - 1))
for shift in (0..<(bytesNeeded - 1)).reversed() {
// Shift and mask the integer.
self.append(UInt8(truncatingIfNeeded: (length >> (shift * 8))))
}
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension Int {
fileprivate var _bytesNeededToEncodeASN1Length: Int {
// ASN.1 lengths are in two forms. If we can store the length in 7 bits, we should:
// that requires only one byte. Otherwise, we need multiple bytes: work out how many,
// plus one for the length of the length bytes.
if self <= 0x7F {
return 1
} else {
// We need to work out how many bytes we need. There are many fancy bit-twiddling
// ways of doing this, but honestly we don't do this enough to need them, so we'll
// do it the easy way. This math is done on UInt because it makes the shift semantics clean.
// We save a branch here because we can never overflow this addition.
return UInt(self).neededBytes &+ 1
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension UInt {
// Bytes needed to store a given integer in 7 bit bytes.
fileprivate var neededBytes: Int {
let neededBits = self.bitWidth - self.leadingZeroBitCount
return (neededBits + 7) / 8
}
}
#endif
@@ -19,9 +19,14 @@ import Foundation
#endif
extension Data {
// This enhancement can only be present on 6.1 or later because of the
// absence of https://github.com/swiftlang/swift/pull/76186 in older
// compilers.
#if compiler(>=6.1)
// This overload reduces allocations when used in a chain of infix operations.
static func + (lhs: consuming Data, rhs: consuming Data) -> Data {
lhs.append(contentsOf: rhs)
return lhs
}
#endif
}
@@ -0,0 +1,35 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2025 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2014 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
protocol ThreadOps {
associatedtype ThreadSpecificKey
associatedtype ThreadSpecificKeyDestructor
static func allocateThreadSpecificValue(destructor: ThreadSpecificKeyDestructor) -> ThreadSpecificKey
static func deallocateThreadSpecificValue(_ key: ThreadSpecificKey)
static func getThreadSpecificValue(_ key: ThreadSpecificKey) -> UnsafeMutableRawPointer?
static func setThreadSpecificValue(key: ThreadSpecificKey, value: UnsafeMutableRawPointer?)
}
@@ -0,0 +1,73 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2025 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if os(Linux) || os(Android) || os(FreeBSD) || canImport(Darwin)
#if canImport(Glibc)
@preconcurrency import Glibc
#elseif canImport(Bionic)
@preconcurrency import Bionic
#elseif canImport(Musl)
@preconcurrency import Musl
#elseif canImport(Android)
@preconcurrency import Android
#elseif canImport(Darwin)
import Darwin
#endif
typealias ThreadOpsSystem = ThreadOpsPosix
enum ThreadOpsPosix: ThreadOps {
typealias ThreadSpecificKey = pthread_key_t
#if canImport(Darwin)
typealias ThreadSpecificKeyDestructor = @convention(c) (UnsafeMutableRawPointer) -> Void
#else
typealias ThreadSpecificKeyDestructor = @convention(c) (UnsafeMutableRawPointer?) -> Void
#endif
static func allocateThreadSpecificValue(destructor: @escaping ThreadSpecificKeyDestructor) -> ThreadSpecificKey {
var value = pthread_key_t()
let result = pthread_key_create(&value, Optional(destructor))
precondition(result == 0, "pthread_key_create failed: \(result)")
return value
}
static func deallocateThreadSpecificValue(_ key: ThreadSpecificKey) {
let result = pthread_key_delete(key)
precondition(result == 0, "pthread_key_delete failed: \(result)")
}
static func getThreadSpecificValue(_ key: ThreadSpecificKey) -> UnsafeMutableRawPointer? {
pthread_getspecific(key)
}
static func setThreadSpecificValue(key: ThreadSpecificKey, value: UnsafeMutableRawPointer?) {
let result = pthread_setspecific(key, value)
precondition(result == 0, "pthread_setspecific failed: \(result)")
}
}
#endif
@@ -0,0 +1,111 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2025 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
//
//===----------------------------------------------------------------------===//
// Derived from swift-nio's ThreadSpecificVariable type.
/// A ``ThreadSpecificVariable`` is a variable that can be read and set like a normal variable except that it holds
/// different variables per thread.
///
/// ``ThreadSpecificVariable`` is thread-safe so it can be used with multiple threads at the same time but the value
/// returned by ``currentValue`` is defined per thread.
///
/// - Note: Though ``ThreadSpecificVariable`` is thread-safe, it is not `Sendable` unless `Value` is `Sendable`.
/// If ``ThreadSpecificVariable`` were unconditionally `Sendable`, it could be used to "smuggle"
/// non-`Sendable` state out of an actor or other isolation domain without triggering warnings. If you
/// are attempting to use ``ThreadSpecificVariable`` with non-`Sendable` data, consider using a dynamic
/// enforcement tool like `NIOLoopBoundBox` to police the access.
final class ThreadSpecificVariable<Value: AnyObject> {
// the actual type in there is `Box<(ThreadSpecificVariable<T>, T)>` but we can't use that as C functions can't capture (even types)
private typealias BoxedType = Box<(AnyObject, AnyObject)>
private class Key {
private var underlyingKey: ThreadOpsSystem.ThreadSpecificKey
internal init(destructor: @escaping ThreadOpsSystem.ThreadSpecificKeyDestructor) {
self.underlyingKey = ThreadOpsSystem.allocateThreadSpecificValue(destructor: destructor)
}
deinit {
ThreadOpsSystem.deallocateThreadSpecificValue(self.underlyingKey)
}
func get() -> UnsafeMutableRawPointer? {
ThreadOpsSystem.getThreadSpecificValue(self.underlyingKey)
}
func set(value: UnsafeMutableRawPointer?) {
ThreadOpsSystem.setThreadSpecificValue(key: self.underlyingKey, value: value)
}
}
private let key: Key
/// Initialize a new `ThreadSpecificVariable` without a current value (`currentValue == nil`).
init() {
self.key = Key(destructor: {
Unmanaged<BoxedType>.fromOpaque(($0 as UnsafeMutableRawPointer?)!).release()
})
}
/// Initialize a new `ThreadSpecificVariable` with `value` for the calling thread. After calling this, the calling
/// thread will see `currentValue == value` but on all other threads `currentValue` will be `nil` until changed.
///
/// - Parameters:
/// - value: The value to set for the calling thread.
convenience init(value: Value) {
self.init()
self.currentValue = value
}
/// The value for the current thread.
@available(
*,
noasync,
message: "threads can change between suspension points and therefore the thread specific value too"
)
var currentValue: Value? {
get {
self.get()
}
set {
self.set(newValue)
}
}
/// Get the current value for the calling thread.
private func get() -> Value? {
guard let raw = self.key.get() else { return nil }
// parenthesize the return value to silence the cast warning
return
(Unmanaged<BoxedType>
.fromOpaque(raw)
.takeUnretainedValue()
.value.1 as! Value)
}
/// Set the current value for the calling threads. The `currentValue` for all other threads remains unchanged.
private func set(_ newValue: Value?) {
if let raw = self.key.get() {
Unmanaged<BoxedType>.fromOpaque(raw).release()
}
self.key.set(value: newValue.map { Unmanaged.passRetained(Box((self, $0))).toOpaque() })
}
}
extension ThreadSpecificVariable: @unchecked Sendable where Value: Sendable {}
final class Box<T> {
let value: T
init(_ value: T) { self.value = value }
}
@@ -0,0 +1,56 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2025 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if os(Windows)
import WinSDK
typealias ThreadOpsSystem = ThreadOpsWindows
enum ThreadOpsWindows: ThreadOps {
typealias ThreadSpecificKey = DWORD
typealias ThreadSpecificKeyDestructor = @convention(c) (UnsafeMutableRawPointer?) -> Void
static func allocateThreadSpecificValue(destructor: @escaping ThreadSpecificKeyDestructor) -> ThreadSpecificKey {
FlsAlloc(destructor)
}
static func deallocateThreadSpecificValue(_ key: ThreadSpecificKey) {
let dwResult: Bool = FlsFree(key)
precondition(dwResult, "FlsFree: \(GetLastError())")
}
static func getThreadSpecificValue(_ key: ThreadSpecificKey) -> UnsafeMutableRawPointer? {
FlsGetValue(key)
}
static func setThreadSpecificValue(key: ThreadSpecificKey, value: UnsafeMutableRawPointer?) {
FlsSetValue(key, value)
}
}
#endif
@@ -162,6 +162,14 @@ final class CBCTests: XCTestCase {
}
}
}
func testToDataConversion() throws {
let randomBytes = (0..<16).map { _ in UInt8.random(in: UInt8.min...UInt8.max) }
let dataIn = Data(randomBytes)
let iv = try AES._CBC.IV(ivBytes: dataIn)
let dataOut = Data(iv)
XCTAssertEqual(dataIn, dataOut)
}
}
+196 -20
View File
@@ -18,17 +18,24 @@ import XCTest
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
final class ARCAPITests: XCTestCase {
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
func testVectors() throws {
let data = ARCEncodedTestVector.data(using: .utf8)!
let decoder = JSONDecoder()
for vector in try decoder.decode([ARCTestVector].self, from: data) {
try testVector(vector)
let vectors = try decoder.decode([ARCTestVector].self, from: data)
XCTAssert(vectors.count > 0, "No test vectors found")
for vector in vectors {
switch vector.suite {
case "ARCV1-P256": try testVector(vector, using: P256.self)
case "ARCV1-P384": try testVector(vector, using: P384.self)
default: XCTFail("Test vector suite not supported: \(vector.suite)")
}
}
}
func testVector(_ vector: ARCTestVector) throws {
fileprivate func testVector<Curve: ARCCurve>(_ vector: ARCTestVector, using _: Curve.Type = Curve.self) throws {
// [Issuer] Create the server secrets.
let privateKey = try P384._ARCV1.PrivateKey(rawRepresentation: Data(
let privateKey = try Curve._ARCV1.PrivateKey(rawRepresentation: Data(
hexString: vector.ServerKey.x0 + vector.ServerKey.x1 + vector.ServerKey.x2 + vector.ServerKey.xb
))
@@ -52,14 +59,14 @@ final class ARCAPITests: XCTestCase {
_ = (publicKeyBytes, requestContext, presentationContext, presentationLimit)
// [Client] Obtain public key out of band (other serializations may be available).
let publicKey = try P384._ARCV1.PublicKey(rawRepresentation: publicKeyBytes)
let publicKey = try Curve._ARCV1.PublicKey(rawRepresentation: publicKeyBytes)
// [Client] Prepare a credential request using fixed values from test vector.
let precredential = try publicKey.prepareCredentialRequest(
requestContext: requestContext,
m1: P384._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.CredentialRequest.m1)),
r1: P384._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.CredentialRequest.r1)),
r2: P384._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.CredentialRequest.r2))
m1: Curve._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.CredentialRequest.m1)),
r1: Curve._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.CredentialRequest.r1)),
r2: Curve._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.CredentialRequest.r2))
)
// [Client -> Issuer] Send the credential request.
@@ -67,17 +74,17 @@ final class ARCAPITests: XCTestCase {
// [CHECK] Credential request scalars match test vector.
XCTAssertEqual(
credentialRequestBytes[..<(2 * P384.compressedx962PointByteCount)].hexString,
credentialRequestBytes[..<(2 * Curve.compressedx962PointByteCount)].hexString,
vector.CredentialRequest.m1_enc + vector.CredentialRequest.m2_enc
)
// [Issuer] Receive the credential request.
let credentialRequest = try P384._ARCV1.CredentialRequest(rawRepresentation: credentialRequestBytes)
let credentialRequest = try Curve._ARCV1.CredentialRequest(rawRepresentation: credentialRequestBytes)
// [Issuer] Generate a credential response with fixed value from test vector.
let credentialResponse = try privateKey.issue(
credentialRequest,
b: P384._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.CredentialResponse.b))
b: Curve._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.CredentialResponse.b))
)
// [Issuer -> Client] Send the credential response.
@@ -85,7 +92,7 @@ final class ARCAPITests: XCTestCase {
// [CHECK] Credential response scalars match test vector, excluding proof.
XCTAssertEqual(
credentialResponseBytes[..<(6 * P384.compressedx962PointByteCount)].hexString,
credentialResponseBytes[..<(6 * Curve.compressedx962PointByteCount)].hexString,
vector.CredentialResponse.U
+ vector.CredentialResponse.enc_U_prime
+ vector.CredentialResponse.X0_aux
@@ -95,7 +102,7 @@ final class ARCAPITests: XCTestCase {
)
// [Client] Receive the credential response.
let _ = try P384._ARCV1.CredentialResponse(rawRepresentation: credentialResponseBytes)
let _ = try Curve._ARCV1.CredentialResponse(rawRepresentation: credentialResponseBytes)
// [Client] Generate a credential.
var credential = try publicKey.finalize(credentialResponse, for: precredential)
@@ -111,9 +118,9 @@ final class ARCAPITests: XCTestCase {
context: presentationContext,
presentationLimit: presentationLimit,
fixedNonce: Int(vector.Presentation1.nonce.dropFirst(2), radix: 16)!,
a: P384._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.Presentation1.a)),
r: P384._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.Presentation1.r)),
z: P384._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.Presentation1.z))
a: Curve._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.Presentation1.a)),
r: Curve._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.Presentation1.r)),
z: Curve._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.Presentation1.z))
)
// NOTE: The presentation proof depends on randomly generated blinding factors. This layer doesn't expose
@@ -135,14 +142,14 @@ final class ARCAPITests: XCTestCase {
// [CHECK]: Serialization of presentation (ecluding proof) matches spec.
XCTAssertEqual(
presentation.rawRepresentation[..<(4 * P384.compressedx962PointByteCount)].hexString,
presentation.rawRepresentation[..<(4 * Curve.compressedx962PointByteCount)].hexString,
vector.Presentation1.U
+ vector.Presentation1.U_prime_commit
+ vector.Presentation1.m1_commit
+ vector.Presentation1.tag
)
XCTAssertEqual(
presentation.rawRepresentation[(4 * P384.compressedx962PointByteCount)...].hexString.count,
presentation.rawRepresentation[(4 * Curve.compressedx962PointByteCount)...].hexString.count,
vector.Presentation1.proof.count
)
@@ -155,12 +162,12 @@ final class ARCAPITests: XCTestCase {
+ vector.Presentation1.proof
)
XCTAssertEqual(
try P384._ARCV1.Presentation(rawRepresentation: testVectorPresentationBytes).rawRepresentation.hexString,
try Curve._ARCV1.Presentation(rawRepresentation: testVectorPresentationBytes).rawRepresentation.hexString,
testVectorPresentationBytes.hexString
)
// [Verifier] Receive the presentation (and the nonce, out of band).
let receivedPresentation = try P384._ARCV1.Presentation(rawRepresentation: testVectorPresentationBytes)
let receivedPresentation = try Curve._ARCV1.Presentation(rawRepresentation: testVectorPresentationBytes)
let nonce = Int(vector.Presentation1.nonce.dropFirst(2), radix: 16)!
// [Verifier] Verify the presentation.
@@ -174,3 +181,172 @@ final class ARCAPITests: XCTestCase {
XCTAssertTrue(validPresentation)
}
}
// MARK: - Fileprivate protocols to create a unified test over the ARC curves.
fileprivate protocol ARCCredentialRequest {
init(rawRepresentation: some DataProtocol) throws
var rawRepresentation: Data { get }
}
fileprivate protocol ARCCredentialResponse {
init(rawRepresentation: some DataProtocol) throws
var rawRepresentation: Data { get }
}
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, macCatalyst 13.2, visionOS 1.2, *)
fileprivate protocol ARCPresentation<H2G> {
associatedtype H2G: HashToGroup
var backing: ARC.Presentation<H2G> { get }
init(rawRepresentation: some DataProtocol) throws
var rawRepresentation: Data { get }
}
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, macCatalyst 13.2, visionOS 1.2, *)
fileprivate protocol ARCCredential<H2G, Presentation> {
associatedtype H2G: HashToGroup
associatedtype Presentation: ARCPresentation
var backing: ARC.Credential<H2G> { get }
mutating func makePresentation(
context: some DataProtocol,
presentationLimit: Int,
fixedNonce: Int?,
a: H2G.G.Scalar,
r: H2G.G.Scalar,
z: H2G.G.Scalar
) throws -> (presentation: Presentation, nonce: Int)
mutating func makePresentation(context: some DataProtocol, presentationLimit: Int) throws -> (presentation: Presentation, nonce: Int)
}
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, macCatalyst 13.2, visionOS 1.2, *)
fileprivate protocol ARCPrivateKey<H2G, CredentialRequest, CredentialResponse, Credential, Presentation> {
associatedtype H2G: HashToGroup
associatedtype Credential
associatedtype PublicKey: ARCPublicKey<H2G, CredentialResponse, Credential>
associatedtype CredentialRequest: ARCCredentialRequest
associatedtype CredentialResponse: ARCCredentialResponse
associatedtype Presentation: ARCPresentation
init(rawRepresentation: some DataProtocol) throws
var rawRepresentation: Data { get }
var publicKey: PublicKey { get }
func issue(_ credentialRequest: CredentialRequest, b: H2G.G.Scalar) throws -> CredentialResponse
func verify(
_: Presentation,
requestContext: some DataProtocol,
presentationContext: some DataProtocol,
presentationLimit: Int,
nonce: Int
) throws -> Bool
}
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, macCatalyst 13.2, visionOS 1.2, *)
fileprivate protocol ARCPublicKey<H2G, CredentialResponse, Credential> {
associatedtype H2G: HashToGroup
associatedtype Precredential: ARCPrecredential
associatedtype CredentialResponse: ARCCredentialResponse
associatedtype Credential: ARCCredential
init(rawRepresentation: some DataProtocol) throws
var rawRepresentation: Data { get }
func prepareCredentialRequest(requestContext: some DataProtocol, m1: H2G.G.Scalar, r1: H2G.G.Scalar, r2: H2G.G.Scalar) throws -> Precredential
func prepareCredentialRequest(requestContext: some DataProtocol) throws -> Precredential
func finalize(_ credentialResponse: CredentialResponse, for precredential: Precredential) throws -> Credential
}
fileprivate protocol ARCPrecredential {
associatedtype CredentialRequest: ARCCredentialRequest
var credentialRequest: CredentialRequest { get }
}
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, macCatalyst 13.2, visionOS 1.2, *)
fileprivate protocol ARCV1<H2G> {
associatedtype H2G: HashToGroup
associatedtype CredentialRequest: ARCCredentialRequest
associatedtype CredentialResponse: ARCCredentialResponse
associatedtype Presentation: ARCPresentation<H2G>
associatedtype Credential: ARCCredential<H2G, Presentation>
associatedtype PrivateKey: ARCPrivateKey<H2G, CredentialRequest, CredentialResponse, Credential, Presentation>
associatedtype PublicKey: ARCPublicKey<H2G, CredentialResponse, Credential>
}
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, macCatalyst 13.2, visionOS 1.2, *)
fileprivate protocol ARCCurve: OpenSSLSupportedNISTCurve {
associatedtype H2G: HashToGroup where H2G == OpenSSLHashToCurve<Self>
associatedtype _ARCV1: ARCV1<H2G>
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P256._ARCV1.Precredential: ARCPrecredential {}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P256._ARCV1.CredentialRequest: ARCCredentialRequest {}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P256._ARCV1.CredentialResponse: ARCCredentialResponse {}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P256._ARCV1.Credential: ARCCredential {}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P256._ARCV1.Presentation: ARCPresentation {}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P256._ARCV1.PublicKey: ARCPublicKey {
typealias H2G = P256._ARCV1.H2G
}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P256._ARCV1.PrivateKey: ARCPrivateKey {}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P256._ARCV1: ARCV1 {}
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P256: ARCCurve {}
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P384._ARCV1.Precredential: ARCPrecredential {}
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P384._ARCV1.CredentialRequest: ARCCredentialRequest {}
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P384._ARCV1.CredentialResponse: ARCCredentialResponse {}
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P384._ARCV1.Credential: ARCCredential {}
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P384._ARCV1.Presentation: ARCPresentation {}
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P384._ARCV1.PublicKey: ARCPublicKey {
typealias H2G = P384._ARCV1.H2G
}
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P384._ARCV1.PrivateKey: ARCPrivateKey {}
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P384._ARCV1: ARCV1 {}
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P384: ARCCurve {}
// Swift 5.10 compiler needs a little more help to infer the conformances.
#if swift(<6.0)
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
fileprivate extension P256._ARCV1.PrivateKey {
typealias H2G = P256._ARCV1.H2G
typealias Credential = P256._ARCV1.Credential
typealias PublicKey = P256._ARCV1.PublicKey
typealias CredentialRequest = P256._ARCV1.CredentialRequest
typealias CredentialResponse = P256._ARCV1.CredentialResponse
typealias Presentation = P256._ARCV1.Presentation
}
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
fileprivate extension P384._ARCV1.PrivateKey {
typealias H2G = P384._ARCV1.H2G
typealias Credential = P384._ARCV1.Credential
typealias PublicKey = P384._ARCV1.PublicKey
typealias CredentialRequest = P384._ARCV1.CredentialRequest
typealias CredentialResponse = P384._ARCV1.CredentialResponse
typealias Presentation = P384._ARCV1.Presentation
}
#endif
@@ -17,30 +17,35 @@ import Crypto
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, macCatalyst 13.2, visionOS 1.2, *)
class ARCEncodingTests: XCTestCase {
func testserverPublicKeyEncoding() throws {
let ciphersuite = ARC.Ciphersuite(HashToCurveImpl<ARCCurve>.self)
func serverPublicKeyEncoding<Curve: SupportedCurveDetailsImpl>(CurveType _: Curve.Type) throws {
let ciphersuite = ARC.Ciphersuite(HashToCurveImpl<Curve>.self)
let server = ARC.Server(ciphersuite: ciphersuite)
let publicKey = server.serverPublicKey
let publicKeyData = publicKey.serialize()
let publicKey2 = try ARC.ServerPublicKey.deserialize(serverPublicKeyData: publicKeyData)
let publicKeyData = publicKey.serialize(ciphersuite: ciphersuite)
let publicKey2 = try ARC.ServerPublicKey.deserialize(serverPublicKeyData: publicKeyData, ciphersuite: ciphersuite)
XCTAssert(publicKey.X0 == publicKey2.X0)
XCTAssert(publicKey.X1 == publicKey2.X1)
XCTAssert(publicKey.X2 == publicKey2.X2)
let publicKeyData2 = publicKey2.serialize()
let publicKeyData2 = publicKey2.serialize(ciphersuite: ciphersuite)
XCTAssertEqual(publicKeyData, publicKeyData2)
}
func testRequestEncoding() throws {
let ciphersuite = ARC.Ciphersuite(HashToCurveImpl<ARCCurve>.self)
func testServerPublicKeyEncoding() throws {
try serverPublicKeyEncoding(CurveType: P256.self)
try serverPublicKeyEncoding(CurveType: P384.self)
}
func requestEncoding<Curve: SupportedCurveDetailsImpl>(CurveType _: Curve.Type) throws {
let ciphersuite = ARC.Ciphersuite(HashToCurveImpl<Curve>.self)
let server = ARC.Server(ciphersuite: ciphersuite)
let requestContext = Data("test request context".utf8)
let precredential = try ARC.Precredential(ciphersuite: ciphersuite, requestContext: requestContext, serverPublicKey: server.serverPublicKey)
let request = precredential.credentialRequest
let requestData = request.serialize()
let request2 = try ARC.CredentialRequest.deserialize(requestData: requestData)
let requestData = request.serialize(ciphersuite: ciphersuite)
let request2 = try ARC.CredentialRequest.deserialize(requestData: requestData, ciphersuite: ciphersuite)
XCTAssert(request.m1Enc == request2.m1Enc)
XCTAssert(request.m2Enc == request2.m2Enc)
XCTAssert(request.proof.challenge == request2.proof.challenge)
@@ -48,20 +53,25 @@ class ARCEncodingTests: XCTestCase {
XCTAssert(response == request2.proof.responses[index])
}
let requestData2 = request2.serialize()
let requestData2 = request2.serialize(ciphersuite: ciphersuite)
XCTAssertEqual(requestData, requestData2)
}
func testResponseEncoding() throws {
let ciphersuite = ARC.Ciphersuite(HashToCurveImpl<ARCCurve>.self)
func testRequestEncoding() throws {
try requestEncoding(CurveType: P256.self)
try requestEncoding(CurveType: P384.self)
}
func responseEncoding<Curve: SupportedCurveDetailsImpl>(CurveType _: Curve.Type) throws {
let ciphersuite = ARC.Ciphersuite(HashToCurveImpl<Curve>.self)
let server = ARC.Server(ciphersuite: ciphersuite)
let requestContext = Data("test request context".utf8)
let precredential = try ARC.Precredential(ciphersuite: ciphersuite, requestContext: requestContext, serverPublicKey: server.serverPublicKey)
let request = precredential.credentialRequest
let response = try server.respond(credentialRequest: request)
let responseData = response.serialize()
let response2 = try ARC.CredentialResponse.deserialize(responseData: responseData)
let responseData = response.serialize(ciphersuite: ciphersuite)
let response2 = try ARC.CredentialResponse.deserialize(responseData: responseData, ciphersuite: ciphersuite)
XCTAssert(response.U == response2.U)
XCTAssert(response.encUPrime == response2.encUPrime)
XCTAssert(response.X0Aux == response2.X0Aux)
@@ -73,12 +83,17 @@ class ARCEncodingTests: XCTestCase {
XCTAssert(response == response2.proof.responses[index])
}
let responseData2 = response2.serialize()
let responseData2 = response2.serialize(ciphersuite: ciphersuite)
XCTAssertEqual(responseData, responseData2)
}
func testCredentialEncoding() throws {
let ciphersuite = ARC.Ciphersuite(HashToCurveImpl<ARCCurve>.self)
func testResponseEncoding() throws {
try responseEncoding(CurveType: P256.self)
try responseEncoding(CurveType: P384.self)
}
func credentialEncoding<Curve: SupportedCurveDetailsImpl>(CurveType _: Curve.Type) throws {
let ciphersuite = ARC.Ciphersuite(HashToCurveImpl<Curve>.self)
let server = ARC.Server(ciphersuite: ciphersuite)
let requestContext = Data("test request context".utf8)
let precredential = try ARC.Precredential(ciphersuite: ciphersuite, requestContext: requestContext, serverPublicKey: server.serverPublicKey)
@@ -86,8 +101,8 @@ class ARCEncodingTests: XCTestCase {
let response = try server.respond(credentialRequest: request)
let credential = try precredential.makeCredential(credentialResponse: response)
let credentialData = try credential.serialize()
let credential2 = try ARC.Credential.deserialize(credentialData: credentialData)
let credentialData = try credential.serialize(ciphersuite: ciphersuite)
let credential2 = try ARC.Credential.deserialize(credentialData: credentialData, ciphersuite: ciphersuite)
XCTAssert(credential.m1 == credential2.m1)
XCTAssert(credential.U == credential2.U)
XCTAssert(credential.UPrime == credential2.UPrime)
@@ -99,12 +114,17 @@ class ARCEncodingTests: XCTestCase {
XCTAssertEqual(value.1, credential2.presentationState.state[key]?.1)
}
let credentialData2 = try credential2.serialize()
let credentialData2 = try credential2.serialize(ciphersuite: ciphersuite)
XCTAssertEqual(credentialData, credentialData2)
}
func testPresentationEncoding() throws {
let ciphersuite = ARC.Ciphersuite(HashToCurveImpl<ARCCurve>.self)
func testCredentialEncoding() throws {
try credentialEncoding(CurveType: P256.self)
try credentialEncoding(CurveType: P384.self)
}
func presentationEncoding<Curve: SupportedCurveDetailsImpl>(CurveType _: Curve.Type) throws {
let ciphersuite = ARC.Ciphersuite(HashToCurveImpl<Curve>.self)
let server = ARC.Server(ciphersuite: ciphersuite)
let requestContext = Data("test request context".utf8)
let precredential = try ARC.Precredential(ciphersuite: ciphersuite, requestContext: requestContext, serverPublicKey: server.serverPublicKey)
@@ -113,8 +133,8 @@ class ARCEncodingTests: XCTestCase {
var credential = try precredential.makeCredential(credentialResponse: response)
let (presentation, _) = try credential.makePresentation(presentationContext: Data("test presentation context".utf8), presentationLimit: 1)
let presentationData = presentation.serialize()
let presentation2 = try ARC.Presentation.deserialize(presentationData: presentationData)
let presentationData = presentation.serialize(ciphersuite: ciphersuite)
let presentation2 = try ARC.Presentation.deserialize(presentationData: presentationData, ciphersuite: ciphersuite)
XCTAssert(presentation.U == presentation2.U)
XCTAssert(presentation.UPrimeCommit == presentation2.UPrimeCommit)
XCTAssert(presentation.m1Commit == presentation2.m1Commit)
@@ -124,10 +144,15 @@ class ARCEncodingTests: XCTestCase {
XCTAssert(response == presentation2.proof.responses[index])
}
let presentationData2 = presentation2.serialize()
let presentationData2 = presentation2.serialize(ciphersuite: ciphersuite)
XCTAssertEqual(presentationData, presentationData2)
}
func testPresentationEncoding() throws {
try presentationEncoding(CurveType: P256.self)
try presentationEncoding(CurveType: P384.self)
}
func testPresentationStateEncoding() throws {
let emptyPresentationState = ARC.PresentationState()
let smallPresentationState = ARC.PresentationState(state: [Data("context1".utf8): (4, [1, 2, 3]), Data("context2".utf8): (10, [4, 5, 6])])
@@ -20,7 +20,7 @@ final class ARCPublicAPITests: XCTestCase {
func testARCEndToEnd() throws {
// [Issuer] Create the server secrets (other initializers will be available).
let privateKey = P384._ARCV1.PrivateKey()
let privateKey = P256._ARCV1.PrivateKey()
// [Issuer] Serialize public key to share with client (other serializations may be available).
let publicKeyBytes = privateKey.publicKey.rawRepresentation
@@ -35,7 +35,7 @@ final class ARCPublicAPITests: XCTestCase {
_ = (publicKeyBytes, requestContext, presentationContext, presentationLimit)
// [Client] Obtain public key out of band (other serializations may be available).
let publicKey = try P384._ARCV1.PublicKey(rawRepresentation: publicKeyBytes)
let publicKey = try P256._ARCV1.PublicKey(rawRepresentation: publicKeyBytes)
// [Client] Prepare a credential request.
let precredential = try publicKey.prepareCredentialRequest(requestContext: requestContext)
@@ -44,7 +44,7 @@ final class ARCPublicAPITests: XCTestCase {
let credentialRequestBytes = precredential.credentialRequest.rawRepresentation
// [Issuer] Receive the credential request.
let credentialRequest = try P384._ARCV1.CredentialRequest(rawRepresentation: credentialRequestBytes)
let credentialRequest = try P256._ARCV1.CredentialRequest(rawRepresentation: credentialRequestBytes)
// [Issuer] Generate a credential response.
let credentialResponse = try privateKey.issue(credentialRequest)
@@ -53,7 +53,7 @@ final class ARCPublicAPITests: XCTestCase {
let credentialResponseBytes = credentialResponse.rawRepresentation
// [Client] Receive the credential response.
let _ = try P384._ARCV1.CredentialResponse(rawRepresentation: credentialResponseBytes)
let _ = try P256._ARCV1.CredentialResponse(rawRepresentation: credentialResponseBytes)
// [Client] Generate a credential.
// NOTE: This is a var because it enforces the presentation limits for each presentation prefix.
@@ -70,7 +70,7 @@ final class ARCPublicAPITests: XCTestCase {
let presentationBytes = presentation.rawRepresentation
// [Verifier] Receive the presentation.
let _ = try P384._ARCV1.Presentation(rawRepresentation: presentationBytes)
let _ = try P256._ARCV1.Presentation(rawRepresentation: presentationBytes)
// [Verifier] Verify the presentation.
let validPresentation = try privateKey.verify(
@@ -87,7 +87,7 @@ final class ARCPublicAPITests: XCTestCase {
}
func testCrendentialEnforcesPresentationLimitLocally() throws {
let privateKey = P384._ARCV1.PrivateKey()
let privateKey = P256._ARCV1.PrivateKey()
let publicKey = privateKey.publicKey
let requestContext = Data("shared request context".utf8)
let presentationContext = Data("shared presentation context".utf8)
@@ -17,6 +17,68 @@ import XCTest
let ARCEncodedTestVector = """
[
{
"Credential": {
"U": "033ee1ebbcff622bc26b10932ed1eb147226d832048fb2337dc0ad7722cb07483d",
"U_prime": "02637fe04cc143281ee607bd8f898e670293dce44a2840b9cbb9e0d1fc7a2b29b4",
"X1": "03c413230a9bd956718aa46138a33f774f4c708d61c1d6400d404243049d4a31dc",
"m1": "eedfe7939e2382934ab5b0f76aae44124955d2c5ebf9b41d88786259c34692d2"
},
"CredentialRequest": {
"m1": "eedfe7939e2382934ab5b0f76aae44124955d2c5ebf9b41d88786259c34692d2",
"m1_enc": "03b8f11506a5302424143573e087fa20195cb5e893a67ef354eae3a78e263c54e4",
"m2": "911fb315257d9ae29d47ecb48c6fa27074dee6860a0489f8db6ac9a486be6a3e",
"m2_enc": "03f1ae4d7b78ba8030bd63859d4f4a909395c52bda34716b6620a2fdd52b336fc9",
"proof": "0f361327abbc724ff0d37db365065bc4bd60e18125842bb4c03a7e5a632a1e95e74dcc440fcb9fb39106922e0d2544e6c82ca710abf35e8b10bf5d61296c9adb7d683eaed9a76a755b73f2b4b6e763a7c7883ce4b5c21bd02cd96b9af18cfb227f1acb4ead77c85049d291ed7841405610843f163e9cc2f6a8869111582324cd32bf13000c129d274ccf5386cb90e839916d5dff7eade18e3eabec415f613911",
"r1": "008035081690bfde3b1e68b91443c22cc791d244340fe957d5aa44d7313740df",
"r2": "d59c5e6ff560cc597c2b8ca25256c720bceca2ab03921492c5e9e4ad3b558002",
"request_context": "74657374207265717565737420636f6e74657874"
},
"CredentialResponse": {
"H_aux": "03d3cd09eeb8d19716586a49260c69309c495a717a36cad3381f6c02ac80b70e64",
"U": "033ee1ebbcff622bc26b10932ed1eb147226d832048fb2337dc0ad7722cb07483d",
"X0_aux": "02d453c121324114367906bd11ffc3b6e6a77b75382497279b1a60ab8412c1dec6",
"X1_aux": "03b0e4b1f376c6207bf34efda46ce54b132a20b90bc28b9152f3e441fe2b508b63",
"X2_aux": "0327369efcb7577abaeb7b56940e6e042126900bdf8bd8944c0adbb7be3ad98e2a",
"b": "e699140babbe599f7dd8f6e3e8f615e5f201d1c2b0bc2f821f19e80a0a0e1e7b",
"enc_U_prime": "035b8e09ce8776f1a2c7ef8610c9a6a39936c5666ab8b28d6629d3685056716482",
"proof": "dd4596175db0b4273fcdff330370d2b5e7a4bf92bf518141f4553af37ef0e1260cb8312affc2462800adba102117448b449985d1704d8afd0df9ac708231561dca56faae325cb56b0a9e8ad07bdc6ce90f6e7430090e970a7240e289218de7a17672bea9a66187d102ffef976fb01af69d8d3aa3156a5a4223dc6d08b8ce9f1d2639a2edc7052404bf1410adf6c41465bd687e3dfa5372ea71f804b56d947bae9482e5707f42dbe35f8b0e11b4a0d27a5a01e1b9a75b66d82b7945eb0b002ee400bebcdc4c3133f804b22bd2d771762058cc35a5033365d2e15150fe46d3b0e98e18ee55f0451b0b171420f73592292e4ff50603c1f0d7769dbd090936090f63"
},
"Presentation1": {
"U": "032704f22133d2ec70f9e6f4bbf64c582220b666f2e2c1d37c3f8995a2a5568c7e",
"U_prime_commit": "03533cf1b2fd53a0716e02425eb42e4c55835aa6b2992d364cba70810d0f8aeb51",
"a": "b78e57df8f0a95d102ff12bbb97e15ed35c23e54f9b4483d30b76772ee60d886",
"m1_commit": "03e412408579105213ed10b6447c85bcd672ba73ecae1e21c463d0df4ef7beb814",
"nonce": "0x0",
"presentation_context": "746573742070726573656e746174696f6e20636f6e74657874",
"proof": "a558da5f17c04adcb0898827aaded14be1dc612dcd12b0579c11bb387ce9ae4b7dbcb3bbe413caaaf754d99e5a342abb7e0041458d670f4b58eda37e745a675295d7a7b86248141d6547b53d793e5c77896ec4dc8dd438ab66d9c8b43ef6b060938a1ca793057b154970ebc3c7ec3a23134e0852d0041f9098ce77311e5b5eca0000000000000000000000000000000000000000000000000000000000000004",
"r": "42252210dd60ddbbf1a57e3b144e26dd693b7644a9626a8c36896ede53d12930",
"tag": "031a774fd87a8f18f6420bea43cf5425e7426eec8ba7b8df5c13dc05f10ec652d9",
"z": "f5a4bbcf14e55e357df9f5ccb5ded37b2b14bc2e1a68e31f86416f0606ee75d1"
},
"Presentation2": {
"U": "035fd233dee2c147155c6008ea64941b6ff7b315aced12531468f2e27bf22e3ef0",
"U_prime_commit": "02434af337b87fd21d1e3d950aebfc8033a3d2e9dd2bb8b9e7953488078754496d",
"a": "95bcf45150a61f5c44a6cfbf343cd9e0f593f127b6f49bec0f9b20f0550504a2",
"m1_commit": "02a578fd3a84eb5b657367b02de39b45fd48ab7781ef8f94efe601274a5ded2a07",
"nonce": "0x1",
"presentation_context": "746573742070726573656e746174696f6e20636f6e74657874",
"proof": "050965cde906fc4723333b100ce0fd9f7b026315f1db16984d4cccb2bc4aa65eb7a17f5b8dfe4f14d40006506ee5fb323e829dd4cb9dc3c455b2e04dd691600aec3cc3f1939198a80acb78b7f90b3bff769cab890f33e4d69b7c302d21ad35ec457d048d3ed7d13ee82c3c0aac2129ad0c8375cf29cd8ea3948a16b9247b1cc5faf69a3116f903b9dcccc4eff31f026041e49797b53c87eca66cfe1040187ef7",
"r": "d7ed72750b6d366ed0febdc539b52d89434f468a578c59d7ca9015b7da240ad6",
"tag": "03084fe6fff0ecc7c33ef5c49b492dda38083f52e9a2b70b88f3d4b4ba7b50afba",
"z": "91eedfb168c556ff5ca3b89d047f482c9279b47f584aab6c7f895f7674251771"
},
"ServerKey": {
"X0": "0232b5e93dc2ff489c20a986a84757c5cc4512f057e1ea92011a26d3ad2c56288d",
"X1": "03c413230a9bd956718aa46138a33f774f4c708d61c1d6400d404243049d4a31dc",
"X2": "02db00f6f8e6d235786a120017bd356fe1c9d09069d3ac9352cc9be10ef1505a55",
"x0": "3338fa65ec36e0290022b48eb562889d89dbfa691d1cde91517fa222ed7ad364",
"x1": "f9db001266677f62c095021db018cd8cbb55941d4073698ce45c405d1348b7b1",
"x2": "350e8040f828bf6ceca27405420cdf3d63cb3aef005f40ba51943c8026877963",
"xb": "fd293126bb49a6d793cd77d7db960f5692fec3b7ec07602c60cd32aee595dffd"
},
"suite": "ARCV1-P256",
},
{
"Credential": {
"U": "02be890d43908e52ed43ae7bc7098f3a7694617fe44a88c33c6fa4eb9e942c0b2bb9d2fd56a44e1d6094fc7b9e8b949055",
@@ -179,9 +241,9 @@ class ARCTestVectors: XCTestCase {
// Verify request proof, by creating a new request with the
// tv.CredentialRequest.proof scalars and verifying it.
let requestProof = try proofFromString(CurveType: Curve.self, value: tv.CredentialRequest.proof, scalarCount: ARC.CredentialRequest.scalarCount)
let requestProof = try proofFromString(CurveType: Curve.self, value: tv.CredentialRequest.proof, scalarCount: ARC.CredentialRequest<HashToCurveImpl<Curve>>.getScalarCount())
let newRequest = ARC.CredentialRequest(m1Enc: precredential.credentialRequest.m1Enc, m2Enc: precredential.credentialRequest.m2Enc, proof: requestProof)
XCTAssert(try newRequest.verify(generatorG: precredential.generatorG, generatorH: precredential.generatorH))
XCTAssert(try newRequest.verify(generatorG: precredential.generatorG, generatorH: precredential.generatorH, ciphersuite: ciphersuite))
// Make a credential response, passing in randomness b
let b = try scalarFromString(CurveType: Curve.self, value: tv.CredentialResponse.b)
@@ -195,9 +257,9 @@ class ARCTestVectors: XCTestCase {
// Verify response proof, by creating a new response with the
// tv.CredentialResponse.proof scalars and verifying it.
let responseProof = try proofFromString(CurveType: Curve.self, value: tv.CredentialResponse.proof, scalarCount: ARC.CredentialResponse.scalarCount)
let responseProof = try proofFromString(CurveType: Curve.self, value: tv.CredentialResponse.proof, scalarCount: ARC.CredentialResponse<HashToCurveImpl<Curve>>.getScalarCount())
let newResponse = ARC.CredentialResponse(U: response.U, encUPrime: response.encUPrime, X0Aux: response.X0Aux, X1Aux: response.X1Aux, X2Aux: response.X2Aux, HAux: response.HAux, proof: responseProof)
XCTAssert(try newResponse.verify(request: precredential.credentialRequest, serverPublicKey: server.serverPublicKey, generatorG: server.generatorG, generatorH: server.generatorH))
XCTAssert(try newResponse.verify(request: precredential.credentialRequest, serverPublicKey: server.serverPublicKey, generatorG: server.generatorG, generatorH: server.generatorH, ciphersuite: ciphersuite))
// Make a credential from the response
var credential = try precredential.makeCredential(credentialResponse: response)
@@ -221,9 +283,9 @@ class ARCTestVectors: XCTestCase {
// Verify presentation1 proof, by creating a new presentation with the
// tv.Presentation1.proof scalars and verifying it.
let presentation1Proof = try proofFromString(CurveType: Curve.self, value: tv.Presentation1.proof, scalarCount: ARC.Presentation.scalarCount)
let presentation1Proof = try proofFromString(CurveType: Curve.self, value: tv.Presentation1.proof, scalarCount: ARC.Presentation<HashToCurveImpl<Curve>>.getScalarCount())
let newPresentation1 = ARC.Presentation(U: presentation1.U, UPrimeCommit: presentation1.UPrimeCommit, m1Commit: presentation1.m1Commit, tag: presentation1.tag, proof: presentation1Proof)
XCTAssert(try newPresentation1.verify(serverPrivateKey: server.serverPrivateKey, X1: server.serverPublicKey.X1, m2: m2, presentationContext: presentationContext1, presentationLimit: 2, nonce: nonce_1, generatorG: credential.generatorG, generatorH: credential.generatorH))
XCTAssert(try newPresentation1.verify(serverPrivateKey: server.serverPrivateKey, X1: server.serverPublicKey.X1, m2: m2, presentationContext: presentationContext1, presentationLimit: 2, nonce: nonce_1, generatorG: credential.generatorG, generatorH: credential.generatorH, ciphersuite: ciphersuite))
// Make a second presentation from the credential, passing in randomness a, r, z
let presentationContext2 = try Data(hexString: tv.Presentation2.presentation_context)
@@ -240,9 +302,9 @@ class ARCTestVectors: XCTestCase {
// Verify presentation2 proof, by creating a new presentation with the
// tv.Presentation2.proof scalars and verifying it.
let presentation2Proof = try proofFromString(CurveType: Curve.self, value: tv.Presentation2.proof, scalarCount: ARC.Presentation.scalarCount)
let presentation2Proof = try proofFromString(CurveType: Curve.self, value: tv.Presentation2.proof, scalarCount: ARC.Presentation<HashToCurveImpl<Curve>>.getScalarCount())
let newPresentation2 = ARC.Presentation(U: presentation2.U, UPrimeCommit: presentation2.UPrimeCommit, m1Commit: presentation2.m1Commit, tag: presentation2.tag, proof: presentation2Proof)
XCTAssert(try newPresentation2.verify(serverPrivateKey: server.serverPrivateKey, X1: server.serverPublicKey.X1, m2: m2, presentationContext: presentationContext2, presentationLimit: 2, nonce: nonce_2, generatorG: credential.generatorG, generatorH: credential.generatorH))
XCTAssert(try newPresentation2.verify(serverPrivateKey: server.serverPrivateKey, X1: server.serverPublicKey.X1, m2: m2, presentationContext: presentationContext2, presentationLimit: 2, nonce: nonce_2, generatorG: credential.generatorG, generatorH: credential.generatorH, ciphersuite: ciphersuite))
// Verify both presentations
XCTAssertTrue(try server.verify(presentation: presentation1, requestContext: requestContext, presentationContext: presentationContext1, presentationLimit: 2, nonce: nonce_1))
@@ -251,7 +313,8 @@ class ARCTestVectors: XCTestCase {
func validateTestVector(_ tv: ARCTestVector) {
switch tv.suite {
case ARC.domain: XCTAssertNoThrow(try self.validate(curveType: P384.self, tv))
case "ARCV1-P256": XCTAssertNoThrow(try self.validate(curveType: P256.self, tv))
case "ARCV1-P384": XCTAssertNoThrow(try self.validate(curveType: P384.self, tv))
default: XCTFail("Unsupported ciphersuite:" + tv.suite)
}
}
+5 -3
View File
@@ -47,7 +47,7 @@ class ARCTests: XCTestCase {
XCTAssert(m1Decrypted == m1 * generatorG)
let m2Decrypted = request.m2Enc - r2 * generatorH
XCTAssert(m2Decrypted == precredential.clientSecrets.m2 * generatorG)
XCTAssert(try request.verify(generatorG: generatorG, generatorH: generatorH))
XCTAssert(try request.verify(generatorG: generatorG, generatorH: generatorH, ciphersuite: ciphersuite))
// Server receives the CredentialRequest, and makes an CredentialResponse with its server keys.
let issuance = try server.respond(credentialRequest: request)
@@ -84,7 +84,8 @@ class ARCTests: XCTestCase {
presentationLimit: presentationLimit,
nonce: nonce1,
generatorG: generatorG,
generatorH: generatorH))
generatorH: generatorH,
ciphersuite: ciphersuite))
// Server verifies Presentation2 with its server keys.
XCTAssert(try server.verify(
@@ -102,7 +103,8 @@ class ARCTests: XCTestCase {
presentationLimit: presentationLimit,
nonce: nonce2,
generatorG: generatorG,
generatorH: generatorH))
generatorH: generatorH,
ciphersuite: ciphersuite))
// Test that two presentations with the same presentationContext and privateAttribute,
// but difference nonces, have different tag elements
+197
View File
@@ -0,0 +1,197 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Crypto
import Foundation
import XCTest
import _CryptoExtras
final class CMACTests: XCTestCase {
// Borrowed from CryptoKit
func testVector1() throws {
let key = try Array(hexString: "a60269f095ad3c3bafae907c6f215de0")
let mac = try Array(hexString: "172084c3fe99fde4af29aa8e6e5fe1")
let msg = try Array(hexString: "cead1c5af16ca89bc0821775f8cba8c25620a03dfd27d6f1186f75f1c0bcfe4a20")
var authenticator = try AES.CMAC(key: SymmetricKey(data: key), outputSize: 15)
authenticator.update(data: msg)
XCTAssert(authenticator.finalize() == mac)
}
// rfc4493 example vectors
// https://datatracker.ietf.org/doc/html/rfc4493#page-11
let exampleVector1 = ""
let exampleVector2 = """
6bc1bee22e409f96e93d7e117393172a
"""
let exampleVector3 = """
6bc1bee22e409f96e93d7e117393172a\
ae2d8a571e03ac9c9eb76fac45af8e51\
30c81c46a35ce411
"""
let exampleVector4 = """
6bc1bee22e409f96e93d7e117393172a\
ae2d8a571e03ac9c9eb76fac45af8e51\
30c81c46a35ce411e5fbc1191a0a52ef\
f69f2445df4f9b17ad2b417be66c3710
"""
func testExampleVector1() throws {
let key = try Array(hexString: "2b7e151628aed2a6abf7158809cf4f3c")
let mac = try Array(hexString: "bb1d6929e95937287fa37d129b756746")
let msg = try Array(hexString: exampleVector1)
var authenticator = try AES.CMAC(key: SymmetricKey(data: key), outputSize: 16)
authenticator.update(data: msg)
XCTAssert(authenticator.finalize() == mac)
}
func testExampleVector2() throws {
let key = try Array(hexString: "2b7e151628aed2a6abf7158809cf4f3c")
let mac = try Array(hexString: "070a16b46b4d4144f79bdd9dd04a287c")
let msg = try Array(hexString: exampleVector2)
var authenticator = try AES.CMAC(key: SymmetricKey(data: key), outputSize: 16)
authenticator.update(data: msg)
XCTAssert(authenticator.finalize() == mac)
}
func testExampleVector2PerByte() throws {
let key = try Array(hexString: "2b7e151628aed2a6abf7158809cf4f3c")
let mac = try Array(hexString: "070a16b46b4d4144f79bdd9dd04a287c")
let msg = try Array(hexString: exampleVector2)
var authenticator = try AES.CMAC(key: SymmetricKey(data: key), outputSize: 16)
for byte in msg {
authenticator.update(data: [byte])
}
XCTAssert(authenticator.finalize() == mac)
}
func testExampleVector3() throws {
let key = try Array(hexString: "2b7e151628aed2a6abf7158809cf4f3c")
let mac = try Array(hexString: "dfa66747de9ae63030ca32611497c827")
let msg = try Array(hexString: exampleVector3)
var authenticator = try AES.CMAC(key: SymmetricKey(data: key), outputSize: 16)
authenticator.update(data: msg)
XCTAssert(authenticator.finalize() == mac)
}
func testExampleVector3PerByte() throws {
let key = try Array(hexString: "2b7e151628aed2a6abf7158809cf4f3c")
let mac = try Array(hexString: "dfa66747de9ae63030ca32611497c827")
let msg = try Array(hexString: exampleVector3)
var authenticator = try AES.CMAC(key: SymmetricKey(data: key), outputSize: 16)
for byte in msg {
authenticator.update(data: [byte])
}
XCTAssert(authenticator.finalize() == mac)
}
// rfc4493 example vector 4
// https://datatracker.ietf.org/doc/html/rfc4493#page-11
func testExampleVector4() throws {
let key = try Array(hexString: "2b7e151628aed2a6abf7158809cf4f3c")
let mac = try Array(hexString: "51f0bebf7e3b9d92fc49741779363cfe")
let msg = try Array(hexString: exampleVector4)
var authenticator = try AES.CMAC(key: SymmetricKey(data: key), outputSize: 16)
authenticator.update(data: msg)
XCTAssert(authenticator.finalize() == mac)
}
// rfc4493 example vector 4
// https://datatracker.ietf.org/doc/html/rfc4493#page-11
func testExampleVector4PerByte() throws {
let key = try Array(hexString: "2b7e151628aed2a6abf7158809cf4f3c")
let mac = try Array(hexString: "51f0bebf7e3b9d92fc49741779363cfe")
let msg = try Array(hexString: exampleVector4)
var authenticator = try AES.CMAC(key: SymmetricKey(data: key), outputSize: 16)
for byte in msg {
authenticator.update(data: [byte])
}
XCTAssert(authenticator.finalize() == mac)
}
func testWycheproof() throws {
try wycheproofTest(jsonName: "aes_cmac_test") { (group: TestGroup) in
for test in group.tests {
precondition(test.flags.isEmpty)
do {
var authenticator = try AES.CMAC(key: test.computedKey, outputSize: test.computedTag.count)
authenticator.update(data: test.computedMsg)
let result = authenticator.finalize()
switch test.result {
case "valid":
XCTAssertTrue(
result == test.computedTag,
"Unexpected invalid test \(test.tcId) (\(test.comment))"
)
case "invalid":
XCTAssertFalse(
result == test.computedTag,
"Unexpected valid test \(test.tcId) (\(test.comment))"
)
default:
fatalError("Unexpected result type")
}
} catch {
XCTAssertTrue(test.result == "invalid", "Unexpected invalid test \(test.tcId) (\(test.comment))")
XCTAssertTrue(
test.comment == "invalid key size",
"Unexpected invalid test \(test.tcId) (\(test.comment))"
)
}
}
}
}
}
struct TestGroup: Codable {
var keySize: Int
var tagSize: Int
var type: String
var tests: [Test]
}
extension TestGroup {
struct Test: Codable {
var tcId: Int
var comment: String
var key: String
var msg: String
var tag: String
var result: String
var flags: [String]
var computedKey: SymmetricKey {
SymmetricKey(hexEncoded: self.key)
}
var computedMsg: Data {
try! Data(hexString: self.msg)
}
var computedTag: Data {
try! Data(hexString: self.tag)
}
}
}
@@ -0,0 +1,104 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2025 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 Foundation
import XCTest
#if !canImport(Darwin) || canImport(CryptoKit, _version: 241.100.42)
// Corresponds to the CryptoKit in XCode 16.3, which has Sendable annotations
import Crypto
@testable import _CryptoExtras
#else
@preconcurrency import Crypto
@testable import _CryptoExtras
#endif
final class ECToolboxBoringSSLTests: XCTestCase {
func testThreadLocalFFAC() async {
await testThreadLocalFFAC(P256.self)
await testThreadLocalFFAC(P384.self)
await testThreadLocalFFAC(P521.self)
}
func testThreadLocalFFAC(_ Curve: (some OpenSSLSupportedNISTCurve & Sendable).Type) async {
let numThreads = 3
let numReadsPerThread = 2
var threads:
[(
thread: Thread,
thisThreadDidReads: XCTestExpectation,
allThreadsDidReads: XCTestExpectation,
thisThreadFinished: XCTestExpectation
)] = []
let objectIdentifiers: LockedBox<[(threadID: Int, ffacID: ObjectIdentifier)]> = .init(initialValue: [])
for i in 1...numThreads {
let thisThreadDidReads = expectation(description: "this thread did its reads")
let allThreadsDidReads = expectation(description: "all threads did their reads")
let thisThreadFinished = expectation(description: "this thread is finished")
let thread = Thread {
for _ in 1...numReadsPerThread {
objectIdentifiers.withLockedValue {
$0.append((i, ObjectIdentifier(Curve.__ffac)))
}
}
thisThreadDidReads.fulfill()
XCTWaiter().wait(for: [allThreadsDidReads], timeout: .greatestFiniteMagnitude)
thisThreadFinished.fulfill()
}
thread.name = "thread-\(i)"
threads.append((thread, thisThreadDidReads, allThreadsDidReads, thisThreadFinished))
thread.start()
}
await fulfillment(of: threads.map(\.thisThreadDidReads), timeout: 0.5)
for thread in threads { thread.allThreadsDidReads.fulfill() }
await fulfillment(of: threads.map(\.thisThreadFinished), timeout: 0.5)
objectIdentifiers.withLockedValue { objectIdentifiers in
XCTAssertEqual(objectIdentifiers.count, numThreads * numReadsPerThread)
for threadID in 1...numThreads {
let partitionBoundary = objectIdentifiers.partition(by: { $0.threadID == threadID })
let otherThreadsObjIDs = objectIdentifiers[..<partitionBoundary].map(\.ffacID)
let thisThreadObjIDs = objectIdentifiers[partitionBoundary...].map(\.ffacID)
let intersection = Set(thisThreadObjIDs).intersection(Set(otherThreadsObjIDs))
XCTAssertEqual(
thisThreadObjIDs.count,
numReadsPerThread,
"Thread should read \(numReadsPerThread) times."
)
XCTAssertEqual(Set(thisThreadObjIDs).count, 1, "Thread should see same object on every read.")
XCTAssert(intersection.isEmpty, "Thread should see different objects from other threads.")
}
}
}
}
final class LockedBox<Value: Sendable>: @unchecked Sendable {
private let lock: NSLock
private var value: Value
init(initialValue: Value) {
self.value = initialValue
self.lock = NSLock()
}
func withLockedValue<ReturnType>(_ body: (inout Value) throws -> ReturnType) rethrows -> ReturnType {
self.lock.lock()
defer {
self.lock.unlock()
}
return try body(&self.value)
}
}
@@ -0,0 +1,201 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Crypto
import Foundation
import XCTest
@testable import _CryptoExtras
final class PKCS8DERRepresentationTests: XCTestCase {
func test_RSA() {
let rsaPrivateKeyPEM = """
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAxeBrlW1i+gXmqC/4XlTppLCXPpksZbxsc0AufsWzpcIxBAQL
jr4LxXyOenZcyhrdXxksEsCJE/8stJuUZgiFyDMesWjoL5bYyOpWrwPyvCMNaC8F
15cKe5n7OSVNU312X0ZSxTZAOrCEH0kGrsXoQn5JgHygVXejSPlHw8F1Pwps3pnc
cRYE9vsHZegspUI3DaqWgmewFWz6jSMY0v1DcZv2Xw+pMLeXEpKKMf+eo90mHShh
n8FijsI1tFuYD++LmM/e1TV1z+W2sPL2CaosBO890WeCyL/bFl4j1lmdnXdBNX+l
ub/5HTqI7hxAm/qonzDs3iV5KK1ZWZTVsPyqtwIDAQABAoIBAQCGLBQG8HMKgXHT
XSOWIxGCIFONmKMoIMmQpFZik3+qx7AgvvVvRqIIuNqLYzKrv+eXEiR2WqMYMhCI
Lm5DeUftZexL84xsqGY6Zdt9NLoko8f1et0FQF9VTCWyq/5wvEPFepOpMY3/vaz4
4bVsULmaTLNeMiMtkL/hPVZSAB2WLjI7EgOq7JamRBCMY+ivtdtqi12kO8vaA2Ns
dSKuU+e8tvAP4o6cMvuLtcqLy2UeoZzYTI998up0tqn+mGHl0DHx6MSi/TbVv3v8
gSQGlBvWzUx85vz+1GyjRn+o4hO/tibtP6aKfWYztIyLgkaU8JuDZzT+CwwmCnEH
ge/JmGuRAoGBAPypZ9MuWi1Ms57nVcpHRSHUc+cO/CfoaC4kRzgh99ApDbL+rj78
9eXkS10Z8hTLQprcznQr+WZhnhNw13PrvzaGhtOXd/xLBnWlqZ6aIGYrJgKu+JLl
yGVBZByG70yXel8IZt9l4CYctlS4D8iYAtdR+CCn8XGrc8JILnwBbYDNAoGBAMh9
tiC8hyIc/wBV/WcgtpY6tPkrN4uw6WREH+UkVpvNM2kMMCgn1YLHbYq1vSKN3rKZ
L9Ep4+8umRMg5yTgq9iURMoNjq+qU8NDF0nRljmyJRvgA5Ez2iQErm3y5dYxK+8w
BRvCkDeOiiu1Mnd9chgu0tQhpfo7o+T3XeXB5omTAoGBAKl3IqlVnKxnls6NEVC0
Tt0q93ZR6bUGv+G6+X3f4qxe7M5S3iJnXrMMVbQjc+iYkJr4YQ0wdX5DGVimxgv9
Ymo6/vGq1ZKF69Y7ADLd479DT6JbI2S79JZdrr0nkBfKPgzBwOY0GYzWk0Dtl8CO
nNE5LHkSy/HW8rSr32nTN1Q9AoGAOdl8GcoMO92d/pzRN1aLGKHr4hGEP3xWe6Xk
hhuMGfyFnwPzSULlKo0coG98GWJSJbppv7KUoEkTxh8yUsO5Eg8GIj7zMuC0tpy/
NX+SFye96WMj5FvPz6DCK9twUfNyN9vlPXNQZZdtatsnqq65oxyvnKHw4FkhG0n8
//SI7p0CgYEA9CoA6/3rRIVKKEOgeCQHDVKIJIauTUskwdrBHLVU7SH+cfQ6VNy6
zp/M54MpUP5jviSL61HmRoEqqcMWLALJHyZ1yQAZXSpthyMw0ahqTUZ71j1ukIO0
UUjK3drJJd2jGQ0LfhlDCX7VmURIqJ6kaQ0WBNAJLFhTW4AS8HGYRZk=
-----END RSA PRIVATE KEY-----
"""
// Same key in PKCS8 DER representation.
let encodedPKCS8DER =
"MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDF4GuVbWL6BeaoL/heVOmksJc+mSxlvGxzQC5+xbOlwjEEBAuOvgvFfI56dlzKGt1fGSwSwIkT/yy0m5RmCIXIMx6xaOgvltjI6lavA/K8Iw1oLwXXlwp7mfs5JU1TfXZfRlLFNkA6sIQfSQauxehCfkmAfKBVd6NI+UfDwXU/CmzemdxxFgT2+wdl6CylQjcNqpaCZ7AVbPqNIxjS/UNxm/ZfD6kwt5cSkoox/56j3SYdKGGfwWKOwjW0W5gP74uYz97VNXXP5baw8vYJqiwE7z3RZ4LIv9sWXiPWWZ2dd0E1f6W5v/kdOojuHECb+qifMOzeJXkorVlZlNWw/Kq3AgMBAAECggEBAIYsFAbwcwqBcdNdI5YjEYIgU42YoyggyZCkVmKTf6rHsCC+9W9Gogi42otjMqu/55cSJHZaoxgyEIgubkN5R+1l7EvzjGyoZjpl2300uiSjx/V63QVAX1VMJbKr/nC8Q8V6k6kxjf+9rPjhtWxQuZpMs14yIy2Qv+E9VlIAHZYuMjsSA6rslqZEEIxj6K+122qLXaQ7y9oDY2x1Iq5T57y28A/ijpwy+4u1yovLZR6hnNhMj33y6nS2qf6YYeXQMfHoxKL9NtW/e/yBJAaUG9bNTHzm/P7UbKNGf6jiE7+2Ju0/pop9ZjO0jIuCRpTwm4NnNP4LDCYKcQeB78mYa5ECgYEA/Kln0y5aLUyznudVykdFIdRz5w78J+hoLiRHOCH30CkNsv6uPvz15eRLXRnyFMtCmtzOdCv5ZmGeE3DXc+u/NoaG05d3/EsGdaWpnpogZismAq74kuXIZUFkHIbvTJd6Xwhm32XgJhy2VLgPyJgC11H4IKfxcatzwkgufAFtgM0CgYEAyH22ILyHIhz/AFX9ZyC2ljq0+Ss3i7DpZEQf5SRWm80zaQwwKCfVgsdtirW9Io3espkv0Snj7y6ZEyDnJOCr2JREyg2Or6pTw0MXSdGWObIlG+ADkTPaJASubfLl1jEr7zAFG8KQN46KK7Uyd31yGC7S1CGl+juj5Pdd5cHmiZMCgYEAqXciqVWcrGeWzo0RULRO3Sr3dlHptQa/4br5fd/irF7szlLeImdeswxVtCNz6JiQmvhhDTB1fkMZWKbGC/1iajr+8arVkoXr1jsAMt3jv0NPolsjZLv0ll2uvSeQF8o+DMHA5jQZjNaTQO2XwI6c0TkseRLL8dbytKvfadM3VD0CgYA52XwZygw73Z3+nNE3VosYoeviEYQ/fFZ7peSGG4wZ/IWfA/NJQuUqjRygb3wZYlIlumm/spSgSRPGHzJSw7kSDwYiPvMy4LS2nL81f5IXJ73pYyPkW8/PoMIr23BR83I32+U9c1Bll21q2yeqrrmjHK+cofDgWSEbSfz/9IjunQKBgQD0KgDr/etEhUooQ6B4JAcNUogkhq5NSyTB2sEctVTtIf5x9DpU3LrOn8zngylQ/mO+JIvrUeZGgSqpwxYsAskfJnXJABldKm2HIzDRqGpNRnvWPW6Qg7RRSMrd2skl3aMZDQt+GUMJftWZREionqRpDRYE0AksWFNbgBLwcZhFmQ=="
let rsaPrivateKeyPKCS8DER = Data(base64Encoded: encodedPKCS8DER)!
// Create private keys from both representations of the same key
let keyFromPEM = try! _RSA.Signing.PrivateKey(pemRepresentation: rsaPrivateKeyPEM)
let keyFromDER = try! _RSA.Signing.PrivateKey(derRepresentation: rsaPrivateKeyPKCS8DER)
XCTAssertEqual(keyFromDER.keySizeInBits, 2048)
XCTAssertEqual(keyFromPEM.keySizeInBits, 2048)
// The keys match
XCTAssertEqual(keyFromPEM.derRepresentation, keyFromDER.derRepresentation)
// Our property creates the expected representation
XCTAssertEqual(keyFromPEM.pkcs8DERRepresentation, rsaPrivateKeyPKCS8DER)
}
func test_ed25519() {
let privateKeyPEM = """
-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VwBCIEIFSrpkDrDWBMoz/YWjFaW9t4TQaKWyalZ6TRDUS/4+LE
-----END PRIVATE KEY-----
"""
// Same key in PKCS8 DER representation.
let privateKeyPKCS8DER = Data(
base64Encoded:
"MC4CAQAwBQYDK2VwBCIEIFSrpkDrDWBMoz/YWjFaW9t4TQaKWyalZ6TRDUS/4+LE"
)!
// We only need the 32 bytes of the key.
let document = try! ASN1.PEMDocument(pemString: privateKeyPEM)
var bytes = document.derBytes
bytes.removeFirst(bytes.count - 32)
let keyFromDER = try! Curve25519.Signing.PrivateKey(rawRepresentation: bytes)
let pkcs8 = keyFromDER.pkcs8DERRepresentation
XCTAssertEqual(pkcs8, privateKeyPKCS8DER)
}
func test_ed25519_rfc_example() {
// Example key from RFC 8410, Section 10.3.
// Create private key from bytes.
let keyBytes = Data(
base64Encoded:
"1O5y2/kTWErVttjx92n4rTr+fCjL8dT74Jeoj0R1WEI="
)!
// Same key in PKCS8 DER representation.
let exampleKeyPKCS8DER = Data(
base64Encoded:
"MC4CAQAwBQYDK2VwBCIEINTuctv5E1hK1bbY8fdp+K06/nwoy/HU++CXqI9EdVhC"
)!
// Create key from the private key bytes and compare our exported representation.
let exampleKey = try! Curve25519.Signing.PrivateKey(rawRepresentation: keyBytes)
XCTAssertEqual(exampleKey.pkcs8DERRepresentation, exampleKeyPKCS8DER)
}
func test_x25519() {
let privateKeyPEM = """
-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VuBCIEIKBtrFwBvmRtGZjMyj0rXewOQclz/8cdEY981glA/w5a
-----END PRIVATE KEY-----
"""
// Same key in PKCS8 DER representation.
let privateKeyPKCS8DER = Data(
base64Encoded:
"MC4CAQAwBQYDK2VuBCIEIKBtrFwBvmRtGZjMyj0rXewOQclz/8cdEY981glA/w5a"
)!
// We only need the 32 bytes of the key.
let document = try! ASN1.PEMDocument(pemString: privateKeyPEM)
var bytes = document.derBytes
bytes.removeFirst(bytes.count - 32)
// Create key from the private key bytes and compare our exported representation.
let keyFromDER = try! Curve25519.KeyAgreement.PrivateKey(rawRepresentation: bytes)
XCTAssertEqual(keyFromDER.pkcs8DERRepresentation, privateKeyPKCS8DER)
}
func test_P256() {
let privateKeyPEM = """
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgO6fz+J/sZqbCki3h
chsrVb69KW8q24pLDwotAtwz/gahRANCAASkBqszxMCGrd8l+xZitPto300blCWk
wRCdoar3UeEEfuH5LsJ3kNjN+oMZmHAmnhHE6cqLHFem/ujsGgrqJ3E8
-----END PRIVATE KEY-----
"""
let encodedPKCS8DER =
"MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgO6fz+J/sZqbCki3hchsrVb69KW8q24pLDwotAtwz/gahRANCAASkBqszxMCGrd8l+xZitPto300blCWkwRCdoar3UeEEfuH5LsJ3kNjN+oMZmHAmnhHE6cqLHFem/ujsGgrqJ3E8"
let privateKeyPKCS8DER = Data(base64Encoded: encodedPKCS8DER)!
// Create key from PEM and compare our exported representation.
let keyFromPEM = try! P256.Signing.PrivateKey(pemRepresentation: privateKeyPEM)
XCTAssertEqual(keyFromPEM.pkcs8DERRepresentation, privateKeyPKCS8DER)
}
func test_P384() {
let privateKeyPEM = """
-----BEGIN PRIVATE KEY-----
MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDD2qUnvEDviY5Hon7fx
rsJmgWCGQcNlU+nXEWOoFPC49kioBm1hsveCH0q3vk9GjZKhZANiAAQFzxvdG2gI
uWZfkAeMW2BzsKGdUWwybx8MHs8fv48MCPmfvL4kIvkU9T7F7diut41ciSzILv5/
gb45xx6+dZjlWxIopstQuBu5v/J4oa3fgN1uYQJTSsKksDi3L52TcnY=
-----END PRIVATE KEY-----
"""
// Same key in PKCS8 DER representation.
let encodedPKCS8DER =
"MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDD2qUnvEDviY5Hon7fxrsJmgWCGQcNlU+nXEWOoFPC49kioBm1hsveCH0q3vk9GjZKhZANiAAQFzxvdG2gIuWZfkAeMW2BzsKGdUWwybx8MHs8fv48MCPmfvL4kIvkU9T7F7diut41ciSzILv5/gb45xx6+dZjlWxIopstQuBu5v/J4oa3fgN1uYQJTSsKksDi3L52TcnY="
let privateKeyPKCS8DER = Data(base64Encoded: encodedPKCS8DER)!
// Create key from PEM and compare our exported representation.
let keyFromPEM = try! P384.Signing.PrivateKey(pemRepresentation: privateKeyPEM)
XCTAssertEqual(keyFromPEM.pkcs8DERRepresentation, privateKeyPKCS8DER)
}
func test_P521() {
let privateKeyPEM = """
-----BEGIN PRIVATE KEY-----
MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIBcQv0MVt8xb5teBQJ
Mqn7wnQ2GVzgL+jkMERcMaABU7+UL7uC0ff+15RKEI2RwKLVUVvp3WJigCHBDpwY
qI9OFnyhgYkDgYYABAD7PeX+GFUa99yyhYJ4WReKq2nLUOjo+ZZ+pdepc0EaESj+
8o2Sv4mRjIU0s3WFTNx0mh9BKiszBNRu2nq148ZfCwAcAiJu4xcwR2o+L7BqNadJ
1hCoVItbL61BWxAMITZPegQLMV1K7SMS6NNkYBBIh10Q870tBO26VJ5wMm5K46MA
Cg==
-----END PRIVATE KEY-----
"""
// Same key in PKCS8 DER representation.
let encodedPKCS8DER =
"MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIBcQv0MVt8xb5teBQJMqn7wnQ2GVzgL+jkMERcMaABU7+UL7uC0ff+15RKEI2RwKLVUVvp3WJigCHBDpwYqI9OFnyhgYkDgYYABAD7PeX+GFUa99yyhYJ4WReKq2nLUOjo+ZZ+pdepc0EaESj+8o2Sv4mRjIU0s3WFTNx0mh9BKiszBNRu2nq148ZfCwAcAiJu4xcwR2o+L7BqNadJ1hCoVItbL61BWxAMITZPegQLMV1K7SMS6NNkYBBIh10Q870tBO26VJ5wMm5K46MACg=="
let privateKeyPKCS8DER = Data(base64Encoded: encodedPKCS8DER)
// Create key from PEM and compare our exported representation.
let keyFromPEM = try! P521.Signing.PrivateKey(pemRepresentation: privateKeyPEM)
XCTAssertEqual(keyFromPEM.pkcs8DERRepresentation, privateKeyPKCS8DER)
}
}
@@ -45,7 +45,11 @@ extension Array where Element == UInt8 {
init(hexString: String) throws {
self.init()
guard hexString.count.isMultiple(of: 2), !hexString.isEmpty else {
if hexString.count == 0 {
return
}
if hexString.count % 2 != 0 {
throw ByteHexEncodingErrors.incorrectString
}
File diff suppressed because it is too large. Load diff
+2
View File
@@ -13,5 +13,7 @@
##===----------------------------------------------------------------------===##
if(NOT TARGET SwiftCrypto)
include(CMakeFindDependencyMacro)
find_dependency(SwiftASN1)
include(@SWIFT_CRYPTO_EXPORTS_FILE@)
endif()
+78
View File
@@ -0,0 +1,78 @@
#!/bin/bash
##===----------------------------------------------------------------------===##
##
## This source file is part of the SwiftCrypto open source project
##
## Copyright (c) 2019-2025 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
##
##===----------------------------------------------------------------------===##
#
# This script generates Swift SDKs for Linux targets using the swift-sdk-generator.
# It should be run once before running the `vendor-boringssl.sh` script, which requires
# the Linux Swift SDKs to be installed.
#
# Usage:
# 1. Run this script to generate and install the Swift SDKs. This script can be re-run to
# re-generate Swift SDKs if needed. Old SDKs will be removed before installing newly
# generated ones.
#
set -e
SWIFT_VERSION=5.10
DISTRO_NAME=ubuntu
DISTRO_VERSION=jammy
DISTRO_VERSION_GENERATOR=22.04
TMPDIR=$(mktemp -d /tmp/.workingXXXXXX)
function generate_swift_sdk {
TARGET_ARCH=$1
SDK_NAME="${SWIFT_VERSION}-RELEASE_${DISTRO_NAME}_${DISTRO_VERSION}_${TARGET_ARCH}"
cd "$TMPDIR"
if [ ! -d swift-sdk-generator ]; then
echo "Cloning SDK generator..."
git clone https://github.com/swiftlang/swift-sdk-generator.git
fi
cd swift-sdk-generator
if [ "$TARGET_ARCH" = "armv7" ]; then
DOWNLOAD_FILE=swift-${SWIFT_VERSION}-RELEASE-${DISTRO_NAME}-${DISTRO_VERSION}-armv7-install
DOWNLOAD_PATH="${TMPDIR}/${DOWNLOAD_FILE}"
echo "Downloading armv7 runtime..."
wget -nc https://github.com/swift-embedded-linux/armhf-debian/releases/download/${SWIFT_VERSION}/${DOWNLOAD_FILE}.tar.gz && \
echo "Extracting armv7 runtime..." && \
mkdir "${DOWNLOAD_PATH}" && true && \
tar -xf ${DOWNLOAD_FILE}.tar.gz -C "${DOWNLOAD_PATH}"
echo "Creating Swift SDK for ${TARGET_ARCH}..."
swift run swift-sdk-generator make-linux-sdk \
--swift-version ${SWIFT_VERSION}-RELEASE \
--distribution-name ${DISTRO_NAME} \
--distribution-version ${DISTRO_VERSION_GENERATOR} \
--target armv7-unknown-linux-gnueabihf \
--target-swift-package-path "${DOWNLOAD_PATH}"
else
echo "Creating Swift SDK for ${TARGET_ARCH}..."
swift run swift-sdk-generator make-linux-sdk \
--swift-version ${SWIFT_VERSION}-RELEASE \
--distribution-name ${DISTRO_NAME} \
--distribution-version ${DISTRO_VERSION_GENERATOR} \
--target "${TARGET_ARCH}-unknown-linux-gnu"
fi
swift sdk remove "${SDK_NAME}" || true # ignore error if it doesn't exist
swift sdk install "Bundles/${SDK_NAME}.artifactbundle"
}
echo "Generating Swift SDKs for Linux targets..."
generate_swift_sdk "x86_64"
generate_swift_sdk "aarch64"
generate_swift_sdk "armv7"
+18 -10
View File
@@ -45,6 +45,11 @@ DSTROOT=Sources/CCryptoBoringSSL
TMPDIR=$(mktemp -d /tmp/.workingXXXXXX)
SRCROOT="${TMPDIR}/src/boringssl.googlesource.com/boringssl"
# BoringSSL revision can be passed as the first argument to this script.
if [ "$#" -gt 0 ]; then
BORINGSSL_REVISION="$1"
fi
# This function namespaces the awkward inline functions declared in OpenSSL
# and BoringSSL.
function namespace_inlines {
@@ -101,16 +106,16 @@ function mangle_symbols {
)
# Now cross compile for our targets.
docker run -t -i --rm --privileged -v"$(pwd)":/src -w/src --platform linux/arm64 swift:5.10-jammy \
swift build --product CCryptoBoringSSL
docker run -t -i --rm --privileged -v"$(pwd)":/src -w/src --platform linux/amd64 swift:5.10-jammy \
swift build --product CCryptoBoringSSL
# NOTE: This requires running the `generate-linux-sdks.sh` script first to generate the Swift SDKs.
swift build --swift-sdk 5.10-RELEASE_ubuntu_jammy_x86_64 --product CCryptoBoringSSL
swift build --swift-sdk 5.10-RELEASE_ubuntu_jammy_aarch64 --product CCryptoBoringSSL
swift build --swift-sdk 5.10-RELEASE_ubuntu_jammy_armv7 --product CCryptoBoringSSL
# Now we need to generate symbol mangles for Linux. We can do this in
# one go for all of them.
(
cd "${SRCROOT}"
go run "util/read_symbols.go" -obj-file-format elf -out "${TMPDIR}/symbols-linux-all.txt" "${HERE}"/.build/*-unknown-linux-gnu/debug/libCCryptoBoringSSL.a
go run "util/read_symbols.go" -obj-file-format elf -out "${TMPDIR}/symbols-linux-all.txt" "${HERE}"/.build/*-unknown-linux-*/debug/libCCryptoBoringSSL.a
)
# Now we concatenate all the symbols together and uniquify it. At this stage remove anything that
@@ -170,9 +175,14 @@ echo "CLONING boringssl"
mkdir -p "$SRCROOT"
git clone https://boringssl.googlesource.com/boringssl "$SRCROOT"
cd "$SRCROOT"
BORINGSSL_REVISION=$(git rev-parse HEAD)
if [ "$BORINGSSL_REVISION" ]; then
echo "CHECKING OUT boringssl@${BORINGSSL_REVISION}"
git checkout "$BORINGSSL_REVISION"
else
BORINGSSL_REVISION=$(git rev-parse HEAD)
echo "CLONED boringssl@${BORINGSSL_REVISION}"
fi
cd "$HERE"
echo "CLONED boringssl@${BORINGSSL_REVISION}"
echo "OBTAINING submodules"
(
@@ -248,7 +258,7 @@ echo "DISABLING assembly on x86 Windows"
# x86 Windows builds require nasm for acceleration. SwiftPM can't do that right now,
# so we disable the assembly.
cd "$DSTROOT"
gsed -i "/#define OPENSSL_HEADER_BASE_H/a#if defined(_WIN32) && (defined(__x86_64) || defined(_M_AMD64) || defined(_M_X64) || defined(__x86) || defined(__i386) || defined(__i386__) || defined(_M_IX86))\n#define OPENSSL_NO_ASM\n#endif" "include/openssl/base.h"
$sed -i "/#define OPENSSL_HEADER_BASE_H/a#if defined(_WIN32) && (defined(__x86_64) || defined(_M_AMD64) || defined(_M_X64) || defined(__x86) || defined(__i386) || defined(__i386__) || defined(_M_IX86))\n#define OPENSSL_NO_ASM\n#endif" "include/openssl/base.h"
)
@@ -347,8 +357,6 @@ cat << EOF > "$DSTROOT/include/CCryptoBoringSSL.h"
#include "CCryptoBoringSSL_hrss.h"
#include "CCryptoBoringSSL_md4.h"
#include "CCryptoBoringSSL_md5.h"
#include "CCryptoBoringSSL_mldsa.h"
#include "CCryptoBoringSSL_mlkem.h"
#include "CCryptoBoringSSL_obj_mac.h"
#include "CCryptoBoringSSL_objects.h"
#include "CCryptoBoringSSL_opensslv.h"