mirror of
https://github.com/apple/swift-crypto
synced 2026-11-26 04:47:49 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b0b1963823 | ||
|
|
40ca846975 | ||
|
|
e652730d73 | ||
|
|
3280a5f728 | ||
|
|
1fa43495bc | ||
|
|
9f96b82711 | ||
|
|
281a92df6c | ||
|
|
32adcc5038 | ||
|
|
1586608eee | ||
|
|
f8fad2f95a | ||
|
|
6ff0a3b147 | ||
|
|
ab0beab369 | ||
|
|
57de8e7cb8 | ||
|
|
6a032cf17d | ||
|
|
404c818e35 | ||
|
|
47df2f1f6d | ||
|
|
c2cbadd726 | ||
|
|
deb49b961e | ||
|
|
0f6f68df04 | ||
|
|
1c80d3aff5 | ||
|
|
25847ff705 | ||
|
|
8c018d0882 | ||
|
|
a629920495 | ||
|
|
a9d1d5ab89 | ||
|
|
da9d28d69e | ||
|
|
f79a3ffbc0 | ||
|
|
fa2832e44b | ||
|
|
315a799ccc | ||
|
|
3ed653865a | ||
|
|
47d3869a72 | ||
|
|
c3d9fc8938 | ||
|
|
1ca42a1885 | ||
|
|
1b6b2e274e | ||
|
|
2d37b1192f | ||
|
|
c5b1d7f0cb | ||
|
|
476538ccb8 | ||
|
|
5ef6059b2b | ||
|
|
bb4ba815da | ||
|
|
fa308c07a6 | ||
|
|
a5a71cfcbc | ||
|
|
31611736b0 |
No files matched your search
@@ -0,0 +1,28 @@
|
|||||||
|
{
|
||||||
|
"name": "swift-crypto",
|
||||||
|
"image": "swift:latest",
|
||||||
|
"features": {
|
||||||
|
"ghcr.io/devcontainers/features/common-utils:2": {
|
||||||
|
"installZsh": "false",
|
||||||
|
"username": "vscode",
|
||||||
|
"upgradePackages": "false"
|
||||||
|
},
|
||||||
|
"ghcr.io/devcontainers/features/git:1": {
|
||||||
|
"version": "latest"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"capAdd": ["CAP_SYS_PTRACE"],
|
||||||
|
"securityOpt": ["seccomp=unconfined"],
|
||||||
|
"customizations": {
|
||||||
|
"vscode": {
|
||||||
|
"settings": {
|
||||||
|
"swift.path": "/usr/bin",
|
||||||
|
"lldb.library": "/usr/lib/liblldb.so"
|
||||||
|
},
|
||||||
|
"extensions": [
|
||||||
|
"swiftlang.swift-vscode"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"remoteUser": "vscode"
|
||||||
|
}
|
||||||
@@ -15,19 +15,19 @@ jobs:
|
|||||||
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
|
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
|
||||||
with:
|
with:
|
||||||
linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
|
linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
|
||||||
linux_6_0_arguments_override: "--explicit-target-dependency-import-check error"
|
|
||||||
linux_6_1_arguments_override: "--explicit-target-dependency-import-check error"
|
linux_6_1_arguments_override: "--explicit-target-dependency-import-check error"
|
||||||
linux_6_2_arguments_override: "--explicit-target-dependency-import-check error"
|
linux_6_2_arguments_override: "--explicit-target-dependency-import-check error"
|
||||||
|
linux_6_3_arguments_override: "--explicit-target-dependency-import-check error"
|
||||||
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
|
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
|
||||||
linux_nightly_main_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_6_1_enabled: true
|
||||||
windows_6_2_enabled: true
|
windows_6_2_enabled: true
|
||||||
|
windows_6_3_enabled: true
|
||||||
windows_nightly_next_enabled: true
|
windows_nightly_next_enabled: true
|
||||||
windows_nightly_main_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_6_1_arguments_override: "--explicit-target-dependency-import-check error"
|
||||||
windows_6_2_arguments_override: "--explicit-target-dependency-import-check error"
|
windows_6_2_arguments_override: "--explicit-target-dependency-import-check error"
|
||||||
|
windows_6_3_arguments_override: "--explicit-target-dependency-import-check error"
|
||||||
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
|
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
|
||||||
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
|
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
|
||||||
|
|
||||||
@@ -35,9 +35,9 @@ jobs:
|
|||||||
name: Release builds
|
name: Release builds
|
||||||
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
|
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
|
||||||
with:
|
with:
|
||||||
windows_6_0_enabled: true
|
|
||||||
windows_6_1_enabled: true
|
windows_6_1_enabled: true
|
||||||
windows_6_2_enabled: true
|
windows_6_2_enabled: true
|
||||||
|
windows_6_3_enabled: true
|
||||||
windows_nightly_next_enabled: true
|
windows_nightly_next_enabled: true
|
||||||
windows_nightly_main_enabled: true
|
windows_nightly_main_enabled: true
|
||||||
|
|
||||||
@@ -55,3 +55,4 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
runner_pool: nightly
|
runner_pool: nightly
|
||||||
build_scheme: swift-crypto-Package
|
build_scheme: swift-crypto-Package
|
||||||
|
swift_6_1_enabled: false
|
||||||
@@ -10,39 +10,35 @@ on:
|
|||||||
jobs:
|
jobs:
|
||||||
soundness:
|
soundness:
|
||||||
name: Soundness
|
name: Soundness
|
||||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
|
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.13
|
||||||
with:
|
with:
|
||||||
license_header_check_project_name: "SwiftCrypto"
|
license_header_check_project_name: "SwiftCrypto"
|
||||||
docs_check_enabled: false
|
docs_check_enabled: false
|
||||||
|
format_check_container_image: "swift:latest"
|
||||||
|
|
||||||
unit-tests:
|
unit-tests:
|
||||||
name: Unit tests
|
name: Unit tests
|
||||||
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
|
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
|
||||||
with:
|
with:
|
||||||
linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
|
linux_6_2_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||||
linux_6_0_arguments_override: "--explicit-target-dependency-import-check error"
|
linux_6_3_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||||
linux_6_1_arguments_override: "--explicit-target-dependency-import-check error"
|
linux_nightly_next_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||||
linux_6_2_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"
|
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
|
||||||
windows_6_0_enabled: true
|
|
||||||
windows_6_1_enabled: true
|
|
||||||
windows_6_2_enabled: true
|
windows_6_2_enabled: true
|
||||||
|
windows_6_3_enabled: true
|
||||||
windows_nightly_next_enabled: true
|
windows_nightly_next_enabled: true
|
||||||
windows_nightly_main_enabled: true
|
windows_nightly_main_enabled: true
|
||||||
windows_6_0_arguments_override: "--explicit-target-dependency-import-check error"
|
windows_6_2_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||||
windows_6_1_arguments_override: "--explicit-target-dependency-import-check error"
|
windows_6_3_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||||
windows_6_2_arguments_override: "--explicit-target-dependency-import-check error"
|
windows_nightly_next_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||||
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
|
|
||||||
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
|
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
|
||||||
|
|
||||||
release-builds:
|
release-builds:
|
||||||
name: Release builds
|
name: Release builds
|
||||||
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
|
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
|
||||||
with:
|
with:
|
||||||
windows_6_0_enabled: true
|
|
||||||
windows_6_1_enabled: true
|
|
||||||
windows_6_2_enabled: true
|
windows_6_2_enabled: true
|
||||||
|
windows_6_3_enabled: true
|
||||||
windows_nightly_next_enabled: true
|
windows_nightly_next_enabled: true
|
||||||
windows_nightly_main_enabled: true
|
windows_nightly_main_enabled: true
|
||||||
|
|
||||||
@@ -52,13 +48,16 @@ jobs:
|
|||||||
|
|
||||||
cmake-checks:
|
cmake-checks:
|
||||||
name: CMake checks
|
name: CMake checks
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
swift_version: ["6.2", "6.3", "6.4"]
|
||||||
uses: apple/swift-nio/.github/workflows/cmake_tests.yml@main
|
uses: apple/swift-nio/.github/workflows/cmake_tests.yml@main
|
||||||
with:
|
with:
|
||||||
update_cmake_lists_config: >-
|
update_cmake_lists_config: >-
|
||||||
{
|
{
|
||||||
"targets": [
|
"targets": [
|
||||||
{ "name": "CCryptoBoringSSL", "type": "source", "exceptions": [] },
|
{ "name": "CCryptoBoringSSL", "type": "source", "exceptions": [] },
|
||||||
{ "name": "CCryptoBoringSSLShims", "type": "source", "exceptions": [] },
|
|
||||||
{ "name": "CryptoBoringWrapper", "type": "source", "exceptions": [] },
|
{ "name": "CryptoBoringWrapper", "type": "source", "exceptions": [] },
|
||||||
{ "name": "CXKCP", "type": "source", "exceptions": [] },
|
{ "name": "CXKCP", "type": "source", "exceptions": [] },
|
||||||
{ "name": "CXKCPShims", "type": "source", "exceptions": [] },
|
{ "name": "CXKCPShims", "type": "source", "exceptions": [] },
|
||||||
@@ -67,6 +66,7 @@ jobs:
|
|||||||
{ "name": "CCryptoBoringSSL", "type": "assembly", "exceptions": [ "*/AES/*.swift" ] }
|
{ "name": "CCryptoBoringSSL", "type": "assembly", "exceptions": [ "*/AES/*.swift" ] }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
image: "swift:${{ matrix.swift_version }}"
|
||||||
|
|
||||||
macos-tests:
|
macos-tests:
|
||||||
name: macOS tests
|
name: macOS tests
|
||||||
@@ -74,6 +74,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
runner_pool: general
|
runner_pool: general
|
||||||
build_scheme: swift-crypto-Package
|
build_scheme: swift-crypto-Package
|
||||||
|
swift_6_1_enabled: false
|
||||||
|
|
||||||
static-sdk:
|
static-sdk:
|
||||||
name: Static SDK
|
name: Static SDK
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ jobs:
|
|||||||
timeout-minutes: 1
|
timeout-minutes: 1
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v6
|
||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
- name: Check for Semantic Version label
|
- name: Check for Semantic Version label
|
||||||
|
|||||||
@@ -65,6 +65,8 @@ Sources/Crypto/Signatures/ECDSA.swift
|
|||||||
Sources/Crypto/Signatures/Ed25519.swift
|
Sources/Crypto/Signatures/Ed25519.swift
|
||||||
Sources/Crypto/Signatures/MLDSA.swift
|
Sources/Crypto/Signatures/MLDSA.swift
|
||||||
Sources/Crypto/Signatures/Signature.swift
|
Sources/Crypto/Signatures/Signature.swift
|
||||||
|
Sources/Crypto/Util/ArraySpanHelpers.swift
|
||||||
|
Sources/Crypto/Util/Data+ArraySpan.swift
|
||||||
Sources/Crypto/Util/PrettyBytes.swift
|
Sources/Crypto/Util/PrettyBytes.swift
|
||||||
Sources/Crypto/Util/SafeCompare.swift
|
Sources/Crypto/Util/SafeCompare.swift
|
||||||
Sources/Crypto/Util/SecureBytes.swift
|
Sources/Crypto/Util/SecureBytes.swift
|
||||||
@@ -136,6 +138,7 @@ Tests/CryptoTests/Signatures/ECDSA/RawECDSASignaturesTests.swift
|
|||||||
Tests/CryptoTests/Signatures/EdDSA/Ed25519-Runner.swift
|
Tests/CryptoTests/Signatures/EdDSA/Ed25519-Runner.swift
|
||||||
Tests/CryptoTests/Signatures/MLDSA/MLDSAKeyGenTests.swift
|
Tests/CryptoTests/Signatures/MLDSA/MLDSAKeyGenTests.swift
|
||||||
Tests/CryptoTests/Signatures/MLDSA/MLDSATests.swift
|
Tests/CryptoTests/Signatures/MLDSA/MLDSATests.swift
|
||||||
|
Tests/CryptoTests/SymmetricKeyTests/SymmetricKeyTests.swift
|
||||||
Tests/CryptoTests/Utils/PrettyBytes.swift
|
Tests/CryptoTests/Utils/PrettyBytes.swift
|
||||||
Tests/CryptoTests/Utils/RFCVector.swift
|
Tests/CryptoTests/Utils/RFCVector.swift
|
||||||
Tests/CryptoTests/Utils/SplitData.swift
|
Tests/CryptoTests/Utils/SplitData.swift
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ import FoundationEssentials
|
|||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
let benchmarks = {
|
let benchmarks: @Sendable () -> Void = {
|
||||||
let defaultMetrics: [BenchmarkMetric] = [.mallocCountTotal, .cpuTotal]
|
let defaultMetrics: [BenchmarkMetric] = [.mallocCountTotal, .cpuTotal]
|
||||||
|
|
||||||
Benchmark(
|
Benchmark(
|
||||||
@@ -208,4 +208,145 @@ let benchmarks = {
|
|||||||
blackHole(try key1.sharedSecretFromKeyAgreement(with: key2.publicKey))
|
blackHole(try key1.sharedSecretFromKeyAgreement(with: key2.publicKey))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Benchmark(
|
||||||
|
"hmac-sha256-authenticate",
|
||||||
|
configuration: Benchmark.Configuration(
|
||||||
|
metrics: defaultMetrics,
|
||||||
|
scalingFactor: .mega,
|
||||||
|
maxDuration: .seconds(10_000_000),
|
||||||
|
maxIterations: 5
|
||||||
|
)
|
||||||
|
) { benchmark in
|
||||||
|
let key = SymmetricKey(size: .bits256)
|
||||||
|
let message = Data(repeating: 0x41, count: 1024)
|
||||||
|
|
||||||
|
benchmark.startMeasurement()
|
||||||
|
|
||||||
|
for _ in benchmark.scaledIterations {
|
||||||
|
blackHole(HMAC<SHA256>.authenticationCode(for: message, using: key))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Benchmark(
|
||||||
|
"hkdf-sha256-derive",
|
||||||
|
configuration: Benchmark.Configuration(
|
||||||
|
metrics: defaultMetrics,
|
||||||
|
scalingFactor: .kilo,
|
||||||
|
maxDuration: .seconds(10_000_000),
|
||||||
|
maxIterations: 10
|
||||||
|
)
|
||||||
|
) { benchmark in
|
||||||
|
let inputKeyMaterial = SymmetricKey(size: .bits256)
|
||||||
|
let salt = Data("benchmark salt".utf8)
|
||||||
|
let info = Data("benchmark info".utf8)
|
||||||
|
|
||||||
|
benchmark.startMeasurement()
|
||||||
|
|
||||||
|
for _ in benchmark.scaledIterations {
|
||||||
|
blackHole(
|
||||||
|
HKDF<SHA256>.deriveKey(
|
||||||
|
inputKeyMaterial: inputKeyMaterial,
|
||||||
|
salt: salt,
|
||||||
|
info: info,
|
||||||
|
outputByteCount: 1024
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Benchmark(
|
||||||
|
"aes-keywrap-unwrap",
|
||||||
|
configuration: Benchmark.Configuration(
|
||||||
|
metrics: defaultMetrics,
|
||||||
|
scalingFactor: .mega,
|
||||||
|
maxDuration: .seconds(10_000_000),
|
||||||
|
maxIterations: 5
|
||||||
|
)
|
||||||
|
) { benchmark in
|
||||||
|
let kek = SymmetricKey(size: .bits256)
|
||||||
|
let wrapped = try AES.KeyWrap.wrap(SymmetricKey(size: .bits256), using: kek)
|
||||||
|
|
||||||
|
benchmark.startMeasurement()
|
||||||
|
|
||||||
|
for _ in benchmark.scaledIterations {
|
||||||
|
blackHole(try AES.KeyWrap.unwrap(wrapped, using: kek))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if #available(macOS 26.0, *) {
|
||||||
|
Benchmark(
|
||||||
|
"mlkem768-decapsulate",
|
||||||
|
configuration: Benchmark.Configuration(
|
||||||
|
metrics: defaultMetrics,
|
||||||
|
scalingFactor: .kilo,
|
||||||
|
maxDuration: .seconds(10_000_000),
|
||||||
|
maxIterations: 10
|
||||||
|
)
|
||||||
|
) { benchmark in
|
||||||
|
let privateKey = try MLKEM768.PrivateKey()
|
||||||
|
let encapsulated = try privateKey.publicKey.encapsulate().encapsulated
|
||||||
|
|
||||||
|
benchmark.startMeasurement()
|
||||||
|
|
||||||
|
for _ in benchmark.scaledIterations {
|
||||||
|
blackHole(try privateKey.decapsulate(encapsulated))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Benchmark(
|
||||||
|
"pbkdf2-sha256-derive",
|
||||||
|
configuration: Benchmark.Configuration(
|
||||||
|
metrics: defaultMetrics,
|
||||||
|
scalingFactor: .kilo,
|
||||||
|
maxDuration: .seconds(10_000_000),
|
||||||
|
maxIterations: 10
|
||||||
|
)
|
||||||
|
) { benchmark in
|
||||||
|
let password = Data("benchmark password".utf8)
|
||||||
|
let salt = Data("benchmark salt".utf8)
|
||||||
|
|
||||||
|
benchmark.startMeasurement()
|
||||||
|
|
||||||
|
for _ in benchmark.scaledIterations {
|
||||||
|
blackHole(
|
||||||
|
try KDF.Insecure.PBKDF2.deriveKey(
|
||||||
|
from: password,
|
||||||
|
salt: salt,
|
||||||
|
using: .sha256,
|
||||||
|
outputByteCount: 32,
|
||||||
|
unsafeUncheckedRounds: 1_000
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Benchmark(
|
||||||
|
"scrypt-derive",
|
||||||
|
configuration: Benchmark.Configuration(
|
||||||
|
metrics: defaultMetrics,
|
||||||
|
scalingFactor: .kilo,
|
||||||
|
maxDuration: .seconds(10_000_000),
|
||||||
|
maxIterations: 3
|
||||||
|
)
|
||||||
|
) { benchmark in
|
||||||
|
let password = Data("benchmark password".utf8)
|
||||||
|
let salt = Data("benchmark salt".utf8)
|
||||||
|
|
||||||
|
benchmark.startMeasurement()
|
||||||
|
|
||||||
|
for _ in benchmark.scaledIterations {
|
||||||
|
blackHole(
|
||||||
|
try KDF.Scrypt.deriveKey(
|
||||||
|
from: password,
|
||||||
|
salt: salt,
|
||||||
|
outputByteCount: 32,
|
||||||
|
rounds: 1 << 10,
|
||||||
|
blockSize: 8,
|
||||||
|
parallelism: 1
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
// swift-tools-version:5.10
|
// swift-tools-version:6.2
|
||||||
import PackageDescription
|
import PackageDescription
|
||||||
|
|
||||||
let package = Package(
|
let package = Package(
|
||||||
|
|||||||
+7
-8
@@ -12,7 +12,7 @@
|
|||||||
##
|
##
|
||||||
##===----------------------------------------------------------------------===##
|
##===----------------------------------------------------------------------===##
|
||||||
|
|
||||||
cmake_minimum_required(VERSION 3.15.1)
|
cmake_minimum_required(VERSION 3.16)
|
||||||
|
|
||||||
if(POLICY CMP0157)
|
if(POLICY CMP0157)
|
||||||
cmake_policy(SET CMP0157 NEW)
|
cmake_policy(SET CMP0157 NEW)
|
||||||
@@ -25,18 +25,14 @@ list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules)
|
|||||||
|
|
||||||
include(SwiftSupport)
|
include(SwiftSupport)
|
||||||
|
|
||||||
if(CMAKE_VERSION VERSION_LESS 3.16 AND CMAKE_SYSTEM_NAME STREQUAL Windows)
|
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
|
||||||
else()
|
|
||||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
|
||||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
|
||||||
endif()
|
|
||||||
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||||
set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift)
|
set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift)
|
||||||
|
|
||||||
set(SWIFT_CRYPTO_COMPILE_OPTIONS
|
set(SWIFT_CRYPTO_COMPILE_OPTIONS
|
||||||
-package-name com.apple.swift-crypto
|
-package-name com.apple.swift-crypto
|
||||||
|
-enable-experimental-feature Lifetimes
|
||||||
)
|
)
|
||||||
|
|
||||||
option(BUILD_SHARED_LIBS "Build shared libraries by default" YES)
|
option(BUILD_SHARED_LIBS "Build shared libraries by default" YES)
|
||||||
@@ -78,5 +74,8 @@ if(NOT SwiftASN1_FOUND)
|
|||||||
FetchContent_MakeAvailable(ASN1)
|
FetchContent_MakeAvailable(ASN1)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
# Set after vending swift-asn1 so its targets keep their own language mode.
|
||||||
|
set(CMAKE_Swift_LANGUAGE_VERSION 6)
|
||||||
|
|
||||||
add_subdirectory(Sources)
|
add_subdirectory(Sources)
|
||||||
add_subdirectory(cmake/modules)
|
add_subdirectory(cmake/modules)
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
# Code of Conduct
|
|
||||||
|
|
||||||
The code of conduct for this project can be found at https://swift.org/code-of-conduct.
|
|
||||||
+30
-10
@@ -5,6 +5,18 @@ your contribution to Apple and the community, and agree by submitting the patch
|
|||||||
that your contributions are licensed under the Apache 2.0 license (see
|
that your contributions are licensed under the Apache 2.0 license (see
|
||||||
`LICENSE.txt`).
|
`LICENSE.txt`).
|
||||||
|
|
||||||
|
## AI tools
|
||||||
|
|
||||||
|
Human discourse is an essential part of open source development. To encourage
|
||||||
|
productive collaboration between contributors and maintainers, please refrain
|
||||||
|
from using AI tools for the following:
|
||||||
|
|
||||||
|
- Issues: titles, bodies, and comments.
|
||||||
|
- Pull requests: titles, descriptions, and comments.
|
||||||
|
|
||||||
|
Contributors who feel more comfortable writing in another language may use
|
||||||
|
automated translation tools, but must include their original content in their
|
||||||
|
preferred language.
|
||||||
|
|
||||||
## How to submit a bug report
|
## How to submit a bug report
|
||||||
|
|
||||||
@@ -44,19 +56,27 @@ $ uname -a
|
|||||||
Linux beefy.machine 4.4.0-101-generic #124-Ubuntu SMP Fri Nov 10 18:29:59 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
|
Linux beefy.machine 4.4.0-101-generic #124-Ubuntu SMP Fri Nov 10 18:29:59 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
|
||||||
```
|
```
|
||||||
|
|
||||||
## Writing a Patch
|
## Contributing a pull request
|
||||||
|
|
||||||
A good swift-crypto patch is:
|
> [!IMPORTANT]
|
||||||
|
> To ensure productive use of contributor and maintainer time and resources,
|
||||||
|
> contributors must first agree their proposed change with a maintainer in an
|
||||||
|
> issue. Pull requests opened without prior discussion may be closed without
|
||||||
|
> review.
|
||||||
|
|
||||||
1. Concise, and contains as few changes as needed to achieve the end result.
|
If there is no issue already tracking the problem or feature request, please
|
||||||
2. Tested, ensuring that any tests provided failed before the patch and pass after it.
|
file a new one using your own voice (see "AI tools" usage above).
|
||||||
3. Documented, adding API documentation as needed to cover new functions and properties.
|
|
||||||
4. Accompanied by a great commit message, using our commit message template.
|
|
||||||
|
|
||||||
|
Once an issue is assigned to you, follow these steps:
|
||||||
|
|
||||||
## How to contribute your work
|
- Prepare your change, keeping in mind that a good patch is:
|
||||||
|
- Concise, and contains as few changes as needed to achieve the end result.
|
||||||
Please open a pull request at https://github.com/apple/swift-crypto. Make sure the CI passes, and then wait for code review.
|
- Tested, ensuring that any tests provided failed before the patch and pass
|
||||||
|
after it.
|
||||||
|
- Documented, adding API documentation as needed to cover new functions and
|
||||||
|
properties.
|
||||||
|
- Accompanied by a great commit message.
|
||||||
|
- Open a pull request and wait for code review by the maintainers.
|
||||||
|
|
||||||
### How to update CMakeLists files
|
### How to update CMakeLists files
|
||||||
|
|
||||||
@@ -69,7 +89,7 @@ act --container-architecture linux/amd64 pull_request -j cmake-lists -W ./.githu
|
|||||||
|
|
||||||
You can find the underlying script at https://github.com/apple/swift-nio/blob/main/scripts/update-cmake-lists.sh . Using the script directly is less straightforwards because it requires you to pass the JSON config from the `pull_request.yml` file into the script, such as:
|
You can find the underlying script at https://github.com/apple/swift-nio/blob/main/scripts/update-cmake-lists.sh . Using the script directly is less straightforwards because it requires you to pass the JSON config from the `pull_request.yml` file into the script, such as:
|
||||||
```
|
```
|
||||||
curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/update-cmake-lists.sh | CONFIG_JSON='{"targets":[{"name":"CCryptoBoringSSL","type":"source","exceptions":[]},{"name":"CCryptoBoringSSLShims","type":"source","exceptions":[]},{"name":"CryptoBoringWrapper","type":"source","exceptions":[]},{"name":"Crypto","type":"source","exceptions":[]},{"name":"CryptoExtras","type":"source","exceptions":[]},{"name":"CCryptoBoringSSL","type":"assembly","exceptions":["*/AES/*.swift"]}]}' bash
|
curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/update-cmake-lists.sh | CONFIG_JSON='{"targets":[{"name":"CCryptoBoringSSL","type":"source","exceptions":[]},{"name":"CryptoBoringWrapper","type":"source","exceptions":[]},{"name":"Crypto","type":"source","exceptions":[]},{"name":"CryptoExtras","type":"source","exceptions":[]},{"name":"CCryptoBoringSSL","type":"assembly","exceptions":["*/AES/*.swift"]}]}' bash
|
||||||
```
|
```
|
||||||
|
|
||||||
## API Evolution
|
## API Evolution
|
||||||
|
|||||||
+37
-66
@@ -1,4 +1,4 @@
|
|||||||
// swift-tools-version:6.0
|
// swift-tools-version:6.2
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
//
|
//
|
||||||
// This source file is part of the SwiftCrypto open source project
|
// This source file is part of the SwiftCrypto open source project
|
||||||
@@ -26,56 +26,31 @@ import PackageDescription
|
|||||||
|
|
||||||
import class Foundation.ProcessInfo
|
import class Foundation.ProcessInfo
|
||||||
|
|
||||||
// To develop this on Apple platforms, set this to true
|
// NOTE: To develop the the non-Darwin Crypto target on macOS, use a Dev Container.
|
||||||
let development = false
|
let nonDarwinPlatforms: [Platform] = [
|
||||||
|
.linux,
|
||||||
|
.android,
|
||||||
|
.windows,
|
||||||
|
.wasi,
|
||||||
|
.openbsd,
|
||||||
|
// The SwiftPM Platform symbol is not yet public but the underlying platform name is set.
|
||||||
|
// -- https://github.com/swiftlang/swift-package-manager/blob/swift-6.2.3-RELEASE/Sources/PackageDescription/SupportedPlatforms.swift#L75
|
||||||
|
.custom("freebsd"),
|
||||||
|
]
|
||||||
|
|
||||||
// Ideally, we should use `.when(platforms:)` to set `swiftSettings` and
|
var swiftSettings: [SwiftSetting] = [
|
||||||
// `dependencies` like on other platforms. However, `Platform.freebsd` is not
|
.define("CRYPTO_IN_SWIFTPM"),
|
||||||
// yet available, and therefore we guard the settings behind this boolean.
|
.enableExperimentalFeature("Lifetimes"),
|
||||||
#if os(FreeBSD)
|
.enableExperimentalFeature("SourceWarningControl"),
|
||||||
let isFreeBSD = true
|
]
|
||||||
#else
|
|
||||||
let isFreeBSD = false
|
// Only enable CheckImplementationOnly on 6.4 -- 6.3 has the feature, but produces many false positives.
|
||||||
|
#if compiler(>=6.4)
|
||||||
|
swiftSettings.append(.enableExperimentalFeature("CheckImplementationOnly"))
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
let swiftSettings: [SwiftSetting]
|
// A resource makes SwiftPM generate a `Bundle.module` accessor that imports Foundation, not just FoundationEssentials.
|
||||||
let dependencies: [Target.Dependency]
|
// `canImport(Darwin)` checks the host, not the target, so cross-compiling from Darwin still adds the resource.
|
||||||
if development || isFreeBSD {
|
|
||||||
swiftSettings = [
|
|
||||||
.define("CRYPTO_IN_SWIFTPM"),
|
|
||||||
.define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API"),
|
|
||||||
]
|
|
||||||
dependencies = [
|
|
||||||
"CCryptoBoringSSL",
|
|
||||||
"CCryptoBoringSSLShims",
|
|
||||||
"CryptoBoringWrapper",
|
|
||||||
"CXKCP",
|
|
||||||
"CXKCPShims",
|
|
||||||
]
|
|
||||||
} else {
|
|
||||||
let platforms: [Platform] = [
|
|
||||||
Platform.linux,
|
|
||||||
Platform.android,
|
|
||||||
Platform.windows,
|
|
||||||
Platform.wasi,
|
|
||||||
Platform.openbsd,
|
|
||||||
]
|
|
||||||
swiftSettings = [
|
|
||||||
.define("CRYPTO_IN_SWIFTPM"),
|
|
||||||
.define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API", .when(platforms: platforms)),
|
|
||||||
]
|
|
||||||
dependencies = [
|
|
||||||
.target(name: "CCryptoBoringSSL", condition: .when(platforms: platforms)),
|
|
||||||
.target(name: "CCryptoBoringSSLShims", condition: .when(platforms: platforms)),
|
|
||||||
.target(name: "CryptoBoringWrapper", condition: .when(platforms: platforms)),
|
|
||||||
.target(name: "CXKCP", condition: .when(platforms: platforms)),
|
|
||||||
.target(name: "CXKCPShims", condition: .when(platforms: platforms)),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
// This doesn't work when cross-compiling: the privacy manifest will be included in the Bundle and
|
|
||||||
// Foundation will be linked. This is, however, strictly better than unconditionally adding the
|
|
||||||
// resource.
|
|
||||||
#if canImport(Darwin)
|
#if canImport(Darwin)
|
||||||
let privacyManifestExclude: [String] = []
|
let privacyManifestExclude: [String] = []
|
||||||
let privacyManifestResource: [PackageDescription.Resource] = [.copy("PrivacyInfo.xcprivacy")]
|
let privacyManifestResource: [PackageDescription.Resource] = [.copy("PrivacyInfo.xcprivacy")]
|
||||||
@@ -128,6 +103,10 @@ let package = Package(
|
|||||||
.when(platforms: [Platform.wasi])
|
.when(platforms: [Platform.wasi])
|
||||||
),
|
),
|
||||||
.define("OPENSSL_NO_ASM", .when(platforms: [Platform.wasi])),
|
.define("OPENSSL_NO_ASM", .when(platforms: [Platform.wasi])),
|
||||||
|
// BoringSSL is vendored verbatim; we don't fix its warnings. Xcode enables
|
||||||
|
// -Wshorten-64-to-32 by default (SwiftPM does not), which produces dozens
|
||||||
|
// of warnings. Silence that group here.
|
||||||
|
.disableWarning("shorten-64-to-32"),
|
||||||
]
|
]
|
||||||
),
|
),
|
||||||
.target(
|
.target(
|
||||||
@@ -143,16 +122,9 @@ let package = Package(
|
|||||||
.headerSearchPath("low/KeccakP-1600"),
|
.headerSearchPath("low/KeccakP-1600"),
|
||||||
.headerSearchPath("low/common"),
|
.headerSearchPath("low/common"),
|
||||||
.headerSearchPath("common"),
|
.headerSearchPath("common"),
|
||||||
|
.disableWarning("macro-redefined"),
|
||||||
]
|
]
|
||||||
),
|
),
|
||||||
.target(
|
|
||||||
name: "CCryptoBoringSSLShims",
|
|
||||||
dependencies: ["CCryptoBoringSSL"],
|
|
||||||
exclude: privacyManifestExclude + [
|
|
||||||
"CMakeLists.txt"
|
|
||||||
],
|
|
||||||
resources: privacyManifestResource
|
|
||||||
),
|
|
||||||
.target(
|
.target(
|
||||||
name: "CXKCPShims",
|
name: "CXKCPShims",
|
||||||
dependencies: ["CXKCP"],
|
dependencies: ["CXKCP"],
|
||||||
@@ -163,16 +135,16 @@ let package = Package(
|
|||||||
),
|
),
|
||||||
.target(
|
.target(
|
||||||
name: "Crypto",
|
name: "Crypto",
|
||||||
dependencies: dependencies,
|
dependencies: [
|
||||||
|
.target(name: "CCryptoBoringSSL", condition: .when(platforms: nonDarwinPlatforms)),
|
||||||
|
.target(name: "CryptoBoringWrapper", condition: .when(platforms: nonDarwinPlatforms)),
|
||||||
|
.target(name: "CXKCP", condition: .when(platforms: nonDarwinPlatforms)),
|
||||||
|
.target(name: "CXKCPShims", condition: .when(platforms: nonDarwinPlatforms)),
|
||||||
|
],
|
||||||
exclude: privacyManifestExclude + [
|
exclude: privacyManifestExclude + [
|
||||||
|
"vendored-sources.txt",
|
||||||
"CMakeLists.txt",
|
"CMakeLists.txt",
|
||||||
"AEADs/Nonces.swift.gyb",
|
|
||||||
"Digests/Digests.swift.gyb",
|
|
||||||
"Key Agreement/ECDH.swift.gyb",
|
|
||||||
"Signatures/ECDSA.swift.gyb",
|
|
||||||
"Signatures/MLDSA.swift.gyb",
|
|
||||||
"Signatures/BoringSSL/MLDSA_boring.swift.gyb",
|
"Signatures/BoringSSL/MLDSA_boring.swift.gyb",
|
||||||
"KEM/MLKEM.swift.gyb",
|
|
||||||
"KEM/BoringSSL/MLKEM_boring.swift.gyb",
|
"KEM/BoringSSL/MLKEM_boring.swift.gyb",
|
||||||
],
|
],
|
||||||
resources: privacyManifestResource,
|
resources: privacyManifestResource,
|
||||||
@@ -182,7 +154,6 @@ let package = Package(
|
|||||||
name: "CryptoExtras",
|
name: "CryptoExtras",
|
||||||
dependencies: [
|
dependencies: [
|
||||||
"CCryptoBoringSSL",
|
"CCryptoBoringSSL",
|
||||||
"CCryptoBoringSSLShims",
|
|
||||||
"CryptoBoringWrapper",
|
"CryptoBoringWrapper",
|
||||||
"Crypto",
|
"Crypto",
|
||||||
.product(name: "SwiftASN1", package: "swift-asn1"),
|
.product(name: "SwiftASN1", package: "swift-asn1"),
|
||||||
@@ -204,12 +175,12 @@ let package = Package(
|
|||||||
name: "CryptoBoringWrapper",
|
name: "CryptoBoringWrapper",
|
||||||
dependencies: [
|
dependencies: [
|
||||||
"CCryptoBoringSSL",
|
"CCryptoBoringSSL",
|
||||||
"CCryptoBoringSSLShims",
|
|
||||||
],
|
],
|
||||||
exclude: privacyManifestExclude + [
|
exclude: privacyManifestExclude + [
|
||||||
"CMakeLists.txt"
|
"CMakeLists.txt"
|
||||||
],
|
],
|
||||||
resources: privacyManifestResource
|
resources: privacyManifestResource,
|
||||||
|
swiftSettings: swiftSettings
|
||||||
),
|
),
|
||||||
.executableTarget(name: "crypto-shasum", dependencies: ["Crypto"]),
|
.executableTarget(name: "crypto-shasum", dependencies: ["Crypto"]),
|
||||||
.testTarget(
|
.testTarget(
|
||||||
|
|||||||
@@ -7,9 +7,9 @@ Swift Crypto is an open-source implementation of a substantial portion of the AP
|
|||||||
Swift Crypto is available as a Swift Package Manager package. To use it, add the following dependency in your `Package.swift`:
|
Swift Crypto is available as a Swift Package Manager package. To use it, add the following dependency in your `Package.swift`:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
// swift-crypto 1.x, 2.x, 3.x, and 4.x are almost API compatible, so most clients
|
// swift-crypto 1.x, 2.x, 3.x, 4.x, and 5.x are almost API compatible, so most clients
|
||||||
// should allow any of them
|
// should allow any of them
|
||||||
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "5.0.0"),
|
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "6.0.0"),
|
||||||
```
|
```
|
||||||
|
|
||||||
and to your target, add `Crypto` to your dependencies. You can then `import Crypto` to get access to Swift Crypto's functionality.
|
and to your target, add `Crypto` to your dependencies. You can then `import Crypto` to get access to Swift Crypto's functionality.
|
||||||
@@ -28,13 +28,14 @@ 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 an Apple platform where CryptoKit is already available, Swift Crypto compiles its entire API surface down to nothing and simply re-exports the API of CryptoKit. This means that when using Apple platforms Swift Crypto simply delegates all work to the core implementation of CryptoKit, as though Swift Crypto was not even there.
|
||||||
|
|
||||||
When building Swift Crypto for use on Linux or Windows, Swift Crypto builds substantially more code. In particular, we build:
|
When building Swift Crypto for use on other platforms, Swift Crypto builds substantially more code. In particular, we build:
|
||||||
|
|
||||||
1. A vendored copy of BoringSSL's libcrypto.
|
1. A vendored copy of BoringSSL's libcrypto.
|
||||||
2. The common API of Swift Crypto and CryptoKit.
|
2. A vendored copy of XKCP's libXKCP.
|
||||||
3. The backing implementation of this common API, which calls into BoringSSL.
|
3. The common API of Swift Crypto and CryptoKit.
|
||||||
|
4. The backing implementation of this common API, which calls into BoringSSL or XKCP.
|
||||||
|
|
||||||
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The backing BoringSSL-based implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIS predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL implementation of the library in your application, no matter the platform.
|
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The BoringSSL/XKCP backing implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIs predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL/XKCP implementation of the library in your application, no matter the platform.
|
||||||
|
|
||||||
## Evolution
|
## Evolution
|
||||||
|
|
||||||
@@ -48,11 +49,11 @@ Note that Swift Crypto does not intend to support all possible cryptographic pri
|
|||||||
|
|
||||||
### Code Organisation
|
### Code Organisation
|
||||||
|
|
||||||
Files in this repository are divided into two groups, based on whether they have a name that ends in `_boring` or are in a `BoringSSL` directory, or if they are not.
|
Files in this repository are divided into two groups, based on whether they have a name that ends in `_boring`/`_xkcp` or are in a `BoringSSL`/`XKCP` directory, or if they are not.
|
||||||
|
|
||||||
Files that meet the above criteria are specific to the Swift Crypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or access a BoringSSL API, it needs to be marked this way.
|
Files that meet the above criteria are specific to the Swift Crypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or `import CXKCP` or access a BoringSSL or XKCP API, it needs to be marked this way.
|
||||||
|
|
||||||
Files that do not have the `_boring` suffix are part of the public API of CryptoKit. Changing these requires passing a higher bar, as any change in these files must be accompanied by a change in CryptoKit itself.
|
Files that do not have the `_boring` or `_xkcp` suffix are part of the public API of CryptoKit. Changing these requires passing a higher bar, as any change in these files must be accompanied by a change in CryptoKit itself.
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
@@ -108,7 +109,7 @@ If you believe you have identified a vulnerability in Swift Crypto, please [repo
|
|||||||
|
|
||||||
### Swift versions
|
### Swift versions
|
||||||
|
|
||||||
The most recent versions of Swift Crypto support Swift 6 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
|
The most recent versions of Swift Crypto support Swift 6.2 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
|
||||||
|
|
||||||
Swift Crypto | Minimum Swift Version
|
Swift Crypto | Minimum Swift Version
|
||||||
--------------------|----------------------
|
--------------------|----------------------
|
||||||
@@ -120,7 +121,9 @@ Swift Crypto | Minimum Swift Version
|
|||||||
`3.3.0 ..< 3.8.0` | 5.8
|
`3.3.0 ..< 3.8.0` | 5.8
|
||||||
`3.9.0 ..< 3.13.0` | 5.9
|
`3.9.0 ..< 3.13.0` | 5.9
|
||||||
`3.13.0 ..< 4.0.0` | 5.10
|
`3.13.0 ..< 4.0.0` | 5.10
|
||||||
`4.0.0 ...` | 6.0
|
`4.0.0 ..< 4.4.0` | 6.0
|
||||||
|
`4.4.0 ..< 5.0.0` | 6.1
|
||||||
|
`5.0.0 ...` | 6.2
|
||||||
|
|
||||||
### Compatibility
|
### Compatibility
|
||||||
|
|
||||||
@@ -136,13 +139,19 @@ Swift Crypto 3.0.0 was released in September 2023. Again the only breaking chang
|
|||||||
|
|
||||||
Swift Crypto 4.0.0 was released in September 2025. Again the only breaking change was the addition of new cases in the `CryptoError` enumeration, so most users can safely depend on the 1.0.0, 2.0.0, 3.0.0, or 4.0.0 series of releases. Note that in this release `_CryptoExtras` was renamed to `CryptoExtras`. The old products and targets have been kept around for compatibility reasons, but users depending only on new code should use `CryptoExtras` not `_CryptoExtras`.
|
Swift Crypto 4.0.0 was released in September 2025. Again the only breaking change was the addition of new cases in the `CryptoError` enumeration, so most users can safely depend on the 1.0.0, 2.0.0, 3.0.0, or 4.0.0 series of releases. Note that in this release `_CryptoExtras` was renamed to `CryptoExtras`. The old products and targets have been kept around for compatibility reasons, but users depending only on new code should use `CryptoExtras` not `_CryptoExtras`.
|
||||||
|
|
||||||
|
Swift Crypto 5.0.0 was released in September 2026. Because this version is only supported on Swift versions that support extensible enums, this release has mechanically marked all non-frozen public enums in CryptoKit as `@nonexhaustive`, which should mitigate the need for any future major releases of Swift Crypto. Most users will be able to depend on the 1.0.0, 2.0.0, 3.0.0, 4.0.0 or 5.0.0 series of releases.
|
||||||
|
|
||||||
To do so, please use the following dependency in your `Package.swift`:
|
To do so, please use the following dependency in your `Package.swift`:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "5.0.0"),
|
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "6.0.0"),
|
||||||
```
|
```
|
||||||
|
|
||||||
### Developing Swift Crypto on macOS
|
### Developing Swift Crypto on macOS
|
||||||
|
|
||||||
Swift Crypto normally defers to the OS implementation of CryptoKit on macOS. Naturally, this makes developing Swift Crypto on macOS tricky. To get Swift Crypto to build the open source implementation on macOS, in `Package.swift`, change `let development = false` to `let development = true`, as this will force Swift Crypto to build its public API.
|
Swift Crypto normally defers to the OS implementation of CryptoKit on macOS. Naturally, this makes developing Swift Crypto on macOS tricky. To get Swift Crypto to build the open source implementation on macOS, in `Package.swift`, use a Linux container. A Dev Container config is provided in the repo to make this easier.
|
||||||
|
|
||||||
|
|
||||||
|
## Acknowledgements
|
||||||
|
|
||||||
|
This project contains source code from the BoringSSL and XKCP projects.
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
##===----------------------------------------------------------------------===##
|
|
||||||
##
|
|
||||||
## This source file is part of the SwiftCrypto open source project
|
|
||||||
##
|
|
||||||
## Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors
|
|
||||||
## Licensed under Apache License v2.0
|
|
||||||
##
|
|
||||||
## See LICENSE.txt for license information
|
|
||||||
## See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
|
||||||
##
|
|
||||||
## SPDX-License-Identifier: Apache-2.0
|
|
||||||
##
|
|
||||||
##===----------------------------------------------------------------------===##
|
|
||||||
|
|
||||||
add_library(CCryptoBoringSSLShims STATIC
|
|
||||||
"shims.c"
|
|
||||||
)
|
|
||||||
|
|
||||||
target_include_directories(CCryptoBoringSSLShims PUBLIC
|
|
||||||
include
|
|
||||||
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>)
|
|
||||||
|
|
||||||
target_link_libraries(CCryptoBoringSSLShims PUBLIC
|
|
||||||
CCryptoBoringSSL)
|
|
||||||
|
|
||||||
set_target_properties(CCryptoBoringSSLShims PROPERTIES
|
|
||||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
|
||||||
|
|
||||||
set_property(GLOBAL APPEND PROPERTY SWIFT_CRYPTO_EXPORTS CCryptoBoringSSLShims)
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
||||||
<plist version="1.0">
|
|
||||||
<dict>
|
|
||||||
<key>NSPrivacyTracking</key>
|
|
||||||
<false/>
|
|
||||||
<key>NSPrivacyAccessedAPITypes</key>
|
|
||||||
<array/>
|
|
||||||
<key>NSPrivacyCollectedDataTypes</key>
|
|
||||||
<array/>
|
|
||||||
<key>NSPrivacyTrackingDomains</key>
|
|
||||||
<array/>
|
|
||||||
</dict>
|
|
||||||
</plist>
|
|
||||||
|
|
||||||
@@ -1,155 +0,0 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
|
||||||
//
|
|
||||||
// This source file is part of the SwiftCrypto open source project
|
|
||||||
//
|
|
||||||
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
|
|
||||||
// Licensed under Apache License v2.0
|
|
||||||
//
|
|
||||||
// See LICENSE.txt for license information
|
|
||||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
|
||||||
//
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
//
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
#ifndef C_CRYPTO_BORINGSSL_SHIMS_H
|
|
||||||
#define C_CRYPTO_BORINGSSL_SHIMS_H
|
|
||||||
|
|
||||||
// This is for instances when `swift package generate-xcodeproj` is used as CCryptoBoringSSL
|
|
||||||
// is treated as a framework and requires the framework's name as a prefix.
|
|
||||||
#if __has_include(<CCryptoBoringSSL/CCryptoBoringSSL.h>)
|
|
||||||
#include <CCryptoBoringSSL/CCryptoBoringSSL.h>
|
|
||||||
#else
|
|
||||||
#include <CCryptoBoringSSL.h>
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if defined(__cplusplus)
|
|
||||||
extern "C" {
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// MARK:- Pointer type shims
|
|
||||||
// This section of the code handles shims that change uint8_t* pointers to
|
|
||||||
// void *s. This is done because Swift does not have the rule that C does, that
|
|
||||||
// pointers to uint8_t can safely alias any other pointer. That means that Swift
|
|
||||||
// Unsafe[Mutable]RawPointer cannot be passed to uint8_t * APIs, which is very
|
|
||||||
// awkward, so we shim these to avoid the need to call bindMemory in Swift (which is
|
|
||||||
// wrong).
|
|
||||||
//
|
|
||||||
// Our relevant citation is: https://github.com/apple/swift-nio-extras/pull/56#discussion_r329330295.
|
|
||||||
// We want this to land: https://bugs.swift.org/browse/SR-11087. Once that lands we can remove these
|
|
||||||
// shims.
|
|
||||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_init(EVP_AEAD_CTX *ctx, const EVP_AEAD *aead,
|
|
||||||
const void *key, size_t key_len, size_t tag_len,
|
|
||||||
ENGINE *impl);
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_seal_scatter(
|
|
||||||
const EVP_AEAD_CTX *ctx,
|
|
||||||
void *out,
|
|
||||||
void *out_tag,
|
|
||||||
size_t *out_tag_len,
|
|
||||||
size_t max_out_tag_len,
|
|
||||||
const void *nonce,
|
|
||||||
size_t nonce_len,
|
|
||||||
const void *in,
|
|
||||||
size_t in_len,
|
|
||||||
const void *extra_in,
|
|
||||||
size_t extra_in_len,
|
|
||||||
const void *ad,
|
|
||||||
size_t ad_len);
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(const EVP_AEAD_CTX *ctx, void *out,
|
|
||||||
const void *nonce, size_t nonce_len,
|
|
||||||
const void *in, size_t in_len,
|
|
||||||
const void *in_tag, size_t in_tag_len,
|
|
||||||
const void *ad, size_t ad_len);
|
|
||||||
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open(const EVP_AEAD_CTX *ctx, void *out, size_t *out_len, size_t max_out_len,
|
|
||||||
const void *nonce, size_t nonce_len,
|
|
||||||
const void *in, size_t in_len,
|
|
||||||
const void *ad, size_t ad_len);
|
|
||||||
|
|
||||||
|
|
||||||
void CCryptoBoringSSLShims_ED25519_keypair(void *out_public_key, void *out_private_key);
|
|
||||||
|
|
||||||
void CCryptoBoringSSLShims_ED25519_keypair_from_seed(void *out_public_key,
|
|
||||||
void *out_private_key,
|
|
||||||
const void *seed);
|
|
||||||
|
|
||||||
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_do_sign(const void *digest, size_t digest_len,
|
|
||||||
const EC_KEY *eckey);
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_ECDSA_do_verify(const void *digest, size_t digest_len,
|
|
||||||
const ECDSA_SIG *sig, const EC_KEY *eckey);
|
|
||||||
|
|
||||||
void CCryptoBoringSSLShims_X25519_keypair(void *out_public_value, void *out_private_key);
|
|
||||||
|
|
||||||
void CCryptoBoringSSLShims_X25519_public_from_private(void *out_public_value,
|
|
||||||
const void *private_key);
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_X25519(void *out_shared_key, const void *private_key,
|
|
||||||
const void *peer_public_value);
|
|
||||||
|
|
||||||
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(const void *in, size_t in_len);
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_ED25519_verify(const void *message, size_t message_len,
|
|
||||||
const void *signature, const void *public_key);
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_ED25519_sign(void *out_sig, const void *message,
|
|
||||||
size_t message_len, const void *private_key);
|
|
||||||
|
|
||||||
BIGNUM *CCryptoBoringSSLShims_BN_bin2bn(const void *in, size_t len, BIGNUM *ret);
|
|
||||||
|
|
||||||
size_t CCryptoBoringSSLShims_BN_bn2bin(const BIGNUM *in, void *out);
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_BN_mod(BIGNUM *rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_RSA_verify(int hash_nid, const void *msg, size_t msg_len,
|
|
||||||
const void *sig, size_t sig_len, RSA *rsa);
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_RSA_verify_pss_mgf1(RSA *rsa, const void *msg,
|
|
||||||
size_t msg_len, const EVP_MD *md,
|
|
||||||
const EVP_MD *mgf1_md, int salt_len,
|
|
||||||
const void *sig, size_t sig_len);
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_RSA_sign(int hash_nid, const void *in,
|
|
||||||
unsigned int in_len, void *out,
|
|
||||||
unsigned int *out_len, RSA *rsa);
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_RSA_sign_pss_mgf1(RSA *rsa, size_t *out_len, void *out,
|
|
||||||
size_t max_out, const void *in,
|
|
||||||
size_t in_len, const EVP_MD *md,
|
|
||||||
const EVP_MD *mgf1_md, int salt_len);
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_RSA_public_encrypt(int flen, const void *from, void *to,
|
|
||||||
RSA *rsa, int padding);
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_RSA_private_decrypt(int flen, const void *from, void *to,
|
|
||||||
RSA *rsa, int padding);
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, void *out,
|
|
||||||
size_t *out_len, const void *in,
|
|
||||||
size_t in_len);
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, void *out,
|
|
||||||
size_t *out_len, const void *in,
|
|
||||||
size_t in_len);
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_EC_hash_to_curve_p256_xmd_sha256_sswu(const EC_GROUP *group, EC_POINT *out,
|
|
||||||
const void *dst, size_t dst_len,
|
|
||||||
const void *msg, size_t msg_len);
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_EC_hash_to_curve_p384_xmd_sha384_sswu(const EC_GROUP *group, EC_POINT *out,
|
|
||||||
const void *dst, size_t dst_len,
|
|
||||||
const void *msg, size_t msg_len);
|
|
||||||
|
|
||||||
size_t CCryptoBoringSSLShims_EC_POINT_point2oct(const EC_GROUP *group,
|
|
||||||
const EC_POINT *point,
|
|
||||||
point_conversion_form_t form,
|
|
||||||
void *buf, size_t max_out,
|
|
||||||
BN_CTX *ctx);
|
|
||||||
|
|
||||||
#if defined(__cplusplus)
|
|
||||||
}
|
|
||||||
#endif // defined(__cplusplus)
|
|
||||||
|
|
||||||
#endif // C_CRYPTO_BORINGSSL_SHIMS_H
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
module CCryptoBoringSSLShims {
|
|
||||||
header "CCryptoBoringSSLShims.h"
|
|
||||||
export *
|
|
||||||
}
|
|
||||||
@@ -1,190 +0,0 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
|
||||||
//
|
|
||||||
// This source file is part of the SwiftCrypto open source project
|
|
||||||
//
|
|
||||||
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
|
|
||||||
// Licensed under Apache License v2.0
|
|
||||||
//
|
|
||||||
// See LICENSE.txt for license information
|
|
||||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
|
||||||
//
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
//
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
#include <CCryptoBoringSSLShims.h>
|
|
||||||
|
|
||||||
// MARK:- Pointer type shims
|
|
||||||
// This section of the code handles shims that change uint8_t* pointers to
|
|
||||||
// void *s. This is done because Swift does not have the rule that C does, that
|
|
||||||
// pointers to uint8_t can safely alias any other pointer. That means that Swift
|
|
||||||
// Unsafe[Mutable]RawPointer cannot be passed to uint8_t * APIs, which is very
|
|
||||||
// awkward, so we shim these to avoid the need to call bindMemory in Swift (which is
|
|
||||||
// wrong).
|
|
||||||
//
|
|
||||||
// Our relevant citation is: https://github.com/apple/swift-nio-extras/pull/56#discussion_r329330295.
|
|
||||||
// We want this to land: https://bugs.swift.org/browse/SR-11087. Once that lands we can remove these
|
|
||||||
// shims.
|
|
||||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_init(EVP_AEAD_CTX *ctx, const EVP_AEAD *aead,
|
|
||||||
const void *key, size_t key_len, size_t tag_len,
|
|
||||||
ENGINE *impl) {
|
|
||||||
return CCryptoBoringSSL_EVP_AEAD_CTX_init(ctx, aead, key, key_len, tag_len, impl);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_seal_scatter(
|
|
||||||
const EVP_AEAD_CTX *ctx,
|
|
||||||
void *out,
|
|
||||||
void *out_tag,
|
|
||||||
size_t *out_tag_len,
|
|
||||||
size_t max_out_tag_len,
|
|
||||||
const void *nonce,
|
|
||||||
size_t nonce_len,
|
|
||||||
const void *in,
|
|
||||||
size_t in_len,
|
|
||||||
const void *extra_in,
|
|
||||||
size_t extra_in_len,
|
|
||||||
const void *ad,
|
|
||||||
size_t ad_len) {
|
|
||||||
return CCryptoBoringSSL_EVP_AEAD_CTX_seal_scatter(ctx, out, out_tag, out_tag_len, max_out_tag_len, nonce, nonce_len, in, in_len, extra_in, extra_in_len, ad, ad_len);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(const EVP_AEAD_CTX *ctx, void *out,
|
|
||||||
const void *nonce, size_t nonce_len,
|
|
||||||
const void *in, size_t in_len,
|
|
||||||
const void *in_tag, size_t in_tag_len,
|
|
||||||
const void *ad, size_t ad_len) {
|
|
||||||
return CCryptoBoringSSL_EVP_AEAD_CTX_open_gather(ctx, out, nonce, nonce_len, in, in_len, in_tag, in_tag_len, ad, ad_len);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open(const EVP_AEAD_CTX *ctx, void *out, size_t *out_len, size_t max_out_len,
|
|
||||||
const void *nonce, size_t nonce_len,
|
|
||||||
const void *in, size_t in_len,
|
|
||||||
const void *ad, size_t ad_len) {
|
|
||||||
return CCryptoBoringSSL_EVP_AEAD_CTX_open(ctx, out, out_len, max_out_len, nonce, nonce_len, in, in_len, ad, ad_len);
|
|
||||||
}
|
|
||||||
|
|
||||||
void CCryptoBoringSSLShims_ED25519_keypair(void *out_public_key, void *out_private_key) {
|
|
||||||
CCryptoBoringSSL_ED25519_keypair(out_public_key, out_private_key);
|
|
||||||
}
|
|
||||||
|
|
||||||
void CCryptoBoringSSLShims_ED25519_keypair_from_seed(void *out_public_key,
|
|
||||||
void *out_private_key,
|
|
||||||
const void *seed) {
|
|
||||||
CCryptoBoringSSL_ED25519_keypair_from_seed(out_public_key, out_private_key, seed);
|
|
||||||
}
|
|
||||||
|
|
||||||
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_do_sign(const void *digest, size_t digest_len,
|
|
||||||
const EC_KEY *eckey) {
|
|
||||||
return CCryptoBoringSSL_ECDSA_do_sign(digest, digest_len, eckey);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_ECDSA_do_verify(const void *digest, size_t digest_len,
|
|
||||||
const ECDSA_SIG *sig, const EC_KEY *eckey) {
|
|
||||||
return CCryptoBoringSSL_ECDSA_do_verify(digest, digest_len, sig, eckey);
|
|
||||||
}
|
|
||||||
|
|
||||||
void CCryptoBoringSSLShims_X25519_keypair(void *out_public_value, void *out_private_key) {
|
|
||||||
CCryptoBoringSSL_X25519_keypair(out_public_value, out_private_key);
|
|
||||||
}
|
|
||||||
|
|
||||||
void CCryptoBoringSSLShims_X25519_public_from_private(void *out_public_value,
|
|
||||||
const void *private_key) {
|
|
||||||
CCryptoBoringSSL_X25519_public_from_private(out_public_value, private_key);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_X25519(void *out_shared_key, const void *private_key,
|
|
||||||
const void *peer_public_value) {
|
|
||||||
return CCryptoBoringSSL_X25519(out_shared_key, private_key, peer_public_value);
|
|
||||||
}
|
|
||||||
|
|
||||||
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(const void *in, size_t in_len) {
|
|
||||||
return CCryptoBoringSSL_ECDSA_SIG_from_bytes(in, in_len);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_ED25519_verify(const void *message, size_t message_len,
|
|
||||||
const void *signature, const void *public_key) {
|
|
||||||
return CCryptoBoringSSL_ED25519_verify(message, message_len, signature, public_key);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_ED25519_sign(void *out_sig, const void *message,
|
|
||||||
size_t message_len, const void *private_key) {
|
|
||||||
return CCryptoBoringSSL_ED25519_sign(out_sig, message, message_len, private_key);
|
|
||||||
}
|
|
||||||
|
|
||||||
BIGNUM *CCryptoBoringSSLShims_BN_bin2bn(const void *in, size_t len, BIGNUM *ret) {
|
|
||||||
return CCryptoBoringSSL_BN_bin2bn(in, len, ret);
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t CCryptoBoringSSLShims_BN_bn2bin(const BIGNUM *in, void *out) {
|
|
||||||
return CCryptoBoringSSL_BN_bn2bin(in, out);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_BN_mod(BIGNUM *rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) {
|
|
||||||
return BN_mod(rem, a, m, ctx);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_RSA_verify(int hash_nid, const void *msg, size_t msg_len,
|
|
||||||
const void *sig, size_t sig_len, RSA *rsa) {
|
|
||||||
return CCryptoBoringSSL_RSA_verify(hash_nid, msg, msg_len, sig, sig_len, rsa);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_RSA_verify_pss_mgf1(RSA *rsa, const void *msg,
|
|
||||||
size_t msg_len, const EVP_MD *md,
|
|
||||||
const EVP_MD *mgf1_md, int salt_len,
|
|
||||||
const void *sig, size_t sig_len) {
|
|
||||||
return CCryptoBoringSSL_RSA_verify_pss_mgf1(rsa, msg, msg_len, md, mgf1_md, salt_len, sig, sig_len);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_RSA_sign(int hash_nid, const void *in,
|
|
||||||
unsigned int in_len, void *out,
|
|
||||||
unsigned int *out_len, RSA *rsa) {
|
|
||||||
return CCryptoBoringSSL_RSA_sign(hash_nid, in, in_len, out, out_len, rsa);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_RSA_sign_pss_mgf1(RSA *rsa, size_t *out_len, void *out,
|
|
||||||
size_t max_out, const void *in,
|
|
||||||
size_t in_len, const EVP_MD *md,
|
|
||||||
const EVP_MD *mgf1_md, int salt_len) {
|
|
||||||
return CCryptoBoringSSL_RSA_sign_pss_mgf1(rsa, out_len, out, max_out, in, in_len, md, mgf1_md, salt_len);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_RSA_public_encrypt(int flen, const void *from, void *to,
|
|
||||||
RSA *rsa, int padding) {
|
|
||||||
return CCryptoBoringSSL_RSA_public_encrypt(flen, from, to, rsa, padding);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_RSA_private_decrypt(int flen, const void *from, void *to,
|
|
||||||
RSA *rsa, int padding) {
|
|
||||||
return CCryptoBoringSSL_RSA_private_decrypt(flen, from, to, rsa, padding);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, void *out,
|
|
||||||
size_t *out_len, const void *in,
|
|
||||||
size_t in_len) {
|
|
||||||
return CCryptoBoringSSL_EVP_PKEY_encrypt(ctx, out, out_len, in, in_len);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, void *out,
|
|
||||||
size_t *out_len, const void *in,
|
|
||||||
size_t in_len) {
|
|
||||||
return CCryptoBoringSSL_EVP_PKEY_decrypt(ctx, out, out_len, in, in_len);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_EC_hash_to_curve_p256_xmd_sha256_sswu(const EC_GROUP *group, EC_POINT *out,
|
|
||||||
const void *dst, size_t dst_len,
|
|
||||||
const void *msg, size_t msg_len) {
|
|
||||||
return CCryptoBoringSSL_EC_hash_to_curve_p256_xmd_sha256_sswu(group, out, dst, dst_len, msg, msg_len);
|
|
||||||
}
|
|
||||||
|
|
||||||
int CCryptoBoringSSLShims_EC_hash_to_curve_p384_xmd_sha384_sswu(const EC_GROUP *group, EC_POINT *out,
|
|
||||||
const void *dst, size_t dst_len,
|
|
||||||
const void *msg, size_t msg_len) {
|
|
||||||
return CCryptoBoringSSL_EC_hash_to_curve_p384_xmd_sha384_sswu(group, out, dst, dst_len, msg, msg_len);
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t CCryptoBoringSSLShims_EC_POINT_point2oct(const EC_GROUP *group,
|
|
||||||
const EC_POINT *point,
|
|
||||||
point_conversion_form_t form,
|
|
||||||
void *buf, size_t max_out,
|
|
||||||
BN_CTX *ctx) {
|
|
||||||
return CCryptoBoringSSL_EC_POINT_point2oct(group, point, form, buf, max_out, ctx);
|
|
||||||
}
|
|
||||||
@@ -13,7 +13,6 @@
|
|||||||
##===----------------------------------------------------------------------===##
|
##===----------------------------------------------------------------------===##
|
||||||
|
|
||||||
add_subdirectory(CCryptoBoringSSL)
|
add_subdirectory(CCryptoBoringSSL)
|
||||||
add_subdirectory(CCryptoBoringSSLShims)
|
|
||||||
add_subdirectory(CXKCP)
|
add_subdirectory(CXKCP)
|
||||||
add_subdirectory(CXKCPShims)
|
add_subdirectory(CXKCPShims)
|
||||||
add_subdirectory(CryptoBoringWrapper)
|
add_subdirectory(CryptoBoringWrapper)
|
||||||
|
|||||||
@@ -11,36 +11,29 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias AESGCMImpl = CoreCryptoGCMImpl
|
|
||||||
#else
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias AESGCMImpl = OpenSSLAESGCMImpl
|
typealias AESGCMImpl = OpenSSLAESGCMImpl
|
||||||
#endif
|
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension AES {
|
extension AES {
|
||||||
/// The Advanced Encryption Standard (AES) Galois Counter Mode (GCM) cipher
|
/// The Advanced Encryption Standard (AES) Galois Counter Mode (GCM) cipher
|
||||||
/// suite.
|
/// suite.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum GCM: Cipher, Sendable {
|
public enum GCM: Cipher, Sendable {
|
||||||
static let tagByteCount = 16
|
static let tagByteCount = 16
|
||||||
static let defaultNonceByteCount = 12
|
static let defaultNonceByteCount = 12
|
||||||
|
|
||||||
|
/// Fixed-length array of tagByteCount bytes.
|
||||||
|
typealias TagStorage = [16 of UInt8]
|
||||||
|
|
||||||
/// Secures the given plaintext message with encryption and an
|
/// Secures the given plaintext message with encryption and an
|
||||||
/// authentication tag that covers both the encrypted data and
|
/// authentication tag that covers both the encrypted data and
|
||||||
/// additional data.
|
/// additional data.
|
||||||
@@ -71,6 +64,30 @@ extension AES {
|
|||||||
return try AESGCMImpl.seal(key: key, message: message, nonce: nonce, authenticatedData: Data?.none)
|
return try AESGCMImpl.seal(key: key, message: message, nonce: nonce, authenticatedData: Data?.none)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Secures the given plaintext message with encryption and an optional authentication tag.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - message: The plaintext data to seal, which will be updated in place.
|
||||||
|
/// - key: A cryptographic key used to seal the message.
|
||||||
|
/// - nonce: The nonce the sealing process requires.
|
||||||
|
/// - authenticatedData: Additional data to be authenticated, if provided.
|
||||||
|
/// - tag: receives the 16-byte authentication tag
|
||||||
|
#if compiler(<6.3)
|
||||||
|
@_lifetime(message: copy message)
|
||||||
|
#endif
|
||||||
|
public static func seal(
|
||||||
|
inPlace message: inout MutableRawSpan,
|
||||||
|
using key: SymmetricKey,
|
||||||
|
nonce: Nonce,
|
||||||
|
authenticating authenticatedData: RawSpan? = nil,
|
||||||
|
tag: inout OutputRawSpan
|
||||||
|
) throws(CryptoKitMetaError) {
|
||||||
|
return try AESGCMImpl.seal(
|
||||||
|
key: key, message: &message, nonce: nonce.bytes,
|
||||||
|
authenticatedData: authenticatedData, tag: &tag
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/// Decrypts the message and verifies the authenticity of both the
|
/// Decrypts the message and verifies the authenticity of both the
|
||||||
/// encrypted message and additional data.
|
/// encrypted message and additional data.
|
||||||
///
|
///
|
||||||
@@ -99,10 +116,39 @@ extension AES {
|
|||||||
public static func open(_ sealedBox: SealedBox, using key: SymmetricKey) throws(CryptoKitMetaError) -> Data {
|
public static func open(_ sealedBox: SealedBox, using key: SymmetricKey) throws(CryptoKitMetaError) -> Data {
|
||||||
return try AESGCMImpl.open(key: key, sealedBox: sealedBox, authenticatedData: Data?.none)
|
return try AESGCMImpl.open(key: key, sealedBox: sealedBox, authenticatedData: Data?.none)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Decrypts the message and verifies its authenticity.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - message: The message, which will be decrypted in place.
|
||||||
|
/// - key: The cryptographic key that was used to seal the message.
|
||||||
|
/// - nonce: The nonce used to encrypt the message.
|
||||||
|
/// - tag : The 16-byte authentication tag.
|
||||||
|
/// - authenticatedData: Additional data that was authenticated.
|
||||||
|
///
|
||||||
|
/// The call throws an error if decryption or authentication fail.
|
||||||
|
#if compiler(<6.3)
|
||||||
|
@_lifetime(message: copy message)
|
||||||
|
#endif
|
||||||
|
public static func open(
|
||||||
|
inPlace message: inout MutableRawSpan,
|
||||||
|
using key: SymmetricKey,
|
||||||
|
nonce: Nonce,
|
||||||
|
authenticating authenticatedData: RawSpan? = nil,
|
||||||
|
tag: RawSpan
|
||||||
|
) throws(CryptoKitMetaError) {
|
||||||
|
try AESGCMImpl
|
||||||
|
.open(
|
||||||
|
key: key,
|
||||||
|
message: &message,
|
||||||
|
nonce: nonce.bytes,
|
||||||
|
authenticatedData: authenticatedData,
|
||||||
|
tag: tag
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension AES.GCM {
|
extension AES.GCM {
|
||||||
/// A secure container for your data that you can access using a cipher.
|
/// A secure container for your data that you can access using a cipher.
|
||||||
///
|
///
|
||||||
@@ -118,7 +164,6 @@ extension AES.GCM {
|
|||||||
///
|
///
|
||||||
/// The receiver uses another instance of the same cipher, like the
|
/// The receiver uses another instance of the same cipher, like the
|
||||||
/// ``open(_:using:)`` method, to open the box.
|
/// ``open(_:using:)`` method, to open the box.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SealedBox: AEADSealedBox, Sendable {
|
public struct SealedBox: AEADSealedBox, Sendable {
|
||||||
private let combinedRepresentation: Data
|
private let combinedRepresentation: Data
|
||||||
private let nonceByteCount: Int
|
private let nonceByteCount: Int
|
||||||
@@ -201,10 +246,10 @@ extension AES.GCM {
|
|||||||
throw error(CryptoKitError.incorrectParameterSize)
|
throw error(CryptoKitError.incorrectParameterSize)
|
||||||
}
|
}
|
||||||
|
|
||||||
let nonceByteCount = nonce.bytes.count
|
let nonceByteCount = nonce.storage.count
|
||||||
var combinedRepresentation = Data()
|
var combinedRepresentation = Data()
|
||||||
combinedRepresentation.reserveCapacity(nonceByteCount + ciphertext.count + tag.count)
|
combinedRepresentation.reserveCapacity(nonceByteCount + ciphertext.count + tag.count)
|
||||||
combinedRepresentation.append(contentsOf: nonce.bytes)
|
combinedRepresentation.append(contentsOf: nonce.storage)
|
||||||
combinedRepresentation.append(contentsOf: ciphertext)
|
combinedRepresentation.append(contentsOf: ciphertext)
|
||||||
combinedRepresentation.append(contentsOf: tag)
|
combinedRepresentation.append(contentsOf: tag)
|
||||||
|
|
||||||
@@ -213,4 +258,4 @@ extension AES.GCM {
|
|||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,10 +11,14 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
#if hasFeature(SourceWarningControl)
|
||||||
|
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||||
|
#else
|
||||||
@_implementationOnly import CCryptoBoringSSL
|
@_implementationOnly import CCryptoBoringSSL
|
||||||
|
#endif
|
||||||
import CryptoBoringWrapper
|
import CryptoBoringWrapper
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
@@ -35,17 +39,16 @@ enum OpenSSLAESGCMImpl {
|
|||||||
|
|
||||||
let aead = try Self._backingAEAD(key: key)
|
let aead = try Self._backingAEAD(key: key)
|
||||||
|
|
||||||
let ciphertext: Data
|
let combined: Data
|
||||||
let tag: Data
|
|
||||||
if let ad = authenticatedData {
|
if let ad = authenticatedData {
|
||||||
(ciphertext, tag) = try aead.seal(
|
combined = try aead.seal(
|
||||||
message: message,
|
message: message,
|
||||||
key: key,
|
key: key,
|
||||||
nonce: nonce,
|
nonce: nonce,
|
||||||
authenticatedData: ad
|
authenticatedData: ad
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
(ciphertext, tag) = try aead.seal(
|
combined = try aead.seal(
|
||||||
message: message,
|
message: message,
|
||||||
key: key,
|
key: key,
|
||||||
nonce: nonce,
|
nonce: nonce,
|
||||||
@@ -53,7 +56,39 @@ enum OpenSSLAESGCMImpl {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return try AES.GCM.SealedBox(nonce: nonce, ciphertext: ciphertext, tag: tag)
|
return AES.GCM.SealedBox(combined: combined, nonceByteCount: nonce.count)
|
||||||
|
}
|
||||||
|
|
||||||
|
#if compiler(<6.3)
|
||||||
|
@_lifetime(message: copy message)
|
||||||
|
#endif
|
||||||
|
@inlinable
|
||||||
|
static func seal(
|
||||||
|
key: SymmetricKey,
|
||||||
|
message: inout MutableRawSpan,
|
||||||
|
nonce: RawSpan,
|
||||||
|
authenticatedData: RawSpan?,
|
||||||
|
tag: inout OutputRawSpan
|
||||||
|
) throws {
|
||||||
|
let aead = try Self._backingAEAD(key: key)
|
||||||
|
|
||||||
|
if let ad = authenticatedData {
|
||||||
|
try aead.seal(
|
||||||
|
message: &message,
|
||||||
|
key: key,
|
||||||
|
nonce: nonce,
|
||||||
|
authenticatedData: ad,
|
||||||
|
tag: &tag
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
try aead.seal(
|
||||||
|
message: &message,
|
||||||
|
key: key,
|
||||||
|
nonce: nonce,
|
||||||
|
authenticatedData: RawSpan(),
|
||||||
|
tag: &tag
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@inlinable
|
@inlinable
|
||||||
@@ -83,6 +118,38 @@ enum OpenSSLAESGCMImpl {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Open a given message in place.
|
||||||
|
#if compiler(<6.3)
|
||||||
|
@_lifetime(message: copy message)
|
||||||
|
#endif
|
||||||
|
@inlinable
|
||||||
|
static func open(
|
||||||
|
key: SymmetricKey,
|
||||||
|
message: inout MutableRawSpan,
|
||||||
|
nonce: RawSpan,
|
||||||
|
authenticatedData: RawSpan?,
|
||||||
|
tag: RawSpan
|
||||||
|
) throws {
|
||||||
|
let aead = try Self._backingAEAD(key: key)
|
||||||
|
if let authenticatedData {
|
||||||
|
return try aead.open(
|
||||||
|
message: &message,
|
||||||
|
key: key,
|
||||||
|
nonce: nonce,
|
||||||
|
tag: tag,
|
||||||
|
authenticatedData: authenticatedData
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
return try aead.open(
|
||||||
|
message: &message,
|
||||||
|
key: key,
|
||||||
|
nonce: nonce,
|
||||||
|
tag: tag,
|
||||||
|
authenticatedData: RawSpan()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
static func _backingAEAD(key: SymmetricKey) throws -> BoringSSLAEAD {
|
static func _backingAEAD(key: SymmetricKey) throws -> BoringSSLAEAD {
|
||||||
switch key.bitCount {
|
switch key.bitCount {
|
||||||
@@ -97,4 +164,4 @@ enum OpenSSLAESGCMImpl {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,11 +11,14 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
#if hasFeature(SourceWarningControl)
|
||||||
|
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||||
|
#else
|
||||||
@_implementationOnly import CCryptoBoringSSL
|
@_implementationOnly import CCryptoBoringSSL
|
||||||
@_implementationOnly import CCryptoBoringSSLShims
|
#endif
|
||||||
import CryptoBoringWrapper
|
import CryptoBoringWrapper
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
@@ -31,7 +34,7 @@ extension BoringSSLAEAD {
|
|||||||
key: SymmetricKey,
|
key: SymmetricKey,
|
||||||
nonce: Nonce,
|
nonce: Nonce,
|
||||||
authenticatedData: AuthenticatedData
|
authenticatedData: AuthenticatedData
|
||||||
) throws -> (ciphertext: Data, tag: Data) {
|
) throws -> Data {
|
||||||
do {
|
do {
|
||||||
let context = try AEADContext(cipher: self, key: key)
|
let context = try AEADContext(cipher: self, key: key)
|
||||||
return try context.seal(
|
return try context.seal(
|
||||||
@@ -44,6 +47,30 @@ extension BoringSSLAEAD {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Seal a given message in place
|
||||||
|
#if compiler(<6.3)
|
||||||
|
@_lifetime(message: copy message)
|
||||||
|
#endif
|
||||||
|
func seal(
|
||||||
|
message: inout MutableRawSpan,
|
||||||
|
key: SymmetricKey,
|
||||||
|
nonce: RawSpan,
|
||||||
|
authenticatedData: RawSpan,
|
||||||
|
tag: inout OutputRawSpan
|
||||||
|
) throws {
|
||||||
|
do {
|
||||||
|
let context = try AEADContext(cipher: self, key: key)
|
||||||
|
return try context.seal(
|
||||||
|
message: &message,
|
||||||
|
nonce: nonce,
|
||||||
|
authenticatedData: authenticatedData,
|
||||||
|
tag: &tag,
|
||||||
|
)
|
||||||
|
} catch CryptoBoringWrapperError.underlyingCoreCryptoError(let errorCode) {
|
||||||
|
throw CryptoKitError.underlyingCoreCryptoError(error: errorCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Open a given message.
|
/// Open a given message.
|
||||||
func open<Nonce: ContiguousBytes, AuthenticatedData: DataProtocol>(
|
func open<Nonce: ContiguousBytes, AuthenticatedData: DataProtocol>(
|
||||||
ciphertext: Data,
|
ciphertext: Data,
|
||||||
@@ -64,6 +91,30 @@ extension BoringSSLAEAD {
|
|||||||
throw CryptoKitError.underlyingCoreCryptoError(error: errorCode)
|
throw CryptoKitError.underlyingCoreCryptoError(error: errorCode)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Open a given message in place.
|
||||||
|
#if compiler(<6.3)
|
||||||
|
@_lifetime(message: copy message)
|
||||||
|
#endif
|
||||||
|
public func open(
|
||||||
|
message: inout MutableRawSpan,
|
||||||
|
key: SymmetricKey,
|
||||||
|
nonce: RawSpan,
|
||||||
|
tag: RawSpan,
|
||||||
|
authenticatedData: RawSpan
|
||||||
|
) throws {
|
||||||
|
do {
|
||||||
|
let context = try AEADContext(cipher: self, key: key)
|
||||||
|
return try context.open(
|
||||||
|
message: &message,
|
||||||
|
nonce: nonce,
|
||||||
|
tag: tag,
|
||||||
|
authenticatedData: authenticatedData
|
||||||
|
)
|
||||||
|
} catch CryptoBoringWrapperError.underlyingCoreCryptoError(let errorCode) {
|
||||||
|
throw CryptoKitError.underlyingCoreCryptoError(error: errorCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||||
@@ -79,17 +130,16 @@ enum OpenSSLChaChaPolyImpl {
|
|||||||
}
|
}
|
||||||
let nonce = nonce ?? ChaChaPoly.Nonce()
|
let nonce = nonce ?? ChaChaPoly.Nonce()
|
||||||
|
|
||||||
let ciphertext: Data
|
let combined: Data
|
||||||
let tag: Data
|
|
||||||
if let ad = authenticatedData {
|
if let ad = authenticatedData {
|
||||||
(ciphertext, tag) = try BoringSSLAEAD.chacha20.seal(
|
combined = try BoringSSLAEAD.chacha20.seal(
|
||||||
message: message,
|
message: message,
|
||||||
key: key,
|
key: key,
|
||||||
nonce: nonce,
|
nonce: nonce,
|
||||||
authenticatedData: ad
|
authenticatedData: ad
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
(ciphertext, tag) = try BoringSSLAEAD.chacha20.seal(
|
combined = try BoringSSLAEAD.chacha20.seal(
|
||||||
message: message,
|
message: message,
|
||||||
key: key,
|
key: key,
|
||||||
nonce: nonce,
|
nonce: nonce,
|
||||||
@@ -97,7 +147,40 @@ enum OpenSSLChaChaPolyImpl {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return try ChaChaPoly.SealedBox(nonce: nonce, ciphertext: ciphertext, tag: tag)
|
return ChaChaPoly.SealedBox(combined: combined, nonceByteCount: nonce.count)
|
||||||
|
}
|
||||||
|
|
||||||
|
#if compiler(<6.3)
|
||||||
|
@_lifetime(message: copy message)
|
||||||
|
#endif
|
||||||
|
static func encrypt(
|
||||||
|
key: SymmetricKey,
|
||||||
|
inPlace message: inout MutableRawSpan,
|
||||||
|
nonce: RawSpan,
|
||||||
|
authenticatedData: RawSpan?,
|
||||||
|
tag: inout OutputRawSpan
|
||||||
|
) throws {
|
||||||
|
guard key.bitCount == ChaChaPoly.keyBitsCount else {
|
||||||
|
throw CryptoKitError.incorrectKeySize
|
||||||
|
}
|
||||||
|
|
||||||
|
if let ad = authenticatedData {
|
||||||
|
try BoringSSLAEAD.chacha20.seal(
|
||||||
|
message: &message,
|
||||||
|
key: key,
|
||||||
|
nonce: nonce,
|
||||||
|
authenticatedData: ad,
|
||||||
|
tag: &tag
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
try BoringSSLAEAD.chacha20.seal(
|
||||||
|
message: &message,
|
||||||
|
key: key,
|
||||||
|
nonce: nonce,
|
||||||
|
authenticatedData: RawSpan(),
|
||||||
|
tag: &tag
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static func decrypt<AD: DataProtocol>(
|
static func decrypt<AD: DataProtocol>(
|
||||||
@@ -127,5 +210,39 @@ enum OpenSSLChaChaPolyImpl {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#if compiler(<6.3)
|
||||||
|
@_lifetime(message: copy message)
|
||||||
|
#endif
|
||||||
|
static func decrypt(
|
||||||
|
key: SymmetricKey,
|
||||||
|
inPlace message: inout MutableRawSpan,
|
||||||
|
nonce: RawSpan,
|
||||||
|
tag: RawSpan,
|
||||||
|
authenticatedData: RawSpan?
|
||||||
|
) throws {
|
||||||
|
guard key.bitCount == ChaChaPoly.keyBitsCount else {
|
||||||
|
throw CryptoKitError.incorrectKeySize
|
||||||
|
}
|
||||||
|
|
||||||
|
if let authenticatedData {
|
||||||
|
try BoringSSLAEAD.chacha20.open(
|
||||||
|
message: &message,
|
||||||
|
key: key,
|
||||||
|
nonce: nonce,
|
||||||
|
tag: tag,
|
||||||
|
authenticatedData: authenticatedData
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
try BoringSSLAEAD.chacha20.open(
|
||||||
|
message: &message,
|
||||||
|
key: key,
|
||||||
|
nonce: nonce,
|
||||||
|
tag: tag,
|
||||||
|
authenticatedData: RawSpan()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,30 +11,21 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias ChaChaPolyImpl = CoreCryptoChaChaPolyImpl
|
|
||||||
#else
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias ChaChaPolyImpl = OpenSSLChaChaPolyImpl
|
typealias ChaChaPolyImpl = OpenSSLChaChaPolyImpl
|
||||||
#endif
|
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
|
|
||||||
/// An implementation of the ChaCha20-Poly1305 cipher.
|
/// An implementation of the ChaCha20-Poly1305 cipher.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum ChaChaPoly: Cipher, Sendable {
|
public enum ChaChaPoly: Cipher, Sendable {
|
||||||
static let tagByteCount = 16
|
static let tagByteCount = 16
|
||||||
static let keyBitsCount = 256
|
static let keyBitsCount = 256
|
||||||
@@ -70,6 +61,28 @@ public enum ChaChaPoly: Cipher, Sendable {
|
|||||||
return try ChaChaPolyImpl.encrypt(key: key, message: message, nonce: nonce, authenticatedData: Data?.none)
|
return try ChaChaPolyImpl.encrypt(key: key, message: message, nonce: nonce, authenticatedData: Data?.none)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Secures the given plaintext message in place with encryption and an
|
||||||
|
/// authentication tag.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - message: The plaintext data to seal.
|
||||||
|
/// - key: A cryptographic key used to seal the message.
|
||||||
|
/// - nonce: The nonce the sealing process requires.
|
||||||
|
/// - authenticatedData: Additional data to be authenticated.
|
||||||
|
/// - tag: Will be updated with the 16-byte authentication tag.
|
||||||
|
#if compiler(<6.3)
|
||||||
|
@_lifetime(message: copy message)
|
||||||
|
#endif
|
||||||
|
public static func seal(
|
||||||
|
inPlace message: inout MutableRawSpan,
|
||||||
|
using key: SymmetricKey,
|
||||||
|
nonce: Nonce,
|
||||||
|
authenticating authenticatedData: RawSpan? = nil,
|
||||||
|
tag: inout OutputRawSpan
|
||||||
|
) throws(CryptoKitMetaError) {
|
||||||
|
try ChaChaPolyImpl.encrypt(key: key, inPlace: &message, nonce: nonce.bytes, authenticatedData: authenticatedData, tag: &tag)
|
||||||
|
}
|
||||||
|
|
||||||
/// Decrypts the message and verifies the authenticity of both the encrypted
|
/// Decrypts the message and verifies the authenticity of both the encrypted
|
||||||
/// message and additional data.
|
/// message and additional data.
|
||||||
///
|
///
|
||||||
@@ -99,9 +112,32 @@ public enum ChaChaPoly: Cipher, Sendable {
|
|||||||
(_ sealedBox: SealedBox, using key: SymmetricKey) throws -> Data {
|
(_ sealedBox: SealedBox, using key: SymmetricKey) throws -> Data {
|
||||||
return try ChaChaPolyImpl.decrypt(key: key, ciphertext: sealedBox, authenticatedData: Data?.none)
|
return try ChaChaPolyImpl.decrypt(key: key, ciphertext: sealedBox, authenticatedData: Data?.none)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Decrypts the message and verifies the authenticity of both the encrypted
|
||||||
|
/// message and additional data.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - message: The message, which will be decrypted in place.
|
||||||
|
/// - key: The cryptographic key that was used to seal the message.
|
||||||
|
/// - nonce: The nonce used to encrypt the message.
|
||||||
|
/// - tag : The 16-byte authentication tag.
|
||||||
|
/// - authenticatedData: Additional data that was authenticated.
|
||||||
|
///
|
||||||
|
/// The call throws an error if decryption or authentication fail.
|
||||||
|
#if compiler(<6.3)
|
||||||
|
@_lifetime(message: copy message)
|
||||||
|
#endif
|
||||||
|
public static func open(
|
||||||
|
inPlace message: inout MutableRawSpan,
|
||||||
|
using key: SymmetricKey,
|
||||||
|
nonce: Nonce,
|
||||||
|
authenticating authenticatedData: RawSpan? = nil,
|
||||||
|
tag: RawSpan
|
||||||
|
) throws(CryptoKitMetaError) {
|
||||||
|
try ChaChaPolyImpl.decrypt(key: key, inPlace: &message, nonce: nonce.bytes, tag: tag, authenticatedData: authenticatedData)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ChaChaPoly {
|
extension ChaChaPoly {
|
||||||
/// A secure container for your data that you access using a cipher.
|
/// A secure container for your data that you access using a cipher.
|
||||||
///
|
///
|
||||||
@@ -118,7 +154,6 @@ extension ChaChaPoly {
|
|||||||
/// The receiver uses another instance of the same cipher, like the
|
/// The receiver uses another instance of the same cipher, like the
|
||||||
/// ``open(_:using:)`` method, to open the box.
|
/// ``open(_:using:)`` method, to open the box.
|
||||||
@frozen
|
@frozen
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SealedBox: AEADSealedBox, Sendable {
|
public struct SealedBox: AEADSealedBox, Sendable {
|
||||||
/// A combined element composed of the tag, the nonce, and the
|
/// A combined element composed of the tag, the nonce, and the
|
||||||
/// ciphertext.
|
/// ciphertext.
|
||||||
@@ -178,4 +213,4 @@ extension ChaChaPoly {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,22 +11,18 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
protocol AEADSealedBox: Sendable {
|
protocol AEADSealedBox: Sendable {
|
||||||
associatedtype Nonce: Sequence
|
associatedtype Nonce: Sequence
|
||||||
/// The authentication tag
|
/// The authentication tag
|
||||||
@@ -46,7 +42,6 @@ protocol AEADSealedBox: Sendable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A type representing authenticated encryption with associated data.
|
/// A type representing authenticated encryption with associated data.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
protocol Cipher {
|
protocol Cipher {
|
||||||
associatedtype Key
|
associatedtype Key
|
||||||
associatedtype SealedBox: AEADSealedBox
|
associatedtype SealedBox: AEADSealedBox
|
||||||
|
|||||||
@@ -11,18 +11,15 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
// MARK: - Generated file, do NOT edit
|
// MARK: - Generated file, do NOT edit
|
||||||
// any edits of this file WILL be overwritten and thus discarded
|
// any edits of this file WILL be overwritten and thus discarded
|
||||||
// see section `gyb` in `README` for details.
|
// see section `gyb` in `README` for details.
|
||||||
@@ -31,29 +28,56 @@ public import Foundation
|
|||||||
|
|
||||||
|
|
||||||
// MARK: - AES.GCM + Nonce
|
// MARK: - AES.GCM + Nonce
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension AES.GCM {
|
extension AES.GCM {
|
||||||
/// A value used once during a cryptographic operation and then discarded.
|
/// A value used once during a cryptographic operation and then discarded.
|
||||||
///
|
///
|
||||||
/// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical
|
/// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical
|
||||||
/// that nonces are unique per call to encryption APIs in order to protect the
|
/// that nonces are unique per call to encryption APIs in order to protect the
|
||||||
/// integrity of the encryption.
|
/// integrity of the encryption.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct Nonce: ContiguousBytes, Sequence, Sendable {
|
public struct Nonce: ContiguousBytes, Sequence, Sendable {
|
||||||
let bytes: Data
|
typealias Storage = ContiguousArray<UInt8>
|
||||||
|
|
||||||
|
let storage: Storage
|
||||||
|
|
||||||
/// Creates a new random nonce.
|
/// Creates a new random nonce.
|
||||||
///
|
///
|
||||||
/// The default nonce is a 12-byte random nonce.
|
/// The default nonce is a 12-byte random nonce.
|
||||||
public init() {
|
public init() {
|
||||||
var data = Data(repeating: 0, count: AES.GCM.defaultNonceByteCount)
|
self.storage = Self.randomNonceStorage
|
||||||
data.withUnsafeMutableBytes {
|
|
||||||
assert($0.count == AES.GCM.defaultNonceByteCount)
|
|
||||||
$0.initializeWithRandomBytes(count: AES.GCM.defaultNonceByteCount)
|
|
||||||
}
|
|
||||||
self.bytes = data
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Creates a nonce from the given data.
|
||||||
|
///
|
||||||
|
/// Unless your use case calls for a nonce with a specific value, use the
|
||||||
|
/// ``init()`` method to instead create a random nonce.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - data: A data representation of the nonce.
|
||||||
|
/// The initializer throws an error if the data has a length smaller than 12 bytes.
|
||||||
|
internal init(data: RawSpan) throws(CryptoKitMetaError) {
|
||||||
|
if data.byteCount < AES.GCM.defaultNonceByteCount {
|
||||||
|
throw error(CryptoKitError.incorrectParameterSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
self.storage = Storage(copying: data)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a nonce from the given data.
|
||||||
|
///
|
||||||
|
/// Unless your use case calls for a nonce with a specific value, use the
|
||||||
|
/// ``init()`` method to instead create a random nonce.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - bytes: The bytes that represent the nonce.
|
||||||
|
/// The initializer throws an error if the data has a length smaller than 12 bytes.
|
||||||
|
public init(copying bytes: RawSpan) throws(CryptoKitMetaError) {
|
||||||
|
if bytes.byteCount < AES.GCM.defaultNonceByteCount {
|
||||||
|
throw error(CryptoKitError.incorrectParameterSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
self.storage = Storage(copying: bytes)
|
||||||
|
}
|
||||||
|
|
||||||
/// Creates a nonce from the given data.
|
/// Creates a nonce from the given data.
|
||||||
///
|
///
|
||||||
/// Unless your use case calls for a nonce with a specific value, use the
|
/// Unless your use case calls for a nonce with a specific value, use the
|
||||||
@@ -67,9 +91,9 @@ extension AES.GCM {
|
|||||||
throw error(CryptoKitError.incorrectParameterSize)
|
throw error(CryptoKitError.incorrectParameterSize)
|
||||||
}
|
}
|
||||||
|
|
||||||
self.bytes = Data(data)
|
self.storage = Storage(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Calls the given closure with a pointer to the underlying bytes of the array’s
|
/// Calls the given closure with a pointer to the underlying bytes of the array’s
|
||||||
/// contiguous storage.
|
/// contiguous storage.
|
||||||
///
|
///
|
||||||
@@ -91,39 +115,93 @@ extension AES.GCM {
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
/// The bytes stored in the nonce.
|
||||||
|
public var bytes: RawSpan {
|
||||||
|
get {
|
||||||
|
storage.span.bytes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The number of bytes stored in the nonce.
|
||||||
|
public var count: Int { storage.count }
|
||||||
|
|
||||||
/// Returns an iterator over the elements of the nonce.
|
/// Returns an iterator over the elements of the nonce.
|
||||||
public func makeIterator() -> Array<UInt8>.Iterator {
|
public func makeIterator() -> Array<UInt8>.Iterator {
|
||||||
self.withUnsafeBytes({ (buffPtr) in
|
self.withUnsafeBytes({ (buffPtr) in
|
||||||
return Array(buffPtr).makeIterator()
|
return Array(buffPtr).makeIterator()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Storage for a new, random nonce.
|
||||||
|
static var randomNonceStorage: Storage {
|
||||||
|
var data = Storage(repeating: 0, count: AES.GCM.defaultNonceByteCount)
|
||||||
|
assert(data.count == AES.GCM.defaultNonceByteCount)
|
||||||
|
|
||||||
|
var mutableSpan = data.mutableSpan
|
||||||
|
var mutableBytes = mutableSpan.mutableBytes
|
||||||
|
initializeRandomNonce(into: &mutableBytes)
|
||||||
|
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Initialize the given mutable span with random bytes.
|
||||||
|
static func initializeRandomNonce(into data: inout MutableRawSpan) {
|
||||||
|
data.initializeWithRandomBytes(count: data.byteCount)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - ChaChaPoly + Nonce
|
// MARK: - ChaChaPoly + Nonce
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ChaChaPoly {
|
extension ChaChaPoly {
|
||||||
/// A value used once during a cryptographic operation and then discarded.
|
/// A value used once during a cryptographic operation and then discarded.
|
||||||
///
|
///
|
||||||
/// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical
|
/// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical
|
||||||
/// that nonces are unique per call to encryption APIs in order to protect the
|
/// that nonces are unique per call to encryption APIs in order to protect the
|
||||||
/// integrity of the encryption.
|
/// integrity of the encryption.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct Nonce: ContiguousBytes, Sequence, Sendable {
|
public struct Nonce: ContiguousBytes, Sequence, Sendable {
|
||||||
let bytes: Data
|
typealias Storage = [12 of UInt8]
|
||||||
|
|
||||||
|
let storage: Storage
|
||||||
|
|
||||||
/// Creates a new random nonce.
|
/// Creates a new random nonce.
|
||||||
///
|
///
|
||||||
/// The default nonce is a 12-byte random nonce.
|
/// The default nonce is a 12-byte random nonce.
|
||||||
public init() {
|
public init() {
|
||||||
var data = Data(repeating: 0, count: ChaChaPoly.nonceByteCount)
|
self.storage = Self.randomNonceStorage
|
||||||
data.withUnsafeMutableBytes {
|
|
||||||
assert($0.count == ChaChaPoly.nonceByteCount)
|
|
||||||
$0.initializeWithRandomBytes(count: ChaChaPoly.nonceByteCount)
|
|
||||||
}
|
|
||||||
self.bytes = data
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Creates a nonce from the given data.
|
||||||
|
///
|
||||||
|
/// Unless your use case calls for a nonce with a specific value, use the
|
||||||
|
/// ``init()`` method to instead create a random nonce.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - data: A 12-byte data representation of the nonce.
|
||||||
|
/// The initializer throws an error if the data isn't 12 bytes long.
|
||||||
|
internal init(data: RawSpan) throws(CryptoKitMetaError) {
|
||||||
|
if data.byteCount != ChaChaPoly.nonceByteCount {
|
||||||
|
throw error(CryptoKitError.incorrectParameterSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
self.storage = Storage(copying: data)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a nonce from the given data.
|
||||||
|
///
|
||||||
|
/// Unless your use case calls for a nonce with a specific value, use the
|
||||||
|
/// ``init()`` method to instead create a random nonce.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - bytes: The bytes that represent the nonce.
|
||||||
|
/// The initializer throws an error if the data isn't 12 bytes long.
|
||||||
|
public init(copying bytes: RawSpan) throws(CryptoKitMetaError) {
|
||||||
|
if bytes.byteCount != ChaChaPoly.nonceByteCount {
|
||||||
|
throw error(CryptoKitError.incorrectParameterSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
self.storage = Storage(copying: bytes)
|
||||||
|
}
|
||||||
|
|
||||||
/// Creates a nonce from the given data.
|
/// Creates a nonce from the given data.
|
||||||
///
|
///
|
||||||
/// Unless your use case calls for a nonce with a specific value, use the
|
/// Unless your use case calls for a nonce with a specific value, use the
|
||||||
@@ -137,9 +215,9 @@ extension ChaChaPoly {
|
|||||||
throw error(CryptoKitError.incorrectParameterSize)
|
throw error(CryptoKitError.incorrectParameterSize)
|
||||||
}
|
}
|
||||||
|
|
||||||
self.bytes = Data(data)
|
self.storage = Storage(copying: data)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Calls the given closure with a pointer to the underlying bytes of the array’s
|
/// Calls the given closure with a pointer to the underlying bytes of the array’s
|
||||||
/// contiguous storage.
|
/// contiguous storage.
|
||||||
///
|
///
|
||||||
@@ -161,12 +239,38 @@ extension ChaChaPoly {
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
/// The bytes stored in the nonce.
|
||||||
|
public var bytes: RawSpan {
|
||||||
|
get {
|
||||||
|
storage.span.bytes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The number of bytes stored in the nonce.
|
||||||
|
public var count: Int { storage.count }
|
||||||
|
|
||||||
/// Returns an iterator over the elements of the nonce.
|
/// Returns an iterator over the elements of the nonce.
|
||||||
public func makeIterator() -> Array<UInt8>.Iterator {
|
public func makeIterator() -> Array<UInt8>.Iterator {
|
||||||
self.withUnsafeBytes({ (buffPtr) in
|
self.withUnsafeBytes({ (buffPtr) in
|
||||||
return Array(buffPtr).makeIterator()
|
return Array(buffPtr).makeIterator()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Storage for a new, random nonce.
|
||||||
|
static var randomNonceStorage: Storage {
|
||||||
|
var data = Storage(repeating: 0)
|
||||||
|
|
||||||
|
var mutableSpan = data.mutableSpan
|
||||||
|
var mutableBytes = mutableSpan.mutableBytes
|
||||||
|
initializeRandomNonce(into: &mutableBytes)
|
||||||
|
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Initialize the given mutable span with random bytes.
|
||||||
|
static func initializeRandomNonce(into data: inout MutableRawSpan) {
|
||||||
|
data.initializeWithRandomBytes(count: data.byteCount)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
|
||||||
//
|
|
||||||
// This source file is part of the SwiftCrypto open source project
|
|
||||||
//
|
|
||||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
|
||||||
// Licensed under Apache License v2.0
|
|
||||||
//
|
|
||||||
// See LICENSE.txt for license information
|
|
||||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
|
||||||
//
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
//
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
@_exported import CryptoKit
|
|
||||||
#else
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
|
||||||
public import FoundationEssentials
|
|
||||||
#else
|
|
||||||
public import Foundation
|
|
||||||
#endif
|
|
||||||
#endif
|
|
||||||
// MARK: - Generated file, do NOT edit
|
|
||||||
// any edits of this file WILL be overwritten and thus discarded
|
|
||||||
// see section `gyb` in `README` for details.
|
|
||||||
|
|
||||||
%{
|
|
||||||
ciphers = [{"name": "AES.GCM", "recommendedNonceSize": "AES.GCM.defaultNonceByteCount", "nonceValidation": "< AES.GCM.defaultNonceByteCount", "dataDescription": "/// - data: A data representation of the nonce.\n/// The initializer throws an error if the data has a length smaller than 12 bytes."}]
|
|
||||||
|
|
||||||
if "NO_CHACHAPOLY" in globals():
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
ciphers.append({"name": "ChaChaPoly", "recommendedNonceSize": "ChaChaPoly.nonceByteCount", "nonceValidation": "!= ChaChaPoly.nonceByteCount", "dataDescription": "/// - data: A 12-byte data representation of the nonce.\n/// The initializer throws an error if the data isn't 12 bytes long."})
|
|
||||||
}%
|
|
||||||
|
|
||||||
|
|
||||||
% for cipher in ciphers:
|
|
||||||
%{
|
|
||||||
name = cipher["name"]
|
|
||||||
nonceSize = cipher["recommendedNonceSize"]
|
|
||||||
nonceValidation = cipher["nonceValidation"]
|
|
||||||
dataDescription = cipher["dataDescription"]
|
|
||||||
}%
|
|
||||||
|
|
||||||
// MARK: - ${name} + Nonce
|
|
||||||
extension ${name} {
|
|
||||||
/// A value used once during a cryptographic operation and then discarded.
|
|
||||||
///
|
|
||||||
/// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical
|
|
||||||
/// that nonces are unique per call to encryption APIs in order to protect the
|
|
||||||
/// integrity of the encryption.
|
|
||||||
public struct Nonce: ContiguousBytes, Sequence, Sendable {
|
|
||||||
let bytes: Data
|
|
||||||
|
|
||||||
/// Creates a new random nonce.
|
|
||||||
///
|
|
||||||
/// The default nonce is a 12-byte random nonce.
|
|
||||||
public init() {
|
|
||||||
var data = Data(repeating: 0, count: ${nonceSize})
|
|
||||||
data.withUnsafeMutableBytes {
|
|
||||||
assert($0.count == ${nonceSize})
|
|
||||||
$0.initializeWithRandomBytes(count: ${nonceSize})
|
|
||||||
}
|
|
||||||
self.bytes = data
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a nonce from the given data.
|
|
||||||
///
|
|
||||||
/// Unless your use case calls for a nonce with a specific value, use the
|
|
||||||
/// ``init()`` method to instead create a random nonce.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
${dataDescription}
|
|
||||||
public init<D: DataProtocol>(data: D) throws(CryptoKitMetaError) {
|
|
||||||
if data.count ${nonceValidation} {
|
|
||||||
throw error(CryptoKitError.incorrectParameterSize)
|
|
||||||
}
|
|
||||||
|
|
||||||
self.bytes = Data(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Calls the given closure with a pointer to the underlying bytes of the array’s
|
|
||||||
/// contiguous storage.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - body: A closure with an `UnsafeRawBufferPointer` parameter that points to the
|
|
||||||
/// contiguous storage for the array. The system creates the storage if it doesn’t
|
|
||||||
/// exist. If body has a return value, that value is also used as the return value
|
|
||||||
/// for the ``withUnsafeBytes(_:)`` method. The argument is valid only for
|
|
||||||
/// the duration of the closure’s execution.
|
|
||||||
///
|
|
||||||
/// - Returns: The return value, if any, of the body closure parameter.
|
|
||||||
#if !hasFeature(Embedded)
|
|
||||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
|
||||||
return try self.bytes.withUnsafeBytes(body)
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
public func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
|
|
||||||
return try self.bytes.withUnsafeBytes(body)
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/// Returns an iterator over the elements of the nonce.
|
|
||||||
public func makeIterator() -> Array<UInt8>.Iterator {
|
|
||||||
self.withUnsafeBytes({ (buffPtr) in
|
|
||||||
return Array(buffPtr).makeIterator()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
% end
|
|
||||||
#endif // Linux or !SwiftPM
|
|
||||||
@@ -11,19 +11,16 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
// This module implements "just enough" ASN.1. Specifically, we implement exactly enough ASN.1 DER parsing to handle
|
// This module implements "just enough" ASN.1. Specifically, we implement exactly enough ASN.1 DER parsing to handle
|
||||||
// the following use-cases:
|
// the following use-cases:
|
||||||
@@ -112,18 +109,15 @@ import Foundation
|
|||||||
// generally: that is, we don't hard-code special knowledge of these formats as part of the parsing process. Instead we have written a
|
// generally: that is, we don't hard-code special knowledge of these formats as part of the parsing process. Instead we have written a
|
||||||
// parser that can divide the world of ASN.1 into parseable chunks, and then we try to decode specific formats from those chunks. This
|
// parser that can divide the world of ASN.1 into parseable chunks, and then we try to decode specific formats from those chunks. This
|
||||||
// allows us to extend things in the future without too much pain.
|
// allows us to extend things in the future without too much pain.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal enum ASN1 { }
|
internal enum ASN1 { }
|
||||||
|
|
||||||
// MARK: - Parser Node
|
// MARK: - Parser Node
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
/// An `ASN1ParserNode` is a representation of a parsed ASN.1 TLV section. An `ASN1ParserNode` may be primitive, or may be composed of other `ASN1ParserNode`s.
|
/// An `ASN1ParserNode` is a representation of a parsed ASN.1 TLV section. An `ASN1ParserNode` may be primitive, or may be composed of other `ASN1ParserNode`s.
|
||||||
/// In our representation, we keep track of this by storing a node "depth", which allows rapid forward and backward scans to hop over sections
|
/// In our representation, we keep track of this by storing a node "depth", which allows rapid forward and backward scans to hop over sections
|
||||||
/// we're uninterested in.
|
/// we're uninterested in.
|
||||||
///
|
///
|
||||||
/// This type is not exposed to users of the API: it is only used internally for implementation of the user-level API.
|
/// This type is not exposed to users of the API: it is only used internally for implementation of the user-level API.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
fileprivate struct ASN1ParserNode {
|
fileprivate struct ASN1ParserNode {
|
||||||
/// The identifier.
|
/// The identifier.
|
||||||
var identifier: ASN1Identifier
|
var identifier: ASN1Identifier
|
||||||
@@ -136,11 +130,9 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1ParserNode: Hashable { }
|
extension ASN1.ASN1ParserNode: Hashable { }
|
||||||
|
|
||||||
#if !hasFeature(Embedded)
|
#if !hasFeature(Embedded)
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1ParserNode: CustomStringConvertible {
|
extension ASN1.ASN1ParserNode: CustomStringConvertible {
|
||||||
var description: String {
|
var description: String {
|
||||||
return "ASN1.ASN1ParserNode(identifier: \(self.identifier), depth: \(self.depth), dataBytes: \(self.dataBytes?.count ?? 0))"
|
return "ASN1.ASN1ParserNode(identifier: \(self.identifier), depth: \(self.depth), dataBytes: \(self.dataBytes?.count ?? 0))"
|
||||||
@@ -149,7 +141,6 @@ extension ASN1.ASN1ParserNode: CustomStringConvertible {
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
// MARK: - Sequence, SequenceOf, and Set
|
// MARK: - Sequence, SequenceOf, and Set
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
/// Parse the node as an ASN.1 sequence.
|
/// Parse the node as an ASN.1 sequence.
|
||||||
internal static func sequence<T>(_ node: ASN1Node, identifier: ASN1.ASN1Identifier, _ builder: (inout ASN1.ASN1NodeCollection.Iterator) throws(CryptoKitMetaError) -> T) throws(CryptoKitMetaError) -> T {
|
internal static func sequence<T>(_ node: ASN1Node, identifier: ASN1.ASN1Identifier, _ builder: (inout ASN1.ASN1NodeCollection.Iterator) throws(CryptoKitMetaError) -> T) throws(CryptoKitMetaError) -> T {
|
||||||
@@ -198,7 +189,6 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Optional explicitly tagged
|
// MARK: - Optional explicitly tagged
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
/// Parses an optional explicitly tagged element. Throws on a tag mismatch, returns nil if the element simply isn't there.
|
/// Parses an optional explicitly tagged element. Throws on a tag mismatch, returns nil if the element simply isn't there.
|
||||||
///
|
///
|
||||||
@@ -236,7 +226,6 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - DEFAULT
|
// MARK: - DEFAULT
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
/// Parses a value that is encoded with a DEFAULT. Such a value is optional, and if absent will
|
/// Parses a value that is encoded with a DEFAULT. Such a value is optional, and if absent will
|
||||||
/// be replaced with its default.
|
/// be replaced with its default.
|
||||||
@@ -285,10 +274,8 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Parsing
|
// MARK: - Parsing
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
/// A parsed representation of ASN.1.
|
/// A parsed representation of ASN.1.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
fileprivate struct ASN1ParseResult {
|
fileprivate struct ASN1ParseResult {
|
||||||
private static let maximumNodeDepth = 10
|
private static let maximumNodeDepth = 10
|
||||||
|
|
||||||
@@ -352,10 +339,8 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1ParseResult: Hashable { }
|
extension ASN1.ASN1ParseResult: Hashable { }
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
static func parse(_ data: [UInt8]) throws(CryptoKitMetaError) -> ASN1Node {
|
static func parse(_ data: [UInt8]) throws(CryptoKitMetaError) -> ASN1Node {
|
||||||
return try parse(data[...])
|
return try parse(data[...])
|
||||||
@@ -384,13 +369,11 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - ASN1NodeCollection
|
// MARK: - ASN1NodeCollection
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
/// Represents a collection of ASN.1 nodes contained in a constructed ASN.1 node.
|
/// Represents a collection of ASN.1 nodes contained in a constructed ASN.1 node.
|
||||||
///
|
///
|
||||||
/// Constructed ASN.1 nodes are made up of multiple child nodes. This object represents the collection of those child nodes.
|
/// Constructed ASN.1 nodes are made up of multiple child nodes. This object represents the collection of those child nodes.
|
||||||
/// It allows us to lazily construct the child nodes, potentially skipping over them when we don't care about them.
|
/// It allows us to lazily construct the child nodes, potentially skipping over them when we don't care about them.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal struct ASN1NodeCollection {
|
internal struct ASN1NodeCollection {
|
||||||
private var nodes: ArraySlice<ASN1ParserNode>
|
private var nodes: ArraySlice<ASN1ParserNode>
|
||||||
|
|
||||||
@@ -408,9 +391,7 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1NodeCollection: Sequence {
|
extension ASN1.ASN1NodeCollection: Sequence {
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct Iterator: IteratorProtocol {
|
struct Iterator: IteratorProtocol {
|
||||||
private var nodes: ArraySlice<ASN1.ASN1ParserNode>
|
private var nodes: ArraySlice<ASN1.ASN1ParserNode>
|
||||||
private var depth: Int
|
private var depth: Int
|
||||||
@@ -444,7 +425,6 @@ extension ASN1.ASN1NodeCollection: Sequence {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - ASN1Node
|
// MARK: - ASN1Node
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
/// An `ASN1Node` is a single entry in the ASN.1 representation of a data structure.
|
/// An `ASN1Node` is a single entry in the ASN.1 representation of a data structure.
|
||||||
///
|
///
|
||||||
@@ -454,7 +434,6 @@ extension ASN1 {
|
|||||||
///
|
///
|
||||||
/// In this way, ASN.1 objects tend to form a "tree", where each object is represented by a single top-level constructed
|
/// In this way, ASN.1 objects tend to form a "tree", where each object is represented by a single top-level constructed
|
||||||
/// node that contains other objects and primitives, eventually reaching the bottom which is made up of primitive objects.
|
/// node that contains other objects and primitives, eventually reaching the bottom which is made up of primitive objects.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal struct ASN1Node {
|
internal struct ASN1Node {
|
||||||
internal var identifier: ASN1Identifier
|
internal var identifier: ASN1Identifier
|
||||||
|
|
||||||
@@ -463,10 +442,8 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - ASN1Node.Content
|
// MARK: - ASN1Node.Content
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1Node {
|
extension ASN1.ASN1Node {
|
||||||
/// The content of a single ASN1Node.
|
/// The content of a single ASN1Node.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
enum Content {
|
enum Content {
|
||||||
case constructed(ASN1.ASN1NodeCollection)
|
case constructed(ASN1.ASN1NodeCollection)
|
||||||
case primitive(ArraySlice<UInt8>)
|
case primitive(ArraySlice<UInt8>)
|
||||||
@@ -474,9 +451,7 @@ extension ASN1.ASN1Node {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Serializing
|
// MARK: - Serializing
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct Serializer {
|
struct Serializer {
|
||||||
var serializedBytes: [UInt8]
|
var serializedBytes: [UInt8]
|
||||||
|
|
||||||
@@ -586,12 +561,10 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Helpers
|
// MARK: - Helpers
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal protocol ASN1Parseable {
|
internal protocol ASN1Parseable {
|
||||||
init(asn1Encoded: ASN1.ASN1Node) throws(CryptoKitMetaError)
|
init(asn1Encoded: ASN1.ASN1Node) throws(CryptoKitMetaError)
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1Parseable {
|
extension ASN1Parseable {
|
||||||
internal init(asn1Encoded sequenceNodeIterator: inout ASN1.ASN1NodeCollection.Iterator) throws(CryptoKitMetaError) {
|
internal init(asn1Encoded sequenceNodeIterator: inout ASN1.ASN1NodeCollection.Iterator) throws(CryptoKitMetaError) {
|
||||||
guard let node = sequenceNodeIterator.next() else {
|
guard let node = sequenceNodeIterator.next() else {
|
||||||
@@ -610,13 +583,11 @@ extension ASN1Parseable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal protocol ASN1Serializable {
|
internal protocol ASN1Serializable {
|
||||||
func serialize(into coder: inout ASN1.Serializer) throws(CryptoKitMetaError)
|
func serialize(into coder: inout ASN1.Serializer) throws(CryptoKitMetaError)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Covers ASN.1 types that may be implicitly tagged. Not all nodes can be!
|
/// Covers ASN.1 types that may be implicitly tagged. Not all nodes can be!
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal protocol ASN1ImplicitlyTaggable: ASN1Parseable, ASN1Serializable {
|
internal protocol ASN1ImplicitlyTaggable: ASN1Parseable, ASN1Serializable {
|
||||||
/// The tag that the first node will use "by default" if the grammar omits
|
/// The tag that the first node will use "by default" if the grammar omits
|
||||||
/// any more specific tag definition.
|
/// any more specific tag definition.
|
||||||
@@ -627,7 +598,6 @@ internal protocol ASN1ImplicitlyTaggable: ASN1Parseable, ASN1Serializable {
|
|||||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError)
|
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError)
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1ImplicitlyTaggable {
|
extension ASN1ImplicitlyTaggable {
|
||||||
internal init(asn1Encoded sequenceNodeIterator: inout ASN1.ASN1NodeCollection.Iterator,
|
internal init(asn1Encoded sequenceNodeIterator: inout ASN1.ASN1NodeCollection.Iterator,
|
||||||
withIdentifier identifier: ASN1.ASN1Identifier = Self.defaultIdentifier) throws(CryptoKitMetaError) {
|
withIdentifier identifier: ASN1.ASN1Identifier = Self.defaultIdentifier) throws(CryptoKitMetaError) {
|
||||||
@@ -655,7 +625,6 @@ extension ASN1ImplicitlyTaggable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ArraySlice where Element == UInt8 {
|
extension ArraySlice where Element == UInt8 {
|
||||||
fileprivate mutating func readASN1Length() throws(CryptoKitMetaError) -> UInt? {
|
fileprivate mutating func readASN1Length() throws(CryptoKitMetaError) -> UInt? {
|
||||||
guard let firstByte = self.popFirst() else {
|
guard let firstByte = self.popFirst() else {
|
||||||
@@ -704,7 +673,6 @@ extension ArraySlice where Element == UInt8 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension FixedWidthInteger {
|
extension FixedWidthInteger {
|
||||||
internal init<Bytes: Collection>(bigEndianBytes bytes: Bytes) throws(CryptoKitMetaError) where Bytes.Element == UInt8 {
|
internal init<Bytes: Collection>(bigEndianBytes bytes: Bytes) throws(CryptoKitMetaError) where Bytes.Element == UInt8 {
|
||||||
guard bytes.count <= (Self.bitWidth / 8) else {
|
guard bytes.count <= (Self.bitWidth / 8) else {
|
||||||
@@ -722,7 +690,6 @@ extension FixedWidthInteger {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Array where Element == UInt8 {
|
extension Array where Element == UInt8 {
|
||||||
fileprivate mutating func writeIdentifier(_ identifier: ASN1.ASN1Identifier) {
|
fileprivate mutating func writeIdentifier(_ identifier: ASN1.ASN1Identifier) {
|
||||||
self.append(identifier.baseTag)
|
self.append(identifier.baseTag)
|
||||||
@@ -748,7 +715,6 @@ extension Array where Element == UInt8 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Int {
|
extension Int {
|
||||||
fileprivate var bytesNeededToEncode: Int {
|
fileprivate var bytesNeededToEncode: Int {
|
||||||
// ASN.1 lengths are in two forms. If we can store the length in 7 bits, we should:
|
// ASN.1 lengths are in two forms. If we can store the length in 7 bits, we should:
|
||||||
@@ -766,7 +732,6 @@ extension Int {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension FixedWidthInteger {
|
extension FixedWidthInteger {
|
||||||
// Bytes needed to store a given integer.
|
// Bytes needed to store a given integer.
|
||||||
internal var neededBytes: Int {
|
internal var neededBytes: Int {
|
||||||
@@ -775,4 +740,4 @@ extension FixedWidthInteger {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,21 +11,17 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
/// An ASN1 ANY represents...well, anything.
|
/// An ASN1 ANY represents...well, anything.
|
||||||
///
|
///
|
||||||
@@ -34,7 +30,6 @@ extension ASN1 {
|
|||||||
///
|
///
|
||||||
/// The only things we allow users to do with ASN.1 ANYs is to try to decode them as something else,
|
/// The only things we allow users to do with ASN.1 ANYs is to try to decode them as something else,
|
||||||
/// to create them from something else, or to serialize them.
|
/// to create them from something else, or to serialize them.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct ASN1Any: ASN1Parseable, ASN1Serializable, Hashable {
|
struct ASN1Any: ASN1Parseable, ASN1Serializable, Hashable {
|
||||||
fileprivate var serializedBytes: ArraySlice<UInt8>
|
fileprivate var serializedBytes: ArraySlice<UInt8>
|
||||||
|
|
||||||
@@ -66,18 +61,16 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1Parseable {
|
extension ASN1Parseable {
|
||||||
init(asn1Any: ASN1.ASN1Any) throws(CryptoKitMetaError) {
|
init(asn1Any: ASN1.ASN1Any) throws(CryptoKitMetaError) {
|
||||||
try self.init(asn1Encoded: asn1Any.serializedBytes)
|
try self.init(asn1Encoded: asn1Any.serializedBytes)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1ImplicitlyTaggable {
|
extension ASN1ImplicitlyTaggable {
|
||||||
init(asn1Any: ASN1.ASN1Any, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
init(asn1Any: ASN1.ASN1Any, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||||
try self.init(asn1Encoded: asn1Any.serializedBytes, withIdentifier: identifier)
|
try self.init(asn1Encoded: asn1Any.serializedBytes, withIdentifier: identifier)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,24 +11,19 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
/// A bitstring is a representation of...well...some bits.
|
/// A bitstring is a representation of...well...some bits.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct ASN1BitString: ASN1ImplicitlyTaggable {
|
struct ASN1BitString: ASN1ImplicitlyTaggable {
|
||||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||||
.primitiveBitString
|
.primitiveBitString
|
||||||
@@ -67,10 +62,8 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1BitString: Hashable { }
|
extension ASN1.ASN1BitString: Hashable { }
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1BitString: ContiguousBytes {
|
extension ASN1.ASN1BitString: ContiguousBytes {
|
||||||
#if hasFeature(Embedded)
|
#if hasFeature(Embedded)
|
||||||
func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
|
func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
|
||||||
@@ -83,4 +76,4 @@ extension ASN1.ASN1BitString: ContiguousBytes {
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,21 +11,17 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Bool: ASN1ImplicitlyTaggable {
|
extension Bool: ASN1ImplicitlyTaggable {
|
||||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||||
.boolean
|
.boolean
|
||||||
@@ -64,4 +60,4 @@ extension Bool: ASN1ImplicitlyTaggable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,25 +11,20 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
/// An `ASN1Identifier` is a representation of the abstract notion of an ASN.1 identifier. Identifiers have a number of properties that relate to both the specific
|
/// An `ASN1Identifier` is a representation of the abstract notion of an ASN.1 identifier. Identifiers have a number of properties that relate to both the specific
|
||||||
/// tag number as well as the properties of the identifier in the stream.
|
/// tag number as well as the properties of the identifier in the stream.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal struct ASN1Identifier {
|
internal struct ASN1Identifier {
|
||||||
/// The base tag. In a general ASN.1 implementation we'd need an arbitrary precision integer here as the tag number can be arbitrarily large, but
|
/// The base tag. In a general ASN.1 implementation we'd need an arbitrary precision integer here as the tag number can be arbitrarily large, but
|
||||||
/// we don't need the full generality here.
|
/// we don't need the full generality here.
|
||||||
@@ -122,7 +117,6 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1Identifier {
|
extension ASN1.ASN1Identifier {
|
||||||
internal static let objectIdentifier = try! ASN1.ASN1Identifier(rawIdentifier: 0x06)
|
internal static let objectIdentifier = try! ASN1.ASN1Identifier(rawIdentifier: 0x06)
|
||||||
internal static let primitiveBitString = try! ASN1.ASN1Identifier(rawIdentifier: 0x03)
|
internal static let primitiveBitString = try! ASN1.ASN1Identifier(rawIdentifier: 0x03)
|
||||||
@@ -147,11 +141,9 @@ extension ASN1.ASN1Identifier {
|
|||||||
internal static let generalizedTime = try! ASN1.ASN1Identifier(rawIdentifier: 0x18)
|
internal static let generalizedTime = try! ASN1.ASN1Identifier(rawIdentifier: 0x18)
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1Identifier: Hashable { }
|
extension ASN1.ASN1Identifier: Hashable { }
|
||||||
|
|
||||||
#if !hasFeature(Embedded)
|
#if !hasFeature(Embedded)
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1Identifier: CustomStringConvertible {
|
extension ASN1.ASN1Identifier: CustomStringConvertible {
|
||||||
var description: String {
|
var description: String {
|
||||||
return "ASN1Identifier(\(self.baseTag))"
|
return "ASN1Identifier(\(self.baseTag))"
|
||||||
@@ -159,4 +151,4 @@ extension ASN1.ASN1Identifier: CustomStringConvertible {
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,19 +11,16 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
/// A protocol that represents any internal object that can present itself as a INTEGER, or be parsed from
|
/// A protocol that represents any internal object that can present itself as a INTEGER, or be parsed from
|
||||||
/// a INTEGER.
|
/// a INTEGER.
|
||||||
@@ -31,7 +28,6 @@ import Foundation
|
|||||||
/// This is not a very good solution for a fully-fledged ASN.1 library: we'd rather have a better numerics
|
/// This is not a very good solution for a fully-fledged ASN.1 library: we'd rather have a better numerics
|
||||||
/// protocol that could both initialize from and serialize to either bytes or words. However, no such
|
/// protocol that could both initialize from and serialize to either bytes or words. However, no such
|
||||||
/// protocol exists today.
|
/// protocol exists today.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
protocol ASN1IntegerRepresentable: ASN1ImplicitlyTaggable {
|
protocol ASN1IntegerRepresentable: ASN1ImplicitlyTaggable {
|
||||||
associatedtype IntegerBytes: RandomAccessCollection where IntegerBytes.Element == UInt8
|
associatedtype IntegerBytes: RandomAccessCollection where IntegerBytes.Element == UInt8
|
||||||
|
|
||||||
@@ -44,7 +40,6 @@ protocol ASN1IntegerRepresentable: ASN1ImplicitlyTaggable {
|
|||||||
func withBigEndianIntegerBytes<ReturnType>(_ body: (IntegerBytes) throws(CryptoKitMetaError) -> ReturnType) throws(CryptoKitMetaError) -> ReturnType
|
func withBigEndianIntegerBytes<ReturnType>(_ body: (IntegerBytes) throws(CryptoKitMetaError) -> ReturnType) throws(CryptoKitMetaError) -> ReturnType
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1IntegerRepresentable {
|
extension ASN1IntegerRepresentable {
|
||||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||||
.integer
|
.integer
|
||||||
@@ -113,7 +108,6 @@ extension ASN1IntegerRepresentable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Auto-conformance for FixedWidthInteger with fixed width magnitude.
|
// MARK: - Auto-conformance for FixedWidthInteger with fixed width magnitude.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1IntegerRepresentable where Self: FixedWidthInteger {
|
extension ASN1IntegerRepresentable where Self: FixedWidthInteger {
|
||||||
init(asn1IntegerBytes bytes: ArraySlice<UInt8>) throws(CryptoKitMetaError) {
|
init(asn1IntegerBytes bytes: ArraySlice<UInt8>) throws(CryptoKitMetaError) {
|
||||||
// Defer to the FixedWidthInteger constructor.
|
// Defer to the FixedWidthInteger constructor.
|
||||||
@@ -134,7 +128,6 @@ extension ASN1IntegerRepresentable where Self: FixedWidthInteger {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct IntegerBytesCollection<Integer: FixedWidthInteger> {
|
struct IntegerBytesCollection<Integer: FixedWidthInteger> {
|
||||||
private var integer: Integer
|
private var integer: Integer
|
||||||
|
|
||||||
@@ -143,9 +136,7 @@ struct IntegerBytesCollection<Integer: FixedWidthInteger> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension IntegerBytesCollection: RandomAccessCollection {
|
extension IntegerBytesCollection: RandomAccessCollection {
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct Index {
|
struct Index {
|
||||||
fileprivate var byteNumber: Int
|
fileprivate var byteNumber: Int
|
||||||
|
|
||||||
@@ -179,10 +170,8 @@ extension IntegerBytesCollection: RandomAccessCollection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension IntegerBytesCollection.Index: Equatable { }
|
extension IntegerBytesCollection.Index: Equatable { }
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension IntegerBytesCollection.Index: Comparable {
|
extension IntegerBytesCollection.Index: Comparable {
|
||||||
// Comparable here is backwards to the original ordering.
|
// Comparable here is backwards to the original ordering.
|
||||||
static func <(lhs: Self, rhs: Self) -> Bool {
|
static func <(lhs: Self, rhs: Self) -> Bool {
|
||||||
@@ -202,7 +191,6 @@ extension IntegerBytesCollection.Index: Comparable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension IntegerBytesCollection.Index: Strideable {
|
extension IntegerBytesCollection.Index: Strideable {
|
||||||
func advanced(by n: Int) -> IntegerBytesCollection<Integer>.Index {
|
func advanced(by n: Int) -> IntegerBytesCollection<Integer>.Index {
|
||||||
return IntegerBytesCollection.Index(byteNumber: self.byteNumber - n)
|
return IntegerBytesCollection.Index(byteNumber: self.byteNumber - n)
|
||||||
@@ -214,37 +202,26 @@ extension IntegerBytesCollection.Index: Strideable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Int8: ASN1IntegerRepresentable { }
|
extension Int8: ASN1IntegerRepresentable { }
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension UInt8: ASN1IntegerRepresentable { }
|
extension UInt8: ASN1IntegerRepresentable { }
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Int16: ASN1IntegerRepresentable { }
|
extension Int16: ASN1IntegerRepresentable { }
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension UInt16: ASN1IntegerRepresentable { }
|
extension UInt16: ASN1IntegerRepresentable { }
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Int32: ASN1IntegerRepresentable { }
|
extension Int32: ASN1IntegerRepresentable { }
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension UInt32: ASN1IntegerRepresentable { }
|
extension UInt32: ASN1IntegerRepresentable { }
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Int64: ASN1IntegerRepresentable { }
|
extension Int64: ASN1IntegerRepresentable { }
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension UInt64: ASN1IntegerRepresentable { }
|
extension UInt64: ASN1IntegerRepresentable { }
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Int: ASN1IntegerRepresentable { }
|
extension Int: ASN1IntegerRepresentable { }
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension UInt: ASN1IntegerRepresentable { }
|
extension UInt: ASN1IntegerRepresentable { }
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension RandomAccessCollection where Element == UInt8 {
|
extension RandomAccessCollection where Element == UInt8 {
|
||||||
fileprivate func trimLeadingExcessBytes() -> SubSequence {
|
fileprivate func trimLeadingExcessBytes() -> SubSequence {
|
||||||
var slice = self[...]
|
var slice = self[...]
|
||||||
@@ -292,11 +269,10 @@ extension RandomAccessCollection where Element == UInt8 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension UInt8 {
|
extension UInt8 {
|
||||||
fileprivate var topBitSet: Bool {
|
fileprivate var topBitSet: Bool {
|
||||||
return (self & 0x80) != 0
|
return (self & 0x80) != 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,24 +11,19 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
/// An ASN1 NULL represents nothing.
|
/// An ASN1 NULL represents nothing.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct ASN1Null: ASN1ImplicitlyTaggable, Hashable {
|
struct ASN1Null: ASN1ImplicitlyTaggable, Hashable {
|
||||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||||
.null
|
.null
|
||||||
@@ -52,4 +47,4 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,24 +11,19 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
/// An octet string is a representation of a string of octets.
|
/// An octet string is a representation of a string of octets.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct ASN1OctetString: ASN1ImplicitlyTaggable {
|
struct ASN1OctetString: ASN1ImplicitlyTaggable {
|
||||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||||
.primitiveOctetString
|
.primitiveOctetString
|
||||||
@@ -60,10 +55,8 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1OctetString: Hashable { }
|
extension ASN1.ASN1OctetString: Hashable { }
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1OctetString: ContiguousBytes {
|
extension ASN1.ASN1OctetString: ContiguousBytes {
|
||||||
#if hasFeature(Embedded)
|
#if hasFeature(Embedded)
|
||||||
func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
|
func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
|
||||||
@@ -76,4 +69,4 @@ extension ASN1.ASN1OctetString: ContiguousBytes {
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,21 +11,17 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
private func contents(of string: StaticString) -> ArraySlice<UInt8> {
|
private func contents(of string: StaticString) -> ArraySlice<UInt8> {
|
||||||
if string.hasPointerRepresentation {
|
if string.hasPointerRepresentation {
|
||||||
return ArraySlice(
|
return ArraySlice(
|
||||||
@@ -41,11 +37,9 @@ private func contents(of string: StaticString) -> ArraySlice<UInt8> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
/// A UTF8String is roughly what it sounds like. We note that all the string types are encoded as implicitly tagged
|
/// A UTF8String is roughly what it sounds like. We note that all the string types are encoded as implicitly tagged
|
||||||
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
|
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct ASN1UTF8String: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes {
|
struct ASN1UTF8String: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes {
|
||||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||||
.primitiveUTF8String
|
.primitiveUTF8String
|
||||||
@@ -89,7 +83,6 @@ extension ASN1 {
|
|||||||
|
|
||||||
/// We note that all the string types are encoded as implicitly tagged
|
/// We note that all the string types are encoded as implicitly tagged
|
||||||
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
|
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct ASN1TeletexString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes {
|
struct ASN1TeletexString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes {
|
||||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||||
.primitiveTeletexString
|
.primitiveTeletexString
|
||||||
@@ -133,7 +126,6 @@ extension ASN1 {
|
|||||||
|
|
||||||
/// We note that all the string types are encoded as implicitly tagged
|
/// We note that all the string types are encoded as implicitly tagged
|
||||||
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
|
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct ASN1PrintableString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes {
|
struct ASN1PrintableString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes {
|
||||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||||
.primitivePrintableString
|
.primitivePrintableString
|
||||||
@@ -177,7 +169,6 @@ extension ASN1 {
|
|||||||
|
|
||||||
/// We note that all the string types are encoded as implicitly tagged
|
/// We note that all the string types are encoded as implicitly tagged
|
||||||
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
|
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct ASN1UniversalString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes {
|
struct ASN1UniversalString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes {
|
||||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||||
.primitiveUniversalString
|
.primitiveUniversalString
|
||||||
@@ -221,7 +212,6 @@ extension ASN1 {
|
|||||||
|
|
||||||
/// We note that all the string types are encoded as implicitly tagged
|
/// We note that all the string types are encoded as implicitly tagged
|
||||||
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
|
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct ASN1BMPString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes {
|
struct ASN1BMPString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes {
|
||||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||||
.primitiveBMPString
|
.primitiveBMPString
|
||||||
@@ -265,35 +255,30 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#if !hasFeature(Embedded)
|
#if !hasFeature(Embedded)
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1TeletexString: ExpressibleByStringLiteral {
|
extension ASN1.ASN1TeletexString: ExpressibleByStringLiteral {
|
||||||
public init(stringLiteral value: StringLiteralType) {
|
public init(stringLiteral value: StringLiteralType) {
|
||||||
self.bytes = ArraySlice(value.utf8)
|
self.bytes = ArraySlice(value.utf8)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1UTF8String: ExpressibleByStringLiteral {
|
extension ASN1.ASN1UTF8String: ExpressibleByStringLiteral {
|
||||||
public init(stringLiteral value: StringLiteralType) {
|
public init(stringLiteral value: StringLiteralType) {
|
||||||
self.bytes = ArraySlice(value.utf8)
|
self.bytes = ArraySlice(value.utf8)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1PrintableString: ExpressibleByStringLiteral {
|
extension ASN1.ASN1PrintableString: ExpressibleByStringLiteral {
|
||||||
public init(stringLiteral value: StringLiteralType) {
|
public init(stringLiteral value: StringLiteralType) {
|
||||||
self.bytes = ArraySlice(value.utf8)
|
self.bytes = ArraySlice(value.utf8)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1UniversalString: ExpressibleByStringLiteral {
|
extension ASN1.ASN1UniversalString: ExpressibleByStringLiteral {
|
||||||
public init(stringLiteral value: StringLiteralType) {
|
public init(stringLiteral value: StringLiteralType) {
|
||||||
self.bytes = ArraySlice(value.utf8)
|
self.bytes = ArraySlice(value.utf8)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1BMPString: ExpressibleByStringLiteral {
|
extension ASN1.ASN1BMPString: ExpressibleByStringLiteral {
|
||||||
public init(stringLiteral value: StringLiteralType) {
|
public init(stringLiteral value: StringLiteralType) {
|
||||||
self.bytes = ArraySlice(value.utf8)
|
self.bytes = ArraySlice(value.utf8)
|
||||||
@@ -302,4 +287,4 @@ extension ASN1.ASN1BMPString: ExpressibleByStringLiteral {
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,31 +11,24 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
// For temporary purposes we pretend that ArraySlice is our "bigint" type. We don't really need anything else.
|
// For temporary purposes we pretend that ArraySlice is our "bigint" type. We don't really need anything else.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ArraySlice: ASN1Serializable where Element == UInt8 { }
|
extension ArraySlice: ASN1Serializable where Element == UInt8 { }
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ArraySlice: ASN1Parseable where Element == UInt8 { }
|
extension ArraySlice: ASN1Parseable where Element == UInt8 { }
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ArraySlice: ASN1ImplicitlyTaggable where Element == UInt8 { }
|
extension ArraySlice: ASN1ImplicitlyTaggable where Element == UInt8 { }
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 {
|
extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 {
|
||||||
// We only use unsigned "bigint"s
|
// We only use unsigned "bigint"s
|
||||||
static var isSigned: Bool {
|
static var isSigned: Bool {
|
||||||
@@ -51,4 +44,4 @@ extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,23 +11,18 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct GeneralizedTime: ASN1ImplicitlyTaggable, Hashable {
|
struct GeneralizedTime: ASN1ImplicitlyTaggable, Hashable {
|
||||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||||
.generalizedTime
|
.generalizedTime
|
||||||
@@ -180,7 +175,6 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.GeneralizedTime {
|
extension ASN1.GeneralizedTime {
|
||||||
fileprivate static func parseDateBytes(_ bytes: ArraySlice<UInt8>) throws(CryptoKitMetaError) -> ASN1.GeneralizedTime {
|
fileprivate static func parseDateBytes(_ bytes: ArraySlice<UInt8>) throws(CryptoKitMetaError) -> ASN1.GeneralizedTime {
|
||||||
var bytes = bytes
|
var bytes = bytes
|
||||||
@@ -263,7 +257,6 @@ extension ASN1.GeneralizedTime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ArraySlice where Element == UInt8 {
|
extension ArraySlice where Element == UInt8 {
|
||||||
fileprivate mutating func readFourDigitDecimalInteger() -> Int? {
|
fileprivate mutating func readFourDigitDecimalInteger() -> Int? {
|
||||||
guard let first = self.readTwoDigitDecimalInteger(),
|
guard let first = self.readTwoDigitDecimalInteger(),
|
||||||
@@ -329,7 +322,6 @@ extension ArraySlice where Element == UInt8 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Array where Element == UInt8 {
|
extension Array where Element == UInt8 {
|
||||||
fileprivate mutating func append(_ generalizedTime: ASN1.GeneralizedTime) {
|
fileprivate mutating func append(_ generalizedTime: ASN1.GeneralizedTime) {
|
||||||
self.appendFourDigitDecimal(generalizedTime.year)
|
self.appendFourDigitDecimal(generalizedTime.year)
|
||||||
@@ -401,7 +393,6 @@ extension Array where Element == UInt8 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Int {
|
extension Int {
|
||||||
fileprivate init?(fromDecimalASCII ascii: UInt8) {
|
fileprivate init?(fromDecimalASCII ascii: UInt8) {
|
||||||
let asciiZero = UInt8(48 /* "0" */)
|
let asciiZero = UInt8(48 /* "0" */)
|
||||||
@@ -418,4 +409,4 @@ extension Int {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,28 +11,23 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
/// An Object Identifier is a representation of some kind of object: really any kind of object.
|
/// An Object Identifier is a representation of some kind of object: really any kind of object.
|
||||||
///
|
///
|
||||||
/// It represents a node in an OID hierarchy, and is usually represented as an ordered sequence of numbers.
|
/// It represents a node in an OID hierarchy, and is usually represented as an ordered sequence of numbers.
|
||||||
///
|
///
|
||||||
/// We mostly don't care about the semantics of the thing, we just care about being able to store and compare them.
|
/// We mostly don't care about the semantics of the thing, we just care about being able to store and compare them.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct ASN1ObjectIdentifier: ASN1ImplicitlyTaggable {
|
struct ASN1ObjectIdentifier: ASN1ImplicitlyTaggable {
|
||||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||||
.objectIdentifier
|
.objectIdentifier
|
||||||
@@ -142,19 +137,15 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1ObjectIdentifier: Hashable {}
|
extension ASN1.ASN1ObjectIdentifier: Hashable {}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1ObjectIdentifier: ExpressibleByArrayLiteral {
|
extension ASN1.ASN1ObjectIdentifier: ExpressibleByArrayLiteral {
|
||||||
init(arrayLiteral elements: UInt...) {
|
init(arrayLiteral elements: UInt...) {
|
||||||
self.oidComponents = elements
|
self.oidComponents = elements
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.ASN1ObjectIdentifier {
|
extension ASN1.ASN1ObjectIdentifier {
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
enum NamedCurves {
|
enum NamedCurves {
|
||||||
static let secp256r1: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10_045, 3, 1, 7]
|
static let secp256r1: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10_045, 3, 1, 7]
|
||||||
|
|
||||||
@@ -163,19 +154,16 @@ extension ASN1.ASN1ObjectIdentifier {
|
|||||||
static let secp521r1: ASN1.ASN1ObjectIdentifier = [1, 3, 132, 0, 35]
|
static let secp521r1: ASN1.ASN1ObjectIdentifier = [1, 3, 132, 0, 35]
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
enum HashFunctions {
|
enum HashFunctions {
|
||||||
static let sha256: ASN1.ASN1ObjectIdentifier = [2, 16, 840, 1, 101, 3, 4, 2, 1]
|
static let sha256: ASN1.ASN1ObjectIdentifier = [2, 16, 840, 1, 101, 3, 4, 2, 1]
|
||||||
static let sha384: ASN1.ASN1ObjectIdentifier = [2, 16, 840, 1, 101, 3, 4, 2, 2]
|
static let sha384: ASN1.ASN1ObjectIdentifier = [2, 16, 840, 1, 101, 3, 4, 2, 2]
|
||||||
static let sha512: ASN1.ASN1ObjectIdentifier = [2, 16, 840, 1, 101, 3, 4, 2, 3]
|
static let sha512: ASN1.ASN1ObjectIdentifier = [2, 16, 840, 1, 101, 3, 4, 2, 3]
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
enum AlgorithmIdentifier {
|
enum AlgorithmIdentifier {
|
||||||
static let idEcPublicKey: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10_045, 2, 1]
|
static let idEcPublicKey: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10_045, 2, 1]
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
enum NameAttributes {
|
enum NameAttributes {
|
||||||
static let name: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 41]
|
static let name: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 41]
|
||||||
static let surname: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 4]
|
static let surname: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 4]
|
||||||
@@ -198,7 +186,6 @@ extension ASN1.ASN1ObjectIdentifier {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ArraySlice where Element == UInt8 {
|
extension ArraySlice where Element == UInt8 {
|
||||||
mutating fileprivate func readOIDSubidentifier() throws(CryptoKitMetaError) -> UInt {
|
mutating fileprivate func readOIDSubidentifier() throws(CryptoKitMetaError) -> UInt {
|
||||||
// In principle OID subidentifiers can be too large to fit into a UInt. We are choosing to not care about that
|
// In principle OID subidentifiers can be too large to fit into a UInt. We are choosing to not care about that
|
||||||
@@ -215,7 +202,6 @@ extension ArraySlice where Element == UInt8 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension UInt {
|
extension UInt {
|
||||||
fileprivate init<Bytes: Collection>(sevenBitBigEndianBytes bytes: Bytes) throws(CryptoKitMetaError) where Bytes.Element == UInt8 {
|
fileprivate init<Bytes: Collection>(sevenBitBigEndianBytes bytes: Bytes) throws(CryptoKitMetaError) where Bytes.Element == UInt8 {
|
||||||
// We need to know how many bytes we _need_ to store this "int".
|
// We need to know how many bytes we _need_ to store this "int".
|
||||||
@@ -234,4 +220,4 @@ extension UInt {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,21 +11,17 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
/// An ECDSA signature is laid out as follows:
|
/// An ECDSA signature is laid out as follows:
|
||||||
///
|
///
|
||||||
@@ -35,7 +31,6 @@ extension ASN1 {
|
|||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
/// This type is generic because our different backends want to use different bignum representations.
|
/// This type is generic because our different backends want to use different bignum representations.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct ECDSASignature<IntegerType: ASN1IntegerRepresentable>: ASN1ImplicitlyTaggable {
|
struct ECDSASignature<IntegerType: ASN1IntegerRepresentable>: ASN1ImplicitlyTaggable {
|
||||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||||
.sequence
|
.sequence
|
||||||
@@ -67,4 +62,4 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,24 +11,19 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
/// A PEM document is some data, and a discriminator type that is used to advertise the content.
|
/// A PEM document is some data, and a discriminator type that is used to advertise the content.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct PEMDocument {
|
struct PEMDocument {
|
||||||
private static let lineLength = 64
|
private static let lineLength = 64
|
||||||
|
|
||||||
@@ -97,7 +92,6 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Substring {
|
extension Substring {
|
||||||
fileprivate var pemStartDiscriminator: String? {
|
fileprivate var pemStartDiscriminator: String? {
|
||||||
return self.pemDiscriminator(expectedPrefix: "-----BEGIN ", expectedSuffix: "-----")
|
return self.pemDiscriminator(expectedPrefix: "-----BEGIN ", expectedSuffix: "-----")
|
||||||
@@ -127,4 +121,4 @@ extension Substring {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,20 +11,16 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
// A PKCS#8 private key is one of two formats, depending on the version:
|
// A PKCS#8 private key is one of two formats, depending on the version:
|
||||||
//
|
//
|
||||||
@@ -48,7 +44,6 @@ extension ASN1 {
|
|||||||
//
|
//
|
||||||
// The private key octet string contains (surprise!) a SEC1-encoded private key! So we recursively invoke the
|
// The private key octet string contains (surprise!) a SEC1-encoded private key! So we recursively invoke the
|
||||||
// ASN.1 parser and go again.
|
// ASN.1 parser and go again.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct PKCS8PrivateKey: ASN1ImplicitlyTaggable {
|
struct PKCS8PrivateKey: ASN1ImplicitlyTaggable {
|
||||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||||
return .sequence
|
return .sequence
|
||||||
@@ -110,4 +105,4 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,21 +11,17 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
// For private keys, SEC 1 uses:
|
// For private keys, SEC 1 uses:
|
||||||
//
|
//
|
||||||
@@ -35,7 +31,6 @@ extension ASN1 {
|
|||||||
// parameters [0] EXPLICIT ECDomainParameters OPTIONAL,
|
// parameters [0] EXPLICIT ECDomainParameters OPTIONAL,
|
||||||
// publicKey [1] EXPLICIT BIT STRING OPTIONAL
|
// publicKey [1] EXPLICIT BIT STRING OPTIONAL
|
||||||
// }
|
// }
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct SEC1PrivateKey: ASN1ImplicitlyTaggable {
|
struct SEC1PrivateKey: ASN1ImplicitlyTaggable {
|
||||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||||
return .sequence
|
return .sequence
|
||||||
@@ -118,4 +113,4 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,23 +11,18 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1 {
|
extension ASN1 {
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct SubjectPublicKeyInfo: ASN1ImplicitlyTaggable {
|
struct SubjectPublicKeyInfo: ASN1ImplicitlyTaggable {
|
||||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||||
.sequence
|
.sequence
|
||||||
@@ -70,7 +65,6 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct RFC5480AlgorithmIdentifier: ASN1ImplicitlyTaggable, Hashable {
|
struct RFC5480AlgorithmIdentifier: ASN1ImplicitlyTaggable, Hashable {
|
||||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||||
.sequence
|
.sequence
|
||||||
@@ -121,7 +115,6 @@ extension ASN1 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Algorithm Identifier Statics
|
// MARK: Algorithm Identifier Statics
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension ASN1.RFC5480AlgorithmIdentifier {
|
extension ASN1.RFC5480AlgorithmIdentifier {
|
||||||
static let ecdsaP256 = ASN1.RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey,
|
static let ecdsaP256 = ASN1.RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey,
|
||||||
parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp256r1))
|
parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp256r1))
|
||||||
@@ -133,4 +126,4 @@ extension ASN1.RFC5480AlgorithmIdentifier {
|
|||||||
parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp521r1))
|
parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp521r1))
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -97,11 +97,16 @@ add_library(Crypto
|
|||||||
"Signatures/Ed25519.swift"
|
"Signatures/Ed25519.swift"
|
||||||
"Signatures/MLDSA.swift"
|
"Signatures/MLDSA.swift"
|
||||||
"Signatures/Signature.swift"
|
"Signatures/Signature.swift"
|
||||||
|
"Util/ArraySpanHelpers.swift"
|
||||||
|
"Util/Backports.swift"
|
||||||
"Util/BoringSSL/CryptoKitErrors_boring.swift"
|
"Util/BoringSSL/CryptoKitErrors_boring.swift"
|
||||||
|
"Util/BoringSSL/InlineArray+withBytes_boring.swift"
|
||||||
"Util/BoringSSL/Optional+withUnsafeBytes_boring.swift"
|
"Util/BoringSSL/Optional+withUnsafeBytes_boring.swift"
|
||||||
"Util/BoringSSL/RNG_boring.swift"
|
"Util/BoringSSL/RNG_boring.swift"
|
||||||
"Util/BoringSSL/SafeCompare_boring.swift"
|
"Util/BoringSSL/SafeCompare_boring.swift"
|
||||||
"Util/BoringSSL/Zeroization_boring.swift"
|
"Util/BoringSSL/Zeroization_boring.swift"
|
||||||
|
"Util/BoringSSL/_CryptoModuleAnchor.swift"
|
||||||
|
"Util/Data+ArraySpan.swift"
|
||||||
"Util/PrettyBytes.swift"
|
"Util/PrettyBytes.swift"
|
||||||
"Util/SafeCompare.swift"
|
"Util/SafeCompare.swift"
|
||||||
"Util/SecureBytes.swift"
|
"Util/SecureBytes.swift"
|
||||||
@@ -111,14 +116,8 @@ add_library(Crypto
|
|||||||
target_compile_definitions(Crypto PRIVATE
|
target_compile_definitions(Crypto PRIVATE
|
||||||
"$<$<COMPILE_LANGUAGE:Swift>:CRYPTO_IN_SWIFTPM>")
|
"$<$<COMPILE_LANGUAGE:Swift>:CRYPTO_IN_SWIFTPM>")
|
||||||
|
|
||||||
if(NOT CMAKE_SYSTEM_NAME STREQUAL "Darwin")
|
|
||||||
target_compile_definitions(Crypto PRIVATE
|
|
||||||
"$<$<COMPILE_LANGUAGE:Swift>:CRYPTO_IN_SWIFTPM_FORCE_BUILD_API>")
|
|
||||||
endif()
|
|
||||||
|
|
||||||
target_include_directories(Crypto PRIVATE
|
target_include_directories(Crypto PRIVATE
|
||||||
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
|
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
|
||||||
$<TARGET_PROPERTY:CCryptoBoringSSLShims,INCLUDE_DIRECTORIES>
|
|
||||||
$<TARGET_PROPERTY:CryptoBoringWrapper,INCLUDE_DIRECTORIES>
|
$<TARGET_PROPERTY:CryptoBoringWrapper,INCLUDE_DIRECTORIES>
|
||||||
$<TARGET_PROPERTY:CXKCP,INCLUDE_DIRECTORIES>
|
$<TARGET_PROPERTY:CXKCP,INCLUDE_DIRECTORIES>
|
||||||
$<TARGET_PROPERTY:CXKCPShims,INCLUDE_DIRECTORIES>)
|
$<TARGET_PROPERTY:CXKCPShims,INCLUDE_DIRECTORIES>)
|
||||||
@@ -126,7 +125,6 @@ target_link_libraries(Crypto PUBLIC
|
|||||||
$<$<NOT:$<PLATFORM_ID:Darwin>>:dispatch>
|
$<$<NOT:$<PLATFORM_ID:Darwin>>:dispatch>
|
||||||
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
|
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
|
||||||
CCryptoBoringSSL
|
CCryptoBoringSSL
|
||||||
CCryptoBoringSSLShims
|
|
||||||
CryptoBoringWrapper
|
CryptoBoringWrapper
|
||||||
CXKCP
|
CXKCP
|
||||||
CXKCPShims)
|
CXKCPShims)
|
||||||
|
|||||||
@@ -11,11 +11,12 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
/// General cryptography errors used by CryptoKit.
|
/// General cryptography errors used by CryptoKit.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum CryptoKitError: Error {
|
public enum CryptoKitError: Error {
|
||||||
/// The key size is incorrect.
|
/// The key size is incorrect.
|
||||||
case incorrectKeySize
|
case incorrectKeySize
|
||||||
@@ -34,11 +35,10 @@ public enum CryptoKitError: Error {
|
|||||||
case invalidParameter
|
case invalidParameter
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension CryptoKitError: Equatable, Hashable {}
|
extension CryptoKitError: Equatable, Hashable {}
|
||||||
|
|
||||||
/// Errors from decoding ASN.1 content.
|
/// Errors from decoding ASN.1 content.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum CryptoKitASN1Error: Equatable, Error, Hashable {
|
public enum CryptoKitASN1Error: Equatable, Error, Hashable {
|
||||||
/// The ASN.1 tag for this field is invalid or unsupported.
|
/// The ASN.1 tag for this field is invalid or unsupported.
|
||||||
case invalidFieldIdentifier
|
case invalidFieldIdentifier
|
||||||
@@ -67,7 +67,6 @@ public enum CryptoKitASN1Error: Equatable, Error, Hashable {
|
|||||||
case invalidPEMDocument
|
case invalidPEMDocument
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
enum RSAPSSSPKIErrors: Error {
|
enum RSAPSSSPKIErrors: Error {
|
||||||
case invalidPSSOID
|
case invalidPSSOID
|
||||||
case missingParameters
|
case missingParameters
|
||||||
@@ -79,45 +78,36 @@ enum RSAPSSSPKIErrors: Error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#if hasFeature(Embedded)
|
#if hasFeature(Embedded)
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct RSAPSSSPKIError: Error {
|
public struct RSAPSSSPKIError: Error {
|
||||||
internal var error: RSAPSSSPKIErrors
|
internal var error: RSAPSSSPKIErrors
|
||||||
}
|
}
|
||||||
#else
|
#else
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct RSAPSSSPKIError: Error {
|
struct RSAPSSSPKIError: Error {
|
||||||
internal var error: RSAPSSSPKIErrors
|
internal var error: RSAPSSSPKIErrors
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if hasFeature(Embedded)
|
#if hasFeature(Embedded)
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum CryptoKitMetaError: Error {
|
public enum CryptoKitMetaError: Error {
|
||||||
case cryptoKitError(underlyingError: CryptoKitError)
|
case cryptoKitError(underlyingError: CryptoKitError)
|
||||||
case asn1Error(underlyingError: CryptoKitASN1Error)
|
case asn1Error(underlyingError: CryptoKitASN1Error)
|
||||||
case rsapssspkiError(underlyingError: RSAPSSSPKIError)
|
case rsapssspkiError(underlyingError: RSAPSSSPKIError)
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal func error(_ error: CryptoKitError) -> CryptoKitMetaError {
|
internal func error(_ error: CryptoKitError) -> CryptoKitMetaError {
|
||||||
.cryptoKitError(underlyingError: error)
|
.cryptoKitError(underlyingError: error)
|
||||||
}
|
}
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal func error(_ error: CryptoKitASN1Error) -> CryptoKitMetaError {
|
internal func error(_ error: CryptoKitASN1Error) -> CryptoKitMetaError {
|
||||||
.asn1Error(underlyingError: error)
|
.asn1Error(underlyingError: error)
|
||||||
}
|
}
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal func error(_ error: RSAPSSSPKIErrors) -> CryptoKitMetaError {
|
internal func error(_ error: RSAPSSSPKIErrors) -> CryptoKitMetaError {
|
||||||
.rsapssspkiError(underlyingError: RSAPSSSPKIError(error: error))
|
.rsapssspkiError(underlyingError: RSAPSSSPKIError(error: error))
|
||||||
}
|
}
|
||||||
#else /* !hasFeature(Embedded) */
|
#else
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public typealias CryptoKitMetaError = any Error
|
public typealias CryptoKitMetaError = any Error
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal func error(_ error: CryptoKitError) -> CryptoKitError { error }
|
internal func error(_ error: CryptoKitError) -> CryptoKitError { error }
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal func error(_ error: CryptoKitASN1Error) -> CryptoKitASN1Error { error }
|
internal func error(_ error: CryptoKitASN1Error) -> CryptoKitASN1Error { error }
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal func error(_ error: RSAPSSSPKIErrors) -> RSAPSSSPKIErrors { error }
|
internal func error(_ error: RSAPSSSPKIErrors) -> RSAPSSSPKIErrors { error }
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
|||||||
@@ -11,10 +11,14 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
#if hasFeature(SourceWarningControl)
|
||||||
|
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||||
|
#else
|
||||||
@_implementationOnly import CCryptoBoringSSL
|
@_implementationOnly import CCryptoBoringSSL
|
||||||
|
#endif
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||||
protocol HashFunctionImplementationDetails: HashFunction where Digest: DigestPrivate {}
|
protocol HashFunctionImplementationDetails: HashFunction where Digest: DigestPrivate {}
|
||||||
@@ -173,10 +177,10 @@ private final class DigestContext<H: BoringSSLBackedHashFunction> {
|
|||||||
private var context: H.Context
|
private var context: H.Context
|
||||||
|
|
||||||
init() {
|
init() {
|
||||||
guard let contex = H.initialize() else {
|
guard let context = H.initialize() else {
|
||||||
preconditionFailure("Unable to initialize digest state")
|
preconditionFailure("Unable to initialize digest state")
|
||||||
}
|
}
|
||||||
self.context = contex
|
self.context = context
|
||||||
}
|
}
|
||||||
|
|
||||||
init(copying original: DigestContext) {
|
init(copying original: DigestContext) {
|
||||||
@@ -202,7 +206,7 @@ private final class DigestContext<H: BoringSSLBackedHashFunction> {
|
|||||||
preconditionFailure("Unable to finalize digest state")
|
preconditionFailure("Unable to finalize digest state")
|
||||||
}
|
}
|
||||||
// We force unwrap here because if the digest size is wrong it's an internal error.
|
// We force unwrap here because if the digest size is wrong it's an internal error.
|
||||||
return H.Digest(bufferPointer: UnsafeRawBufferPointer(digestPointer))!
|
return H.Digest(copying: digestPointer.bytes)!
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -210,4 +214,4 @@ private final class DigestContext<H: BoringSSLBackedHashFunction> {
|
|||||||
withUnsafeMutablePointer(to: &self.context) { $0.zeroize() }
|
withUnsafeMutablePointer(to: &self.context) { $0.zeroize() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,60 +11,46 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
#if hasFeature(Embedded)
|
#if hasFeature(Embedded)
|
||||||
/// A type that represents the output of a hash.
|
/// A type that represents the output of a hash.
|
||||||
@preconcurrency
|
@preconcurrency
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public protocol Digest: Hashable, Sendable, ContiguousBytes, Sequence where Element == UInt8 {
|
public protocol Digest: Hashable, Sendable, ContiguousBytes, Sequence where Element == UInt8 {
|
||||||
/// The number of bytes in the digest.
|
/// The number of bytes in the digest.
|
||||||
static var byteCount: Int { get }
|
static var byteCount: Int { get }
|
||||||
}
|
}
|
||||||
#else // hasFeature(Embedded)
|
#else
|
||||||
/// A type that represents the output of a hash.
|
/// A type that represents the output of a hash.
|
||||||
@preconcurrency
|
@preconcurrency
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public protocol Digest: Hashable, Sendable, ContiguousBytes, CustomStringConvertible, Sequence where Element == UInt8 {
|
public protocol Digest: Hashable, Sendable, ContiguousBytes, CustomStringConvertible, Sequence where Element == UInt8 {
|
||||||
/// The number of bytes in the digest.
|
/// The number of bytes in the digest.
|
||||||
static var byteCount: Int { get }
|
static var byteCount: Int { get }
|
||||||
}
|
}
|
||||||
#endif // hasFeature(Embedded)
|
#endif // hasFeature(Embedded)
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
protocol DigestPrivate: Digest {
|
protocol DigestPrivate: Digest {
|
||||||
init?(bufferPointer: UnsafeRawBufferPointer)
|
init?(initializingWith body: (inout OutputRawSpan) -> ())
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension DigestPrivate {
|
extension DigestPrivate {
|
||||||
@inlinable
|
@inlinable
|
||||||
init?(bytes: [UInt8]) {
|
init?(copying bytes: RawSpan) {
|
||||||
let some = bytes.withUnsafeBytes { bufferPointer in
|
self.init() {
|
||||||
return Self(bufferPointer: bufferPointer)
|
$0.append(contentsOf: bytes)
|
||||||
}
|
|
||||||
|
|
||||||
if some != nil {
|
|
||||||
self = some!
|
|
||||||
} else {
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Digest {
|
extension Digest {
|
||||||
public func makeIterator() -> Array<UInt8>.Iterator {
|
public func makeIterator() -> Array<UInt8>.Iterator {
|
||||||
self.withUnsafeBytes({ (buffPtr) in
|
self.withUnsafeBytes({ (buffPtr) in
|
||||||
@@ -74,7 +60,6 @@ extension Digest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// We want to implement constant-time comparison for digests.
|
// We want to implement constant-time comparison for digests.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Digest {
|
extension Digest {
|
||||||
/// Determines whether two digests are equal.
|
/// Determines whether two digests are equal.
|
||||||
///
|
///
|
||||||
@@ -107,7 +92,6 @@ extension Digest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#if !hasFeature(Embedded)
|
#if !hasFeature(Embedded)
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Digest {
|
extension Digest {
|
||||||
public var description: String {
|
public var description: String {
|
||||||
return "\(Self.self): \(Array(self).hexString)"
|
return "\(Self.self): \(Array(self).hexString)"
|
||||||
@@ -115,4 +99,4 @@ extension Digest {
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,7 +11,8 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
// MARK: - Generated file, do NOT edit
|
// MARK: - Generated file, do NOT edit
|
||||||
@@ -22,18 +23,18 @@
|
|||||||
|
|
||||||
// MARK: - SHA256Digest + DigestPrivate
|
// MARK: - SHA256Digest + DigestPrivate
|
||||||
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 256-bit digest.
|
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 256-bit digest.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SHA256Digest: DigestPrivate {
|
public struct SHA256Digest: DigestPrivate {
|
||||||
let bytes: (UInt64, UInt64, UInt64, UInt64)
|
let bytes: (UInt64, UInt64, UInt64, UInt64)
|
||||||
|
|
||||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
|
||||||
guard bufferPointer.count == 32 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
||||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||||
targetPtr.copyMemory(from: bufferPointer)
|
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
|
||||||
|
body(&output)
|
||||||
|
return output.finalize(for: targetPtr)
|
||||||
|
}
|
||||||
|
guard initialized == 32 else {
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
self.bytes = bytes
|
self.bytes = bytes
|
||||||
}
|
}
|
||||||
@@ -105,18 +106,18 @@ public struct SHA256Digest: DigestPrivate {
|
|||||||
|
|
||||||
// MARK: - SHA384Digest + DigestPrivate
|
// MARK: - SHA384Digest + DigestPrivate
|
||||||
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 384-bit digest.
|
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 384-bit digest.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SHA384Digest: DigestPrivate {
|
public struct SHA384Digest: DigestPrivate {
|
||||||
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
|
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
|
||||||
|
|
||||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
|
||||||
guard bufferPointer.count == 48 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
||||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||||
targetPtr.copyMemory(from: bufferPointer)
|
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
|
||||||
|
body(&output)
|
||||||
|
return output.finalize(for: targetPtr)
|
||||||
|
}
|
||||||
|
guard initialized == 48 else {
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
self.bytes = bytes
|
self.bytes = bytes
|
||||||
}
|
}
|
||||||
@@ -190,18 +191,18 @@ public struct SHA384Digest: DigestPrivate {
|
|||||||
|
|
||||||
// MARK: - SHA512Digest + DigestPrivate
|
// MARK: - SHA512Digest + DigestPrivate
|
||||||
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 512-bit digest.
|
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 512-bit digest.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SHA512Digest: DigestPrivate {
|
public struct SHA512Digest: DigestPrivate {
|
||||||
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
|
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
|
||||||
|
|
||||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
|
||||||
guard bufferPointer.count == 64 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
||||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||||
targetPtr.copyMemory(from: bufferPointer)
|
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
|
||||||
|
body(&output)
|
||||||
|
return output.finalize(for: targetPtr)
|
||||||
|
}
|
||||||
|
guard initialized == 64 else {
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
self.bytes = bytes
|
self.bytes = bytes
|
||||||
}
|
}
|
||||||
@@ -274,22 +275,21 @@ public struct SHA512Digest: DigestPrivate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Insecure {
|
extension Insecure {
|
||||||
// MARK: - SHA1Digest + DigestPrivate
|
// MARK: - SHA1Digest + DigestPrivate
|
||||||
/// The output of a SHA1 hash.
|
/// The output of a SHA1 hash.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SHA1Digest: DigestPrivate {
|
public struct SHA1Digest: DigestPrivate {
|
||||||
let bytes: (UInt64, UInt64, UInt64)
|
let bytes: (UInt64, UInt64, UInt64)
|
||||||
|
|
||||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
|
||||||
guard bufferPointer.count == 20 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var bytes = (UInt64(0), UInt64(0), UInt64(0))
|
var bytes = (UInt64(0), UInt64(0), UInt64(0))
|
||||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||||
targetPtr.copyMemory(from: bufferPointer)
|
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
|
||||||
|
body(&output)
|
||||||
|
return output.finalize(for: targetPtr)
|
||||||
|
}
|
||||||
|
guard initialized == 20 else {
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
self.bytes = bytes
|
self.bytes = bytes
|
||||||
}
|
}
|
||||||
@@ -357,22 +357,21 @@ public struct SHA1Digest: DigestPrivate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Insecure {
|
extension Insecure {
|
||||||
// MARK: - MD5Digest + DigestPrivate
|
// MARK: - MD5Digest + DigestPrivate
|
||||||
/// The output of a MD5 hash.
|
/// The output of a MD5 hash.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct MD5Digest: DigestPrivate {
|
public struct MD5Digest: DigestPrivate {
|
||||||
let bytes: (UInt64, UInt64)
|
let bytes: (UInt64, UInt64)
|
||||||
|
|
||||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
|
||||||
guard bufferPointer.count == 16 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var bytes = (UInt64(0), UInt64(0))
|
var bytes = (UInt64(0), UInt64(0))
|
||||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||||
targetPtr.copyMemory(from: bufferPointer)
|
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
|
||||||
|
body(&output)
|
||||||
|
return output.finalize(for: targetPtr)
|
||||||
|
}
|
||||||
|
guard initialized == 16 else {
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
self.bytes = bytes
|
self.bytes = bytes
|
||||||
}
|
}
|
||||||
@@ -445,18 +444,18 @@ public struct MD5Digest: DigestPrivate {
|
|||||||
|
|
||||||
// MARK: - SHA3_256Digest + DigestPrivate
|
// MARK: - SHA3_256Digest + DigestPrivate
|
||||||
/// The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a 256-bit digest.
|
/// The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a 256-bit digest.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SHA3_256Digest: DigestPrivate {
|
public struct SHA3_256Digest: DigestPrivate {
|
||||||
let bytes: (UInt64, UInt64, UInt64, UInt64)
|
let bytes: (UInt64, UInt64, UInt64, UInt64)
|
||||||
|
|
||||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
|
||||||
guard bufferPointer.count == 32 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
||||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||||
targetPtr.copyMemory(from: bufferPointer)
|
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
|
||||||
|
body(&output)
|
||||||
|
return output.finalize(for: targetPtr)
|
||||||
|
}
|
||||||
|
guard initialized == 32 else {
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
self.bytes = bytes
|
self.bytes = bytes
|
||||||
}
|
}
|
||||||
@@ -526,18 +525,18 @@ public struct SHA3_256Digest: DigestPrivate {
|
|||||||
}
|
}
|
||||||
// MARK: - SHA3_384Digest + DigestPrivate
|
// MARK: - SHA3_384Digest + DigestPrivate
|
||||||
/// The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a 384-bit digest.
|
/// The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a 384-bit digest.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SHA3_384Digest: DigestPrivate {
|
public struct SHA3_384Digest: DigestPrivate {
|
||||||
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
|
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
|
||||||
|
|
||||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
|
||||||
guard bufferPointer.count == 48 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
||||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||||
targetPtr.copyMemory(from: bufferPointer)
|
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
|
||||||
|
body(&output)
|
||||||
|
return output.finalize(for: targetPtr)
|
||||||
|
}
|
||||||
|
guard initialized == 48 else {
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
self.bytes = bytes
|
self.bytes = bytes
|
||||||
}
|
}
|
||||||
@@ -609,18 +608,18 @@ public struct SHA3_384Digest: DigestPrivate {
|
|||||||
}
|
}
|
||||||
// MARK: - SHA3_512Digest + DigestPrivate
|
// MARK: - SHA3_512Digest + DigestPrivate
|
||||||
/// The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a 512-bit digest.
|
/// The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a 512-bit digest.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SHA3_512Digest: DigestPrivate {
|
public struct SHA3_512Digest: DigestPrivate {
|
||||||
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
|
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
|
||||||
|
|
||||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
|
||||||
guard bufferPointer.count == 64 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
||||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||||
targetPtr.copyMemory(from: bufferPointer)
|
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
|
||||||
|
body(&output)
|
||||||
|
return output.finalize(for: targetPtr)
|
||||||
|
}
|
||||||
|
guard initialized == 64 else {
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
self.bytes = bytes
|
self.bytes = bytes
|
||||||
}
|
}
|
||||||
@@ -693,4 +692,4 @@ public struct SHA3_512Digest: DigestPrivate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // !CRYPTOKIT_IN_SEP
|
#endif // !CRYPTOKIT_IN_SEP
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -1,237 +0,0 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
|
||||||
//
|
|
||||||
// This source file is part of the SwiftCrypto open source project
|
|
||||||
//
|
|
||||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
|
||||||
// Licensed under Apache License v2.0
|
|
||||||
//
|
|
||||||
// See LICENSE.txt for license information
|
|
||||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
|
||||||
//
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
//
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
@_exported import CryptoKit
|
|
||||||
#else
|
|
||||||
// MARK: - Generated file, do NOT edit
|
|
||||||
// any edits of this file WILL be overwritten and thus discarded
|
|
||||||
// see section `gyb` in `README` for details.
|
|
||||||
|
|
||||||
%{
|
|
||||||
digests_and_length = [{"name": "SHA256", "count": 32},{"name": "SHA384","count":48},{"name":"SHA512", "count": 64}]
|
|
||||||
if "NO_INSECURE_DIGEST" in globals():
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
digests_and_length.extend([{"name":"SHA1", "count":20, "prefix":"Insecure "},{"name":"MD5", "count":16, "prefix":"Insecure "}])
|
|
||||||
}%
|
|
||||||
|
|
||||||
% for HF in digests_and_length:
|
|
||||||
%{
|
|
||||||
name = HF["name"]
|
|
||||||
byteCount = HF["count"]
|
|
||||||
wordsCount = (byteCount*8)//64 + (0 if ((byteCount*8)%64) == 0 else 1)
|
|
||||||
}%
|
|
||||||
%{
|
|
||||||
if "prefix" in HF.keys():
|
|
||||||
protocol_prefix = ""
|
|
||||||
protocol_prefix = protocol_prefix + "extension " + HF["prefix"] + "{"
|
|
||||||
protocol_suffix = "}"
|
|
||||||
parent = HF["prefix"].strip() + "/" + name
|
|
||||||
else:
|
|
||||||
protocol_prefix = ""
|
|
||||||
protocol_suffix = ""
|
|
||||||
parent = name
|
|
||||||
|
|
||||||
if name == "SHA1" or name == "MD5":
|
|
||||||
abstract = "The output of a " + name + " hash."
|
|
||||||
else:
|
|
||||||
abstract = "The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a " + name[-3:] + "-bit digest."
|
|
||||||
}%
|
|
||||||
${protocol_prefix}
|
|
||||||
// MARK: - ${name}Digest + DigestPrivate
|
|
||||||
/// ${abstract}
|
|
||||||
public struct ${name}Digest: DigestPrivate {
|
|
||||||
let bytes: (${(wordsCount-1)*"UInt64, "+"UInt64"})
|
|
||||||
|
|
||||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
|
||||||
guard bufferPointer.count == ${byteCount} else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var bytes = (${(wordsCount-1)*"UInt64(0), "+"UInt64(0)"})
|
|
||||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
|
||||||
targetPtr.copyMemory(from: bufferPointer)
|
|
||||||
}
|
|
||||||
self.bytes = bytes
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The number of bytes in the digest.
|
|
||||||
public static var byteCount: Int {
|
|
||||||
return ${byteCount}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Invokes the given closure with a buffer pointer covering the raw bytes of
|
|
||||||
/// the digest.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - body: A closure that takes a raw buffer pointer to the bytes of the digest
|
|
||||||
/// and returns the digest.
|
|
||||||
///
|
|
||||||
/// - Returns: The digest, as returned from the body closure.
|
|
||||||
#if !hasFeature(Embedded)
|
|
||||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
|
||||||
return try Swift.withUnsafeBytes(of: bytes) {
|
|
||||||
let boundsCheckedPtr = UnsafeRawBufferPointer(start: $0.baseAddress,
|
|
||||||
count: Self.byteCount)
|
|
||||||
return try body(boundsCheckedPtr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
public func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
|
|
||||||
return try Swift.withUnsafeBytes(of: bytes) { ptr throws(E) -> R in
|
|
||||||
let boundsCheckedPtr = UnsafeRawBufferPointer(start: ptr.baseAddress,
|
|
||||||
count: Self.byteCount)
|
|
||||||
return try body(boundsCheckedPtr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
private func toArray() -> ArraySlice<UInt8> {
|
|
||||||
var array = [UInt8]()
|
|
||||||
array.appendByte(bytes.0)
|
|
||||||
% for index in range(wordsCount-1):
|
|
||||||
array.appendByte(bytes.${index+1})
|
|
||||||
% end
|
|
||||||
return array.prefix(${name}Digest.byteCount)
|
|
||||||
}
|
|
||||||
|
|
||||||
#if !hasFeature(Embedded)
|
|
||||||
/// A human-readable description of the digest.
|
|
||||||
public var description: String {
|
|
||||||
return "\("${name}") digest: \(toArray().hexString)"
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/// Hashes the essential components of the digest by feeding them into the
|
|
||||||
/// given hash function.
|
|
||||||
///
|
|
||||||
/// This method is part of the digest’s conformance to Swift standard library’s
|
|
||||||
/// <doc://com.apple.documentation/documentation/swift/hashable> protocol, making
|
|
||||||
/// it possible to compare digests. Don’t confuse that hashing with the
|
|
||||||
/// cryptographically secure hashing that you use to create the digest in the
|
|
||||||
/// first place by, for example, calling ``${parent}/hash(data:)``.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - hasher: The hash function to use when combining the components of
|
|
||||||
/// the digest.
|
|
||||||
public func hash(into hasher: inout Hasher) {
|
|
||||||
self.withUnsafeBytes { hasher.combine(bytes: $0) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
${protocol_suffix}
|
|
||||||
% end
|
|
||||||
|
|
||||||
|
|
||||||
#if !CRYPTOKIT_IN_SEP
|
|
||||||
%{
|
|
||||||
digests_and_length = [
|
|
||||||
{"name": "SHA3_256", "count": 32},
|
|
||||||
{"name": "SHA3_384", "count": 48},
|
|
||||||
{"name": "SHA3_512", "count": 64}
|
|
||||||
]
|
|
||||||
}%
|
|
||||||
|
|
||||||
% for HF in digests_and_length:
|
|
||||||
%{
|
|
||||||
name = HF["name"]
|
|
||||||
byteCount = HF["count"]
|
|
||||||
wordsCount = (byteCount*8)//64 + (0 if ((byteCount*8)%64) == 0 else 1)
|
|
||||||
}%
|
|
||||||
%{
|
|
||||||
parent = name
|
|
||||||
abstract = "The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a " + name[-3:] + "-bit digest."
|
|
||||||
}%
|
|
||||||
// MARK: - ${name}Digest + DigestPrivate
|
|
||||||
/// ${abstract}
|
|
||||||
public struct ${name}Digest: DigestPrivate {
|
|
||||||
let bytes: (${(wordsCount-1)*"UInt64, "+"UInt64"})
|
|
||||||
|
|
||||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
|
||||||
guard bufferPointer.count == ${byteCount} else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var bytes = (${(wordsCount-1)*"UInt64(0), "+"UInt64(0)"})
|
|
||||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
|
||||||
targetPtr.copyMemory(from: bufferPointer)
|
|
||||||
}
|
|
||||||
self.bytes = bytes
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The number of bytes in the digest.
|
|
||||||
public static var byteCount: Int {
|
|
||||||
return ${byteCount}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Invokes the given closure with a buffer pointer covering the raw bytes of
|
|
||||||
/// the digest.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - body: A closure that takes a raw buffer pointer to the bytes of the digest
|
|
||||||
/// and returns the digest.
|
|
||||||
///
|
|
||||||
/// - Returns: The digest, as returned from the body closure.
|
|
||||||
#if !hasFeature(Embedded)
|
|
||||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
|
||||||
return try Swift.withUnsafeBytes(of: bytes) {
|
|
||||||
let boundsCheckedPtr = UnsafeRawBufferPointer(start: $0.baseAddress,
|
|
||||||
count: Self.byteCount)
|
|
||||||
return try body(boundsCheckedPtr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
public func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
|
|
||||||
return try Swift.withUnsafeBytes(of: bytes) { ptr throws(E) -> R in
|
|
||||||
let boundsCheckedPtr = UnsafeRawBufferPointer(start: ptr.baseAddress,
|
|
||||||
count: Self.byteCount)
|
|
||||||
return try body(boundsCheckedPtr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
private func toArray() -> ArraySlice<UInt8> {
|
|
||||||
var array = [UInt8]()
|
|
||||||
array.appendByte(bytes.0)
|
|
||||||
% for index in range(wordsCount-1):
|
|
||||||
array.appendByte(bytes.${index+1})
|
|
||||||
% end
|
|
||||||
return array.prefix(upTo: ${name}Digest.byteCount)
|
|
||||||
}
|
|
||||||
|
|
||||||
#if !hasFeature(Embedded)
|
|
||||||
/// A human-readable description of the digest.
|
|
||||||
public var description: String {
|
|
||||||
return "\("${name}") digest: \(toArray().hexString)"
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/// Hashes the essential components of the digest by feeding them into the
|
|
||||||
/// given hash function.
|
|
||||||
///
|
|
||||||
/// This method is part of the digest’s conformance to Swift standard library’s
|
|
||||||
/// <doc://com.apple.documentation/documentation/swift/hashable> protocol, making
|
|
||||||
/// it possible to compare digests. Don’t confuse that hashing with the
|
|
||||||
/// cryptographically secure hashing that you use to create the digest in the
|
|
||||||
/// first place by, for example, calling ``${parent}/hash(data:)``.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - hasher: The hash function to use when combining the components of
|
|
||||||
/// the digest.
|
|
||||||
public func hash(into hasher: inout Hasher) {
|
|
||||||
self.withUnsafeBytes { hasher.combine(bytes: $0) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
% end
|
|
||||||
#endif // !CRYPTOKIT_IN_SEP
|
|
||||||
#endif // Linux or !SwiftPM
|
|
||||||
@@ -11,30 +11,18 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias DigestImpl = CoreCryptoDigestImpl
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias DigestImplSHA3 = CoreCryptoDigestImpl
|
|
||||||
#else
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias DigestImpl = OpenSSLDigestImpl
|
typealias DigestImpl = OpenSSLDigestImpl
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias DigestImplSHA3 = XKCPDigestImpl
|
typealias DigestImplSHA3 = XKCPDigestImpl
|
||||||
#endif
|
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
/// A type that performs cryptographically secure hashing.
|
/// A type that performs cryptographically secure hashing.
|
||||||
///
|
///
|
||||||
@@ -55,16 +43,10 @@ public import Foundation
|
|||||||
/// incorporate a secret cryptographic key into the digest computation. Only a
|
/// incorporate a secret cryptographic key into the digest computation. Only a
|
||||||
/// user that has the key can generate a valid MAC.
|
/// user that has the key can generate a valid MAC.
|
||||||
@preconcurrency
|
@preconcurrency
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public protocol HashFunction: Sendable {
|
public protocol HashFunction: Sendable {
|
||||||
/// The number of bytes that represents the hash function’s internal state.
|
/// The number of bytes that represents the hash function’s internal state.
|
||||||
static var blockByteCount: Int { get }
|
static var blockByteCount: Int { get }
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
/// The type of the digest returned by the hash function.
|
|
||||||
associatedtype Digest: CryptoKit.Digest
|
|
||||||
#else
|
|
||||||
associatedtype Digest: Crypto.Digest
|
associatedtype Digest: Crypto.Digest
|
||||||
#endif
|
|
||||||
|
|
||||||
/// Creates a hash function.
|
/// Creates a hash function.
|
||||||
///
|
///
|
||||||
@@ -110,7 +92,15 @@ public protocol HashFunction: Sendable {
|
|||||||
func finalize() -> Digest
|
func finalize() -> Digest
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
extension HashFunction {
|
||||||
|
@inlinable
|
||||||
|
public mutating func update(bytes: RawSpan) {
|
||||||
|
bytes.withUnsafeBytes {
|
||||||
|
self.update(bufferPointer: $0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
extension HashFunction {
|
extension HashFunction {
|
||||||
/// Computes a digest of the buffer.
|
/// Computes a digest of the buffer.
|
||||||
///
|
///
|
||||||
@@ -123,6 +113,18 @@ extension HashFunction {
|
|||||||
hasher.update(bufferPointer: bufferPointer)
|
hasher.update(bufferPointer: bufferPointer)
|
||||||
return hasher.finalize()
|
return hasher.finalize()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Computes a digest of a span of bytes.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - bytes: The bytes to be hashed.
|
||||||
|
/// - Returns: The computed digest.
|
||||||
|
@inlinable
|
||||||
|
public static func hash(bytes: RawSpan) -> Digest {
|
||||||
|
var hasher = Self()
|
||||||
|
hasher.update(bytes: bytes)
|
||||||
|
return hasher.finalize()
|
||||||
|
}
|
||||||
|
|
||||||
/// Computes the digest of the bytes in the given data instance and
|
/// Computes the digest of the bytes in the given data instance and
|
||||||
/// returns the computed digest.
|
/// returns the computed digest.
|
||||||
@@ -171,4 +173,4 @@ extension HashFunction {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,7 +11,8 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
||||||
@@ -26,7 +27,6 @@
|
|||||||
/// in memory, you can compute the digest iteratively by creating a new hash
|
/// in memory, you can compute the digest iteratively by creating a new hash
|
||||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||||
/// data, and then calling the ``finalize()`` method to get the result.
|
/// data, and then calling the ``finalize()`` method to get the result.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public typealias SHA2_256 = SHA256
|
public typealias SHA2_256 = SHA256
|
||||||
|
|
||||||
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
||||||
@@ -41,7 +41,6 @@ public typealias SHA2_256 = SHA256
|
|||||||
/// in memory, you can compute the digest iteratively by creating a new hash
|
/// in memory, you can compute the digest iteratively by creating a new hash
|
||||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||||
/// data, and then calling the ``finalize()`` method to get the result.
|
/// data, and then calling the ``finalize()`` method to get the result.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SHA256: HashFunctionImplementationDetails, Sendable {
|
public struct SHA256: HashFunctionImplementationDetails, Sendable {
|
||||||
/// The number of bytes that represents the hash function’s internal state.
|
/// The number of bytes that represents the hash function’s internal state.
|
||||||
public static let blockByteCount: Int = 64
|
public static let blockByteCount: Int = 64
|
||||||
@@ -113,7 +112,6 @@ public struct SHA256: HashFunctionImplementationDetails, Sendable {
|
|||||||
/// in memory, you can compute the digest iteratively by creating a new hash
|
/// in memory, you can compute the digest iteratively by creating a new hash
|
||||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||||
/// data, and then calling the ``finalize()`` method to get the result.
|
/// data, and then calling the ``finalize()`` method to get the result.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public typealias SHA2_384 = SHA384
|
public typealias SHA2_384 = SHA384
|
||||||
|
|
||||||
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
||||||
@@ -128,7 +126,6 @@ public typealias SHA2_384 = SHA384
|
|||||||
/// in memory, you can compute the digest iteratively by creating a new hash
|
/// in memory, you can compute the digest iteratively by creating a new hash
|
||||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||||
/// data, and then calling the ``finalize()`` method to get the result.
|
/// data, and then calling the ``finalize()`` method to get the result.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SHA384: HashFunctionImplementationDetails, Sendable {
|
public struct SHA384: HashFunctionImplementationDetails, Sendable {
|
||||||
/// The number of bytes that represents the hash function’s internal state.
|
/// The number of bytes that represents the hash function’s internal state.
|
||||||
public static let blockByteCount: Int = 128
|
public static let blockByteCount: Int = 128
|
||||||
@@ -201,7 +198,6 @@ public struct SHA384: HashFunctionImplementationDetails, Sendable {
|
|||||||
/// in memory, you can compute the digest iteratively by creating a new hash
|
/// in memory, you can compute the digest iteratively by creating a new hash
|
||||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||||
/// data, and then calling the ``finalize()`` method to get the result.
|
/// data, and then calling the ``finalize()`` method to get the result.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public typealias SHA2_512 = SHA512
|
public typealias SHA2_512 = SHA512
|
||||||
|
|
||||||
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
||||||
@@ -216,7 +212,6 @@ public typealias SHA2_512 = SHA512
|
|||||||
/// in memory, you can compute the digest iteratively by creating a new hash
|
/// in memory, you can compute the digest iteratively by creating a new hash
|
||||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||||
/// data, and then calling the ``finalize()`` method to get the result.
|
/// data, and then calling the ``finalize()`` method to get the result.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SHA512: HashFunctionImplementationDetails, Sendable {
|
public struct SHA512: HashFunctionImplementationDetails, Sendable {
|
||||||
/// The number of bytes that represents the hash function’s internal state.
|
/// The number of bytes that represents the hash function’s internal state.
|
||||||
public static let blockByteCount: Int = 128
|
public static let blockByteCount: Int = 128
|
||||||
@@ -276,4 +271,4 @@ public struct SHA512: HashFunctionImplementationDetails, Sendable {
|
|||||||
return impl.finalize()
|
return impl.finalize()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,7 +11,8 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
#if !CRYPTOKIT_IN_SEP
|
#if !CRYPTOKIT_IN_SEP
|
||||||
@@ -26,7 +27,6 @@
|
|||||||
/// applications can compute the digest iteratively by creating a new hash
|
/// applications can compute the digest iteratively by creating a new hash
|
||||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||||
/// data, and then calling the ``finalize()`` method to get the result.
|
/// data, and then calling the ``finalize()`` method to get the result.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SHA3_256: HashFunctionImplementationDetails, Sendable {
|
public struct SHA3_256: HashFunctionImplementationDetails, Sendable {
|
||||||
/// The number of bytes that represents the hash function’s internal state.
|
/// The number of bytes that represents the hash function’s internal state.
|
||||||
public static let blockByteCount: Int = 136
|
public static let blockByteCount: Int = 136
|
||||||
@@ -97,7 +97,6 @@ public struct SHA3_256: HashFunctionImplementationDetails, Sendable {
|
|||||||
/// applications can compute the digest iteratively by creating a new hash
|
/// applications can compute the digest iteratively by creating a new hash
|
||||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||||
/// data, and then calling the ``finalize()`` method to get the result.
|
/// data, and then calling the ``finalize()`` method to get the result.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SHA3_384: HashFunctionImplementationDetails, Sendable {
|
public struct SHA3_384: HashFunctionImplementationDetails, Sendable {
|
||||||
/// The number of bytes that represents the hash function’s internal state.
|
/// The number of bytes that represents the hash function’s internal state.
|
||||||
public static let blockByteCount: Int = 104
|
public static let blockByteCount: Int = 104
|
||||||
@@ -168,7 +167,6 @@ public struct SHA3_384: HashFunctionImplementationDetails, Sendable {
|
|||||||
/// applications can compute the digest iteratively by creating a new hash
|
/// applications can compute the digest iteratively by creating a new hash
|
||||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||||
/// data, and then calling the ``finalize()`` method to get the result.
|
/// data, and then calling the ``finalize()`` method to get the result.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SHA3_512: HashFunctionImplementationDetails, Sendable {
|
public struct SHA3_512: HashFunctionImplementationDetails, Sendable {
|
||||||
/// The number of bytes that represents the hash function’s internal state.
|
/// The number of bytes that represents the hash function’s internal state.
|
||||||
public static let blockByteCount: Int = 72
|
public static let blockByteCount: Int = 72
|
||||||
@@ -228,4 +226,4 @@ public struct SHA3_512: HashFunctionImplementationDetails, Sendable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // !CRYPTOKIT_IN_SEP
|
#endif // !CRYPTOKIT_IN_SEP
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,11 +11,16 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
#if hasFeature(SourceWarningControl)
|
||||||
|
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CXKCP
|
||||||
|
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CXKCPShims
|
||||||
|
#else
|
||||||
@_implementationOnly import CXKCP
|
@_implementationOnly import CXKCP
|
||||||
@_implementationOnly import CXKCPShims
|
@_implementationOnly import CXKCPShims
|
||||||
|
#endif
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||||
protocol XKCPBackedHashFunction: HashFunctionImplementationDetails {
|
protocol XKCPBackedHashFunction: HashFunctionImplementationDetails {
|
||||||
@@ -149,7 +154,7 @@ private final class XKCPDigestContext<H: XKCPBackedHashFunction> {
|
|||||||
preconditionFailure("Unable to finalize digest state")
|
preconditionFailure("Unable to finalize digest state")
|
||||||
}
|
}
|
||||||
// We force unwrap here because if the digest size is wrong it's an internal error.
|
// We force unwrap here because if the digest size is wrong it's an internal error.
|
||||||
return H.Digest(bufferPointer: UnsafeRawBufferPointer(digestPointer))!
|
return H.Digest(copying: digestPointer.bytes)!
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -157,4 +162,4 @@ private final class XKCPDigestContext<H: XKCPBackedHashFunction> {
|
|||||||
withUnsafeMutablePointer(to: &self.context) { $0.zeroize() }
|
withUnsafeMutablePointer(to: &self.context) { $0.zeroize() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,25 +11,20 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension HPKE {
|
extension HPKE {
|
||||||
/// The authenticated encryption with associated data (AEAD) algorithms to use in HPKE.
|
/// The authenticated encryption with associated data (AEAD) algorithms to use in HPKE.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum AEAD: CaseIterable, Hashable, Sendable {
|
public enum AEAD: CaseIterable, Hashable, Sendable {
|
||||||
/// An Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 128 bits.
|
/// An Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 128 bits.
|
||||||
case AES_GCM_128
|
case AES_GCM_128
|
||||||
@@ -43,8 +38,7 @@ extension HPKE {
|
|||||||
case exportOnly
|
case exportOnly
|
||||||
|
|
||||||
/// Return the AEAD algorithm identifier as defined in section 7.3 of [RFC 9180](https://www.ietf.org/rfc/rfc9180.pdf).
|
/// Return the AEAD algorithm identifier as defined in section 7.3 of [RFC 9180](https://www.ietf.org/rfc/rfc9180.pdf).
|
||||||
@_spi(HPKEAlgID)
|
internal var value: UInt16 {
|
||||||
public var value: UInt16 {
|
|
||||||
switch self {
|
switch self {
|
||||||
case .AES_GCM_128: return 0x0001
|
case .AES_GCM_128: return 0x0001
|
||||||
case .AES_GCM_256: return 0x0002
|
case .AES_GCM_256: return 0x0002
|
||||||
@@ -58,8 +52,7 @@ extension HPKE {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Return the AEAD key size in bytes
|
/// Return the AEAD key size in bytes
|
||||||
@_spi(HPKEAlgID)
|
internal var keyByteCount: Int {
|
||||||
public var keyByteCount: Int {
|
|
||||||
switch self {
|
switch self {
|
||||||
case .AES_GCM_128:
|
case .AES_GCM_128:
|
||||||
return 16
|
return 16
|
||||||
@@ -73,8 +66,7 @@ extension HPKE {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Return the AEAD nonce size in bytes
|
/// Return the AEAD nonce size in bytes
|
||||||
@_spi(HPKEAlgID)
|
internal var nonceByteCount: Int {
|
||||||
public var nonceByteCount: Int {
|
|
||||||
switch self {
|
switch self {
|
||||||
case .AES_GCM_128, .AES_GCM_256, .chaChaPoly:
|
case .AES_GCM_128, .AES_GCM_256, .chaChaPoly:
|
||||||
return 12
|
return 12
|
||||||
@@ -84,8 +76,7 @@ extension HPKE {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Return the AEAD tag size in bytes
|
/// Return the AEAD tag size in bytes
|
||||||
@_spi(HPKEAlgID)
|
internal var tagByteCount: Int {
|
||||||
public var tagByteCount: Int {
|
|
||||||
switch self {
|
switch self {
|
||||||
case .AES_GCM_128, .AES_GCM_256, .chaChaPoly:
|
case .AES_GCM_128, .AES_GCM_256, .chaChaPoly:
|
||||||
return 16
|
return 16
|
||||||
@@ -98,8 +89,7 @@ extension HPKE {
|
|||||||
return I2OSP(value: Int(self.value), outputByteCount: 2)
|
return I2OSP(value: Int(self.value), outputByteCount: 2)
|
||||||
}
|
}
|
||||||
|
|
||||||
@_spi(MLS)
|
internal func seal<D: DataProtocol, AD: DataProtocol>(_ message: D, authenticating aad: AD, nonce: Data, using key: SymmetricKey) throws -> Data {
|
||||||
public func seal<D: DataProtocol, AD: DataProtocol>(_ message: D, authenticating aad: AD, nonce: Data, using key: SymmetricKey) throws -> Data {
|
|
||||||
switch self {
|
switch self {
|
||||||
case .chaChaPoly:
|
case .chaChaPoly:
|
||||||
return try ChaChaPoly.seal(message, using: key, nonce: ChaChaPoly.Nonce(data: nonce), authenticating: aad).combined.dropFirst(nonce.count)
|
return try ChaChaPoly.seal(message, using: key, nonce: ChaChaPoly.Nonce(data: nonce), authenticating: aad).combined.dropFirst(nonce.count)
|
||||||
@@ -108,8 +98,7 @@ extension HPKE {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@_spi(MLS)
|
internal func open<C: DataProtocol, AD: DataProtocol>(_ ct: C, nonce: Data, authenticating aad: AD, using key: SymmetricKey) throws -> Data {
|
||||||
public func open<C: DataProtocol, AD: DataProtocol>(_ ct: C, nonce: Data, authenticating aad: AD, using key: SymmetricKey) throws -> Data {
|
|
||||||
guard ct.count >= self.tagByteCount else {
|
guard ct.count >= self.tagByteCount else {
|
||||||
throw HPKE.Errors.expectedPSK
|
throw HPKE.Errors.expectedPSK
|
||||||
}
|
}
|
||||||
@@ -132,4 +121,4 @@ extension HPKE {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,22 +11,17 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension HPKE {
|
extension HPKE {
|
||||||
/// Cipher suites to use in hybrid public key encryption (HPKE).
|
/// Cipher suites to use in hybrid public key encryption (HPKE).
|
||||||
///
|
///
|
||||||
@@ -34,7 +29,6 @@ extension HPKE {
|
|||||||
/// and decrypting messages, the key derivation function (KDF) for deriving the shared key, and the key encapsulation
|
/// and decrypting messages, the key derivation function (KDF) for deriving the shared key, and the key encapsulation
|
||||||
/// mechanism (KEM) for sharing the symmetric key. The sender and recipient of encrypted messages need to use the
|
/// mechanism (KEM) for sharing the symmetric key. The sender and recipient of encrypted messages need to use the
|
||||||
/// same cipher suite.
|
/// same cipher suite.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct Ciphersuite: Sendable {
|
public struct Ciphersuite: Sendable {
|
||||||
/// A cipher suite for HPKE that uses NIST P-256 elliptic curve key agreement, SHA-2 key derivation
|
/// A cipher suite for HPKE that uses NIST P-256 elliptic curve key agreement, SHA-2 key derivation
|
||||||
/// with a 256-bit digest, and the Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 256 bits.
|
/// with a 256-bit digest, and the Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 256 bits.
|
||||||
@@ -83,4 +77,4 @@ extension HPKE {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,24 +11,20 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension HPKE {
|
extension HPKE {
|
||||||
/// The key derivation functions to use in HPKE.
|
/// The key derivation functions to use in HPKE.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum KDF: CaseIterable, Hashable, Sendable {
|
public enum KDF: CaseIterable, Hashable, Sendable {
|
||||||
/// An HMAC-based key derivation function that uses SHA-2 hashing with a 256-bit digest.
|
/// An HMAC-based key derivation function that uses SHA-2 hashing with a 256-bit digest.
|
||||||
case HKDF_SHA256
|
case HKDF_SHA256
|
||||||
@@ -38,8 +34,7 @@ extension HPKE {
|
|||||||
case HKDF_SHA512
|
case HKDF_SHA512
|
||||||
|
|
||||||
/// Return the KDF algorithm identifier as defined in section 7.2 of [RFC 9180](https://www.ietf.org/rfc/rfc9180.pdf).
|
/// Return the KDF algorithm identifier as defined in section 7.2 of [RFC 9180](https://www.ietf.org/rfc/rfc9180.pdf).
|
||||||
@_spi(HPKEAlgID)
|
internal var value: UInt16 {
|
||||||
public var value: UInt16 {
|
|
||||||
switch self {
|
switch self {
|
||||||
case .HKDF_SHA256: return 0x0001
|
case .HKDF_SHA256: return 0x0001
|
||||||
case .HKDF_SHA384: return 0x0002
|
case .HKDF_SHA384: return 0x0002
|
||||||
@@ -73,8 +68,7 @@ extension HPKE {
|
|||||||
/// - ikm: The initial key material the derivation function uses to derive a key.
|
/// - ikm: The initial key material the derivation function uses to derive a key.
|
||||||
///
|
///
|
||||||
/// - Returns: A pseudorandom, cryptographically strong key in the form of a hashed authentication code.
|
/// - Returns: A pseudorandom, cryptographically strong key in the form of a hashed authentication code.
|
||||||
@_spi(MLS)
|
internal func extract<S: DataProtocol>(salt: S, ikm: SymmetricKey) -> SymmetricKey {
|
||||||
public func extract<S: DataProtocol>(salt: S, ikm: SymmetricKey) -> SymmetricKey {
|
|
||||||
switch self {
|
switch self {
|
||||||
case .HKDF_SHA256:
|
case .HKDF_SHA256:
|
||||||
return SymmetricKey(data: HKDF<SHA256>.extract(inputKeyMaterial: ikm, salt: salt))
|
return SymmetricKey(data: HKDF<SHA256>.extract(inputKeyMaterial: ikm, salt: salt))
|
||||||
@@ -96,8 +90,7 @@ extension HPKE {
|
|||||||
/// - outputByteCount: The length in bytes of the resulting symmetric key.
|
/// - outputByteCount: The length in bytes of the resulting symmetric key.
|
||||||
///
|
///
|
||||||
/// - Returns: The derived symmetric key.
|
/// - Returns: The derived symmetric key.
|
||||||
@_spi(MLS)
|
internal func expand(prk: SymmetricKey, info: Data, outputByteCount: Int) -> SymmetricKey {
|
||||||
public func expand(prk: SymmetricKey, info: Data, outputByteCount: Int) -> SymmetricKey {
|
|
||||||
switch self {
|
switch self {
|
||||||
case .HKDF_SHA256:
|
case .HKDF_SHA256:
|
||||||
return SymmetricKey(data: HKDF<SHA256>.expand(pseudoRandomKey: prk, info: info, outputByteCount: outputByteCount))
|
return SymmetricKey(data: HKDF<SHA256>.expand(pseudoRandomKey: prk, info: info, outputByteCount: outputByteCount))
|
||||||
@@ -110,4 +103,4 @@ extension HPKE {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,39 +11,28 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
private let suiteIDLabel = Data("KEM".utf8)
|
private let suiteIDLabel = Data("KEM".utf8)
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension HPKE {
|
extension HPKE {
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct KexUtils {
|
struct KexUtils {
|
||||||
static func ExtractAndExpand(dh: ContiguousBytes, enc: Data,
|
static func ExtractAndExpand(dh: ContiguousBytes, enc: Data,
|
||||||
pkRm: Data, pkSm: Data? = nil, kem: HPKE.KEM, kdf: HPKE.KDF) -> SymmetricKey {
|
pkRm: Data, pkSm: Data? = nil, kem: HPKE.KEM, kdf: HPKE.KDF) -> SymmetricKey {
|
||||||
var suiteID = suiteIDLabel
|
var suiteID = suiteIDLabel
|
||||||
suiteID.append(kem.identifier)
|
suiteID.append(kem.identifier)
|
||||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
return CryptoKit.ExtractAndExpand(zz: dh, kemContext: kemContext(enc: enc, pkRm: pkRm, pkSm: pkSm),
|
|
||||||
suiteID: suiteID, kem: kem, kdf: kdf)
|
|
||||||
#else
|
|
||||||
return Crypto.ExtractAndExpand(zz: dh, kemContext: kemContext(enc: enc, pkRm: pkRm, pkSm: pkSm),
|
return Crypto.ExtractAndExpand(zz: dh, kemContext: kemContext(enc: enc, pkRm: pkRm, pkSm: pkSm),
|
||||||
suiteID: suiteID, kem: kem, kdf: kdf)
|
suiteID: suiteID, kem: kem, kdf: kdf)
|
||||||
#endif
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static func kemContext(enc: Data, pkRm: Data, pkSm: Data? = nil) -> Data {
|
static func kemContext(enc: Data, pkRm: Data, pkSm: Data? = nil) -> Data {
|
||||||
@@ -56,4 +45,4 @@ extension HPKE {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,47 +11,36 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
private let protocolLabel = Data("HPKE-v1".utf8)
|
private let protocolLabel = Data("HPKE-v1".utf8)
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
private let eaePRKLabel = Data("eae_prk".utf8)
|
private let eaePRKLabel = Data("eae_prk".utf8)
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
private let sharedSecretLabel = Data("shared_secret".utf8)
|
private let sharedSecretLabel = Data("shared_secret".utf8)
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Data {
|
extension Data {
|
||||||
internal init(unsafeFromContiguousBytes cb: ContiguousBytes) {
|
internal init(unsafeFromContiguousBytes cb: ContiguousBytes) {
|
||||||
self = cb.withUnsafeBytes { return Data($0) }
|
self = cb.withUnsafeBytes { return Data($0) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal func ExtractAndExpand(zz: ContiguousBytes, kemContext: Data, suiteID: Data, kem: HPKE.KEM, kdf: HPKE.KDF) -> SymmetricKey {
|
internal func ExtractAndExpand(zz: ContiguousBytes, kemContext: Data, suiteID: Data, kem: HPKE.KEM, kdf: HPKE.KDF) -> SymmetricKey {
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
let eaePrk = LabeledExtract(salt: Data(), label: eaePRKLabel, ikm: zz, suiteID: suiteID, kdf: kdf)
|
let eaePrk = LabeledExtract(salt: Data(), label: eaePRKLabel, ikm: zz, suiteID: suiteID, kdf: kdf)
|
||||||
|
|
||||||
return LabeledExpand(prk: eaePrk, label: sharedSecretLabel,
|
return LabeledExpand(prk: eaePrk, label: sharedSecretLabel,
|
||||||
info: kemContext, outputByteCount: kem.nSecret, suiteID: suiteID, kdf: kdf)
|
info: kemContext, outputByteCount: kem.nSecret, suiteID: suiteID, kdf: kdf)
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal func LabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, suiteID: Data, kdf: HPKE.KDF) -> SymmetricKey {
|
internal func LabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, suiteID: Data, kdf: HPKE.KDF) -> SymmetricKey {
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
var labeled_ikm = protocolLabel
|
var labeled_ikm = protocolLabel
|
||||||
labeled_ikm.append(suiteID)
|
labeled_ikm.append(suiteID)
|
||||||
labeled_ikm.append(label)
|
labeled_ikm.append(label)
|
||||||
@@ -59,9 +48,7 @@ internal func LabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, su
|
|||||||
return kdf.extract(salt: salt ?? Data(), ikm: SymmetricKey(data: labeled_ikm))
|
return kdf.extract(salt: salt ?? Data(), ikm: SymmetricKey(data: labeled_ikm))
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal func LabeledExpand<Info: DataProtocol>(prk: SymmetricKey, label: Data, info: Info, outputByteCount: UInt16, suiteID: Data, kdf: HPKE.KDF) -> SymmetricKey {
|
internal func LabeledExpand<Info: DataProtocol>(prk: SymmetricKey, label: Data, info: Info, outputByteCount: UInt16, suiteID: Data, kdf: HPKE.KDF) -> SymmetricKey {
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
var labeled_info = I2OSP(value: Int(outputByteCount), outputByteCount: 2)
|
var labeled_info = I2OSP(value: Int(outputByteCount), outputByteCount: 2)
|
||||||
labeled_info.append(protocolLabel)
|
labeled_info.append(protocolLabel)
|
||||||
labeled_info.append(suiteID)
|
labeled_info.append(suiteID)
|
||||||
@@ -70,14 +57,12 @@ internal func LabeledExpand<Info: DataProtocol>(prk: SymmetricKey, label: Data,
|
|||||||
return kdf.expand(prk: prk, info: labeled_info, outputByteCount: Int(outputByteCount))
|
return kdf.expand(prk: prk, info: labeled_info, outputByteCount: Int(outputByteCount))
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal func NonSecretOutputLabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, suiteID: Data, kdf: HPKE.KDF) -> Data {
|
internal func NonSecretOutputLabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, suiteID: Data, kdf: HPKE.KDF) -> Data {
|
||||||
return Data(unsafeFromContiguousBytes: LabeledExtract(salt: salt, label: label, ikm: ikm, suiteID: suiteID, kdf: kdf))
|
return Data(unsafeFromContiguousBytes: LabeledExtract(salt: salt, label: label, ikm: ikm, suiteID: suiteID, kdf: kdf))
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal func NonSecretOutputLabeledExpand(prk: SymmetricKey, label: Data, info: Data, outputByteCount: UInt16, suiteID: Data, kdf: HPKE.KDF) -> Data {
|
internal func NonSecretOutputLabeledExpand(prk: SymmetricKey, label: Data, info: Data, outputByteCount: UInt16, suiteID: Data, kdf: HPKE.KDF) -> Data {
|
||||||
return Data(unsafeFromContiguousBytes: LabeledExpand(prk: prk, label: label, info: info, outputByteCount: outputByteCount, suiteID: suiteID, kdf: kdf))
|
return Data(unsafeFromContiguousBytes: LabeledExpand(prk: prk, label: label, info: info, outputByteCount: outputByteCount, suiteID: suiteID, kdf: kdf))
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,13 +11,11 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
#if os(Windows)
|
#if os(Windows)
|
||||||
import ucrt
|
import ucrt
|
||||||
@@ -36,25 +34,16 @@ import FoundationEssentials
|
|||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal func I2OSP(value: Int, outputByteCount: Int) -> Data {
|
internal func I2OSP(value: Int, outputByteCount: Int) -> Data {
|
||||||
precondition(outputByteCount > 0, "Cannot I2OSP with no output length.")
|
precondition(outputByteCount > 0, "Cannot I2OSP with no output length.")
|
||||||
precondition(value >= 0, "I2OSP requires a non-null value.")
|
precondition(value >= 0, "I2OSP requires a non-null value.")
|
||||||
|
|
||||||
#if !CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
let requiredBytes = Int(ceil(log2(Double(max(value, 1) + 1)) / 8))
|
let requiredBytes = Int(ceil(log2(Double(max(value, 1) + 1)) / 8))
|
||||||
#else
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
let requiredBytes = Int((log2_bridge(Double(max(value, 1) + 1)) / 8).rounded(.up))
|
|
||||||
#endif
|
|
||||||
|
|
||||||
precondition(outputByteCount >= requiredBytes)
|
precondition(outputByteCount >= requiredBytes)
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
var data = Data(repeating: 0, count: outputByteCount)
|
var data = Data(repeating: 0, count: outputByteCount)
|
||||||
|
|
||||||
for i in (outputByteCount - requiredBytes)...(outputByteCount - 1) {
|
for i in (outputByteCount - requiredBytes)...(outputByteCount - 1) {
|
||||||
@@ -64,4 +53,4 @@ internal func I2OSP(value: Int, outputByteCount: Int) -> Data {
|
|||||||
return data
|
return data
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,23 +11,19 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
/// A type that ``HPKE`` uses to encode the public key.
|
/// A type that ``HPKE`` uses to encode the public key.
|
||||||
@preconcurrency
|
@preconcurrency
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public protocol HPKEPublicKeySerialization: Sendable {
|
public protocol HPKEPublicKeySerialization: Sendable {
|
||||||
/// Creates a public key from an encoded representation.
|
/// Creates a public key from an encoded representation.
|
||||||
///
|
///
|
||||||
@@ -46,7 +42,6 @@ public protocol HPKEPublicKeySerialization: Sendable {
|
|||||||
|
|
||||||
/// A type that represents the public key in a Diffie-Hellman key exchange.
|
/// A type that represents the public key in a Diffie-Hellman key exchange.
|
||||||
@preconcurrency
|
@preconcurrency
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public protocol HPKEDiffieHellmanPublicKey: HPKEPublicKeySerialization, Sendable where EphemeralPrivateKey.PublicKey == Self {
|
public protocol HPKEDiffieHellmanPublicKey: HPKEPublicKeySerialization, Sendable where EphemeralPrivateKey.PublicKey == Self {
|
||||||
/// The type of the ephemeral private key.
|
/// The type of the ephemeral private key.
|
||||||
associatedtype EphemeralPrivateKey: HPKEDiffieHellmanPrivateKeyGeneration
|
associatedtype EphemeralPrivateKey: HPKEDiffieHellmanPrivateKeyGeneration
|
||||||
@@ -54,7 +49,6 @@ public protocol HPKEDiffieHellmanPublicKey: HPKEPublicKeySerialization, Sendable
|
|||||||
|
|
||||||
/// A type that represents the public key in HPKE
|
/// A type that represents the public key in HPKE
|
||||||
@preconcurrency
|
@preconcurrency
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public protocol HPKEKEMPublicKey: KEMPublicKey, HPKEPublicKeySerialization where EphemeralPrivateKey.PublicKey == Self {
|
public protocol HPKEKEMPublicKey: KEMPublicKey, HPKEPublicKeySerialization where EphemeralPrivateKey.PublicKey == Self {
|
||||||
/// The type of the ephemeral private key.
|
/// The type of the ephemeral private key.
|
||||||
associatedtype EphemeralPrivateKey: HPKEKEMPrivateKeyGeneration
|
associatedtype EphemeralPrivateKey: HPKEKEMPrivateKeyGeneration
|
||||||
@@ -62,17 +56,14 @@ public protocol HPKEKEMPublicKey: KEMPublicKey, HPKEPublicKeySerialization where
|
|||||||
|
|
||||||
/// A type that represents the private key in a Diffie-Hellman key exchange.
|
/// A type that represents the private key in a Diffie-Hellman key exchange.
|
||||||
@preconcurrency
|
@preconcurrency
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public protocol HPKEDiffieHellmanPrivateKey: Sendable, DiffieHellmanKeyAgreement where PublicKey: HPKEDiffieHellmanPublicKey {}
|
public protocol HPKEDiffieHellmanPrivateKey: Sendable, DiffieHellmanKeyAgreement where PublicKey: HPKEDiffieHellmanPublicKey {}
|
||||||
|
|
||||||
/// A type that represents the private key in HPKE.
|
/// A type that represents the private key in HPKE.
|
||||||
@preconcurrency
|
@preconcurrency
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public protocol HPKEKEMPrivateKey: Sendable, KEMPrivateKey where PublicKey: HPKEKEMPublicKey {}
|
public protocol HPKEKEMPrivateKey: Sendable, KEMPrivateKey where PublicKey: HPKEKEMPublicKey {}
|
||||||
|
|
||||||
/// A type that represents the generation of private keys in a Diffie-Hellman key exchange.
|
/// A type that represents the generation of private keys in a Diffie-Hellman key exchange.
|
||||||
@preconcurrency
|
@preconcurrency
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public protocol HPKEDiffieHellmanPrivateKeyGeneration: HPKEDiffieHellmanPrivateKey, Sendable {
|
public protocol HPKEDiffieHellmanPrivateKeyGeneration: HPKEDiffieHellmanPrivateKey, Sendable {
|
||||||
/// Creates a private key generator.
|
/// Creates a private key generator.
|
||||||
init()
|
init()
|
||||||
@@ -80,27 +71,20 @@ public protocol HPKEDiffieHellmanPrivateKeyGeneration: HPKEDiffieHellmanPrivateK
|
|||||||
|
|
||||||
/// A type that represents the generation of private keys in HPKE
|
/// A type that represents the generation of private keys in HPKE
|
||||||
@preconcurrency
|
@preconcurrency
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public protocol HPKEKEMPrivateKeyGeneration: HPKEKEMPrivateKey, Sendable {
|
public protocol HPKEKEMPrivateKeyGeneration: HPKEKEMPrivateKey, Sendable {
|
||||||
/// Creates a private key generator.
|
/// Creates a private key generator.
|
||||||
init() throws
|
init() throws
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension HPKE {
|
extension HPKE {
|
||||||
/// A container for Diffie-Hellman key encapsulation mechanisms (KEMs).
|
/// A container for Diffie-Hellman key encapsulation mechanisms (KEMs).
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum DHKEM: Sendable {
|
public enum DHKEM: Sendable {
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct PublicKey<DHPK: HPKEDiffieHellmanPublicKey>: KEMPublicKey where DHPK == DHPK.EphemeralPrivateKey.PublicKey {
|
struct PublicKey<DHPK: HPKEDiffieHellmanPublicKey>: KEMPublicKey where DHPK == DHPK.EphemeralPrivateKey.PublicKey {
|
||||||
let kem: HPKE.KEM
|
let kem: HPKE.KEM
|
||||||
let key: DHPK
|
let key: DHPK
|
||||||
|
|
||||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
typealias EncapsulationResult = CryptoKit.KEM.EncapsulationResult
|
|
||||||
#else
|
|
||||||
typealias EncapsulationResult = Crypto.KEM.EncapsulationResult
|
typealias EncapsulationResult = Crypto.KEM.EncapsulationResult
|
||||||
#endif
|
|
||||||
|
|
||||||
init(_ publicKey: DHPK, kem: HPKE.KEM) throws {
|
init(_ publicKey: DHPK, kem: HPKE.KEM) throws {
|
||||||
// TODO: Validate Ciphersuite Mismatches
|
// TODO: Validate Ciphersuite Mismatches
|
||||||
@@ -124,7 +108,6 @@ extension HPKE {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct PrivateKey<DHSK: HPKEDiffieHellmanPrivateKey>: KEMPrivateKey {
|
struct PrivateKey<DHSK: HPKEDiffieHellmanPrivateKey>: KEMPrivateKey {
|
||||||
let kem: HPKE.KEM
|
let kem: HPKE.KEM
|
||||||
let key: DHSK
|
let key: DHSK
|
||||||
@@ -185,4 +168,4 @@ extension HPKE {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,26 +11,19 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Curve25519.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {}
|
extension Curve25519.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {}
|
||||||
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Curve25519.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
extension Curve25519.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
||||||
/// The type of the ephemeral private key associated with this public key.
|
/// The type of the ephemeral private key associated with this public key.
|
||||||
public typealias EphemeralPrivateKey = Curve25519.KeyAgreement.PrivateKey
|
public typealias EphemeralPrivateKey = Curve25519.KeyAgreement.PrivateKey
|
||||||
@@ -73,4 +66,4 @@ extension Curve25519.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
|||||||
public typealias HPKEEphemeralPrivateKey = Curve25519.KeyAgreement.PrivateKey
|
public typealias HPKEEphemeralPrivateKey = Curve25519.KeyAgreement.PrivateKey
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,21 +11,17 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P256.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
extension P256.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
||||||
/// Creates a NIST P-256 elliptic curve private key for use with Diffie-Hellman key exchange.
|
/// Creates a NIST P-256 elliptic curve private key for use with Diffie-Hellman key exchange.
|
||||||
public init() {
|
public init() {
|
||||||
@@ -33,8 +29,6 @@ extension P256.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P256.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
extension P256.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
||||||
/// The type of the ephemeral private key associated with this public key.
|
/// The type of the ephemeral private key associated with this public key.
|
||||||
public typealias EphemeralPrivateKey = P256.KeyAgreement.PrivateKey
|
public typealias EphemeralPrivateKey = P256.KeyAgreement.PrivateKey
|
||||||
@@ -74,8 +68,6 @@ extension P256.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
|||||||
public typealias HPKEEphemeralPrivateKey = P256.KeyAgreement.PrivateKey
|
public typealias HPKEEphemeralPrivateKey = P256.KeyAgreement.PrivateKey
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P384.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
extension P384.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
||||||
/// Creates a NIST P-384 elliptic curve private key for use with Diffie-Hellman key exchange.
|
/// Creates a NIST P-384 elliptic curve private key for use with Diffie-Hellman key exchange.
|
||||||
public init() {
|
public init() {
|
||||||
@@ -83,8 +75,6 @@ extension P384.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P384.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
extension P384.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
||||||
/// The type of the ephemeral private key associated with this public key.
|
/// The type of the ephemeral private key associated with this public key.
|
||||||
public typealias EphemeralPrivateKey = P384.KeyAgreement.PrivateKey
|
public typealias EphemeralPrivateKey = P384.KeyAgreement.PrivateKey
|
||||||
@@ -124,8 +114,6 @@ extension P384.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P521.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
extension P521.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
||||||
/// Creates a NIST P-521 elliptic curve private key for use with Diffie-Hellman key exchange.
|
/// Creates a NIST P-521 elliptic curve private key for use with Diffie-Hellman key exchange.
|
||||||
public init() {
|
public init() {
|
||||||
@@ -133,8 +121,6 @@ extension P521.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P521.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
extension P521.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
||||||
/// The type of the ephemeral private key associated with this public key.
|
/// The type of the ephemeral private key associated with this public key.
|
||||||
public typealias EphemeralPrivateKey = P521.KeyAgreement.PrivateKey
|
public typealias EphemeralPrivateKey = P521.KeyAgreement.PrivateKey
|
||||||
@@ -177,4 +163,4 @@ extension P521.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
|||||||
public typealias HPKEEphemeralPrivateKey = P521.KeyAgreement.PrivateKey
|
public typealias HPKEEphemeralPrivateKey = P521.KeyAgreement.PrivateKey
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,30 +11,28 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension HPKE {
|
extension HPKE {
|
||||||
/// The key encapsulation mechanisms to use in HPKE.
|
/// The key encapsulation mechanisms to use in HPKE.
|
||||||
///
|
///
|
||||||
/// The module-lattice key encapsulation mechanism (ML-KEM) is designed to offer increased security in situations
|
/// The module-lattice key encapsulation mechanism (ML-KEM) is designed to offer increased security in situations
|
||||||
/// where an adversary uses a quantum computer.
|
/// where an adversary uses a quantum computer.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum KEM: CaseIterable, Hashable, Sendable {
|
public enum KEM: CaseIterable, Hashable, Sendable {
|
||||||
public static var allCases: [HPKE.KEM] {
|
public static var allCases: [HPKE.KEM] {
|
||||||
var cases = [KEM.P256_HKDF_SHA256, KEM.P384_HKDF_SHA384, KEM.P521_HKDF_SHA512, KEM.Curve25519_HKDF_SHA256]
|
var cases = [KEM.P256_HKDF_SHA256, KEM.P384_HKDF_SHA384, KEM.P521_HKDF_SHA512, KEM.Curve25519_HKDF_SHA256]
|
||||||
cases.append(KEM.XWingMLKEM768X25519)
|
if #available(iOS 19.0, macOS 16.0, watchOS 12.0, tvOS 19.0, macCatalyst 19.0, *) {
|
||||||
|
cases.append(KEM.XWingMLKEM768X25519)
|
||||||
|
}
|
||||||
return cases
|
return cases
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,8 +53,7 @@ extension HPKE {
|
|||||||
case XWingMLKEM768X25519
|
case XWingMLKEM768X25519
|
||||||
|
|
||||||
/// Return the KEM algorithm identifier as defined in section 7.1 of [RFC 9180](https://www.ietf.org/rfc/rfc9180.pdf).
|
/// Return the KEM algorithm identifier as defined in section 7.1 of [RFC 9180](https://www.ietf.org/rfc/rfc9180.pdf).
|
||||||
@_spi(HPKEAlgID)
|
internal var value: UInt16 {
|
||||||
public var value: UInt16 {
|
|
||||||
switch self {
|
switch self {
|
||||||
case .P256_HKDF_SHA256: return 0x0010
|
case .P256_HKDF_SHA256: return 0x0010
|
||||||
case .P384_HKDF_SHA384: return 0x0011
|
case .P384_HKDF_SHA384: return 0x0011
|
||||||
@@ -91,8 +88,7 @@ extension HPKE {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Return the size of the encapsulation in bytes
|
/// Return the size of the encapsulation in bytes
|
||||||
@_spi(HPKEAlgID)
|
internal var nEnc: UInt16 {
|
||||||
public var nEnc: UInt16 {
|
|
||||||
switch self {
|
switch self {
|
||||||
case .P256_HKDF_SHA256: return 65
|
case .P256_HKDF_SHA256: return 65
|
||||||
case .P384_HKDF_SHA384: return 97
|
case .P384_HKDF_SHA384: return 97
|
||||||
@@ -104,4 +100,4 @@ extension HPKE {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,24 +11,20 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension HPKE {
|
extension HPKE {
|
||||||
/// Hybrid public key encryption (HPKE) errors that CryptoKit uses.
|
/// Hybrid public key encryption (HPKE) errors that CryptoKit uses.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum Errors: Error {
|
public enum Errors: Error {
|
||||||
/// The parameters for initializing an HPKE sender or receiver are inconsistent.
|
/// The parameters for initializing an HPKE sender or receiver are inconsistent.
|
||||||
case inconsistentParameters
|
case inconsistentParameters
|
||||||
@@ -49,4 +45,4 @@ extension HPKE {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,18 +11,15 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
/// A container for hybrid public key encryption (HPKE) operations.
|
/// A container for hybrid public key encryption (HPKE) operations.
|
||||||
///
|
///
|
||||||
@@ -53,10 +50,9 @@ public import Foundation
|
|||||||
///
|
///
|
||||||
/// ### Handling errors
|
/// ### Handling errors
|
||||||
/// - ``Errors``
|
/// - ``Errors``
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum HPKE: Sendable {}
|
public enum HPKE: Sendable {}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension HPKE {
|
extension HPKE {
|
||||||
/// Static constant used to store the fixed-string label for the HPKE export API
|
/// Static constant used to store the fixed-string label for the HPKE export API
|
||||||
/// See: https://datatracker.ietf.org/doc/html/rfc9180#name-secret-export
|
/// See: https://datatracker.ietf.org/doc/html/rfc9180#name-secret-export
|
||||||
@@ -70,7 +66,6 @@ extension HPKE {
|
|||||||
/// in turn to retrieve its ciphertext. The recipient of the messages needs to process them in the
|
/// in turn to retrieve its ciphertext. The recipient of the messages needs to process them in the
|
||||||
/// same order as the `Sender`, using the same encryption mode, cipher suite, and key schedule information
|
/// same order as the `Sender`, using the same encryption mode, cipher suite, and key schedule information
|
||||||
/// (`info`), as well as the `Sender`'s ``encapsulatedKey``.
|
/// (`info`), as well as the `Sender`'s ``encapsulatedKey``.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct Sender: Sendable {
|
public struct Sender: Sendable {
|
||||||
private var context: Context
|
private var context: Context
|
||||||
/// The encapsulated symmetric key that the recipient uses to decrypt messages.
|
/// The encapsulated symmetric key that the recipient uses to decrypt messages.
|
||||||
@@ -225,7 +220,6 @@ extension HPKE {
|
|||||||
/// same order as the `Sender`, using the same cipher suite, encryption mode, and key schedule information
|
/// same order as the `Sender`, using the same cipher suite, encryption mode, and key schedule information
|
||||||
/// (`info` data).
|
/// (`info` data).
|
||||||
/// Use a separate `Recipient` instance for each stream of messages.
|
/// Use a separate `Recipient` instance for each stream of messages.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct Recipient: Sendable {
|
public struct Recipient: Sendable {
|
||||||
|
|
||||||
private var context: Context
|
private var context: Context
|
||||||
@@ -364,4 +358,4 @@ extension HPKE {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,23 +11,18 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension HPKE {
|
extension HPKE {
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
struct Context: Sendable {
|
struct Context: Sendable {
|
||||||
var keySchedule: KeySchedule
|
var keySchedule: KeySchedule
|
||||||
var encapsulated: Data
|
var encapsulated: Data
|
||||||
@@ -81,4 +76,4 @@ extension HPKE {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,23 +11,18 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension HPKE {
|
extension HPKE {
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal struct KeySchedule: Sendable {
|
internal struct KeySchedule: Sendable {
|
||||||
fileprivate static let pksIDHashLabel = Data("psk_id_hash".utf8)
|
fileprivate static let pksIDHashLabel = Data("psk_id_hash".utf8)
|
||||||
fileprivate static let infoHashLabel = Data("info_hash".utf8)
|
fileprivate static let infoHashLabel = Data("info_hash".utf8)
|
||||||
@@ -163,4 +158,4 @@ extension HPKE {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,14 +11,12 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension HPKE {
|
extension HPKE {
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
internal enum Mode: CaseIterable {
|
internal enum Mode: CaseIterable {
|
||||||
case base
|
case base
|
||||||
case psk
|
case psk
|
||||||
@@ -40,4 +38,4 @@ extension HPKE {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,7 +11,8 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
/// A container for older, cryptographically insecure algorithms.
|
/// A container for older, cryptographically insecure algorithms.
|
||||||
@@ -19,6 +20,6 @@
|
|||||||
/// - Important: These algorithms aren’t considered cryptographically secure,
|
/// - Important: These algorithms aren’t considered cryptographically secure,
|
||||||
/// but the framework provides them for backward compatibility with older
|
/// but the framework provides them for backward compatibility with older
|
||||||
/// services that require them. For new services, avoid these algorithms.
|
/// services that require them. For new services, avoid these algorithms.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum Insecure: Sendable {}
|
public enum Insecure: Sendable {}
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,10 +11,10 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Insecure {
|
extension Insecure {
|
||||||
/// An implementation of SHA1 hashing.
|
/// An implementation of SHA1 hashing.
|
||||||
///
|
///
|
||||||
@@ -32,7 +32,6 @@ extension Insecure {
|
|||||||
/// secure, but is provided for backward compatibility with older services
|
/// secure, but is provided for backward compatibility with older services
|
||||||
/// that require it. For new services, prefer one of the secure hashes, like
|
/// that require it. For new services, prefer one of the secure hashes, like
|
||||||
/// ``SHA512``.
|
/// ``SHA512``.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SHA1: HashFunctionImplementationDetails, Sendable {
|
public struct SHA1: HashFunctionImplementationDetails, Sendable {
|
||||||
/// The number of bytes that represents the hash function’s internal
|
/// The number of bytes that represents the hash function’s internal
|
||||||
/// state.
|
/// state.
|
||||||
@@ -113,7 +112,6 @@ extension Insecure {
|
|||||||
/// secure, but is provided for backward compatibility with older services
|
/// secure, but is provided for backward compatibility with older services
|
||||||
/// that require it. For new services, prefer one of the secure hashes, like
|
/// that require it. For new services, prefer one of the secure hashes, like
|
||||||
/// ``SHA512``.
|
/// ``SHA512``.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct MD5: HashFunctionImplementationDetails, Sendable {
|
public struct MD5: HashFunctionImplementationDetails, Sendable {
|
||||||
/// The number of bytes that represents the hash function’s internal
|
/// The number of bytes that represents the hash function’s internal
|
||||||
/// state.
|
/// state.
|
||||||
@@ -177,4 +175,4 @@ extension Insecure {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -16,10 +16,14 @@
|
|||||||
// any edits of this file WILL be overwritten and thus discarded
|
// any edits of this file WILL be overwritten and thus discarded
|
||||||
// see section `gyb` in `README` for details.
|
// see section `gyb` in `README` for details.
|
||||||
|
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
#if hasFeature(SourceWarningControl)
|
||||||
|
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||||
|
#else
|
||||||
@_implementationOnly import CCryptoBoringSSL
|
@_implementationOnly import CCryptoBoringSSL
|
||||||
|
#endif
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
@@ -145,14 +149,14 @@ extension MLKEM768 {
|
|||||||
throw CryptoKitError.incorrectParameterSize
|
throw CryptoKitError.incorrectParameterSize
|
||||||
}
|
}
|
||||||
|
|
||||||
var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount)
|
return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) {
|
||||||
|
symmetricKeyDataPtr,
|
||||||
let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in
|
count in
|
||||||
let bytes: ContiguousBytes =
|
let bytes: ContiguousBytes =
|
||||||
encapsulated.regions.count == 1
|
encapsulated.regions.count == 1
|
||||||
? encapsulated.regions.first!
|
? encapsulated.regions.first!
|
||||||
: Array(encapsulated)
|
: Array(encapsulated)
|
||||||
return bytes.withUnsafeBytes { encapsulatedPtr in
|
let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in
|
||||||
CCryptoBoringSSL_MLKEM768_decap(
|
CCryptoBoringSSL_MLKEM768_decap(
|
||||||
symmetricKeyDataPtr.baseAddress,
|
symmetricKeyDataPtr.baseAddress,
|
||||||
encapsulatedPtr.baseAddress,
|
encapsulatedPtr.baseAddress,
|
||||||
@@ -160,13 +164,13 @@ extension MLKEM768 {
|
|||||||
&self.key
|
&self.key
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
guard rc == 1 else {
|
guard rc == 1 else {
|
||||||
throw CryptoKitError.internalBoringSSLError()
|
throw CryptoKitError.internalBoringSSLError()
|
||||||
}
|
}
|
||||||
|
|
||||||
return SymmetricKey(data: symmetricKeyData)
|
count = MLKEM.sharedSecretByteCount
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -412,14 +416,14 @@ extension MLKEM1024 {
|
|||||||
throw CryptoKitError.incorrectParameterSize
|
throw CryptoKitError.incorrectParameterSize
|
||||||
}
|
}
|
||||||
|
|
||||||
var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount)
|
return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) {
|
||||||
|
symmetricKeyDataPtr,
|
||||||
let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in
|
count in
|
||||||
let bytes: ContiguousBytes =
|
let bytes: ContiguousBytes =
|
||||||
encapsulated.regions.count == 1
|
encapsulated.regions.count == 1
|
||||||
? encapsulated.regions.first!
|
? encapsulated.regions.first!
|
||||||
: Array(encapsulated)
|
: Array(encapsulated)
|
||||||
return bytes.withUnsafeBytes { encapsulatedPtr in
|
let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in
|
||||||
CCryptoBoringSSL_MLKEM1024_decap(
|
CCryptoBoringSSL_MLKEM1024_decap(
|
||||||
symmetricKeyDataPtr.baseAddress,
|
symmetricKeyDataPtr.baseAddress,
|
||||||
encapsulatedPtr.baseAddress,
|
encapsulatedPtr.baseAddress,
|
||||||
@@ -427,13 +431,13 @@ extension MLKEM1024 {
|
|||||||
&self.key
|
&self.key
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
guard rc == 1 else {
|
guard rc == 1 else {
|
||||||
throw CryptoKitError.internalBoringSSLError()
|
throw CryptoKitError.internalBoringSSLError()
|
||||||
}
|
}
|
||||||
|
|
||||||
return SymmetricKey(data: symmetricKeyData)
|
count = MLKEM.sharedSecretByteCount
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -568,4 +572,4 @@ enum MLKEM {
|
|||||||
static let sharedSecretByteCount = 32
|
static let sharedSecretByteCount = 32
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#endif // canImport(CryptoKit)
|
||||||
@@ -16,10 +16,14 @@
|
|||||||
// any edits of this file WILL be overwritten and thus discarded
|
// any edits of this file WILL be overwritten and thus discarded
|
||||||
// see section `gyb` in `README` for details.
|
// see section `gyb` in `README` for details.
|
||||||
|
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
#if hasFeature(SourceWarningControl)
|
||||||
|
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||||
|
#else
|
||||||
@_implementationOnly import CCryptoBoringSSL
|
@_implementationOnly import CCryptoBoringSSL
|
||||||
|
#endif
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
@@ -149,14 +153,14 @@ extension MLKEM${parameter_set} {
|
|||||||
throw CryptoKitError.incorrectParameterSize
|
throw CryptoKitError.incorrectParameterSize
|
||||||
}
|
}
|
||||||
|
|
||||||
var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount)
|
return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) {
|
||||||
|
symmetricKeyDataPtr,
|
||||||
let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in
|
count in
|
||||||
let bytes: ContiguousBytes =
|
let bytes: ContiguousBytes =
|
||||||
encapsulated.regions.count == 1
|
encapsulated.regions.count == 1
|
||||||
? encapsulated.regions.first!
|
? encapsulated.regions.first!
|
||||||
: Array(encapsulated)
|
: Array(encapsulated)
|
||||||
return bytes.withUnsafeBytes { encapsulatedPtr in
|
let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in
|
||||||
CCryptoBoringSSL_MLKEM${parameter_set}_decap(
|
CCryptoBoringSSL_MLKEM${parameter_set}_decap(
|
||||||
symmetricKeyDataPtr.baseAddress,
|
symmetricKeyDataPtr.baseAddress,
|
||||||
encapsulatedPtr.baseAddress,
|
encapsulatedPtr.baseAddress,
|
||||||
@@ -164,13 +168,13 @@ extension MLKEM${parameter_set} {
|
|||||||
&self.key
|
&self.key
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
guard rc == 1 else {
|
guard rc == 1 else {
|
||||||
throw CryptoKitError.internalBoringSSLError()
|
throw CryptoKitError.internalBoringSSLError()
|
||||||
}
|
}
|
||||||
|
|
||||||
return SymmetricKey(data: symmetricKeyData)
|
count = MLKEM.sharedSecretByteCount
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -306,4 +310,4 @@ enum MLKEM {
|
|||||||
static let sharedSecretByteCount = 32
|
static let sharedSecretByteCount = 32
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#endif // canImport(CryptoKit)
|
||||||
@@ -12,10 +12,14 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
#if hasFeature(SourceWarningControl)
|
||||||
|
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||||
|
#else
|
||||||
@_implementationOnly import CCryptoBoringSSL
|
@_implementationOnly import CCryptoBoringSSL
|
||||||
|
#endif
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
@@ -289,4 +293,4 @@ struct OpenSSLMLKEMPrivateKeyImpl<Parameters: BoringSSLBackedMLKEMParameters>: B
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#endif // canImport(CryptoKit)
|
||||||
@@ -12,10 +12,14 @@
|
|||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
|
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
#if hasFeature(SourceWarningControl)
|
||||||
|
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||||
|
#else
|
||||||
@_implementationOnly import CCryptoBoringSSL
|
@_implementationOnly import CCryptoBoringSSL
|
||||||
|
#endif
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
@@ -127,6 +131,7 @@ struct OpenSSLXWingPrivateKeyImpl: Sendable {
|
|||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||||
extension OpenSSLXWingPrivateKeyImpl {
|
extension OpenSSLXWingPrivateKeyImpl {
|
||||||
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||||
final class Backing: @unchecked Sendable {
|
final class Backing: @unchecked Sendable {
|
||||||
private var privateKey: XWING_private_key
|
private var privateKey: XWING_private_key
|
||||||
|
|
||||||
@@ -236,7 +241,13 @@ extension OpenSSLXWingPrivateKeyImpl {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func decapsulate(_ encapsulated: Data) throws -> SymmetricKey {
|
func decapsulate(_ encapsulated: Data) throws -> SymmetricKey {
|
||||||
try SymmetricKey(unsafeUninitializedCapacity: Int(XWING_SHARED_SECRET_BYTES)) { sharedSecretBytes, count in
|
guard encapsulated.count == Int(XWING_CIPHERTEXT_BYTES) else {
|
||||||
|
throw CryptoKitError.incorrectParameterSize
|
||||||
|
}
|
||||||
|
|
||||||
|
return try SymmetricKey(unsafeUninitializedCapacity: Int(XWING_SHARED_SECRET_BYTES)) {
|
||||||
|
sharedSecretBytes,
|
||||||
|
count in
|
||||||
try encapsulated.withUnsafeBytes { encapsulatedSecretBytes in
|
try encapsulated.withUnsafeBytes { encapsulatedSecretBytes in
|
||||||
let rc = CCryptoBoringSSL_XWING_decap(
|
let rc = CCryptoBoringSSL_XWING_decap(
|
||||||
sharedSecretBytes.baseAddress,
|
sharedSecretBytes.baseAddress,
|
||||||
@@ -253,4 +264,4 @@ extension OpenSSLXWingPrivateKeyImpl {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,24 +11,20 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension KEM {
|
extension KEM {
|
||||||
/// Errors that CryptoKit throws when it encounters problems in key encapsulation mechanism (KEM) operations.
|
/// Errors that CryptoKit throws when it encounters problems in key encapsulation mechanism (KEM) operations.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum Errors: Error {
|
public enum Errors: Error {
|
||||||
/// The public key CryptoKit receives when it initializes a key encapsulation operation doesn't match the expected value.
|
/// The public key CryptoKit receives when it initializes a key encapsulation operation doesn't match the expected value.
|
||||||
case publicKeyMismatchDuringInitialization
|
case publicKeyMismatchDuringInitialization
|
||||||
@@ -38,4 +34,4 @@ extension KEM {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,27 +11,23 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
/// A key encapsulation mechanism.
|
/// A key encapsulation mechanism.
|
||||||
///
|
///
|
||||||
/// Use a key encapsulation mechanism (KEM) to protect a symmetric cryptographic key that you share with another party.
|
/// Use a key encapsulation mechanism (KEM) to protect a symmetric cryptographic key that you share with another party.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum KEM: Sendable {
|
public enum KEM: Sendable {
|
||||||
/// The result of a key encapsulation operation.
|
/// The result of a key encapsulation operation.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct EncapsulationResult: Sendable {
|
public struct EncapsulationResult: Sendable {
|
||||||
/// The shared secret.
|
/// The shared secret.
|
||||||
public let sharedSecret: SymmetricKey
|
public let sharedSecret: SymmetricKey
|
||||||
@@ -48,7 +44,6 @@ public enum KEM: Sendable {
|
|||||||
|
|
||||||
/// The public key for a key encapsulation mechanism.
|
/// The public key for a key encapsulation mechanism.
|
||||||
@preconcurrency
|
@preconcurrency
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public protocol KEMPublicKey: Sendable {
|
public protocol KEMPublicKey: Sendable {
|
||||||
/// Generates and encapsulates a shared secret.
|
/// Generates and encapsulates a shared secret.
|
||||||
///
|
///
|
||||||
@@ -60,7 +55,6 @@ public protocol KEMPublicKey: Sendable {
|
|||||||
|
|
||||||
/// The private key for a key encapsulation mechanism.
|
/// The private key for a key encapsulation mechanism.
|
||||||
@preconcurrency
|
@preconcurrency
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public protocol KEMPrivateKey: Sendable {
|
public protocol KEMPrivateKey: Sendable {
|
||||||
associatedtype PublicKey: KEMPublicKey
|
associatedtype PublicKey: KEMPublicKey
|
||||||
|
|
||||||
@@ -79,4 +73,25 @@ public protocol KEMPrivateKey: Sendable {
|
|||||||
/// The associated public key.
|
/// The associated public key.
|
||||||
var publicKey: PublicKey { get }
|
var publicKey: PublicKey { get }
|
||||||
}
|
}
|
||||||
#endif // Linux or !SwiftPM
|
|
||||||
|
/// A one-time private key for a key encapsulation mechanism, which can only decapsulate once but it does so faster.
|
||||||
|
@preconcurrency
|
||||||
|
public protocol KEMOneTimePrivateKey: ~Copyable, Sendable {
|
||||||
|
associatedtype PublicKey: KEMPublicKey
|
||||||
|
|
||||||
|
/// Generates a new random private key.
|
||||||
|
/// - Returns: The generated private key.
|
||||||
|
///
|
||||||
|
/// Give the ``publicKey`` to another person so that they can encapsulate
|
||||||
|
/// shared secrets that you recover by calling ``decapsulate(_:)``.
|
||||||
|
static func generate() throws -> Self
|
||||||
|
|
||||||
|
/// Recovers a shared secret from an encapsulated representation.
|
||||||
|
/// - Parameter encapsulated: The encapsulated shared secret that someone created using this key's ``publicKey``.
|
||||||
|
/// - Returns: The decapsulated shared secret.
|
||||||
|
consuming func decapsulate(_ encapsulated: Data) throws -> SymmetricKey
|
||||||
|
|
||||||
|
/// The associated public key.
|
||||||
|
var publicKey: PublicKey { get }
|
||||||
|
}
|
||||||
|
#endif // canImport(CryptoKit)
|
||||||
+110
-25
@@ -11,7 +11,8 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
@@ -20,27 +21,17 @@ public import FoundationEssentials
|
|||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias MLKEMPublicKeyImpl = CoreCryptoMLKEMPublicKeyImpl
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias MLKEMPrivateKeyImpl = CoreCryptoMLKEMPrivateKeyImpl
|
|
||||||
#else
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias MLKEMPublicKeyImpl = OpenSSLMLKEMPublicKeyImpl
|
typealias MLKEMPublicKeyImpl = OpenSSLMLKEMPublicKeyImpl
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias MLKEMPrivateKeyImpl = OpenSSLMLKEMPrivateKeyImpl
|
typealias MLKEMPrivateKeyImpl = OpenSSLMLKEMPrivateKeyImpl
|
||||||
#endif
|
typealias MLKEMOneTimePrivateKeyImpl = OpenSSLMLKEMPrivateKeyImpl
|
||||||
|
|
||||||
|
|
||||||
/// The Module-Lattice key encapsulation mechanism (KEM).
|
/// The Module-Lattice key encapsulation mechanism (KEM).
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum MLKEM768: Sendable {}
|
public enum MLKEM768: Sendable {}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension MLKEM768 {
|
extension MLKEM768 {
|
||||||
/// A public key you use to encapsulate shared secrets with the Module-Lattice key encapsulation mechanism.
|
/// A public key you use to encapsulate shared secrets with the Module-Lattice key encapsulation mechanism.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PublicKey: KEMPublicKey, Sendable {
|
public struct PublicKey: KEMPublicKey, Sendable {
|
||||||
var impl: MLKEMPublicKeyImpl<MLKEM768>
|
var impl: MLKEMPublicKeyImpl<MLKEM768>
|
||||||
|
|
||||||
@@ -70,7 +61,6 @@ extension MLKEM768 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A private key you use to decapsulate shared secrets with the Module-Lattice key encapsulation mechanism.
|
/// A private key you use to decapsulate shared secrets with the Module-Lattice key encapsulation mechanism.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PrivateKey: KEMPrivateKey {
|
public struct PrivateKey: KEMPrivateKey {
|
||||||
internal let impl: MLKEMPrivateKeyImpl<MLKEM768>
|
internal let impl: MLKEMPrivateKeyImpl<MLKEM768>
|
||||||
|
|
||||||
@@ -116,7 +106,7 @@ extension MLKEM768 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Decapsulated a shared secret.
|
/// Decapsulate a shared secret.
|
||||||
///
|
///
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - encapsulated: An encapsulated shared secret, that you get by calling ``MLKEM768/PublicKey/encapsulate()`` on the corresponding public key.
|
/// - encapsulated: An encapsulated shared secret, that you get by calling ``MLKEM768/PublicKey/encapsulate()`` on the corresponding public key.
|
||||||
@@ -128,7 +118,7 @@ extension MLKEM768 {
|
|||||||
/// The corresponding public key.
|
/// The corresponding public key.
|
||||||
public var publicKey: MLKEM768.PublicKey {
|
public var publicKey: MLKEM768.PublicKey {
|
||||||
get {
|
get {
|
||||||
try self.impl.publicKey
|
self.impl.publicKey
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,7 +131,7 @@ extension MLKEM768 {
|
|||||||
}
|
}
|
||||||
let seed = Data(integrityCheckedRepresentation).subdata(in: 0..<MLKEMPrivateKeyImpl<MLKEM768>.seedSize)
|
let seed = Data(integrityCheckedRepresentation).subdata(in: 0..<MLKEMPrivateKeyImpl<MLKEM768>.seedSize)
|
||||||
let publicKeyHashData = Data(integrityCheckedRepresentation).subdata(in: MLKEMPrivateKeyImpl<MLKEM768>.seedSize..<integrityCheckedRepresentation.count)
|
let publicKeyHashData = Data(integrityCheckedRepresentation).subdata(in: MLKEMPrivateKeyImpl<MLKEM768>.seedSize..<integrityCheckedRepresentation.count)
|
||||||
let publicKeyHash = SHA3_256Digest(bytes: [UInt8](publicKeyHashData))
|
let publicKeyHash = SHA3_256Digest(copying: publicKeyHashData.bytes)
|
||||||
|
|
||||||
self.impl = try MLKEMPrivateKeyImpl<MLKEM768>(seedRepresentation: seed, publicKeyHash: publicKeyHash)
|
self.impl = try MLKEMPrivateKeyImpl<MLKEM768>(seedRepresentation: seed, publicKeyHash: publicKeyHash)
|
||||||
}
|
}
|
||||||
@@ -155,17 +145,64 @@ extension MLKEM768 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A one-time-use private key to decapsulate a shared secret with the Module-Lattice key encapsulation mechanism.
|
||||||
|
///
|
||||||
|
/// The associated decapsulation function can be multiple times faster than the one implemented for PrivateKey,
|
||||||
|
/// but this private key can only be used to decapsulate a shared secret once.
|
||||||
|
public struct OneTimePrivateKey: KEMOneTimePrivateKey, ~Copyable {
|
||||||
|
internal let impl: MLKEMOneTimePrivateKeyImpl<MLKEM768>
|
||||||
|
|
||||||
|
internal init(_ impl: MLKEMOneTimePrivateKeyImpl<MLKEM768>) {
|
||||||
|
self.impl = impl
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a one-time-use private key that reuses the key material of an existing private key.
|
||||||
|
///
|
||||||
|
/// This is used by the tests to check that the one-time decapsulation function is consistent with the regular one.
|
||||||
|
internal init(reusingForTestingOnly privateKey: MLKEM768.PrivateKey) {
|
||||||
|
self.impl = try! MLKEMOneTimePrivateKeyImpl<MLKEM768>(
|
||||||
|
seedRepresentation: privateKey.impl.seedRepresentation,
|
||||||
|
publicKeyRawRepresentation: privateKey.impl.publicKey.rawRepresentation
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates a new, random one-time-use private key.
|
||||||
|
public static func generate() throws -> MLKEM768.OneTimePrivateKey {
|
||||||
|
let impl = try MLKEMOneTimePrivateKeyImpl<MLKEM768>.generatePrivateKey()
|
||||||
|
return OneTimePrivateKey(impl)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Initializes a random one-time-use private key.
|
||||||
|
public init() throws {
|
||||||
|
self = try OneTimePrivateKey.generate()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decapsulate a shared secret.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - encapsulated: An encapsulated shared secret, that you get by calling ``MLKEM768/PublicKey/encapsulate()`` on the corresponding public key.
|
||||||
|
/// - Returns: The shared secret.
|
||||||
|
public consuming func decapsulate<D: DataProtocol>(_ encapsulated: D) throws -> SymmetricKey {
|
||||||
|
return try impl.decapsulate(encapsulated: encapsulated)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The corresponding public key.
|
||||||
|
public var publicKey: MLKEM768.PublicKey {
|
||||||
|
get {
|
||||||
|
self.impl.publicKey
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// The Module-Lattice key encapsulation mechanism (KEM).
|
/// The Module-Lattice key encapsulation mechanism (KEM).
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum MLKEM1024: Sendable {}
|
public enum MLKEM1024: Sendable {}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension MLKEM1024 {
|
extension MLKEM1024 {
|
||||||
/// A public key you use to encapsulate shared secrets with the Module-Lattice key encapsulation mechanism.
|
/// A public key you use to encapsulate shared secrets with the Module-Lattice key encapsulation mechanism.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PublicKey: KEMPublicKey, Sendable {
|
public struct PublicKey: KEMPublicKey, Sendable {
|
||||||
var impl: MLKEMPublicKeyImpl<MLKEM1024>
|
var impl: MLKEMPublicKeyImpl<MLKEM1024>
|
||||||
|
|
||||||
@@ -195,7 +232,6 @@ extension MLKEM1024 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A private key you use to decapsulate shared secrets with the Module-Lattice key encapsulation mechanism.
|
/// A private key you use to decapsulate shared secrets with the Module-Lattice key encapsulation mechanism.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PrivateKey: KEMPrivateKey {
|
public struct PrivateKey: KEMPrivateKey {
|
||||||
internal let impl: MLKEMPrivateKeyImpl<MLKEM1024>
|
internal let impl: MLKEMPrivateKeyImpl<MLKEM1024>
|
||||||
|
|
||||||
@@ -241,7 +277,7 @@ extension MLKEM1024 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Decapsulated a shared secret.
|
/// Decapsulate a shared secret.
|
||||||
///
|
///
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - encapsulated: An encapsulated shared secret, that you get by calling ``MLKEM1024/PublicKey/encapsulate()`` on the corresponding public key.
|
/// - encapsulated: An encapsulated shared secret, that you get by calling ``MLKEM1024/PublicKey/encapsulate()`` on the corresponding public key.
|
||||||
@@ -253,7 +289,7 @@ extension MLKEM1024 {
|
|||||||
/// The corresponding public key.
|
/// The corresponding public key.
|
||||||
public var publicKey: MLKEM1024.PublicKey {
|
public var publicKey: MLKEM1024.PublicKey {
|
||||||
get {
|
get {
|
||||||
try self.impl.publicKey
|
self.impl.publicKey
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -266,7 +302,7 @@ extension MLKEM1024 {
|
|||||||
}
|
}
|
||||||
let seed = Data(integrityCheckedRepresentation).subdata(in: 0..<MLKEMPrivateKeyImpl<MLKEM1024>.seedSize)
|
let seed = Data(integrityCheckedRepresentation).subdata(in: 0..<MLKEMPrivateKeyImpl<MLKEM1024>.seedSize)
|
||||||
let publicKeyHashData = Data(integrityCheckedRepresentation).subdata(in: MLKEMPrivateKeyImpl<MLKEM1024>.seedSize..<integrityCheckedRepresentation.count)
|
let publicKeyHashData = Data(integrityCheckedRepresentation).subdata(in: MLKEMPrivateKeyImpl<MLKEM1024>.seedSize..<integrityCheckedRepresentation.count)
|
||||||
let publicKeyHash = SHA3_256Digest(bytes: [UInt8](publicKeyHashData))
|
let publicKeyHash = SHA3_256Digest(copying: publicKeyHashData.bytes)
|
||||||
|
|
||||||
self.impl = try MLKEMPrivateKeyImpl<MLKEM1024>(seedRepresentation: seed, publicKeyHash: publicKeyHash)
|
self.impl = try MLKEMPrivateKeyImpl<MLKEM1024>(seedRepresentation: seed, publicKeyHash: publicKeyHash)
|
||||||
}
|
}
|
||||||
@@ -280,7 +316,56 @@ extension MLKEM1024 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A one-time-use private key to decapsulate a shared secret with the Module-Lattice key encapsulation mechanism.
|
||||||
|
///
|
||||||
|
/// The associated decapsulation function can be multiple times faster than the one implemented for PrivateKey,
|
||||||
|
/// but this private key can only be used to decapsulate a shared secret once.
|
||||||
|
public struct OneTimePrivateKey: KEMOneTimePrivateKey, ~Copyable {
|
||||||
|
internal let impl: MLKEMOneTimePrivateKeyImpl<MLKEM1024>
|
||||||
|
|
||||||
|
internal init(_ impl: MLKEMOneTimePrivateKeyImpl<MLKEM1024>) {
|
||||||
|
self.impl = impl
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a one-time-use private key that reuses the key material of an existing private key.
|
||||||
|
///
|
||||||
|
/// This is used by the tests to check that the one-time decapsulation function is consistent with the regular one.
|
||||||
|
internal init(reusingForTestingOnly privateKey: MLKEM1024.PrivateKey) {
|
||||||
|
self.impl = try! MLKEMOneTimePrivateKeyImpl<MLKEM1024>(
|
||||||
|
seedRepresentation: privateKey.impl.seedRepresentation,
|
||||||
|
publicKeyRawRepresentation: privateKey.impl.publicKey.rawRepresentation
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates a new, random one-time-use private key.
|
||||||
|
public static func generate() throws -> MLKEM1024.OneTimePrivateKey {
|
||||||
|
let impl = try MLKEMOneTimePrivateKeyImpl<MLKEM1024>.generatePrivateKey()
|
||||||
|
return OneTimePrivateKey(impl)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Initializes a random one-time-use private key.
|
||||||
|
public init() throws {
|
||||||
|
self = try OneTimePrivateKey.generate()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decapsulate a shared secret.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - encapsulated: An encapsulated shared secret, that you get by calling ``MLKEM1024/PublicKey/encapsulate()`` on the corresponding public key.
|
||||||
|
/// - Returns: The shared secret.
|
||||||
|
public consuming func decapsulate<D: DataProtocol>(_ encapsulated: D) throws -> SymmetricKey {
|
||||||
|
return try impl.decapsulate(encapsulated: encapsulated)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The corresponding public key.
|
||||||
|
public var publicKey: MLKEM1024.PublicKey {
|
||||||
|
get {
|
||||||
|
self.impl.publicKey
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -1,162 +0,0 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
|
||||||
//
|
|
||||||
// This source file is part of the SwiftCrypto open source project
|
|
||||||
//
|
|
||||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
|
||||||
// Licensed under Apache License v2.0
|
|
||||||
//
|
|
||||||
// See LICENSE.txt for license information
|
|
||||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
|
||||||
//
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
//
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
@_exported import CryptoKit
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
|
||||||
public import FoundationEssentials
|
|
||||||
#else
|
|
||||||
public import Foundation
|
|
||||||
#endif
|
|
||||||
%{
|
|
||||||
MLKEM_VARIANTS = [{"name": "MLKEM768", "ccinfo": "cckem_mlkem768()!"}, {"name": "MLKEM1024", "ccinfo": "cckem_mlkem1024()!"}]
|
|
||||||
}%
|
|
||||||
|
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
typealias MLKEMPublicKeyImpl = CoreCryptoMLKEMPublicKeyImpl
|
|
||||||
typealias MLKEMPrivateKeyImpl = CoreCryptoMLKEMPrivateKeyImpl
|
|
||||||
#else
|
|
||||||
typealias MLKEMPublicKeyImpl = OpenSSLMLKEMPublicKeyImpl
|
|
||||||
typealias MLKEMPrivateKeyImpl = OpenSSLMLKEMPrivateKeyImpl
|
|
||||||
#endif
|
|
||||||
|
|
||||||
% for MLKEM_VARIANT in MLKEM_VARIANTS:
|
|
||||||
%{
|
|
||||||
NAME = MLKEM_VARIANT["name"]
|
|
||||||
INFO = MLKEM_VARIANT["ccinfo"]
|
|
||||||
}%
|
|
||||||
|
|
||||||
/// The Module-Lattice key encapsulation mechanism (KEM).
|
|
||||||
public enum ${NAME}: Sendable {}
|
|
||||||
|
|
||||||
extension ${NAME} {
|
|
||||||
/// A public key you use to encapsulate shared secrets with the Module-Lattice key encapsulation mechanism.
|
|
||||||
public struct PublicKey: KEMPublicKey, Sendable {
|
|
||||||
var impl: MLKEMPublicKeyImpl<${NAME}>
|
|
||||||
|
|
||||||
/// Initializes a public key from a raw representation.
|
|
||||||
/// - Parameter rawRepresentation: Data that represents the public key.
|
|
||||||
public init<D: DataProtocol>(rawRepresentation: D) throws {
|
|
||||||
self.impl = try MLKEMPublicKeyImpl(rawRepresentation: rawRepresentation)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A serialized representation of the public key.
|
|
||||||
public var rawRepresentation: Data {
|
|
||||||
get {
|
|
||||||
return self.impl.rawRepresentation
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Generates and encapsulates a shared secret.
|
|
||||||
///
|
|
||||||
/// - Returns: an encapsulated shared secret, that you decapsulate by calling ``${NAME}/PrivateKey/decapsulate(_:)`` on the corresponding private key.
|
|
||||||
public func encapsulate() throws -> KEM.EncapsulationResult {
|
|
||||||
return try self.impl.encapsulate()
|
|
||||||
}
|
|
||||||
|
|
||||||
func encapsulateWithSeed(encapSeed: Data) throws -> KEM.EncapsulationResult {
|
|
||||||
return try self.impl.encapsulateWithSeed(encapSeed)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A private key you use to decapsulate shared secrets with the Module-Lattice key encapsulation mechanism.
|
|
||||||
public struct PrivateKey: KEMPrivateKey {
|
|
||||||
internal let impl: MLKEMPrivateKeyImpl<${NAME}>
|
|
||||||
|
|
||||||
internal init(_ impl: MLKEMPrivateKeyImpl<${NAME}>) {
|
|
||||||
self.impl = impl
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Generates a new, random private key.
|
|
||||||
public static func generate() throws -> ${NAME}.PrivateKey {
|
|
||||||
let impl = try MLKEMPrivateKeyImpl<${NAME}>.generatePrivateKey()
|
|
||||||
return PrivateKey(impl)
|
|
||||||
}
|
|
||||||
|
|
||||||
static func generateWithSeed(_ seed: Data) throws -> ${NAME}.PrivateKey {
|
|
||||||
let impl = try MLKEMPrivateKeyImpl<${NAME}>.generateWithSeed(seed)
|
|
||||||
return PrivateKey(impl)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Initializes a random private key.
|
|
||||||
public init() throws {
|
|
||||||
self = try PrivateKey.generate()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Initializes a private key from a seed representation and optional public key.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - seedRepresentation: The seed representation `d||z`, as specified in the `ML-KEM.KeyGen_internal(d,z)` algorithm (Algorithm 16) of FIPS 203.
|
|
||||||
/// - publicKey: An optional public key. Pass this to check that the initialized private key is consistent with the public key. The initializer throws if the public key doesn't match the expected value.
|
|
||||||
public init<D: DataProtocol>(seedRepresentation: D, publicKey: ${NAME}.PublicKey?) throws {
|
|
||||||
var publicKeyRawRepresentation: Data? = nil
|
|
||||||
if publicKey != nil {
|
|
||||||
publicKeyRawRepresentation = publicKey!.rawRepresentation
|
|
||||||
}
|
|
||||||
self.impl = try MLKEMPrivateKeyImpl<${NAME}>(seedRepresentation: seedRepresentation, publicKeyRawRepresentation: publicKeyRawRepresentation)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The private key's seed representation.
|
|
||||||
///
|
|
||||||
/// The seed is `d||z`, as specified in the algorithm `ML-KEM.KeyGen_internal(d,z)` (Algorithm 16) of FIPS 203.
|
|
||||||
public var seedRepresentation: Data {
|
|
||||||
get {
|
|
||||||
return self.impl.seedRepresentation
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Decapsulated a shared secret.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - encapsulated: An encapsulated shared secret, that you get by calling ``${NAME}/PublicKey/encapsulate()`` on the corresponding public key.
|
|
||||||
/// - Returns: The shared secret.
|
|
||||||
public func decapsulate<D: DataProtocol>(_ encapsulated: D) throws -> SymmetricKey {
|
|
||||||
return try impl.decapsulate(encapsulated: encapsulated)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The corresponding public key.
|
|
||||||
public var publicKey: ${NAME}.PublicKey {
|
|
||||||
get {
|
|
||||||
try self.impl.publicKey
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Initializes a private key from an integrity-checked representation.
|
|
||||||
///
|
|
||||||
/// - Parameter integrityCheckedRepresentation: A representation of the private key that includes the seed value, and a hash of the corresponding public key.
|
|
||||||
public init<D: DataProtocol>(integrityCheckedRepresentation: D) throws {
|
|
||||||
guard integrityCheckedRepresentation.count == MLKEMPrivateKeyImpl<${NAME}>.seedSize + 32 else {
|
|
||||||
throw KEM.Errors.invalidSeed
|
|
||||||
}
|
|
||||||
let seed = Data(integrityCheckedRepresentation).subdata(in: 0..<MLKEMPrivateKeyImpl<${NAME}>.seedSize)
|
|
||||||
let publicKeyHashData = Data(integrityCheckedRepresentation).subdata(in: MLKEMPrivateKeyImpl<${NAME}>.seedSize..<integrityCheckedRepresentation.count)
|
|
||||||
let publicKeyHash = SHA3_256Digest(bytes: [UInt8](publicKeyHashData))
|
|
||||||
|
|
||||||
self.impl = try MLKEMPrivateKeyImpl<${NAME}>(seedRepresentation: seed, publicKeyHash: publicKeyHash)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An integrity-checked representation of the private key.
|
|
||||||
///
|
|
||||||
/// This representation includes the seed value, and a hash of the corresponding public key.
|
|
||||||
public var integrityCheckedRepresentation: Data {
|
|
||||||
get {
|
|
||||||
return self.impl.integrityCheckedRepresentation
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
% end
|
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
|
||||||
@@ -11,7 +11,12 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
|
@_exported import CryptoKit
|
||||||
|
#else
|
||||||
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
@@ -21,26 +26,15 @@ import FoundationEssentials
|
|||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias XWingPublicKeyImpl = CoreCryptoXWingPublicKeyImpl
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias XWingPrivateKeyImpl = CoreCryptoXWingPrivateKeyImpl
|
|
||||||
#else
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias XWingPublicKeyImpl = OpenSSLXWingPublicKeyImpl
|
typealias XWingPublicKeyImpl = OpenSSLXWingPublicKeyImpl
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias XWingPrivateKeyImpl = OpenSSLXWingPrivateKeyImpl
|
typealias XWingPrivateKeyImpl = OpenSSLXWingPrivateKeyImpl
|
||||||
#endif
|
|
||||||
|
|
||||||
/// The X-Wing (ML-KEM768 with X25519) Key Encapsulation Mechanism, defined in
|
/// The X-Wing (ML-KEM768 with X25519) Key Encapsulation Mechanism, defined in
|
||||||
/// https://datatracker.ietf.org/doc/html/draft-connolly-cfrg-xwing-kem-06
|
/// https://datatracker.ietf.org/doc/html/draft-connolly-cfrg-xwing-kem-06
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum XWingMLKEM768X25519: Sendable {}
|
public enum XWingMLKEM768X25519: Sendable {}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension XWingMLKEM768X25519 {
|
extension XWingMLKEM768X25519 {
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PublicKey: KEMPublicKey {
|
public struct PublicKey: KEMPublicKey {
|
||||||
var impl: XWingPublicKeyImpl
|
var impl: XWingPublicKeyImpl
|
||||||
|
|
||||||
@@ -63,9 +57,8 @@ extension XWingMLKEM768X25519 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PrivateKey: KEMPrivateKey {
|
public struct PrivateKey: KEMPrivateKey {
|
||||||
private var impl: XWingPrivateKeyImpl
|
var impl: XWingPrivateKeyImpl
|
||||||
|
|
||||||
public var seedRepresentation: Data {
|
public var seedRepresentation: Data {
|
||||||
get {
|
get {
|
||||||
@@ -101,9 +94,49 @@ extension XWingMLKEM768X25519 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A one-time-use private key to decapsulate a shared secret with the X-Wing key encapsulation mechanism.
|
||||||
|
///
|
||||||
|
/// The associated decapsulation function can be multiple times faster than the one implemented for PrivateKey,
|
||||||
|
/// but this private key can only be used to decapsulate a shared secret once.
|
||||||
|
public struct OneTimePrivateKey: KEMOneTimePrivateKey, ~Copyable {
|
||||||
|
private var impl: XWingPrivateKeyImpl
|
||||||
|
|
||||||
|
internal init(impl: XWingPrivateKeyImpl) {
|
||||||
|
self.impl = impl
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a one-time-use private key that reuses the key material of an existing private key.
|
||||||
|
///
|
||||||
|
/// This is used by the tests to check that the one-time decapsulation function is consistent with the regular one.
|
||||||
|
internal init(reusingForTestingOnly privateKey: XWingMLKEM768X25519.PrivateKey) {
|
||||||
|
self.impl = privateKey.impl
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates a new, random one-time-use private key.
|
||||||
|
public static func generate() throws -> XWingMLKEM768X25519.OneTimePrivateKey {
|
||||||
|
let impl = try XWingPrivateKeyImpl.generate()
|
||||||
|
return OneTimePrivateKey(impl: impl)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decapsulate a shared secret.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - encapsulated: An encapsulated shared secret, that you get by calling ``XWingMLKEM768X25519/PublicKey/encapsulate()`` on the corresponding public key.
|
||||||
|
/// - Returns: The shared secret.
|
||||||
|
public consuming func decapsulate(_ encapsulated: Data) throws -> SymmetricKey {
|
||||||
|
return try impl.decapsulate(encapsulated)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The corresponding public key.
|
||||||
|
public var publicKey: XWingMLKEM768X25519.PublicKey {
|
||||||
|
get {
|
||||||
|
XWingMLKEM768X25519.PublicKey(impl: self.impl.publicKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension XWingMLKEM768X25519.PrivateKey: HPKEKEMPrivateKeyGeneration {
|
extension XWingMLKEM768X25519.PrivateKey: HPKEKEMPrivateKeyGeneration {
|
||||||
public init() throws {
|
public init() throws {
|
||||||
self = try Self.generate()
|
self = try Self.generate()
|
||||||
@@ -121,13 +154,18 @@ extension XWingMLKEM768X25519.PrivateKey: HPKEKEMPrivateKeyGeneration {
|
|||||||
public init<D: DataProtocol>(integrityCheckedRepresentation: D) throws {
|
public init<D: DataProtocol>(integrityCheckedRepresentation: D) throws {
|
||||||
let seed = integrityCheckedRepresentation.dropLast(32) // sizeof(SHA3-256 digest)
|
let seed = integrityCheckedRepresentation.dropLast(32) // sizeof(SHA3-256 digest)
|
||||||
let publicKeyHashBytes = integrityCheckedRepresentation.dropFirst(32)
|
let publicKeyHashBytes = integrityCheckedRepresentation.dropFirst(32)
|
||||||
let publicKeyHash = SHA3_256Digest(bytes: [UInt8](publicKeyHashBytes))
|
let publicKeyHash = SHA3_256Digest { output in
|
||||||
|
for region in publicKeyHashBytes.regions {
|
||||||
|
region.withUnsafeBytes {
|
||||||
|
output.append(contentsOf: $0.bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
self = try XWingMLKEM768X25519.PrivateKey.init(seedRepresentation: seed, publicKeyHash: publicKeyHash)
|
self = try XWingMLKEM768X25519.PrivateKey.init(seedRepresentation: seed, publicKeyHash: publicKeyHash)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension XWingMLKEM768X25519.PublicKey: HPKEKEMPublicKey {
|
extension XWingMLKEM768X25519.PublicKey: HPKEKEMPublicKey {
|
||||||
/// The type of the ephemeral private key associated with this public key.
|
/// The type of the ephemeral private key associated with this public key.
|
||||||
public typealias EphemeralPrivateKey = XWingMLKEM768X25519.PrivateKey
|
public typealias EphemeralPrivateKey = XWingMLKEM768X25519.PrivateKey
|
||||||
@@ -169,4 +207,5 @@ extension XWingMLKEM768X25519.PublicKey: HPKEKEMPublicKey {
|
|||||||
/// The type of the ephemeral private key associated with this public key.
|
/// The type of the ephemeral private key associated with this public key.
|
||||||
public typealias HPKEEphemeralPrivateKey = XWingMLKEM768X25519.PrivateKey
|
public typealias HPKEEphemeralPrivateKey = XWingMLKEM768X25519.PrivateKey
|
||||||
}
|
}
|
||||||
#endif // Linux or !SwiftPM
|
#endif
|
||||||
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,10 +11,14 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
#if hasFeature(SourceWarningControl)
|
||||||
|
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||||
|
#else
|
||||||
@_implementationOnly import CCryptoBoringSSL
|
@_implementationOnly import CCryptoBoringSSL
|
||||||
|
#endif
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||||
extension P256.KeyAgreement.PrivateKey {
|
extension P256.KeyAgreement.PrivateKey {
|
||||||
@@ -45,4 +49,4 @@ extension P521.KeyAgreement.PrivateKey {
|
|||||||
return SharedSecret(ss: key)
|
return SharedSecret(ss: key)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,23 +11,19 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
/// A Diffie-Hellman Key Agreement Key
|
/// A Diffie-Hellman Key Agreement Key
|
||||||
@preconcurrency
|
@preconcurrency
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public protocol DiffieHellmanKeyAgreement: Sendable {
|
public protocol DiffieHellmanKeyAgreement: Sendable {
|
||||||
/// The public key share type to perform the DH Key Agreement
|
/// The public key share type to perform the DH Key Agreement
|
||||||
associatedtype PublicKey: Sendable
|
associatedtype PublicKey: Sendable
|
||||||
@@ -58,7 +54,6 @@ public protocol DiffieHellmanKeyAgreement: Sendable {
|
|||||||
/// symmetric key suitable for creating a message authentication code like
|
/// symmetric key suitable for creating a message authentication code like
|
||||||
/// ``HMAC``, or for opening and closing a sealed box with a cipher like
|
/// ``HMAC``, or for opening and closing a sealed box with a cipher like
|
||||||
/// ``ChaChaPoly`` or ``AES``.
|
/// ``ChaChaPoly`` or ``AES``.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SharedSecret: ContiguousBytes, Sendable {
|
public struct SharedSecret: ContiguousBytes, Sendable {
|
||||||
var ss: SecureBytes
|
var ss: SecureBytes
|
||||||
|
|
||||||
@@ -119,7 +114,6 @@ public struct SharedSecret: ContiguousBytes, Sendable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension SharedSecret: Hashable {
|
extension SharedSecret: Hashable {
|
||||||
public func hash(into hasher: inout Hasher) {
|
public func hash(into hasher: inout Hasher) {
|
||||||
ss.withUnsafeBytes { hasher.combine(bytes: $0) }
|
ss.withUnsafeBytes { hasher.combine(bytes: $0) }
|
||||||
@@ -127,7 +121,6 @@ extension SharedSecret: Hashable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// We want to implement constant-time comparison for digests.
|
// We want to implement constant-time comparison for digests.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension SharedSecret: Equatable {
|
extension SharedSecret: Equatable {
|
||||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||||
return safeCompare(lhs, rhs)
|
return safeCompare(lhs, rhs)
|
||||||
@@ -153,7 +146,6 @@ extension SharedSecret: Equatable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#if !hasFeature(Embedded)
|
#if !hasFeature(Embedded)
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension SharedSecret: CustomStringConvertible {
|
extension SharedSecret: CustomStringConvertible {
|
||||||
public var description: String {
|
public var description: String {
|
||||||
return "\(Self.self): \(ss.hexString)"
|
return "\(Self.self): \(ss.hexString)"
|
||||||
@@ -161,7 +153,6 @@ extension SharedSecret: CustomStringConvertible {
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension HashFunction {
|
extension HashFunction {
|
||||||
// A wrapper function to keep the unsafe code in one place.
|
// A wrapper function to keep the unsafe code in one place.
|
||||||
mutating func update(_ secret: SharedSecret) {
|
mutating func update(_ secret: SharedSecret) {
|
||||||
@@ -176,4 +167,4 @@ extension HashFunction {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,46 +11,32 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias NISTCurvePublicKeyImpl = CoreCryptoNISTCurvePublicKeyImpl
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias NISTCurvePrivateKeyImpl = CoreCryptoNISTCurvePrivateKeyImpl
|
|
||||||
#else
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias NISTCurvePublicKeyImpl = OpenSSLNISTCurvePublicKeyImpl
|
typealias NISTCurvePublicKeyImpl = OpenSSLNISTCurvePublicKeyImpl
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias NISTCurvePrivateKeyImpl = OpenSSLNISTCurvePrivateKeyImpl
|
typealias NISTCurvePrivateKeyImpl = OpenSSLNISTCurvePrivateKeyImpl
|
||||||
#endif
|
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
// MARK: - Generated file, do NOT edit
|
// MARK: - Generated file, do NOT edit
|
||||||
// any edits of this file WILL be overwritten and thus discarded
|
// any edits of this file WILL be overwritten and thus discarded
|
||||||
// see section `gyb` in `README` for details.
|
// see section `gyb` in `README` for details.
|
||||||
|
|
||||||
// MARK: - P256 + Signing
|
// MARK: - P256 + Signing
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P256 {
|
extension P256 {
|
||||||
|
|
||||||
/// A mechanism used to create or verify a cryptographic signature using
|
/// A mechanism used to create or verify a cryptographic signature using
|
||||||
/// the NIST P-256 elliptic curve digital signature algorithm (ECDSA).
|
/// the NIST P-256 elliptic curve digital signature algorithm (ECDSA).
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum Signing: Sendable {
|
public enum Signing: Sendable {
|
||||||
|
|
||||||
/// A P-256 public key used to verify cryptographic signatures.
|
/// A P-256 public key used to verify cryptographic signatures.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PublicKey: NISTECPublicKey, Sendable {
|
public struct PublicKey: NISTECPublicKey, Sendable {
|
||||||
var impl: NISTCurvePublicKeyImpl<P256>
|
var impl: NISTCurvePublicKeyImpl<P256>
|
||||||
|
|
||||||
@@ -154,7 +140,6 @@ extension P256 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A P-256 private key used to create cryptographic signatures.
|
/// A P-256 private key used to create cryptographic signatures.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
||||||
let impl: NISTCurvePrivateKeyImpl<P256>
|
let impl: NISTCurvePrivateKeyImpl<P256>
|
||||||
|
|
||||||
@@ -204,6 +189,9 @@ extension P256 {
|
|||||||
self = try .init(rawRepresentation: parsed.privateKey)
|
self = try .init(rawRepresentation: parsed.privateKey)
|
||||||
case "PRIVATE KEY":
|
case "PRIVATE KEY":
|
||||||
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
||||||
|
guard parsed.algorithm == .ecdsaP256 else {
|
||||||
|
throw CryptoKitASN1Error.invalidASN1Object
|
||||||
|
}
|
||||||
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
||||||
default:
|
default:
|
||||||
throw CryptoKitASN1Error.invalidPEMDocument
|
throw CryptoKitASN1Error.invalidPEMDocument
|
||||||
@@ -224,6 +212,9 @@ extension P256 {
|
|||||||
|
|
||||||
do {
|
do {
|
||||||
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
||||||
|
guard key.algorithm == .ecdsaP256 else {
|
||||||
|
throw CryptoKitASN1Error.invalidASN1Object
|
||||||
|
}
|
||||||
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
||||||
} catch {
|
} catch {
|
||||||
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
||||||
@@ -267,17 +258,15 @@ extension P256 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// MARK: - P256 + KeyAgreement
|
// MARK: - P256 + KeyAgreement
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P256 {
|
extension P256 {
|
||||||
|
|
||||||
/// A mechanism used to create a shared secret between two users by
|
/// A mechanism used to create a shared secret between two users by
|
||||||
/// performing NIST P-256 elliptic curve Diffie Hellman (ECDH) key
|
/// performing NIST P-256 elliptic curve Diffie Hellman (ECDH) key
|
||||||
/// exchange.
|
/// exchange.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum KeyAgreement: Sendable {
|
public enum KeyAgreement: Sendable {
|
||||||
|
|
||||||
/// A P-256 public key used for key agreement.
|
/// A P-256 public key used for key agreement.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PublicKey: NISTECPublicKey, Sendable {
|
public struct PublicKey: NISTECPublicKey, Sendable {
|
||||||
var impl: NISTCurvePublicKeyImpl<P256>
|
var impl: NISTCurvePublicKeyImpl<P256>
|
||||||
|
|
||||||
@@ -381,7 +370,6 @@ extension P256 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A P-256 private key used for key agreement.
|
/// A P-256 private key used for key agreement.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
||||||
let impl: NISTCurvePrivateKeyImpl<P256>
|
let impl: NISTCurvePrivateKeyImpl<P256>
|
||||||
|
|
||||||
@@ -431,6 +419,9 @@ extension P256 {
|
|||||||
self = try .init(rawRepresentation: parsed.privateKey)
|
self = try .init(rawRepresentation: parsed.privateKey)
|
||||||
case "PRIVATE KEY":
|
case "PRIVATE KEY":
|
||||||
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
||||||
|
guard parsed.algorithm == .ecdsaP256 else {
|
||||||
|
throw CryptoKitASN1Error.invalidASN1Object
|
||||||
|
}
|
||||||
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
||||||
default:
|
default:
|
||||||
throw CryptoKitASN1Error.invalidPEMDocument
|
throw CryptoKitASN1Error.invalidPEMDocument
|
||||||
@@ -451,6 +442,9 @@ extension P256 {
|
|||||||
|
|
||||||
do {
|
do {
|
||||||
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
||||||
|
guard key.algorithm == .ecdsaP256 else {
|
||||||
|
throw CryptoKitASN1Error.invalidASN1Object
|
||||||
|
}
|
||||||
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
||||||
} catch {
|
} catch {
|
||||||
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
||||||
@@ -494,16 +488,14 @@ extension P256 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// MARK: - P384 + Signing
|
// MARK: - P384 + Signing
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P384 {
|
extension P384 {
|
||||||
|
|
||||||
/// A mechanism used to create or verify a cryptographic signature using
|
/// A mechanism used to create or verify a cryptographic signature using
|
||||||
/// the NIST P-384 elliptic curve digital signature algorithm (ECDSA).
|
/// the NIST P-384 elliptic curve digital signature algorithm (ECDSA).
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum Signing: Sendable {
|
public enum Signing: Sendable {
|
||||||
|
|
||||||
/// A P-384 public key used to verify cryptographic signatures.
|
/// A P-384 public key used to verify cryptographic signatures.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PublicKey: NISTECPublicKey, Sendable {
|
public struct PublicKey: NISTECPublicKey, Sendable {
|
||||||
var impl: NISTCurvePublicKeyImpl<P384>
|
var impl: NISTCurvePublicKeyImpl<P384>
|
||||||
|
|
||||||
@@ -607,7 +599,6 @@ extension P384 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A P-384 private key used to create cryptographic signatures.
|
/// A P-384 private key used to create cryptographic signatures.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
||||||
let impl: NISTCurvePrivateKeyImpl<P384>
|
let impl: NISTCurvePrivateKeyImpl<P384>
|
||||||
|
|
||||||
@@ -657,6 +648,9 @@ extension P384 {
|
|||||||
self = try .init(rawRepresentation: parsed.privateKey)
|
self = try .init(rawRepresentation: parsed.privateKey)
|
||||||
case "PRIVATE KEY":
|
case "PRIVATE KEY":
|
||||||
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
||||||
|
guard parsed.algorithm == .ecdsaP384 else {
|
||||||
|
throw CryptoKitASN1Error.invalidASN1Object
|
||||||
|
}
|
||||||
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
||||||
default:
|
default:
|
||||||
throw CryptoKitASN1Error.invalidPEMDocument
|
throw CryptoKitASN1Error.invalidPEMDocument
|
||||||
@@ -677,6 +671,9 @@ extension P384 {
|
|||||||
|
|
||||||
do {
|
do {
|
||||||
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
||||||
|
guard key.algorithm == .ecdsaP384 else {
|
||||||
|
throw CryptoKitASN1Error.invalidASN1Object
|
||||||
|
}
|
||||||
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
||||||
} catch {
|
} catch {
|
||||||
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
||||||
@@ -720,17 +717,15 @@ extension P384 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// MARK: - P384 + KeyAgreement
|
// MARK: - P384 + KeyAgreement
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P384 {
|
extension P384 {
|
||||||
|
|
||||||
/// A mechanism used to create a shared secret between two users by
|
/// A mechanism used to create a shared secret between two users by
|
||||||
/// performing NIST P-384 elliptic curve Diffie Hellman (ECDH) key
|
/// performing NIST P-384 elliptic curve Diffie Hellman (ECDH) key
|
||||||
/// exchange.
|
/// exchange.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum KeyAgreement: Sendable {
|
public enum KeyAgreement: Sendable {
|
||||||
|
|
||||||
/// A P-384 public key used for key agreement.
|
/// A P-384 public key used for key agreement.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PublicKey: NISTECPublicKey, Sendable {
|
public struct PublicKey: NISTECPublicKey, Sendable {
|
||||||
var impl: NISTCurvePublicKeyImpl<P384>
|
var impl: NISTCurvePublicKeyImpl<P384>
|
||||||
|
|
||||||
@@ -834,7 +829,6 @@ extension P384 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A P-384 private key used for key agreement.
|
/// A P-384 private key used for key agreement.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
||||||
let impl: NISTCurvePrivateKeyImpl<P384>
|
let impl: NISTCurvePrivateKeyImpl<P384>
|
||||||
|
|
||||||
@@ -884,6 +878,9 @@ extension P384 {
|
|||||||
self = try .init(rawRepresentation: parsed.privateKey)
|
self = try .init(rawRepresentation: parsed.privateKey)
|
||||||
case "PRIVATE KEY":
|
case "PRIVATE KEY":
|
||||||
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
||||||
|
guard parsed.algorithm == .ecdsaP384 else {
|
||||||
|
throw CryptoKitASN1Error.invalidASN1Object
|
||||||
|
}
|
||||||
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
||||||
default:
|
default:
|
||||||
throw CryptoKitASN1Error.invalidPEMDocument
|
throw CryptoKitASN1Error.invalidPEMDocument
|
||||||
@@ -904,6 +901,9 @@ extension P384 {
|
|||||||
|
|
||||||
do {
|
do {
|
||||||
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
||||||
|
guard key.algorithm == .ecdsaP384 else {
|
||||||
|
throw CryptoKitASN1Error.invalidASN1Object
|
||||||
|
}
|
||||||
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
||||||
} catch {
|
} catch {
|
||||||
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
||||||
@@ -947,16 +947,14 @@ extension P384 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// MARK: - P521 + Signing
|
// MARK: - P521 + Signing
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P521 {
|
extension P521 {
|
||||||
|
|
||||||
/// A mechanism used to create or verify a cryptographic signature using
|
/// A mechanism used to create or verify a cryptographic signature using
|
||||||
/// the NIST P-521 elliptic curve digital signature algorithm (ECDSA).
|
/// the NIST P-521 elliptic curve digital signature algorithm (ECDSA).
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum Signing: Sendable {
|
public enum Signing: Sendable {
|
||||||
|
|
||||||
/// A P-521 public key used to verify cryptographic signatures.
|
/// A P-521 public key used to verify cryptographic signatures.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PublicKey: NISTECPublicKey, Sendable {
|
public struct PublicKey: NISTECPublicKey, Sendable {
|
||||||
var impl: NISTCurvePublicKeyImpl<P521>
|
var impl: NISTCurvePublicKeyImpl<P521>
|
||||||
|
|
||||||
@@ -1060,7 +1058,6 @@ extension P521 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A P-521 private key used to create cryptographic signatures.
|
/// A P-521 private key used to create cryptographic signatures.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
||||||
let impl: NISTCurvePrivateKeyImpl<P521>
|
let impl: NISTCurvePrivateKeyImpl<P521>
|
||||||
|
|
||||||
@@ -1110,6 +1107,9 @@ extension P521 {
|
|||||||
self = try .init(rawRepresentation: parsed.privateKey)
|
self = try .init(rawRepresentation: parsed.privateKey)
|
||||||
case "PRIVATE KEY":
|
case "PRIVATE KEY":
|
||||||
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
||||||
|
guard parsed.algorithm == .ecdsaP521 else {
|
||||||
|
throw CryptoKitASN1Error.invalidASN1Object
|
||||||
|
}
|
||||||
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
||||||
default:
|
default:
|
||||||
throw CryptoKitASN1Error.invalidPEMDocument
|
throw CryptoKitASN1Error.invalidPEMDocument
|
||||||
@@ -1130,6 +1130,9 @@ extension P521 {
|
|||||||
|
|
||||||
do {
|
do {
|
||||||
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
||||||
|
guard key.algorithm == .ecdsaP521 else {
|
||||||
|
throw CryptoKitASN1Error.invalidASN1Object
|
||||||
|
}
|
||||||
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
||||||
} catch {
|
} catch {
|
||||||
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
||||||
@@ -1173,17 +1176,15 @@ extension P521 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// MARK: - P521 + KeyAgreement
|
// MARK: - P521 + KeyAgreement
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P521 {
|
extension P521 {
|
||||||
|
|
||||||
/// A mechanism used to create a shared secret between two users by
|
/// A mechanism used to create a shared secret between two users by
|
||||||
/// performing NIST P-521 elliptic curve Diffie Hellman (ECDH) key
|
/// performing NIST P-521 elliptic curve Diffie Hellman (ECDH) key
|
||||||
/// exchange.
|
/// exchange.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum KeyAgreement: Sendable {
|
public enum KeyAgreement: Sendable {
|
||||||
|
|
||||||
/// A P-521 public key used for key agreement.
|
/// A P-521 public key used for key agreement.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PublicKey: NISTECPublicKey, Sendable {
|
public struct PublicKey: NISTECPublicKey, Sendable {
|
||||||
var impl: NISTCurvePublicKeyImpl<P521>
|
var impl: NISTCurvePublicKeyImpl<P521>
|
||||||
|
|
||||||
@@ -1287,7 +1288,6 @@ extension P521 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A P-521 private key used for key agreement.
|
/// A P-521 private key used for key agreement.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
||||||
let impl: NISTCurvePrivateKeyImpl<P521>
|
let impl: NISTCurvePrivateKeyImpl<P521>
|
||||||
|
|
||||||
@@ -1337,6 +1337,9 @@ extension P521 {
|
|||||||
self = try .init(rawRepresentation: parsed.privateKey)
|
self = try .init(rawRepresentation: parsed.privateKey)
|
||||||
case "PRIVATE KEY":
|
case "PRIVATE KEY":
|
||||||
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
||||||
|
guard parsed.algorithm == .ecdsaP521 else {
|
||||||
|
throw CryptoKitASN1Error.invalidASN1Object
|
||||||
|
}
|
||||||
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
||||||
default:
|
default:
|
||||||
throw CryptoKitASN1Error.invalidPEMDocument
|
throw CryptoKitASN1Error.invalidPEMDocument
|
||||||
@@ -1357,6 +1360,9 @@ extension P521 {
|
|||||||
|
|
||||||
do {
|
do {
|
||||||
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
||||||
|
guard key.algorithm == .ecdsaP521 else {
|
||||||
|
throw CryptoKitASN1Error.invalidASN1Object
|
||||||
|
}
|
||||||
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
||||||
} catch {
|
} catch {
|
||||||
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
||||||
@@ -1401,7 +1407,6 @@ extension P521 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - P256 + DH
|
// MARK: - P256 + DH
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P256.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
|
extension P256.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
|
||||||
/// Computes a shared secret with the provided public key from another party.
|
/// Computes a shared secret with the provided public key from another party.
|
||||||
///
|
///
|
||||||
@@ -1410,15 +1415,10 @@ extension P256.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
|
|||||||
/// key from this user to create the shared secret.
|
/// key from this user to create the shared secret.
|
||||||
/// - Returns: The computed shared secret.
|
/// - Returns: The computed shared secret.
|
||||||
public func sharedSecretFromKeyAgreement(with publicKeyShare: P256.KeyAgreement.PublicKey) throws(CryptoKitMetaError) -> SharedSecret {
|
public func sharedSecretFromKeyAgreement(with publicKeyShare: P256.KeyAgreement.PublicKey) throws(CryptoKitMetaError) -> SharedSecret {
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
return try self.coreCryptoSharedSecretFromKeyAgreement(with: publicKeyShare)
|
|
||||||
#else
|
|
||||||
return try self.openSSLSharedSecretFromKeyAgreement(with: publicKeyShare)
|
return try self.openSSLSharedSecretFromKeyAgreement(with: publicKeyShare)
|
||||||
#endif
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// MARK: - P384 + DH
|
// MARK: - P384 + DH
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P384.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
|
extension P384.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
|
||||||
/// Computes a shared secret with the provided public key from another party.
|
/// Computes a shared secret with the provided public key from another party.
|
||||||
///
|
///
|
||||||
@@ -1427,15 +1427,10 @@ extension P384.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
|
|||||||
/// key from this user to create the shared secret.
|
/// key from this user to create the shared secret.
|
||||||
/// - Returns: The computed shared secret.
|
/// - Returns: The computed shared secret.
|
||||||
public func sharedSecretFromKeyAgreement(with publicKeyShare: P384.KeyAgreement.PublicKey) throws(CryptoKitMetaError) -> SharedSecret {
|
public func sharedSecretFromKeyAgreement(with publicKeyShare: P384.KeyAgreement.PublicKey) throws(CryptoKitMetaError) -> SharedSecret {
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
return try self.coreCryptoSharedSecretFromKeyAgreement(with: publicKeyShare)
|
|
||||||
#else
|
|
||||||
return try self.openSSLSharedSecretFromKeyAgreement(with: publicKeyShare)
|
return try self.openSSLSharedSecretFromKeyAgreement(with: publicKeyShare)
|
||||||
#endif
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// MARK: - P521 + DH
|
// MARK: - P521 + DH
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P521.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
|
extension P521.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
|
||||||
/// Computes a shared secret with the provided public key from another party.
|
/// Computes a shared secret with the provided public key from another party.
|
||||||
///
|
///
|
||||||
@@ -1444,11 +1439,7 @@ extension P521.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
|
|||||||
/// key from this user to create the shared secret.
|
/// key from this user to create the shared secret.
|
||||||
/// - Returns: The computed shared secret.
|
/// - Returns: The computed shared secret.
|
||||||
public func sharedSecretFromKeyAgreement(with publicKeyShare: P521.KeyAgreement.PublicKey) throws(CryptoKitMetaError) -> SharedSecret {
|
public func sharedSecretFromKeyAgreement(with publicKeyShare: P521.KeyAgreement.PublicKey) throws(CryptoKitMetaError) -> SharedSecret {
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
return try self.coreCryptoSharedSecretFromKeyAgreement(with: publicKeyShare)
|
|
||||||
#else
|
|
||||||
return try self.openSSLSharedSecretFromKeyAgreement(with: publicKeyShare)
|
return try self.openSSLSharedSecretFromKeyAgreement(with: publicKeyShare)
|
||||||
#endif
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -1,305 +0,0 @@
|
|||||||
//===----------------------------------------------------------------------===//
|
|
||||||
//
|
|
||||||
// This source file is part of the SwiftCrypto open source project
|
|
||||||
//
|
|
||||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
|
||||||
// Licensed under Apache License v2.0
|
|
||||||
//
|
|
||||||
// See LICENSE.txt for license information
|
|
||||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
|
||||||
//
|
|
||||||
// SPDX-License-Identifier: Apache-2.0
|
|
||||||
//
|
|
||||||
//===----------------------------------------------------------------------===//
|
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
@_exported import CryptoKit
|
|
||||||
#else
|
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
typealias NISTCurvePublicKeyImpl = CoreCryptoNISTCurvePublicKeyImpl
|
|
||||||
typealias NISTCurvePrivateKeyImpl = CoreCryptoNISTCurvePrivateKeyImpl
|
|
||||||
#else
|
|
||||||
typealias NISTCurvePublicKeyImpl = OpenSSLNISTCurvePublicKeyImpl
|
|
||||||
typealias NISTCurvePrivateKeyImpl = OpenSSLNISTCurvePrivateKeyImpl
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
|
||||||
public import FoundationEssentials
|
|
||||||
#else
|
|
||||||
public import Foundation
|
|
||||||
#endif
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// MARK: - Generated file, do NOT edit
|
|
||||||
// any edits of this file WILL be overwritten and thus discarded
|
|
||||||
// see section `gyb` in `README` for details.
|
|
||||||
|
|
||||||
%{
|
|
||||||
NIST_CURVES = ["P256", "P384", "P521"]
|
|
||||||
CURVES_FUNC = ["Signing", "KeyAgreement"]
|
|
||||||
}%
|
|
||||||
% for CURVE in NIST_CURVES:
|
|
||||||
%{ DISPLAY_CURVE = CURVE[:1] + "-" + CURVE[1:] }%
|
|
||||||
% for FUNC in CURVES_FUNC:
|
|
||||||
// MARK: - ${CURVE} + ${FUNC}
|
|
||||||
extension ${CURVE} {
|
|
||||||
|
|
||||||
% if FUNC == "Signing":
|
|
||||||
/// A mechanism used to create or verify a cryptographic signature using
|
|
||||||
/// the NIST ${DISPLAY_CURVE} elliptic curve digital signature algorithm (ECDSA).
|
|
||||||
% else:
|
|
||||||
/// A mechanism used to create a shared secret between two users by
|
|
||||||
/// performing NIST ${DISPLAY_CURVE} elliptic curve Diffie Hellman (ECDH) key
|
|
||||||
/// exchange.
|
|
||||||
% end
|
|
||||||
public enum ${FUNC}: Sendable {
|
|
||||||
|
|
||||||
% if FUNC == "Signing":
|
|
||||||
%{ READABLE_FUNC = "signing" }%
|
|
||||||
/// A ${DISPLAY_CURVE} public key used to verify cryptographic signatures.
|
|
||||||
% else:
|
|
||||||
%{ READABLE_FUNC = "key agreement" }%
|
|
||||||
/// A ${DISPLAY_CURVE} public key used for key agreement.
|
|
||||||
% end
|
|
||||||
public struct PublicKey: NISTECPublicKey, Sendable {
|
|
||||||
var impl: NISTCurvePublicKeyImpl<${CURVE}>
|
|
||||||
|
|
||||||
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a collection of bytes.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - rawRepresentation: A raw representation of the key as a collection of
|
|
||||||
/// contiguous bytes.
|
|
||||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws(CryptoKitMetaError) {
|
|
||||||
impl = try NISTCurvePublicKeyImpl(rawRepresentation: rawRepresentation)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a compact
|
|
||||||
/// representation of the key.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - compactRepresentation: A compact representation of the key
|
|
||||||
/// as a collection of contiguous bytes.
|
|
||||||
public init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws(CryptoKitMetaError) {
|
|
||||||
impl = try NISTCurvePublicKeyImpl(compactRepresentation: compactRepresentation)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from an ANSI x9.63
|
|
||||||
/// representation.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - x963Representation: An ANSI x9.63 representation of the key.
|
|
||||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws(CryptoKitMetaError) {
|
|
||||||
impl = try NISTCurvePublicKeyImpl(x963Representation: x963Representation)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a compressed representation of
|
|
||||||
/// the key.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - compressedRepresentation: A compressed representation of the key as a collection
|
|
||||||
/// of contiguous bytes.
|
|
||||||
public init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws(CryptoKitMetaError) {
|
|
||||||
impl = try NISTCurvePublicKeyImpl(compressedRepresentation: compressedRepresentation)
|
|
||||||
}
|
|
||||||
|
|
||||||
#if !hasFeature(Embedded)
|
|
||||||
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a Privacy-Enhanced Mail
|
|
||||||
/// (PEM) representation.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - pemRepresentation: A PEM representation of the key.
|
|
||||||
public init(pemRepresentation: String) throws(CryptoKitMetaError) {
|
|
||||||
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
|
|
||||||
guard pem.type == "PUBLIC KEY" else {
|
|
||||||
throw CryptoKitASN1Error.invalidPEMDocument
|
|
||||||
}
|
|
||||||
self = try .init(derRepresentation: pem.derBytes)
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a Distinguished Encoding
|
|
||||||
/// Rules (DER) encoded representation.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - derRepresentation: A DER-encoded representation of the key.
|
|
||||||
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws(CryptoKitMetaError) where Bytes.Element == UInt8 {
|
|
||||||
let bytes = Array(derRepresentation)
|
|
||||||
let parsed = try ASN1.SubjectPublicKeyInfo(asn1Encoded: bytes)
|
|
||||||
self = try .init(x963Representation: parsed.key)
|
|
||||||
}
|
|
||||||
|
|
||||||
init(impl: NISTCurvePublicKeyImpl<${CURVE}>) {
|
|
||||||
self.impl = impl
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A compact representation of the public key.
|
|
||||||
public var compactRepresentation: Data? { impl.compactRepresentation }
|
|
||||||
|
|
||||||
/// A full representation of the public key.
|
|
||||||
public var rawRepresentation: Data { impl.rawRepresentation }
|
|
||||||
|
|
||||||
/// An ANSI x9.63 representation of the public key.
|
|
||||||
public var x963Representation: Data { impl.x963Representation }
|
|
||||||
|
|
||||||
/// A compressed representation of the public key.
|
|
||||||
public var compressedRepresentation: Data { impl.compressedRepresentation }
|
|
||||||
|
|
||||||
/// A Distinguished Encoding Rules (DER) encoded representation of the public key.
|
|
||||||
public var derRepresentation: Data {
|
|
||||||
let spki = ASN1.SubjectPublicKeyInfo(algorithmIdentifier: .ecdsa${CURVE}, key: Array(self.x963Representation))
|
|
||||||
var serializer = ASN1.Serializer()
|
|
||||||
|
|
||||||
// Serializing these keys can't throw
|
|
||||||
try! serializer.serialize(spki)
|
|
||||||
return Data(serializer.serializedBytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
#if !hasFeature(Embedded)
|
|
||||||
/// A Privacy-Enhanced Mail (PEM) representation of the public key.
|
|
||||||
public var pemRepresentation: String {
|
|
||||||
let pemDocument = ASN1.PEMDocument(type: "PUBLIC KEY", derBytes: self.derRepresentation)
|
|
||||||
return pemDocument.pemString
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
% if FUNC == "Signing":
|
|
||||||
/// A ${DISPLAY_CURVE} private key used to create cryptographic signatures.
|
|
||||||
% else:
|
|
||||||
/// A ${DISPLAY_CURVE} private key used for key agreement.
|
|
||||||
% end
|
|
||||||
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
|
||||||
let impl: NISTCurvePrivateKeyImpl<${CURVE}>
|
|
||||||
|
|
||||||
/// Creates a random ${DISPLAY_CURVE} private key for ${READABLE_FUNC}.
|
|
||||||
///
|
|
||||||
/// Keys that use a compact point encoding enable shorter public keys, but aren’t
|
|
||||||
/// compliant with FIPS certification. If your app requires FIPS certification,
|
|
||||||
/// create a key with ``init(rawRepresentation:)``.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - compactRepresentable: A Boolean value that indicates whether CryptoKit
|
|
||||||
/// creates the key with the structure to enable compact point encoding.
|
|
||||||
public init(compactRepresentable: Bool = true) {
|
|
||||||
impl = NISTCurvePrivateKeyImpl(compactRepresentable: compactRepresentable)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a ${DISPLAY_CURVE} private key for ${READABLE_FUNC} from an ANSI x9.63
|
|
||||||
/// representation.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - x963Representation: An ANSI x9.63 representation of the key.
|
|
||||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws(CryptoKitMetaError) {
|
|
||||||
impl = try NISTCurvePrivateKeyImpl(x963: x963Representation)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a ${DISPLAY_CURVE} private key for ${READABLE_FUNC} from a collection of bytes.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - rawRepresentation: A raw representation of the key as a collection of
|
|
||||||
/// contiguous bytes.
|
|
||||||
public init<Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws(CryptoKitMetaError) {
|
|
||||||
impl = try NISTCurvePrivateKeyImpl(data: rawRepresentation)
|
|
||||||
}
|
|
||||||
|
|
||||||
#if !hasFeature(Embedded)
|
|
||||||
/// Creates a ${DISPLAY_CURVE} private key for ${READABLE_FUNC} from a Privacy-Enhanced Mail
|
|
||||||
/// PEM) representation.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - pemRepresentation: A PEM representation of the key.
|
|
||||||
public init(pemRepresentation: String) throws(CryptoKitMetaError) {
|
|
||||||
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
|
|
||||||
|
|
||||||
switch pem.type {
|
|
||||||
case "EC PRIVATE KEY":
|
|
||||||
let parsed = try ASN1.SEC1PrivateKey(asn1Encoded: Array(pem.derBytes))
|
|
||||||
self = try .init(rawRepresentation: parsed.privateKey)
|
|
||||||
case "PRIVATE KEY":
|
|
||||||
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
|
||||||
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
|
||||||
default:
|
|
||||||
throw CryptoKitASN1Error.invalidPEMDocument
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/// Creates a ${DISPLAY_CURVE} private key for ${READABLE_FUNC} from a Distinguished Encoding
|
|
||||||
/// Rules (DER) encoded representation.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - derRepresentation: A DER-encoded representation of the key.
|
|
||||||
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws(CryptoKitMetaError) where Bytes.Element == UInt8 {
|
|
||||||
let bytes = Array(derRepresentation)
|
|
||||||
|
|
||||||
// We have to try to parse this twice because we have no information about what kind of key this is.
|
|
||||||
// We try with PKCS#8 first, and then fall back to SEC.1.
|
|
||||||
|
|
||||||
do {
|
|
||||||
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
|
||||||
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
|
||||||
} catch {
|
|
||||||
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
|
||||||
self = try .init(rawRepresentation: key.privateKey)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
init(impl: NISTCurvePrivateKeyImpl<${CURVE}>) {
|
|
||||||
self.impl = impl
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The corresponding public key.
|
|
||||||
public var publicKey: ${CURVE}.${FUNC}.PublicKey {
|
|
||||||
return PublicKey(impl: impl.publicKey())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A data representation of the private key.
|
|
||||||
public var rawRepresentation: Data { impl.rawRepresentation }
|
|
||||||
|
|
||||||
/// An ANSI x9.63 representation of the private key.
|
|
||||||
public var x963Representation: Data { impl.x963Representation }
|
|
||||||
|
|
||||||
/// A Distinguished Encoding Rules (DER) encoded representation of the private key.
|
|
||||||
public var derRepresentation: Data {
|
|
||||||
let pkey = ASN1.PKCS8PrivateKey(algorithm: .ecdsa${CURVE}, privateKey: Array(self.rawRepresentation), publicKey: Array(self.publicKey.x963Representation))
|
|
||||||
var serializer = ASN1.Serializer()
|
|
||||||
|
|
||||||
// Serializing these keys can't throw
|
|
||||||
try! serializer.serialize(pkey)
|
|
||||||
return Data(serializer.serializedBytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
#if !hasFeature(Embedded)
|
|
||||||
/// A Privacy-Enhanced Mail (PEM) representation of the private key.
|
|
||||||
public var pemRepresentation: String {
|
|
||||||
let pemDocument = ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: self.derRepresentation)
|
|
||||||
return pemDocument.pemString
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
% end
|
|
||||||
% end
|
|
||||||
|
|
||||||
% for CURVE in NIST_CURVES:
|
|
||||||
// MARK: - ${CURVE} + DH
|
|
||||||
extension ${CURVE}.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
|
|
||||||
/// Computes a shared secret with the provided public key from another party.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - publicKeyShare: The public key from another party to be combined with the private
|
|
||||||
/// key from this user to create the shared secret.
|
|
||||||
/// - Returns: The computed shared secret.
|
|
||||||
public func sharedSecretFromKeyAgreement(with publicKeyShare: ${CURVE}.KeyAgreement.PublicKey) throws(CryptoKitMetaError) -> SharedSecret {
|
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
return try self.coreCryptoSharedSecretFromKeyAgreement(with: publicKeyShare)
|
|
||||||
#else
|
|
||||||
return try self.openSSLSharedSecretFromKeyAgreement(with: publicKeyShare)
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
}
|
|
||||||
% end
|
|
||||||
#endif // Linux or !SwiftPM
|
|
||||||
@@ -11,23 +11,18 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
import Foundation
|
||||||
#endif
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
@_spi(ANSIKDF)
|
internal struct ANSIKDFx963<H: HashFunction>: Sendable {
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct ANSIKDFx963<H: HashFunction>: Sendable {
|
|
||||||
public static func deriveKey<Info: DataProtocol>(inputKeyMaterial: SymmetricKey, info: Info, outputByteCount: Int) -> SymmetricKey {
|
public static func deriveKey<Info: DataProtocol>(inputKeyMaterial: SymmetricKey, info: Info, outputByteCount: Int) -> SymmetricKey {
|
||||||
|
|
||||||
guard UInt64(outputByteCount) < (UInt64(H.Digest.byteCount) * UInt64(UInt32.max)) else {
|
guard UInt64(outputByteCount) < (UInt64(H.Digest.byteCount) * UInt64(UInt32.max)) else {
|
||||||
@@ -44,7 +39,11 @@ public struct ANSIKDFx963<H: HashFunction>: Sendable {
|
|||||||
// 1. Compute: Ki = Hash(Z || Counter || [SharedInfo]).
|
// 1. Compute: Ki = Hash(Z || Counter || [SharedInfo]).
|
||||||
var hasher = H()
|
var hasher = H()
|
||||||
inputKeyMaterial.withUnsafeBytes { ikmBytes in
|
inputKeyMaterial.withUnsafeBytes { ikmBytes in
|
||||||
|
#if CRYPTOKIT_URBP_LACKS_CONFORMANCE
|
||||||
|
hasher.update(bufferPointer: ikmBytes)
|
||||||
|
#else
|
||||||
hasher.update(data: ikmBytes)
|
hasher.update(data: ikmBytes)
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
hasher.update(counter.bigEndian)
|
hasher.update(counter.bigEndian)
|
||||||
hasher.update(data: info)
|
hasher.update(data: info)
|
||||||
@@ -56,7 +55,7 @@ public struct ANSIKDFx963<H: HashFunction>: Sendable {
|
|||||||
// Append the bytes of the digest. We don't want to append more than the remaining number of bytes.
|
// Append the bytes of the digest. We don't want to append more than the remaining number of bytes.
|
||||||
let bytesToAppend = min(remainingBytes, H.Digest.byteCount)
|
let bytesToAppend = min(remainingBytes, H.Digest.byteCount)
|
||||||
digest.withUnsafeBytes { digestPtr in
|
digest.withUnsafeBytes { digestPtr in
|
||||||
key.append(digestPtr.prefix(bytesToAppend))
|
key.append(digestPtr.bytes.extracting(first: bytesToAppend))
|
||||||
}
|
}
|
||||||
remainingBytes -= bytesToAppend
|
remainingBytes -= bytesToAppend
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,19 +11,16 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
/// A standards-based implementation of an HMAC-based Key Derivation Function
|
/// A standards-based implementation of an HMAC-based Key Derivation Function
|
||||||
/// (HKDF).
|
/// (HKDF).
|
||||||
@@ -40,8 +37,34 @@ public import Foundation
|
|||||||
/// material in the form of a hashed authentication code, then call
|
/// material in the form of a hashed authentication code, then call
|
||||||
/// ``expand(pseudoRandomKey:info:outputByteCount:)`` using that key material to
|
/// ``expand(pseudoRandomKey:info:outputByteCount:)`` using that key material to
|
||||||
/// generate a symmetric key of the length you specify.
|
/// generate a symmetric key of the length you specify.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct HKDF<H: HashFunction>: Sendable {
|
public struct HKDF<H: HashFunction>: Sendable {
|
||||||
|
/// Derives a symmetric encryption key from a main key or passcode using
|
||||||
|
/// HKDF key derivation with information and salt you specify.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - inputKeyMaterial: The main key or passcode the derivation function
|
||||||
|
/// uses to derive a key.
|
||||||
|
/// - salt: The salt to use for key derivation.
|
||||||
|
/// - info: The shared information to use for key derivation.
|
||||||
|
/// - outputKey: An output span that will be populated with the derived
|
||||||
|
/// symmetric key.
|
||||||
|
#if compiler(<6.3)
|
||||||
|
@_lifetime(outputKey: copy outputKey)
|
||||||
|
#endif
|
||||||
|
public static func deriveKey(inputKeyMaterial: SymmetricKey,
|
||||||
|
salt: RawSpan? = nil,
|
||||||
|
info: RawSpan? = nil,
|
||||||
|
output outputKey: inout OutputRawSpan) {
|
||||||
|
let code = extract(inputKeyMaterial: inputKeyMaterial, salt: salt)
|
||||||
|
code.withUnsafeBytes { codeBytes in
|
||||||
|
expand(
|
||||||
|
pseudoRandomKey: codeBytes.bytes,
|
||||||
|
info: info,
|
||||||
|
into: &outputKey
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Derives a symmetric encryption key from a main key or passcode using
|
/// Derives a symmetric encryption key from a main key or passcode using
|
||||||
/// HKDF key derivation with information and salt you specify.
|
/// HKDF key derivation with information and salt you specify.
|
||||||
///
|
///
|
||||||
@@ -53,11 +76,38 @@ public struct HKDF<H: HashFunction>: Sendable {
|
|||||||
/// - outputByteCount: The length in bytes of the resulting symmetric key.
|
/// - outputByteCount: The length in bytes of the resulting symmetric key.
|
||||||
///
|
///
|
||||||
/// - Returns: The derived symmetric key.
|
/// - Returns: The derived symmetric key.
|
||||||
public static func deriveKey<Salt: DataProtocol, Info: DataProtocol>(inputKeyMaterial: SymmetricKey,
|
public static func deriveKey<Salt: DataProtocol, Info: DataProtocol>(
|
||||||
salt: Salt,
|
inputKeyMaterial: SymmetricKey,
|
||||||
info: Info,
|
salt: Salt,
|
||||||
outputByteCount: Int) -> SymmetricKey {
|
info: Info,
|
||||||
return expand(pseudoRandomKey: extract(inputKeyMaterial: inputKeyMaterial, salt: salt), info: info, outputByteCount: outputByteCount)
|
outputByteCount: Int
|
||||||
|
) -> SymmetricKey {
|
||||||
|
// Fast path: Both salt and info have a single contiguous region, so
|
||||||
|
// go directly to the span.
|
||||||
|
if salt.regions.count == 1 && info.regions.count == 1 {
|
||||||
|
return salt.regions.first!.withUnsafeBytes { saltBytes in
|
||||||
|
info.regions.first!.withUnsafeBytes { infoBytes in
|
||||||
|
SymmetricKey(size: SymmetricKeySize(bitCount: outputByteCount * 8)) { output in
|
||||||
|
deriveKey(
|
||||||
|
inputKeyMaterial: inputKeyMaterial,
|
||||||
|
salt: saltBytes.bytes,
|
||||||
|
info: infoBytes.bytes,
|
||||||
|
output: &output
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Turn salt and info into contiguous regions, then recurse.
|
||||||
|
let contiguousSalt = Array(salt)
|
||||||
|
let contiguousInfo = Array(info)
|
||||||
|
return deriveKey(
|
||||||
|
inputKeyMaterial: inputKeyMaterial,
|
||||||
|
salt: contiguousSalt,
|
||||||
|
info: contiguousInfo,
|
||||||
|
outputByteCount: outputByteCount
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Derives a symmetric encryption key from a main key or passcode using
|
/// Derives a symmetric encryption key from a main key or passcode using
|
||||||
@@ -133,9 +183,31 @@ public struct HKDF<H: HashFunction>: Sendable {
|
|||||||
key = SymmetricKey(data: [UInt8]())
|
key = SymmetricKey(data: [UInt8]())
|
||||||
}
|
}
|
||||||
|
|
||||||
return inputKeyMaterial.withUnsafeBytes { ikmBytes in
|
return HMAC<H>.authenticationCode(for: inputKeyMaterial.bytes, using: key)
|
||||||
return HMAC<H>.authenticationCode(for: ikmBytes, using: key)
|
}
|
||||||
|
|
||||||
|
/// Creates cryptographically strong key material from a main key or
|
||||||
|
/// passcode that you specify.
|
||||||
|
///
|
||||||
|
/// Generate a derived symmetric key from the cryptographically strong key
|
||||||
|
/// material this function creates by calling
|
||||||
|
/// ``expand(pseudoRandomKey:info:outputByteCount:)``.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - inputKeyMaterial: The main key or passcode the derivation function
|
||||||
|
/// uses to derive a key.
|
||||||
|
/// - salt: The salt to use for key derivation.
|
||||||
|
///
|
||||||
|
/// - Returns: A pseudorandom, cryptographically strong key in the form of a
|
||||||
|
/// hashed authentication code.
|
||||||
|
public static func extract(inputKeyMaterial: SymmetricKey, salt: RawSpan?) -> HashedAuthenticationCode<H> {
|
||||||
|
let key = if let salt {
|
||||||
|
SymmetricKey(bytes: salt)
|
||||||
|
} else {
|
||||||
|
SymmetricKey(data: SecureBytes())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return HMAC<H>.authenticationCode(for: inputKeyMaterial.bytes, using: key)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Expands cryptographically strong key material into a derived symmetric
|
/// Expands cryptographically strong key material into a derived symmetric
|
||||||
@@ -152,27 +224,66 @@ public struct HKDF<H: HashFunction>: Sendable {
|
|||||||
///
|
///
|
||||||
/// - Returns: The derived symmetric key.
|
/// - Returns: The derived symmetric key.
|
||||||
public static func expand<PRK: ContiguousBytes, Info: DataProtocol>(pseudoRandomKey prk: PRK, info: Info?, outputByteCount: Int) -> SymmetricKey {
|
public static func expand<PRK: ContiguousBytes, Info: DataProtocol>(pseudoRandomKey prk: PRK, info: Info?, outputByteCount: Int) -> SymmetricKey {
|
||||||
|
SymmetricKey(capacity: outputByteCount) { output in
|
||||||
let iterations: UInt8 = UInt8((Double(outputByteCount) / Double(H.Digest.byteCount)).rounded(.up))
|
prk.withUnsafeBytes { prkBuffer in
|
||||||
|
guard let info else {
|
||||||
var output = SecureBytes()
|
self.expand(pseudoRandomKey: prkBuffer.bytes, info: nil, into: &output)
|
||||||
let key = SymmetricKey(data: prk)
|
return
|
||||||
var TMinusOne = SecureBytes()
|
}
|
||||||
for i in 1...iterations {
|
|
||||||
var hmac = HMAC<H>(key: key)
|
if info.regions.count == 1 {
|
||||||
hmac.update(data: TMinusOne)
|
info.regions.first!.withUnsafeBytes { infoBuffer in
|
||||||
if let info {
|
self.expand(pseudoRandomKey: prkBuffer.bytes, info: infoBuffer.bytes, into: &output)
|
||||||
hmac.update(data: info)
|
}
|
||||||
|
} else {
|
||||||
|
let contiguous = ContiguousArray(info)
|
||||||
|
self.expand(pseudoRandomKey: prkBuffer.bytes, info: contiguous.span.bytes, into: &output)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
withUnsafeBytes(of: i) { counter in
|
|
||||||
hmac.update(bufferPointer: counter)
|
|
||||||
}
|
|
||||||
TMinusOne = SecureBytes(bytes: hmac.finalize())
|
|
||||||
output.append(TMinusOne)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return SymmetricKey(data: output.prefix(outputByteCount))
|
}
|
||||||
|
|
||||||
|
/// Expands cryptographically strong key material into a derived symmetric
|
||||||
|
/// key.
|
||||||
|
///
|
||||||
|
/// Generate cryptographically strong key material to use with this function
|
||||||
|
/// by calling ``extract(inputKeyMaterial:salt:)``.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - prk: A pseudorandom, cryptographically strong key generated from the
|
||||||
|
/// ``extract(inputKeyMaterial:salt:)`` function.
|
||||||
|
/// - info: The shared information to use for key derivation.
|
||||||
|
/// - outputByteCount: The length in bytes of the resulting symmetric key.
|
||||||
|
///
|
||||||
|
/// - Returns: The derived symmetric key.
|
||||||
|
#if compiler(<6.3)
|
||||||
|
@_lifetime(output: copy output)
|
||||||
|
#endif
|
||||||
|
public static func expand(pseudoRandomKey prk: RawSpan, info: RawSpan?, into output: inout OutputRawSpan) {
|
||||||
|
let iterations: UInt8 = UInt8((Double(output.freeCapacity) / Double(H.Digest.byteCount)).rounded(.up))
|
||||||
|
|
||||||
|
let key = SymmetricKey(bytes: prk)
|
||||||
|
var lastIterationBytes = 0
|
||||||
|
for i in 1...iterations {
|
||||||
|
var hmac = HMAC<H>(key: key)
|
||||||
|
hmac.update(bytes: output.bytes.extracting(last: lastIterationBytes))
|
||||||
|
if let info {
|
||||||
|
hmac.update(bytes: info)
|
||||||
|
}
|
||||||
|
|
||||||
|
var buf = i
|
||||||
|
withUnsafeBytes(of: &buf) { rawBuffer in
|
||||||
|
let span = RawSpan(_unsafeBytes: rawBuffer)
|
||||||
|
hmac.update(bytes: span)
|
||||||
|
}
|
||||||
|
hmac.finalize().withUnsafeBytes {
|
||||||
|
let bytesToAppend = $0.bytes.extracting(first: output.freeCapacity)
|
||||||
|
output.append(contentsOf: bytesToAppend)
|
||||||
|
lastIterationBytes = bytesToAppend.byteCount
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,33 +11,23 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias AESWRAPImpl = CoreCryptoAESWRAPImpl
|
|
||||||
#else
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias AESWRAPImpl = BoringSSLAESWRAPImpl
|
typealias AESWRAPImpl = BoringSSLAESWRAPImpl
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension AES {
|
extension AES {
|
||||||
/// An implementation of AES Key Wrapping in accordance with the IETF RFC
|
/// An implementation of AES Key Wrapping in accordance with the IETF RFC
|
||||||
/// 3394 specification.
|
/// 3394 specification.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum KeyWrap: Sendable {
|
public enum KeyWrap: Sendable {
|
||||||
/// Wraps a key using the AES wrap algorithm.
|
/// Wraps a key using the AES wrap algorithm.
|
||||||
///
|
///
|
||||||
@@ -70,4 +60,4 @@ extension AES {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,10 +11,14 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
#if hasFeature(SourceWarningControl)
|
||||||
|
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||||
|
#else
|
||||||
@_implementationOnly import CCryptoBoringSSL
|
@_implementationOnly import CCryptoBoringSSL
|
||||||
|
#endif
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
@@ -29,12 +33,8 @@ enum BoringSSLAESWRAPImpl {
|
|||||||
|
|
||||||
let rc = try key.withUnsafeAESKEY(mode: .encrypting) { aesKey in
|
let rc = try key.withUnsafeAESKEY(mode: .encrypting) { aesKey in
|
||||||
output.withUnsafeMutableBytes { outputPtr -> CInt in
|
output.withUnsafeMutableBytes { outputPtr -> CInt in
|
||||||
// Memory bind is safe: we cannot alias the pointer here.
|
keyToWrap.withUnsafeBytes { keyToWrapPtr -> CInt in
|
||||||
let outputPtr = outputPtr.bindMemory(to: UInt8.self)
|
CCryptoBoringSSL_AES_wrap_key(
|
||||||
return keyToWrap.withUnsafeBytes { keyToWrapPtr -> CInt in
|
|
||||||
// Memory bind is safe: we cannot alias the pointer here.
|
|
||||||
let keyToWrapPtr = keyToWrapPtr.bindMemory(to: UInt8.self)
|
|
||||||
return CCryptoBoringSSL_AES_wrap_key(
|
|
||||||
aesKey,
|
aesKey,
|
||||||
nil,
|
nil,
|
||||||
outputPtr.baseAddress,
|
outputPtr.baseAddress,
|
||||||
@@ -72,10 +72,8 @@ enum BoringSSLAESWRAPImpl {
|
|||||||
key: SymmetricKey,
|
key: SymmetricKey,
|
||||||
contiguousWrappedKey: WrappedKey
|
contiguousWrappedKey: WrappedKey
|
||||||
) throws -> SymmetricKey {
|
) throws -> SymmetricKey {
|
||||||
let unwrapped = try contiguousWrappedKey.withUnsafeBytes { inPtr in
|
try contiguousWrappedKey.withUnsafeBytes { inPtr in
|
||||||
try [UInt8](unsafeUninitializedCapacity: inPtr.count) { outputPtr, count in
|
try SymmetricKey(unsafeUninitializedCapacity: inPtr.count) { outputPtr, count in
|
||||||
// Bind is safe: we cannot violate the aliasing rules here as we never call to arbitrary code.
|
|
||||||
let inPtr = inPtr.bindMemory(to: UInt8.self)
|
|
||||||
let rc = try key.withUnsafeAESKEY(mode: .decrypting) { aesKey in
|
let rc = try key.withUnsafeAESKEY(mode: .decrypting) { aesKey in
|
||||||
CCryptoBoringSSL_AES_unwrap_key(
|
CCryptoBoringSSL_AES_unwrap_key(
|
||||||
aesKey,
|
aesKey,
|
||||||
@@ -95,8 +93,6 @@ enum BoringSSLAESWRAPImpl {
|
|||||||
count = Int(rc)
|
count = Int(rc)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return SymmetricKey(data: unwrapped)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,8 +109,6 @@ extension SymmetricKey {
|
|||||||
_ body: (UnsafePointer<AES_KEY>) throws -> ResultType
|
_ body: (UnsafePointer<AES_KEY>) throws -> ResultType
|
||||||
) throws -> ResultType {
|
) throws -> ResultType {
|
||||||
try self.withUnsafeBytes { bytesPointer in
|
try self.withUnsafeBytes { bytesPointer in
|
||||||
// Bind is safe: cannot alias the pointer here.
|
|
||||||
let bytesPointer = bytesPointer.bindMemory(to: UInt8.self)
|
|
||||||
|
|
||||||
var aesKey = AES_KEY()
|
var aesKey = AES_KEY()
|
||||||
let bitsInKey = UInt32(bytesPointer.count * 8)
|
let bitsInKey = UInt32(bytesPointer.count * 8)
|
||||||
@@ -146,4 +140,4 @@ extension SymmetricKey {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,11 +11,14 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
#if hasFeature(SourceWarningControl)
|
||||||
|
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||||
|
#else
|
||||||
@_implementationOnly import CCryptoBoringSSL
|
@_implementationOnly import CCryptoBoringSSL
|
||||||
@_implementationOnly import CCryptoBoringSSLShims
|
#endif
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
@@ -41,7 +44,7 @@ extension Curve25519.Signing {
|
|||||||
privateKeyBytes in
|
privateKeyBytes in
|
||||||
privateKeyBytes = 64
|
privateKeyBytes = 64
|
||||||
publicKey.withUnsafeMutableBytes { publicKeyPtr in
|
publicKey.withUnsafeMutableBytes { publicKeyPtr in
|
||||||
CCryptoBoringSSLShims_ED25519_keypair(
|
CCryptoBoringSSL_ED25519_keypair(
|
||||||
publicKeyPtr.baseAddress,
|
publicKeyPtr.baseAddress,
|
||||||
privateKeyPtr.baseAddress
|
privateKeyPtr.baseAddress
|
||||||
)
|
)
|
||||||
@@ -75,7 +78,7 @@ extension Curve25519.Signing {
|
|||||||
privateKeyBytes in
|
privateKeyBytes in
|
||||||
privateKeyBytes = 64
|
privateKeyBytes = 64
|
||||||
publicKey.withUnsafeMutableBytes { publicKeyPtr in
|
publicKey.withUnsafeMutableBytes { publicKeyPtr in
|
||||||
CCryptoBoringSSLShims_ED25519_keypair_from_seed(
|
CCryptoBoringSSL_ED25519_keypair_from_seed(
|
||||||
publicKeyPtr.baseAddress,
|
publicKeyPtr.baseAddress,
|
||||||
privateKeyPtr.baseAddress,
|
privateKeyPtr.baseAddress,
|
||||||
seedPtr.baseAddress
|
seedPtr.baseAddress
|
||||||
@@ -123,4 +126,4 @@ extension Curve25519.Signing {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,11 +11,14 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
#if hasFeature(SourceWarningControl)
|
||||||
|
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||||
|
#else
|
||||||
@_implementationOnly import CCryptoBoringSSL
|
@_implementationOnly import CCryptoBoringSSL
|
||||||
@_implementationOnly import CCryptoBoringSSLShims
|
#endif
|
||||||
import CryptoBoringWrapper
|
import CryptoBoringWrapper
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
@@ -74,6 +77,10 @@ struct OpenSSLNISTCurvePrivateKeyImpl<Curve: OpenSSLSupportedNISTCurve>: Sendabl
|
|||||||
self.key = try BoringSSLECPrivateKeyWrapper(rawRepresentation: data)
|
self.key = try BoringSSLECPrivateKeyWrapper(rawRepresentation: data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
init(seed: Data, compactRepresentable: Bool) throws {
|
||||||
|
fatalError("unimplemented on this platform")
|
||||||
|
}
|
||||||
|
|
||||||
func publicKey() -> OpenSSLNISTCurvePublicKeyImpl<Curve> {
|
func publicKey() -> OpenSSLNISTCurvePublicKeyImpl<Curve> {
|
||||||
OpenSSLNISTCurvePublicKeyImpl(wrapping: self.key.publicKey)
|
OpenSSLNISTCurvePublicKeyImpl(wrapping: self.key.publicKey)
|
||||||
}
|
}
|
||||||
@@ -139,7 +146,7 @@ struct OpenSSLNISTCurvePublicKeyImpl<Curve: OpenSSLSupportedNISTCurve>: Sendable
|
|||||||
/// allows some helper operations.
|
/// allows some helper operations.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||||
class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
|
final class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
let key: OpaquePointer
|
let key: OpaquePointer
|
||||||
|
|
||||||
@@ -326,7 +333,7 @@ class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked
|
|||||||
func sign<D: Digest>(digest: D) throws -> ECDSASignature {
|
func sign<D: Digest>(digest: D) throws -> ECDSASignature {
|
||||||
let optionalRawSignature: UnsafeMutablePointer<ECDSA_SIG>? = digest.withUnsafeBytes {
|
let optionalRawSignature: UnsafeMutablePointer<ECDSA_SIG>? = digest.withUnsafeBytes {
|
||||||
digestPtr in
|
digestPtr in
|
||||||
CCryptoBoringSSLShims_ECDSA_do_sign(digestPtr.baseAddress, digestPtr.count, self.key)
|
CCryptoBoringSSL_ECDSA_do_sign(digestPtr.baseAddress, digestPtr.count, self.key)
|
||||||
}
|
}
|
||||||
guard let rawSignature = optionalRawSignature else {
|
guard let rawSignature = optionalRawSignature else {
|
||||||
throw CryptoKitError.internalBoringSSLError()
|
throw CryptoKitError.internalBoringSSLError()
|
||||||
@@ -344,7 +351,7 @@ class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked
|
|||||||
/// allows some helper operations.
|
/// allows some helper operations.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||||
class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
|
final class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
let key: OpaquePointer
|
let key: OpaquePointer
|
||||||
|
|
||||||
@@ -566,7 +573,7 @@ class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked
|
|||||||
func isValidSignature<D: Digest>(_ signature: ECDSASignature, for digest: D) -> Bool {
|
func isValidSignature<D: Digest>(_ signature: ECDSASignature, for digest: D) -> Bool {
|
||||||
let rc: CInt = signature.withUnsafeSignaturePointer { signaturePointer in
|
let rc: CInt = signature.withUnsafeSignaturePointer { signaturePointer in
|
||||||
digest.withUnsafeBytes { digestPointer in
|
digest.withUnsafeBytes { digestPointer in
|
||||||
CCryptoBoringSSLShims_ECDSA_do_verify(
|
CCryptoBoringSSL_ECDSA_do_verify(
|
||||||
digestPointer.baseAddress,
|
digestPointer.baseAddress,
|
||||||
digestPointer.count,
|
digestPointer.count,
|
||||||
signaturePointer,
|
signaturePointer,
|
||||||
@@ -677,7 +684,7 @@ func readRawPublicNumbers(
|
|||||||
/// In a number of places we need to know if an EC key is compact representable. This function implements that check.
|
/// In a number of places we need to know if an EC key is compact representable. This function implements that check.
|
||||||
///
|
///
|
||||||
/// The check is defined in https://tools.ietf.org/id/draft-jivsov-ecc-compact-05.html#rfc.section.4.2.1. Specifically, a
|
/// The check is defined in https://tools.ietf.org/id/draft-jivsov-ecc-compact-05.html#rfc.section.4.2.1. Specifically, a
|
||||||
/// point is compact representable if its y coordinate is the smaller of min(y, p-y) where p is the order of the prime field.
|
/// point is compact representable if its y coordinate is the smaller of min(y, p-y) where p is the prime of the base field.
|
||||||
@usableFromInline
|
@usableFromInline
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||||
func _isCompactRepresentable(
|
func _isCompactRepresentable(
|
||||||
@@ -692,9 +699,9 @@ func _isCompactRepresentable(
|
|||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||||
let context = try! FiniteFieldArithmeticContext(fieldSize: p)
|
let context = try! FiniteFieldArithmeticContext(fieldSize: p)
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||||
let newY = try! context.subtract(y, from: group.order)
|
let newY = try! context.subtract(y, from: p)
|
||||||
|
|
||||||
// The point is compact representable if y is less than or equal to newY.
|
// The point is compact representable if y is less than or equal to newY.
|
||||||
return y <= newY
|
return y <= newY
|
||||||
}
|
}
|
||||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,11 +11,14 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
#if hasFeature(SourceWarningControl)
|
||||||
|
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||||
|
#else
|
||||||
@_implementationOnly import CCryptoBoringSSL
|
@_implementationOnly import CCryptoBoringSSL
|
||||||
@_implementationOnly import CCryptoBoringSSLShims
|
#endif
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
@@ -72,7 +75,7 @@ extension Curve25519.KeyAgreement {
|
|||||||
publicKey.withUnsafeMutableBytes { publicKeyBytes in
|
publicKey.withUnsafeMutableBytes { publicKeyBytes in
|
||||||
precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
|
precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
|
||||||
precondition(privateKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
|
precondition(privateKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
|
||||||
CCryptoBoringSSLShims_X25519_keypair(
|
CCryptoBoringSSL_X25519_keypair(
|
||||||
publicKeyBytes.baseAddress,
|
publicKeyBytes.baseAddress,
|
||||||
privateKeyBytes.baseAddress
|
privateKeyBytes.baseAddress
|
||||||
)
|
)
|
||||||
@@ -100,7 +103,7 @@ extension Curve25519.KeyAgreement {
|
|||||||
publicKeyBytes,
|
publicKeyBytes,
|
||||||
publicKeySize in
|
publicKeySize in
|
||||||
precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
|
precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
|
||||||
CCryptoBoringSSLShims_X25519_public_from_private(
|
CCryptoBoringSSL_X25519_public_from_private(
|
||||||
publicKeyBytes.baseAddress,
|
publicKeyBytes.baseAddress,
|
||||||
privatePointer.baseAddress
|
privatePointer.baseAddress
|
||||||
)
|
)
|
||||||
@@ -118,10 +121,10 @@ extension Curve25519.KeyAgreement {
|
|||||||
) throws
|
) throws
|
||||||
-> SharedSecret
|
-> SharedSecret
|
||||||
{
|
{
|
||||||
let sharedSecret = SecureBytes(
|
let sharedSecret = try SecureBytes(
|
||||||
unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes
|
unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes
|
||||||
) { secretPointer, secretSize in
|
) { secretPointer, secretSize in
|
||||||
self.key.withUnsafeBytes { privateKeyPointer in
|
try self.key.withUnsafeBytes { privateKeyPointer in
|
||||||
// We precondition on all of these sizes because bounds checking is cool.
|
// We precondition on all of these sizes because bounds checking is cool.
|
||||||
// These are fatal instead of guards because we allocated the secret (so it must be right),
|
// These are fatal instead of guards because we allocated the secret (so it must be right),
|
||||||
// we either allocated the private key or validated it on construction (so it must be right),
|
// we either allocated the private key or validated it on construction (so it must be right),
|
||||||
@@ -130,16 +133,17 @@ extension Curve25519.KeyAgreement {
|
|||||||
precondition(privateKeyPointer.count == Curve25519.KeyAgreement.keySizeBytes)
|
precondition(privateKeyPointer.count == Curve25519.KeyAgreement.keySizeBytes)
|
||||||
precondition(publicKeyShare.keyBytes.count == Curve25519.KeyAgreement.keySizeBytes)
|
precondition(publicKeyShare.keyBytes.count == Curve25519.KeyAgreement.keySizeBytes)
|
||||||
|
|
||||||
// We don't check the return code here. This return code only validates that the generated secret is not the weak all-zero
|
// BoringSSL returns 0 when the peer's public key has low order, which makes the shared secret
|
||||||
// secret (it is not possible for BoringSSL's X25519 implementation to fail, which is nice). There is currently what I would
|
// the weak all-zero value. CryptoKit rejects that key agreement, so we do too.
|
||||||
// politely describe as a "lack of consensus" as to whether crypto libraries should reject this secret. CryptoKit on Apple
|
guard
|
||||||
// platforms currently does not, so for the sake of conformance with our peer implementation I will also refuse to check it.
|
CCryptoBoringSSL_X25519(
|
||||||
// We may elect to revisit this decision if the security best-practice thinking changes.
|
secretPointer.baseAddress,
|
||||||
CCryptoBoringSSLShims_X25519(
|
privateKeyPointer.baseAddress,
|
||||||
secretPointer.baseAddress,
|
publicKeyShare.keyBytes
|
||||||
privateKeyPointer.baseAddress,
|
) == 1
|
||||||
publicKeyShare.keyBytes
|
else {
|
||||||
)
|
throw CryptoKitError.internalBoringSSLError()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
secretSize = Curve25519.KeyAgreement.keySizeBytes // We always use all of it.
|
secretSize = Curve25519.KeyAgreement.keySizeBytes // We always use all of it.
|
||||||
@@ -162,4 +166,4 @@ extension Curve25519.KeyAgreement {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,10 +11,11 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
/// An elliptic curve that enables X25519 key agreement and Ed25519 signatures.
|
/// An elliptic curve that enables X25519 key agreement and Ed25519 signatures.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum Curve25519: Sendable {}
|
public enum Curve25519: Sendable {}
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,42 +11,31 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Curve25519.Signing {
|
extension Curve25519.Signing {
|
||||||
static var keyByteCount: Int {
|
static var keyByteCount: Int {
|
||||||
return 32
|
return 32
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Curve25519 {
|
extension Curve25519 {
|
||||||
/// A mechanism used to create or verify a cryptographic signature using
|
/// A mechanism used to create or verify a cryptographic signature using
|
||||||
/// Ed25519.
|
/// Ed25519.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum Signing: Sendable {
|
public enum Signing: Sendable {
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
typealias Curve25519PrivateKeyImpl = Curve25519.Signing.CoreCryptoCurve25519PrivateKeyImpl
|
|
||||||
typealias Curve25519PublicKeyImpl = Curve25519.Signing.CoreCryptoCurve25519PublicKeyImpl
|
|
||||||
#else
|
|
||||||
typealias Curve25519PrivateKeyImpl = Curve25519.Signing.OpenSSLCurve25519PrivateKeyImpl
|
typealias Curve25519PrivateKeyImpl = Curve25519.Signing.OpenSSLCurve25519PrivateKeyImpl
|
||||||
typealias Curve25519PublicKeyImpl = Curve25519.Signing.OpenSSLCurve25519PublicKeyImpl
|
typealias Curve25519PublicKeyImpl = Curve25519.Signing.OpenSSLCurve25519PublicKeyImpl
|
||||||
#endif
|
|
||||||
|
|
||||||
/// A Curve25519 private key used to create cryptographic signatures.
|
/// A Curve25519 private key used to create cryptographic signatures.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PrivateKey: ECPrivateKey, Sendable {
|
public struct PrivateKey: ECPrivateKey, Sendable {
|
||||||
private var baseKey: Curve25519.Signing.Curve25519PrivateKeyImpl
|
private var baseKey: Curve25519.Signing.Curve25519PrivateKeyImpl
|
||||||
|
|
||||||
@@ -82,7 +71,6 @@ extension Curve25519 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A Curve25519 public key used to verify cryptographic signatures.
|
/// A Curve25519 public key used to verify cryptographic signatures.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PublicKey: Sendable {
|
public struct PublicKey: Sendable {
|
||||||
private var baseKey: Curve25519.Signing.Curve25519PublicKeyImpl
|
private var baseKey: Curve25519.Signing.Curve25519PublicKeyImpl
|
||||||
|
|
||||||
@@ -110,4 +98,4 @@ extension Curve25519 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,64 +11,51 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias SupportedCurveDetailsImpl = CorecryptoSupportedNISTCurve
|
|
||||||
#else
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
typealias SupportedCurveDetailsImpl = OpenSSLSupportedNISTCurve
|
typealias SupportedCurveDetailsImpl = OpenSSLSupportedNISTCurve
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
protocol ECPublicKey {
|
protocol ECPublicKey {
|
||||||
init <Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws
|
init <Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws(CryptoKitMetaError)
|
||||||
var rawRepresentation: Data { get }
|
var rawRepresentation: Data { get }
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
protocol ECPrivateKey {
|
protocol ECPrivateKey {
|
||||||
associatedtype PK
|
associatedtype PK
|
||||||
var publicKey: PK { get }
|
var publicKey: PK { get }
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
protocol NISTECPublicKey: ECPublicKey {
|
protocol NISTECPublicKey: ECPublicKey {
|
||||||
init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws
|
init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws(CryptoKitMetaError)
|
||||||
init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws
|
init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws(CryptoKitMetaError)
|
||||||
init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws
|
init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws(CryptoKitMetaError)
|
||||||
|
|
||||||
var compactRepresentation: Data? { get }
|
var compactRepresentation: Data? { get }
|
||||||
var x963Representation: Data { get }
|
var x963Representation: Data { get }
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
protocol NISTECPrivateKey: ECPrivateKey where PK: NISTECPublicKey {
|
protocol NISTECPrivateKey: ECPrivateKey where PK: NISTECPublicKey {
|
||||||
init <Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws
|
init <Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws(CryptoKitMetaError)
|
||||||
var rawRepresentation: Data { get }
|
var rawRepresentation: Data { get }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An elliptic curve that enables NIST P-256 signatures and key agreement.
|
/// An elliptic curve that enables NIST P-256 signatures and key agreement.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum P256: Sendable { }
|
public enum P256: Sendable { }
|
||||||
|
|
||||||
/// An elliptic curve that enables NIST P-384 signatures and key agreement.
|
/// An elliptic curve that enables NIST P-384 signatures and key agreement.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum P384: Sendable { }
|
public enum P384: Sendable { }
|
||||||
|
|
||||||
/// An elliptic curve that enables NIST P-521 signatures and key agreement.
|
/// An elliptic curve that enables NIST P-521 signatures and key agreement.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum P521: Sendable { }
|
public enum P521: Sendable { }
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,42 +11,31 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Curve25519.KeyAgreement {
|
extension Curve25519.KeyAgreement {
|
||||||
static var keyByteCount: Int {
|
static var keyByteCount: Int {
|
||||||
return 32
|
return 32
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension Curve25519 {
|
extension Curve25519 {
|
||||||
/// A mechanism used to create a shared secret between two users by
|
/// A mechanism used to create a shared secret between two users by
|
||||||
/// performing X25519 key agreement.
|
/// performing X25519 key agreement.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum KeyAgreement: Sendable {
|
public enum KeyAgreement: Sendable {
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
typealias Curve25519PrivateKeyImpl = Curve25519.KeyAgreement.CoreCryptoCurve25519PrivateKeyImpl
|
|
||||||
typealias Curve25519PublicKeyImpl = Curve25519.KeyAgreement.CoreCryptoCurve25519PublicKeyImpl
|
|
||||||
#else
|
|
||||||
typealias Curve25519PrivateKeyImpl = Curve25519.KeyAgreement.OpenSSLCurve25519PrivateKeyImpl
|
typealias Curve25519PrivateKeyImpl = Curve25519.KeyAgreement.OpenSSLCurve25519PrivateKeyImpl
|
||||||
typealias Curve25519PublicKeyImpl = Curve25519.KeyAgreement.OpenSSLCurve25519PublicKeyImpl
|
typealias Curve25519PublicKeyImpl = Curve25519.KeyAgreement.OpenSSLCurve25519PublicKeyImpl
|
||||||
#endif
|
|
||||||
|
|
||||||
/// A Curve25519 public key used for key agreement.
|
/// A Curve25519 public key used for key agreement.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PublicKey: ECPublicKey, Sendable {
|
public struct PublicKey: ECPublicKey, Sendable {
|
||||||
fileprivate var baseKey: Curve25519PublicKeyImpl
|
fileprivate var baseKey: Curve25519PublicKeyImpl
|
||||||
|
|
||||||
@@ -86,7 +75,6 @@ extension Curve25519 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A Curve25519 private key used for key agreement.
|
/// A Curve25519 private key used for key agreement.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct PrivateKey: DiffieHellmanKeyAgreement, Sendable {
|
public struct PrivateKey: DiffieHellmanKeyAgreement, Sendable {
|
||||||
fileprivate var baseKey: Curve25519PrivateKeyImpl
|
fileprivate var baseKey: Curve25519PrivateKeyImpl
|
||||||
|
|
||||||
@@ -135,4 +123,4 @@ extension Curve25519 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,19 +11,16 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
/// The sizes that a symmetric cryptographic key can take.
|
/// The sizes that a symmetric cryptographic key can take.
|
||||||
///
|
///
|
||||||
@@ -32,7 +29,6 @@ public import Foundation
|
|||||||
/// standard key sizes, like ``bits128``, ``bits192``, or ``bits256``. When you
|
/// standard key sizes, like ``bits128``, ``bits192``, or ``bits256``. When you
|
||||||
/// need a key with a non-standard length, use the ``init(bitCount:)``
|
/// need a key with a non-standard length, use the ``init(bitCount:)``
|
||||||
/// initializer to create a `SymmetricKeySize` instance with a custom bit count.
|
/// initializer to create a `SymmetricKeySize` instance with a custom bit count.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SymmetricKeySize: Sendable {
|
public struct SymmetricKeySize: Sendable {
|
||||||
/// The number of bits in the key.
|
/// The number of bits in the key.
|
||||||
public let bitCount: Int
|
public let bitCount: Int
|
||||||
@@ -73,7 +69,6 @@ public struct SymmetricKeySize: Sendable {
|
|||||||
/// symmetric key to compute a message authentication code like ``HMAC``, or to
|
/// symmetric key to compute a message authentication code like ``HMAC``, or to
|
||||||
/// open and close a sealed box (``ChaChaPoly/SealedBox`` or
|
/// open and close a sealed box (``ChaChaPoly/SealedBox`` or
|
||||||
/// ``AES/GCM/SealedBox``) using a cipher like ``ChaChaPoly`` or ``AES``.
|
/// ``AES/GCM/SealedBox``) using a cipher like ``ChaChaPoly`` or ``AES``.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct SymmetricKey: ContiguousBytes, Sendable {
|
public struct SymmetricKey: ContiguousBytes, Sendable {
|
||||||
let sb: SecureBytes
|
let sb: SecureBytes
|
||||||
|
|
||||||
@@ -95,6 +90,11 @@ public struct SymmetricKey: ContiguousBytes, Sendable {
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
/// Access the raw bytes of the key.
|
||||||
|
public var bytes: RawSpan {
|
||||||
|
sb.bytes
|
||||||
|
}
|
||||||
|
|
||||||
/// Creates a key from the given data.
|
/// Creates a key from the given data.
|
||||||
///
|
///
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
@@ -103,6 +103,35 @@ public struct SymmetricKey: ContiguousBytes, Sendable {
|
|||||||
self.init(key: SecureBytes(bytes: data))
|
self.init(key: SecureBytes(bytes: data))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Creates a key from the given data.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - bytes: The span of bytes from which to create the key.
|
||||||
|
///
|
||||||
|
/// Note: historical version of init(copying:) below, SPI only.
|
||||||
|
@inlinable
|
||||||
|
internal init(bytes: RawSpan) {
|
||||||
|
self = bytes.withUnsafeBytes { SymmetricKey(data: $0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a key from the given data.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - bytes: The span of bytes from which to create the key.
|
||||||
|
@inlinable
|
||||||
|
public init(copying bytes: RawSpan) {
|
||||||
|
self = bytes.withUnsafeBytes { SymmetricKey(data: $0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a key from the given data, zeroing out the bytes afterward.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - byte: The span of bytes from which to create the key.
|
||||||
|
public init(copyingWithZeroing bytes: inout MutableRawSpan) {
|
||||||
|
self = bytes.withUnsafeBytes { SymmetricKey(data: $0) }
|
||||||
|
bytes.withUnsafeMutableBytes { $0.zeroize() }
|
||||||
|
}
|
||||||
|
|
||||||
/// Generates a new random key of the given size.
|
/// Generates a new random key of the given size.
|
||||||
///
|
///
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
@@ -124,6 +153,25 @@ public struct SymmetricKey: ContiguousBytes, Sendable {
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
/// Create a symmetric key with a closure that will initialize the memory.
|
||||||
|
internal init<E: Error>(capacity: Int, initializingWith callback: (inout OutputRawSpan) throws(E) -> Void) throws(E) {
|
||||||
|
self.init(key: try SecureBytes(capacity: capacity, initializingWith: callback))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a new key of the given size where the key contents are initialized via a callback.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - size: The size of the key to generate. You can use one of the standard
|
||||||
|
/// sizes, like ``SymmetricKeySize/bits256``, or you can create a key of
|
||||||
|
/// custom length by initializing a ``SymmetricKeySize`` instance with a
|
||||||
|
/// non-standard value.
|
||||||
|
/// - callback: A callback that will be invoked to initialize the contents
|
||||||
|
/// of the key. It must initialize the full set of size.bitCount / 8 bytes
|
||||||
|
/// in the provided output span.
|
||||||
|
public init<E: Error>(size: SymmetricKeySize, initializingWith callback: (inout OutputRawSpan) throws(E) -> Void) throws(E) {
|
||||||
|
try self.init(capacity: Int(size.bitCount / 8), initializingWith: callback)
|
||||||
|
}
|
||||||
|
|
||||||
// Fast-path alias for cases whe know we have a SecureBytes object.
|
// Fast-path alias for cases whe know we have a SecureBytes object.
|
||||||
internal init(data: SecureBytes) {
|
internal init(data: SecureBytes) {
|
||||||
self.init(key: data)
|
self.init(key: data)
|
||||||
@@ -145,11 +193,10 @@ public struct SymmetricKey: ContiguousBytes, Sendable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension SymmetricKey: Equatable {
|
extension SymmetricKey: Equatable {
|
||||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||||
return safeCompare(lhs, rhs)
|
return safeCompare(lhs, rhs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,31 +11,15 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
#if os(Windows)
|
|
||||||
import ucrt
|
|
||||||
#elseif canImport(Darwin)
|
|
||||||
import Darwin
|
|
||||||
#elseif canImport(Glibc)
|
|
||||||
import Glibc
|
|
||||||
#elseif canImport(Musl)
|
|
||||||
import Musl
|
|
||||||
#elseif canImport(Android)
|
|
||||||
import Android
|
|
||||||
#elseif canImport(WASILibc)
|
|
||||||
import WASILibc
|
|
||||||
#endif
|
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
/// A hash-based message authentication algorithm.
|
/// A hash-based message authentication algorithm.
|
||||||
///
|
///
|
||||||
@@ -50,7 +34,6 @@ public import Foundation
|
|||||||
/// need to encrypt the data as well as authenticate it, use a cipher like
|
/// need to encrypt the data as well as authenticate it, use a cipher like
|
||||||
/// ``AES`` or ``ChaChaPoly`` to put the data into a sealed box (an instance of
|
/// ``AES`` or ``ChaChaPoly`` to put the data into a sealed box (an instance of
|
||||||
/// ``AES/GCM/SealedBox`` or ``ChaChaPoly/SealedBox``).
|
/// ``AES/GCM/SealedBox`` or ``ChaChaPoly/SealedBox``).
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct HMAC<H: HashFunction>: MACAlgorithm, Sendable {
|
public struct HMAC<H: HashFunction>: MACAlgorithm, Sendable {
|
||||||
/// An alias for the symmetric key type used to compute or verify a message
|
/// An alias for the symmetric key type used to compute or verify a message
|
||||||
/// authentication code.
|
/// authentication code.
|
||||||
@@ -82,41 +65,24 @@ public struct HMAC<H: HashFunction>: MACAlgorithm, Sendable {
|
|||||||
#if os(iOS) && (arch(arm) || arch(i386))
|
#if os(iOS) && (arch(arm) || arch(i386))
|
||||||
fatalError("Unsupported architecture")
|
fatalError("Unsupported architecture")
|
||||||
#else
|
#else
|
||||||
var K: SymmetricKey
|
// HMAC(K, m) = H((K0 ^ opad) || H((K0 ^ ipad) || m)), where K0 is the
|
||||||
if key.byteCount == H.blockByteCount {
|
// key normalized to the hash block size (RFC 2104).
|
||||||
K = key
|
|
||||||
} else if key.byteCount > H.blockByteCount {
|
|
||||||
var array = Array(repeating: UInt8(0), count: H.blockByteCount)
|
|
||||||
|
|
||||||
K = key.withUnsafeBytes { (keyBytes) in
|
|
||||||
let hash = H.hash(bufferPointer: keyBytes)
|
|
||||||
|
|
||||||
return SymmetricKey(data: hash.withUnsafeBytes({ (hashBytes) in
|
|
||||||
memcpy(&array, hashBytes.baseAddress!, hashBytes.count)
|
|
||||||
return array
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
var keyArray = Array(repeating: UInt8(0), count: H.blockByteCount)
|
|
||||||
key.withUnsafeBytes { keyArray.replaceSubrange(0..<$0.count, with: $0) }
|
|
||||||
K = SymmetricKey(data: keyArray)
|
|
||||||
}
|
|
||||||
|
|
||||||
self.innerHasher = H()
|
self.innerHasher = H()
|
||||||
let innerKey = K.withUnsafeBytes {
|
|
||||||
return $0.map({ (keyByte) in
|
|
||||||
keyByte ^ 0x36
|
|
||||||
})
|
|
||||||
}
|
|
||||||
innerHasher.update(data: innerKey)
|
|
||||||
|
|
||||||
self.outerHasher = H()
|
self.outerHasher = H()
|
||||||
let outerKey = K.withUnsafeBytes {
|
withTemporaryZeroingAllocation(byteCount: H.blockByteCount, alignment: 1) { keyBlock in
|
||||||
return $0.map({ (keyByte) in
|
if key.byteCount <= keyBlock.freeCapacity {
|
||||||
keyByte ^ 0x5c
|
keyBlock.append(contentsOf: key.bytes)
|
||||||
})
|
} else if key.byteCount > H.blockByteCount {
|
||||||
|
H.hash(bytes: key.bytes).withBytes { keyBlock.append(contentsOf: $0) }
|
||||||
|
}
|
||||||
|
keyBlock.append(repeating: 0, count: keyBlock.freeCapacity, as: UInt8.self)
|
||||||
|
|
||||||
|
var k0 = keyBlock.mutableBytes
|
||||||
|
for i in 0 ..< k0.byteCount { k0[i] ^= 0x36 } // apply ipad
|
||||||
|
self.innerHasher.update(bytes: k0.bytes)
|
||||||
|
for i in 0 ..< k0.byteCount { k0[i] ^= 0x36 ^ 0x5c } // undo ipad, apply opad
|
||||||
|
self.outerHasher.update(bytes: k0.bytes)
|
||||||
}
|
}
|
||||||
outerHasher.update(data: outerKey)
|
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -133,6 +99,19 @@ public struct HMAC<H: HashFunction>: MACAlgorithm, Sendable {
|
|||||||
return authenticator.finalize()
|
return authenticator.finalize()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Computes a message authentication code for the given data.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - data: The data for which to compute the authentication code.
|
||||||
|
/// - key: The symmetric key used to secure the computation.
|
||||||
|
///
|
||||||
|
/// - Returns: The message authentication code.
|
||||||
|
public static func authenticationCode(for data: RawSpan, using key: SymmetricKey) -> MAC {
|
||||||
|
var authenticator = Self(key: key)
|
||||||
|
authenticator.update(bytes: data)
|
||||||
|
return authenticator.finalize()
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns a Boolean value indicating whether the given message
|
/// Returns a Boolean value indicating whether the given message
|
||||||
/// authentication code is valid for a block of data.
|
/// authentication code is valid for a block of data.
|
||||||
///
|
///
|
||||||
@@ -177,6 +156,10 @@ public struct HMAC<H: HashFunction>: MACAlgorithm, Sendable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public mutating func update(bytes: RawSpan) {
|
||||||
|
innerHasher.update(bytes: bytes)
|
||||||
|
}
|
||||||
|
|
||||||
/// Finalizes the message authentication computation and returns the
|
/// Finalizes the message authentication computation and returns the
|
||||||
/// computed code.
|
/// computed code.
|
||||||
///
|
///
|
||||||
@@ -211,10 +194,18 @@ public struct HMAC<H: HashFunction>: MACAlgorithm, Sendable {
|
|||||||
let computedMac = authenticator.finalize()
|
let computedMac = authenticator.finalize()
|
||||||
return safeCompare(authenticationCodeBytes, computedMac)
|
return safeCompare(authenticationCodeBytes, computedMac)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static func isValidAuthenticationCode<C: ContiguousBytes>(authenticationCodeBytes: C,
|
||||||
|
authenticatedData: UnsafeRawBufferPointer,
|
||||||
|
key: SymmetricKey) -> Bool {
|
||||||
|
var authenticator = Self(key: key)
|
||||||
|
authenticator.update(bufferPointer: authenticatedData)
|
||||||
|
let computedMac = authenticator.finalize()
|
||||||
|
return safeCompare(authenticationCodeBytes, computedMac)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A hash-based message authentication code.
|
/// A hash-based message authentication code.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public struct HashedAuthenticationCode<H: HashFunction>: MessageAuthenticationCode, Sendable {
|
public struct HashedAuthenticationCode<H: HashFunction>: MessageAuthenticationCode, Sendable {
|
||||||
let digest: H.Digest
|
let digest: H.Digest
|
||||||
|
|
||||||
@@ -248,4 +239,4 @@ public struct HashedAuthenticationCode<H: HashFunction>: MessageAuthenticationCo
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,27 +11,19 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
import Foundation
|
import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
protocol MACAlgorithm {
|
protocol MACAlgorithm {
|
||||||
associatedtype Key
|
associatedtype Key
|
||||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
associatedtype MAC: CryptoKit.MessageAuthenticationCode
|
|
||||||
#else
|
|
||||||
associatedtype MAC: Crypto.MessageAuthenticationCode
|
associatedtype MAC: Crypto.MessageAuthenticationCode
|
||||||
#endif
|
|
||||||
|
|
||||||
/// Initializes the MAC Algorithm
|
/// Initializes the MAC Algorithm
|
||||||
///
|
///
|
||||||
@@ -49,7 +41,6 @@ protocol MACAlgorithm {
|
|||||||
func finalize() -> MAC
|
func finalize() -> MAC
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension MACAlgorithm {
|
extension MACAlgorithm {
|
||||||
/// Computes a Message Authentication Code.
|
/// Computes a Message Authentication Code.
|
||||||
///
|
///
|
||||||
@@ -76,4 +67,4 @@ extension MACAlgorithm {
|
|||||||
return mac == Self.authenticationCode(bufferPointer: bufferPointer, using: key)
|
return mac == Self.authenticationCode(bufferPointer: bufferPointer, using: key)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,23 +11,19 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
|
||||||
public import SwiftSystem
|
|
||||||
#else
|
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
public import FoundationEssentials
|
public import FoundationEssentials
|
||||||
#else
|
#else
|
||||||
public import Foundation
|
public import Foundation
|
||||||
#endif
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
#if hasFeature(Embedded)
|
#if hasFeature(Embedded)
|
||||||
/// A type that represents a message authentication code.
|
/// A type that represents a message authentication code.
|
||||||
@preconcurrency
|
@preconcurrency
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public protocol MessageAuthenticationCode: Hashable, ContiguousBytes, Sendable, Sequence where Element == UInt8 {
|
public protocol MessageAuthenticationCode: Hashable, ContiguousBytes, Sendable, Sequence where Element == UInt8 {
|
||||||
/// The number of bytes in the message authentication code.
|
/// The number of bytes in the message authentication code.
|
||||||
var byteCount: Int { get }
|
var byteCount: Int { get }
|
||||||
@@ -35,14 +31,12 @@ public protocol MessageAuthenticationCode: Hashable, ContiguousBytes, Sendable,
|
|||||||
#else
|
#else
|
||||||
/// A type that represents a message authentication code.
|
/// A type that represents a message authentication code.
|
||||||
@preconcurrency
|
@preconcurrency
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
public protocol MessageAuthenticationCode: Hashable, ContiguousBytes, Sendable, CustomStringConvertible, Sequence where Element == UInt8 {
|
public protocol MessageAuthenticationCode: Hashable, ContiguousBytes, Sendable, CustomStringConvertible, Sequence where Element == UInt8 {
|
||||||
/// The number of bytes in the message authentication code.
|
/// The number of bytes in the message authentication code.
|
||||||
var byteCount: Int { get }
|
var byteCount: Int { get }
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension MessageAuthenticationCode {
|
extension MessageAuthenticationCode {
|
||||||
/// Returns a Boolean value indicating whether two message authentication
|
/// Returns a Boolean value indicating whether two message authentication
|
||||||
/// codes are equal.
|
/// codes are equal.
|
||||||
@@ -77,7 +71,7 @@ extension MessageAuthenticationCode {
|
|||||||
|
|
||||||
public func makeIterator() -> Array<UInt8>.Iterator {
|
public func makeIterator() -> Array<UInt8>.Iterator {
|
||||||
self.withUnsafeBytes({ (buffPtr) in
|
self.withUnsafeBytes({ (buffPtr) in
|
||||||
return Array(buffPtr.bindMemory(to: UInt8.self)).makeIterator()
|
return Array(buffPtr).makeIterator()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,4 +81,4 @@ extension MessageAuthenticationCode {
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,16 +11,16 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
|
||||||
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
/// A container for Advanced Encryption Standard (AES) ciphers.
|
/// A container for Advanced Encryption Standard (AES) ciphers.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@nonexhaustive
|
||||||
public enum AES: Sendable {
|
public enum AES: Sendable {
|
||||||
static let blockSizeByteCount = 16
|
static let blockSizeByteCount = 16
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension AES {
|
extension AES {
|
||||||
static func isValidKey(_ key: SymmetricKey) -> Bool {
|
static func isValidKey(_ key: SymmetricKey) -> Bool {
|
||||||
switch key.bitCount {
|
switch key.bitCount {
|
||||||
@@ -35,4 +35,4 @@ extension AES {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // Linux or !SwiftPM
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,11 +11,14 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
#if hasFeature(SourceWarningControl)
|
||||||
|
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||||
|
#else
|
||||||
@_implementationOnly import CCryptoBoringSSL
|
@_implementationOnly import CCryptoBoringSSL
|
||||||
@_implementationOnly import CCryptoBoringSSLShims
|
#endif
|
||||||
import CryptoBoringWrapper
|
import CryptoBoringWrapper
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
@@ -25,13 +28,13 @@ import Foundation
|
|||||||
|
|
||||||
/// A wrapper around BoringSSL's ECDSA_SIG with some lifetime management.
|
/// A wrapper around BoringSSL's ECDSA_SIG with some lifetime management.
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||||
class ECDSASignature {
|
final class ECDSASignature {
|
||||||
private var _baseSig: UnsafeMutablePointer<ECDSA_SIG>
|
private var _baseSig: UnsafeMutablePointer<ECDSA_SIG>
|
||||||
|
|
||||||
init<ContiguousBuffer: ContiguousBytes>(contiguousDERBytes derBytes: ContiguousBuffer) throws {
|
init<ContiguousBuffer: ContiguousBytes>(contiguousDERBytes derBytes: ContiguousBuffer) throws {
|
||||||
self._baseSig = try derBytes.withUnsafeBytes { bytesPtr in
|
self._baseSig = try derBytes.withUnsafeBytes { bytesPtr in
|
||||||
guard
|
guard
|
||||||
let sig = CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(bytesPtr.baseAddress, bytesPtr.count)
|
let sig = CCryptoBoringSSL_ECDSA_SIG_from_bytes(bytesPtr.baseAddress, bytesPtr.count)
|
||||||
else {
|
else {
|
||||||
throw CryptoKitError.internalBoringSSLError()
|
throw CryptoKitError.internalBoringSSLError()
|
||||||
}
|
}
|
||||||
@@ -96,21 +99,6 @@ class ECDSASignature {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@usableFromInline
|
|
||||||
var derBytes: Data {
|
|
||||||
var dataPtr: UnsafeMutablePointer<UInt8>?
|
|
||||||
var length = 0
|
|
||||||
guard CCryptoBoringSSL_ECDSA_SIG_to_bytes(&dataPtr, &length, self._baseSig) == 1 else {
|
|
||||||
fatalError("Unable to marshal signature to DER")
|
|
||||||
}
|
|
||||||
defer {
|
|
||||||
// We must free this pointer.
|
|
||||||
CCryptoBoringSSL_OPENSSL_free(dataPtr)
|
|
||||||
}
|
|
||||||
|
|
||||||
return Data(UnsafeBufferPointer(start: dataPtr, count: length))
|
|
||||||
}
|
|
||||||
|
|
||||||
func withUnsafeSignaturePointer<T>(
|
func withUnsafeSignaturePointer<T>(
|
||||||
_ body: (UnsafeMutablePointer<ECDSA_SIG>) throws -> T
|
_ body: (UnsafeMutablePointer<ECDSA_SIG>) throws -> T
|
||||||
)
|
)
|
||||||
@@ -119,4 +107,4 @@ class ECDSASignature {
|
|||||||
try body(self._baseSig)
|
try body(self._baseSig)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#endif // canImport(CryptoKit)
|
||||||
@@ -11,10 +11,14 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
//===----------------------------------------------------------------------===//
|
//===----------------------------------------------------------------------===//
|
||||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#if canImport(CryptoKit)
|
||||||
@_exported import CryptoKit
|
@_exported import CryptoKit
|
||||||
#else
|
#else
|
||||||
|
#if hasFeature(SourceWarningControl)
|
||||||
|
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||||
|
#else
|
||||||
@_implementationOnly import CCryptoBoringSSL
|
@_implementationOnly import CCryptoBoringSSL
|
||||||
|
#endif
|
||||||
import CryptoBoringWrapper
|
import CryptoBoringWrapper
|
||||||
#if canImport(FoundationEssentials)
|
#if canImport(FoundationEssentials)
|
||||||
import FoundationEssentials
|
import FoundationEssentials
|
||||||
@@ -63,17 +67,6 @@ extension Data {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P256.Signing.ECDSASignature {
|
|
||||||
init<D: DataProtocol>(openSSLDERSignature derRepresentation: D) throws {
|
|
||||||
self.rawRepresentation = try Data(derSignature: derRepresentation, over: P256.self)
|
|
||||||
}
|
|
||||||
|
|
||||||
var openSSLDERRepresentation: Data {
|
|
||||||
try! ECDSASignature(rawRepresentation: self.rawRepresentation).derBytes
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||||
extension P256.Signing.PrivateKey {
|
extension P256.Signing.PrivateKey {
|
||||||
func openSSLSignature<D: Digest>(for digest: D) throws -> P256.Signing.ECDSASignature {
|
func openSSLSignature<D: Digest>(for digest: D) throws -> P256.Signing.ECDSASignature {
|
||||||
@@ -100,17 +93,6 @@ extension P256.Signing.PublicKey {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P384.Signing.ECDSASignature {
|
|
||||||
init<D: DataProtocol>(openSSLDERSignature derRepresentation: D) throws {
|
|
||||||
self.rawRepresentation = try Data(derSignature: derRepresentation, over: P384.self)
|
|
||||||
}
|
|
||||||
|
|
||||||
var openSSLDERRepresentation: Data {
|
|
||||||
try! ECDSASignature(rawRepresentation: self.rawRepresentation).derBytes
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||||
extension P384.Signing.PrivateKey {
|
extension P384.Signing.PrivateKey {
|
||||||
func openSSLSignature<D: Digest>(for digest: D) throws -> P384.Signing.ECDSASignature {
|
func openSSLSignature<D: Digest>(for digest: D) throws -> P384.Signing.ECDSASignature {
|
||||||
@@ -137,17 +119,6 @@ extension P384.Signing.PublicKey {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
||||||
extension P521.Signing.ECDSASignature {
|
|
||||||
init<D: DataProtocol>(openSSLDERSignature derRepresentation: D) throws {
|
|
||||||
self.rawRepresentation = try Data(derSignature: derRepresentation, over: P521.self)
|
|
||||||
}
|
|
||||||
|
|
||||||
var openSSLDERRepresentation: Data {
|
|
||||||
try! ECDSASignature(rawRepresentation: self.rawRepresentation).derBytes
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||||
extension P521.Signing.PrivateKey {
|
extension P521.Signing.PrivateKey {
|
||||||
func openSSLSignature<D: Digest>(for digest: D) throws -> P521.Signing.ECDSASignature {
|
func openSSLSignature<D: Digest>(for digest: D) throws -> P521.Signing.ECDSASignature {
|
||||||
@@ -173,4 +144,4 @@ extension P521.Signing.PublicKey {
|
|||||||
return self.impl.key.isValidSignature(baseSignature, for: digest)
|
return self.impl.key.isValidSignature(baseSignature, for: digest)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
#endif // canImport(CryptoKit)
|
||||||
Loaded 100 of 231 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user