mirror of
https://github.com/apple/swift-crypto
synced 2026-11-22 04:30:39 +00:00
Update to WWDC25 release (#417)
This change updates Crypto to WWDC25 equivalent code. Each of these changes were individually merged to the WWDC25 branch. This includes: - #359 - #363 - #365 - #367 - #368 - #397 - #403 - #410 - #407 - #401 - #415 --------- Co-authored-by: YourMJK <37852512+YourMJK@users.noreply.github.com> Co-authored-by: Si Beaumont <beaumont@apple.com> Co-authored-by: Rick Newton-Rogers <rnro@apple.com> Co-authored-by: Raphael <josephnoir@users.noreply.github.com> Co-authored-by: Evan Wilde <ewilde@apple.com> Co-authored-by: Tim Condon <0xTim@users.noreply.github.com> Co-authored-by: Gus Cairo <gus.cairo@apple.com> Co-authored-by: George Barnett <gbarnett@apple.com> Co-authored-by: Fabrice de Gans <Steelskin@users.noreply.github.com> Co-authored-by: Wojciech Nagrodzki <278594+wnagrodzki@users.noreply.github.com> Co-authored-by: Jesse L. Zamora <xtremekforever@gmail.com> Co-authored-by: aryan-25 <aryan_shah@apple.com> Co-authored-by: Gwynne Raskind <gwynne@vapor.codes> Co-authored-by: 3405691582 <dsk@google.com> Co-authored-by: Paul Toffoloni <69189821+ptoffy@users.noreply.github.com>
This commit is contained in:
322 files changed
+17931
-1751
No files matched your search
@@ -57,8 +57,10 @@ jobs:
|
||||
{ "name": "CCryptoBoringSSL", "type": "source", "exceptions": [] },
|
||||
{ "name": "CCryptoBoringSSLShims", "type": "source", "exceptions": [] },
|
||||
{ "name": "CryptoBoringWrapper", "type": "source", "exceptions": [] },
|
||||
{ "name": "CXKCP", "type": "source", "exceptions": [] },
|
||||
{ "name": "CXKCPShims", "type": "source", "exceptions": [] },
|
||||
{ "name": "Crypto", "type": "source", "exceptions": [] },
|
||||
{ "name": "_CryptoExtras", "type": "source", "exceptions": [] },
|
||||
{ "name": "CryptoExtras", "type": "source", "exceptions": [] },
|
||||
{ "name": "CCryptoBoringSSL", "type": "assembly", "exceptions": [ "*/AES/*.swift" ] }
|
||||
]
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,5 +1,5 @@
|
||||
.DS_Store
|
||||
/.build
|
||||
.build
|
||||
/out
|
||||
/Packages
|
||||
/*.xcodeproj
|
||||
@@ -12,6 +12,7 @@ Package.resolved
|
||||
DerivedData
|
||||
.swiftpm
|
||||
**/gyb.pyc
|
||||
scripts/__pycache__/
|
||||
|
||||
.*.sw[nop]
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ dev/update-benchmark-thresholds
|
||||
**/*.der
|
||||
.swiftformat
|
||||
Sources/CCryptoBoringSSL/*
|
||||
Sources/CXKCP/*
|
||||
**/*.swift.gyb
|
||||
scripts/*.patch
|
||||
scripts/gyb
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
version: 1
|
||||
builder:
|
||||
configs:
|
||||
- documentation_targets: [Crypto, _CryptoExtras]
|
||||
- documentation_targets: [Crypto, CryptoExtras]
|
||||
platform: linux
|
||||
+79
-68
@@ -25,6 +25,7 @@ Sources/Crypto/Digests/Digest.swift
|
||||
Sources/Crypto/Digests/Digests.swift
|
||||
Sources/Crypto/Digests/HashFunctions.swift
|
||||
Sources/Crypto/Digests/HashFunctions_SHA2.swift
|
||||
Sources/Crypto/Digests/HashFunctions_SHA3.swift
|
||||
Sources/Crypto/HPKE/Ciphersuite/HPKE-AEAD.swift
|
||||
Sources/Crypto/HPKE/Ciphersuite/HPKE-Ciphersuite.swift
|
||||
Sources/Crypto/HPKE/Ciphersuite/HPKE-KDF.swift
|
||||
@@ -43,8 +44,12 @@ Sources/Crypto/HPKE/Modes/HPKE-Modes.swift
|
||||
Sources/Crypto/Insecure/Insecure.swift
|
||||
Sources/Crypto/Insecure/Insecure_HashFunctions.swift
|
||||
Sources/Crypto/KEM/KEM.swift
|
||||
Sources/Crypto/KEM/KEM-Errors.swift
|
||||
Sources/Crypto/KEM/MLKEM.swift
|
||||
Sources/Crypto/KEM/XWing.swift
|
||||
Sources/Crypto/Key Agreement/DH.swift
|
||||
Sources/Crypto/Key Agreement/ECDH.swift
|
||||
Sources/Crypto/Key Derivation/ANSIx963.swift
|
||||
Sources/Crypto/Key Derivation/HKDF.swift
|
||||
Sources/Crypto/Key Wrapping/AESWrap.swift
|
||||
Sources/Crypto/Keys/EC/Curve25519.swift
|
||||
@@ -58,51 +63,52 @@ Sources/Crypto/Message Authentication Codes/MessageAuthenticationCode.swift
|
||||
Sources/Crypto/PRF/AES.swift
|
||||
Sources/Crypto/Signatures/ECDSA.swift
|
||||
Sources/Crypto/Signatures/Ed25519.swift
|
||||
Sources/Crypto/Signatures/MLDSA.swift
|
||||
Sources/Crypto/Signatures/Signature.swift
|
||||
Sources/Crypto/Util/PrettyBytes.swift
|
||||
Sources/Crypto/Util/SafeCompare.swift
|
||||
Sources/Crypto/Util/SecureBytes.swift
|
||||
Sources/Crypto/Util/Zeroization.swift
|
||||
Sources/_CryptoExtras/AES/AES_CBC.swift
|
||||
Sources/_CryptoExtras/AES/AES_CFB.swift
|
||||
Sources/_CryptoExtras/AES/AES_CTR.swift
|
||||
Sources/_CryptoExtras/AES/AES_GCM_SIV.swift
|
||||
Sources/_CryptoExtras/AES/Block Function.swift
|
||||
Sources/_CryptoExtras/ARC/ARC+API.swift
|
||||
Sources/_CryptoExtras/ARC/ARC.swift
|
||||
Sources/_CryptoExtras/ARC/ARCCredential.swift
|
||||
Sources/_CryptoExtras/ARC/ARCEncoding.swift
|
||||
Sources/_CryptoExtras/ARC/ARCPrecredential.swift
|
||||
Sources/_CryptoExtras/ARC/ARCPresentation.swift
|
||||
Sources/_CryptoExtras/ARC/ARCRequest.swift
|
||||
Sources/_CryptoExtras/ARC/ARCResponse.swift
|
||||
Sources/_CryptoExtras/ARC/ARCServer.swift
|
||||
Sources/_CryptoExtras/ZKPs/Prover.swift
|
||||
Sources/_CryptoExtras/ZKPs/Verifier.swift
|
||||
Sources/_CryptoExtras/ZKPs/ZKPToolbox.swift
|
||||
Sources/_CryptoExtras/ChaCha20CTR/ChaCha20CTR.swift
|
||||
Sources/_CryptoExtras/ECToolbox/ECToolbox.swift
|
||||
Sources/_CryptoExtras/H2G/HashToField.swift
|
||||
Sources/_CryptoExtras/Key Derivation/KDF.swift
|
||||
Sources/_CryptoExtras/Key Derivation/PBKDF2/PBKDF2.swift
|
||||
Sources/_CryptoExtras/Key Derivation/Scrypt/Scrypt.swift
|
||||
Sources/_CryptoExtras/OPRFs/OPRF.swift
|
||||
Sources/_CryptoExtras/OPRFs/OPRFClient.swift
|
||||
Sources/_CryptoExtras/OPRFs/OPRFServer.swift
|
||||
Sources/_CryptoExtras/OPRFs/VOPRF+API.swift
|
||||
Sources/_CryptoExtras/OPRFs/VOPRFClient.swift
|
||||
Sources/_CryptoExtras/OPRFs/VOPRFServer.swift
|
||||
Sources/_CryptoExtras/RSA/RSA+BlindSigning.swift
|
||||
Sources/_CryptoExtras/RSA/RSA.swift
|
||||
Sources/_CryptoExtras/Util/BoringSSLHelpers.swift
|
||||
Sources/_CryptoExtras/Util/DigestType.swift
|
||||
Sources/_CryptoExtras/Util/Error.swift
|
||||
Sources/_CryptoExtras/Util/I2OSP.swift
|
||||
Sources/_CryptoExtras/Util/IntegerEncoding.swift
|
||||
Sources/_CryptoExtras/Util/PEMDocument.swift
|
||||
Sources/_CryptoExtras/Util/PrettyBytes.swift
|
||||
Sources/_CryptoExtras/Util/SubjectPublicKeyInfo.swift
|
||||
Sources/_CryptoExtras/ZKPs/DLEQ.swift
|
||||
Sources/CryptoExtras/AES/AES_CBC.swift
|
||||
Sources/CryptoExtras/AES/AES_CFB.swift
|
||||
Sources/CryptoExtras/AES/AES_CTR.swift
|
||||
Sources/CryptoExtras/AES/AES_GCM_SIV.swift
|
||||
Sources/CryptoExtras/AES/Block Function.swift
|
||||
Sources/CryptoExtras/ARC/ARC+API.swift
|
||||
Sources/CryptoExtras/ARC/ARC.swift
|
||||
Sources/CryptoExtras/ARC/ARCCredential.swift
|
||||
Sources/CryptoExtras/ARC/ARCEncoding.swift
|
||||
Sources/CryptoExtras/ARC/ARCPrecredential.swift
|
||||
Sources/CryptoExtras/ARC/ARCPresentation.swift
|
||||
Sources/CryptoExtras/ARC/ARCRequest.swift
|
||||
Sources/CryptoExtras/ARC/ARCResponse.swift
|
||||
Sources/CryptoExtras/ARC/ARCServer.swift
|
||||
Sources/CryptoExtras/ZKPs/Prover.swift
|
||||
Sources/CryptoExtras/ZKPs/Verifier.swift
|
||||
Sources/CryptoExtras/ZKPs/ZKPToolbox.swift
|
||||
Sources/CryptoExtras/ChaCha20CTR/ChaCha20CTR.swift
|
||||
Sources/CryptoExtras/ECToolbox/ECToolbox.swift
|
||||
Sources/CryptoExtras/H2G/HashToField.swift
|
||||
Sources/CryptoExtras/Key Derivation/KDF.swift
|
||||
Sources/CryptoExtras/Key Derivation/PBKDF2/PBKDF2.swift
|
||||
Sources/CryptoExtras/Key Derivation/Scrypt/Scrypt.swift
|
||||
Sources/CryptoExtras/OPRFs/OPRF.swift
|
||||
Sources/CryptoExtras/OPRFs/OPRFClient.swift
|
||||
Sources/CryptoExtras/OPRFs/OPRFServer.swift
|
||||
Sources/CryptoExtras/OPRFs/VOPRF+API.swift
|
||||
Sources/CryptoExtras/OPRFs/VOPRFClient.swift
|
||||
Sources/CryptoExtras/OPRFs/VOPRFServer.swift
|
||||
Sources/CryptoExtras/RSA/RSA+BlindSigning.swift
|
||||
Sources/CryptoExtras/RSA/RSA.swift
|
||||
Sources/CryptoExtras/Util/BoringSSLHelpers.swift
|
||||
Sources/CryptoExtras/Util/DigestType.swift
|
||||
Sources/CryptoExtras/Util/Error.swift
|
||||
Sources/CryptoExtras/Util/I2OSP.swift
|
||||
Sources/CryptoExtras/Util/IntegerEncoding.swift
|
||||
Sources/CryptoExtras/Util/PEMDocument.swift
|
||||
Sources/CryptoExtras/Util/PrettyBytes.swift
|
||||
Sources/CryptoExtras/Util/SubjectPublicKeyInfo.swift
|
||||
Sources/CryptoExtras/ZKPs/DLEQ.swift
|
||||
Sources/crypto-shasum/main.swift
|
||||
Tests/CryptoTests/ASN1/ASN1Tests.swift
|
||||
Tests/CryptoTests/ASN1/GeneralizedTimeTests.swift
|
||||
@@ -115,6 +121,9 @@ Tests/CryptoTests/Encodings/DERTests.swift
|
||||
Tests/CryptoTests/Encodings/ECKeyEncodingsTests.swift
|
||||
Tests/CryptoTests/HPKE/HPKETests-TestVectors.swift
|
||||
Tests/CryptoTests/HPKE/HPKETests.swift
|
||||
Tests/CryptoTests/KEM/MLKEMKeyGenTests.swift
|
||||
Tests/CryptoTests/KEM/MLKEMTests.swift
|
||||
Tests/CryptoTests/KEM/XWingTests.swift
|
||||
Tests/CryptoTests/Key Derivation/ECprivateKeysFromSeeds.swift
|
||||
Tests/CryptoTests/Key Derivation/HKDFTests.swift
|
||||
Tests/CryptoTests/Key Derivation/SharedSecretTests.swift
|
||||
@@ -125,36 +134,38 @@ Tests/CryptoTests/SecureBytes/SecureBytesTests.swift
|
||||
Tests/CryptoTests/Signatures/ECDSA/ECDSASignatureTests.swift
|
||||
Tests/CryptoTests/Signatures/ECDSA/RawECDSASignaturesTests.swift
|
||||
Tests/CryptoTests/Signatures/EdDSA/Ed25519-Runner.swift
|
||||
Tests/CryptoTests/Signatures/MLDSA/MLDSAKeyGenTests.swift
|
||||
Tests/CryptoTests/Signatures/MLDSA/MLDSATests.swift
|
||||
Tests/CryptoTests/Utils/PrettyBytes.swift
|
||||
Tests/CryptoTests/Utils/RFCVector.swift
|
||||
Tests/CryptoTests/Utils/SplitData.swift
|
||||
Tests/CryptoTests/Utils/Wycheproof.swift
|
||||
Tests/CryptoTests/Utils/XCTestUtils.swift
|
||||
Tests/_CryptoExtrasTests/AES Block Function Tests.swift
|
||||
Tests/_CryptoExtrasTests/AES-GCM-SIV-Runner.swift
|
||||
Tests/_CryptoExtrasTests/AES_CBCTests.swift
|
||||
Tests/_CryptoExtrasTests/AES_CFBTests.swift
|
||||
Tests/_CryptoExtrasTests/AES_CTRTests.swift
|
||||
Tests/_CryptoExtrasTests/ARC/ARCAPITests.swift
|
||||
Tests/_CryptoExtrasTests/ARC/ARCEncodingTests.swift
|
||||
Tests/_CryptoExtrasTests/ARC/ARCPublicAPITests.swift
|
||||
Tests/_CryptoExtrasTests/ARC/ARCTestVectors.swift
|
||||
Tests/_CryptoExtrasTests/ARC/ARCTests.swift
|
||||
Tests/_CryptoExtrasTests/ChaCha20CTRTests.swift
|
||||
Tests/_CryptoExtrasTests/ECToolbox/HashToCurveTests.swift
|
||||
Tests/_CryptoExtrasTests/OPRFs/ECVOPRFTests.swift
|
||||
Tests/_CryptoExtrasTests/OPRFs/VOPRFAPITests.swift
|
||||
Tests/_CryptoExtrasTests/OPRFs/VOPRFPublicAPITests.swift
|
||||
Tests/_CryptoExtrasTests/PBKDF2Tests.swift
|
||||
Tests/_CryptoExtrasTests/ScryptTests.swift
|
||||
Tests/_CryptoExtrasTests/TestRSABlindSigning.swift
|
||||
Tests/_CryptoExtrasTests/TestRSABlindSigningAPI.swift
|
||||
Tests/_CryptoExtrasTests/TestRSAEncryption.swift
|
||||
Tests/_CryptoExtrasTests/TestRSASigning.swift
|
||||
Tests/_CryptoExtrasTests/Util/IntegerEncodingTests.swift
|
||||
Tests/_CryptoExtrasTests/Utils/BytesUtil.swift
|
||||
Tests/_CryptoExtrasTests/Utils/RFCVector.swift
|
||||
Tests/_CryptoExtrasTests/Utils/SplitData.swift
|
||||
Tests/_CryptoExtrasTests/Utils/Wycheproof.swift
|
||||
Tests/_CryptoExtrasTests/Utils/XCTestUtils.swift
|
||||
Tests/_CryptoExtrasTests/ZKPs/ZKPToolbox.swift
|
||||
Tests/CryptoExtrasTests/AES Block Function Tests.swift
|
||||
Tests/CryptoExtrasTests/AES-GCM-SIV-Runner.swift
|
||||
Tests/CryptoExtrasTests/AES_CBCTests.swift
|
||||
Tests/CryptoExtrasTests/AES_CFBTests.swift
|
||||
Tests/CryptoExtrasTests/AES_CTRTests.swift
|
||||
Tests/CryptoExtrasTests/ARC/ARCAPITests.swift
|
||||
Tests/CryptoExtrasTests/ARC/ARCEncodingTests.swift
|
||||
Tests/CryptoExtrasTests/ARC/ARCPublicAPITests.swift
|
||||
Tests/CryptoExtrasTests/ARC/ARCTestVectors.swift
|
||||
Tests/CryptoExtrasTests/ARC/ARCTests.swift
|
||||
Tests/CryptoExtrasTests/ChaCha20CTRTests.swift
|
||||
Tests/CryptoExtrasTests/ECToolbox/HashToCurveTests.swift
|
||||
Tests/CryptoExtrasTests/OPRFs/ECVOPRFTests.swift
|
||||
Tests/CryptoExtrasTests/OPRFs/VOPRFAPITests.swift
|
||||
Tests/CryptoExtrasTests/OPRFs/VOPRFPublicAPITests.swift
|
||||
Tests/CryptoExtrasTests/PBKDF2Tests.swift
|
||||
Tests/CryptoExtrasTests/ScryptTests.swift
|
||||
Tests/CryptoExtrasTests/TestRSABlindSigning.swift
|
||||
Tests/CryptoExtrasTests/TestRSABlindSigningAPI.swift
|
||||
Tests/CryptoExtrasTests/TestRSAEncryption.swift
|
||||
Tests/CryptoExtrasTests/TestRSASigning.swift
|
||||
Tests/CryptoExtrasTests/Util/IntegerEncodingTests.swift
|
||||
Tests/CryptoExtrasTests/Utils/BytesUtil.swift
|
||||
Tests/CryptoExtrasTests/Utils/RFCVector.swift
|
||||
Tests/CryptoExtrasTests/Utils/SplitData.swift
|
||||
Tests/CryptoExtrasTests/Utils/Wycheproof.swift
|
||||
Tests/CryptoExtrasTests/Utils/XCTestUtils.swift
|
||||
Tests/CryptoExtrasTests/ZKPs/ZKPToolbox.swift
|
||||
@@ -1 +1,2 @@
|
||||
Sources/CCryptoBoringSSL/*
|
||||
Sources/CCryptoBoringSSL/*
|
||||
Sources/CXKCP/*
|
||||
@@ -13,8 +13,13 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
import Benchmark
|
||||
import Crypto
|
||||
import CryptoExtras
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
import _CryptoExtras
|
||||
#endif
|
||||
|
||||
let benchmarks = {
|
||||
let defaultMetrics: [BenchmarkMetric] = [.mallocCountTotal, .cpuTotal]
|
||||
|
||||
@@ -14,7 +14,7 @@ let package = Package(
|
||||
dependencies: [
|
||||
.product(name: "Benchmark", package: "package-benchmark"),
|
||||
.product(name: "Crypto", package: "swift-crypto"),
|
||||
.product(name: "_CryptoExtras", package: "swift-crypto"),
|
||||
.product(name: "CryptoExtras", package: "swift-crypto"),
|
||||
],
|
||||
path: "Benchmarks/",
|
||||
plugins: [
|
||||
|
||||
+1
-1
@@ -69,7 +69,7 @@ act --container-architecture linux/amd64 pull_request -j cmake-lists -W ./.githu
|
||||
|
||||
You can find the underlying script at https://github.com/apple/swift-nio/blob/main/scripts/update-cmake-lists.sh . Using the script directly is less straightforwards because it requires you to pass the JSON config from the `pull_request.yml` file into the script, such as:
|
||||
```
|
||||
curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/update-cmake-lists.sh | CONFIG_JSON='{"targets":[{"name":"CCryptoBoringSSL","type":"source","exceptions":[]},{"name":"CCryptoBoringSSLShims","type":"source","exceptions":[]},{"name":"CryptoBoringWrapper","type":"source","exceptions":[]},{"name":"Crypto","type":"source","exceptions":[]},{"name":"_CryptoExtras","type":"source","exceptions":[]},{"name":"CCryptoBoringSSL","type":"assembly","exceptions":["*/AES/*.swift"]}]}' bash
|
||||
curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/update-cmake-lists.sh | CONFIG_JSON='{"targets":[{"name":"CCryptoBoringSSL","type":"source","exceptions":[]},{"name":"CCryptoBoringSSLShims","type":"source","exceptions":[]},{"name":"CryptoBoringWrapper","type":"source","exceptions":[]},{"name":"Crypto","type":"source","exceptions":[]},{"name":"CryptoExtras","type":"source","exceptions":[]},{"name":"CCryptoBoringSSL","type":"assembly","exceptions":["*/AES/*.swift"]}]}' bash
|
||||
```
|
||||
|
||||
## API Evolution
|
||||
|
||||
+53
-5
@@ -1,4 +1,4 @@
|
||||
// swift-tools-version:5.10
|
||||
// swift-tools-version:6.0
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
@@ -49,6 +49,8 @@ if development || isFreeBSD {
|
||||
"CCryptoBoringSSL",
|
||||
"CCryptoBoringSSLShims",
|
||||
"CryptoBoringWrapper",
|
||||
"CXKCP",
|
||||
"CXKCPShims",
|
||||
]
|
||||
} else {
|
||||
let platforms: [Platform] = [
|
||||
@@ -66,6 +68,8 @@ if development || isFreeBSD {
|
||||
.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)),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -85,7 +89,9 @@ let package = Package(
|
||||
name: "swift-crypto",
|
||||
products: [
|
||||
.library(name: "Crypto", targets: ["Crypto"]),
|
||||
// Kept for backward compatibility
|
||||
.library(name: "_CryptoExtras", targets: ["_CryptoExtras"]),
|
||||
.library(name: "CryptoExtras", targets: ["CryptoExtras"]),
|
||||
/* This target is used only for symbol mangling. It's added and removed automatically because it emits build warnings. MANGLE_START
|
||||
.library(name: "CCryptoBoringSSL", type: .static, targets: ["CCryptoBoringSSL"]),
|
||||
MANGLE_END */
|
||||
@@ -124,6 +130,21 @@ let package = Package(
|
||||
.define("OPENSSL_NO_ASM", .when(platforms: [Platform.wasi])),
|
||||
]
|
||||
),
|
||||
.target(
|
||||
name: "CXKCP",
|
||||
exclude: [
|
||||
"CMakeLists.txt"
|
||||
],
|
||||
cSettings: [
|
||||
.define("XKCP_has_KeccakP1600"),
|
||||
.headerSearchPath("include"),
|
||||
.headerSearchPath("high"),
|
||||
.headerSearchPath("low"),
|
||||
.headerSearchPath("low/KeccakP-1600"),
|
||||
.headerSearchPath("low/common"),
|
||||
.headerSearchPath("common"),
|
||||
]
|
||||
),
|
||||
.target(
|
||||
name: "CCryptoBoringSSLShims",
|
||||
dependencies: ["CCryptoBoringSSL"],
|
||||
@@ -132,6 +153,14 @@ let package = Package(
|
||||
],
|
||||
resources: privacyManifestResource
|
||||
),
|
||||
.target(
|
||||
name: "CXKCPShims",
|
||||
dependencies: ["CXKCP"],
|
||||
exclude: privacyManifestExclude + [
|
||||
"CMakeLists.txt"
|
||||
],
|
||||
resources: privacyManifestResource
|
||||
),
|
||||
.target(
|
||||
name: "Crypto",
|
||||
dependencies: dependencies,
|
||||
@@ -141,12 +170,16 @@ let package = Package(
|
||||
"Digests/Digests.swift.gyb",
|
||||
"Key Agreement/ECDH.swift.gyb",
|
||||
"Signatures/ECDSA.swift.gyb",
|
||||
"Signatures/MLDSA.swift.gyb",
|
||||
"Signatures/BoringSSL/MLDSA_boring.swift.gyb",
|
||||
"KEM/MLKEM.swift.gyb",
|
||||
"KEM/BoringSSL/MLKEM_boring.swift.gyb",
|
||||
],
|
||||
resources: privacyManifestResource,
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.target(
|
||||
name: "_CryptoExtras",
|
||||
name: "CryptoExtras",
|
||||
dependencies: [
|
||||
"CCryptoBoringSSL",
|
||||
"CCryptoBoringSSLShims",
|
||||
@@ -160,6 +193,13 @@ let package = Package(
|
||||
resources: privacyManifestResource,
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.target(
|
||||
name: "_CryptoExtras",
|
||||
dependencies: [
|
||||
"CryptoExtras",
|
||||
],
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.target(
|
||||
name: "CryptoBoringWrapper",
|
||||
dependencies: [
|
||||
@@ -176,13 +216,20 @@ let package = Package(
|
||||
name: "CryptoTests",
|
||||
dependencies: ["Crypto"],
|
||||
resources: [
|
||||
.copy("HPKE/hpke-test-vectors.json")
|
||||
.copy("HPKE/hpke-test-vectors.json"),
|
||||
.copy("KEM/MLKEM768_BSSLKAT.json"),
|
||||
.copy("KEM/MLKEM768KAT.json"),
|
||||
.copy("KEM/MLKEM1024_BSSLKAT.json"),
|
||||
.copy("KEM/MLKEM1024KAT.json"),
|
||||
.copy("KEM/test-vectors.json"),
|
||||
.copy("Signatures/MLDSA/MLDSA65_KeyGen_KAT.json"),
|
||||
.copy("Signatures/MLDSA/MLDSA87_KeyGen_KAT.json"),
|
||||
],
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.testTarget(
|
||||
name: "_CryptoExtrasTests",
|
||||
dependencies: ["_CryptoExtras"],
|
||||
name: "CryptoExtrasTests",
|
||||
dependencies: ["CryptoExtras"],
|
||||
resources: [
|
||||
.copy("ECToolbox/H2CVectors/P256_XMD-SHA-256_SSWU_RO_.json"),
|
||||
.copy("ECToolbox/H2CVectors/P384_XMD-SHA-384_SSWU_RO_.json"),
|
||||
@@ -193,6 +240,7 @@ let package = Package(
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.testTarget(name: "CryptoBoringWrapperTests", dependencies: ["CryptoBoringWrapper"]),
|
||||
.testTarget(name: "CXKCPTests", dependencies: ["CXKCP"]),
|
||||
],
|
||||
cxxLanguageStandard: .cxx17
|
||||
)
|
||||
|
||||
@@ -34,7 +34,7 @@ When building Swift Crypto for use on Linux or Windows, Swift Crypto builds subs
|
||||
2. The common API of Swift Crypto and CryptoKit.
|
||||
3. The backing implementation of this common API, which calls into BoringSSL.
|
||||
|
||||
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The backing BoringSSL-based implementation is unique to Swift Crypto.
|
||||
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The backing BoringSSL-based implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIS predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL implementation of the library in your application, no matter the platform.
|
||||
|
||||
## Evolution
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
#include "CCryptoBoringSSL_cmac.h"
|
||||
#include "CCryptoBoringSSL_conf.h"
|
||||
#include "CCryptoBoringSSL_cpu.h"
|
||||
#include "CCryptoBoringSSL_ctrdrbg.h"
|
||||
#include "CCryptoBoringSSL_curve25519.h"
|
||||
#include "CCryptoBoringSSL_des.h"
|
||||
#include "CCryptoBoringSSL_e_os2.h"
|
||||
@@ -44,6 +45,8 @@
|
||||
#include "CCryptoBoringSSL_hrss.h"
|
||||
#include "CCryptoBoringSSL_md4.h"
|
||||
#include "CCryptoBoringSSL_md5.h"
|
||||
#include "CCryptoBoringSSL_mldsa.h"
|
||||
#include "CCryptoBoringSSL_mlkem.h"
|
||||
#include "CCryptoBoringSSL_obj_mac.h"
|
||||
#include "CCryptoBoringSSL_objects.h"
|
||||
#include "CCryptoBoringSSL_opensslv.h"
|
||||
@@ -60,5 +63,6 @@
|
||||
#include "CCryptoBoringSSL_siphash.h"
|
||||
#include "CCryptoBoringSSL_trust_token.h"
|
||||
#include "CCryptoBoringSSL_x509v3.h"
|
||||
#include "CCryptoBoringSSL_xwing.h"
|
||||
|
||||
#endif // C_CRYPTO_BORINGSSL_H
|
||||
@@ -14,6 +14,8 @@
|
||||
|
||||
add_subdirectory(CCryptoBoringSSL)
|
||||
add_subdirectory(CCryptoBoringSSLShims)
|
||||
add_subdirectory(CXKCP)
|
||||
add_subdirectory(CXKCPShims)
|
||||
add_subdirectory(CryptoBoringWrapper)
|
||||
add_subdirectory(Crypto)
|
||||
add_subdirectory(_CryptoExtras)
|
||||
add_subdirectory(CryptoExtras)
|
||||
@@ -0,0 +1,34 @@
|
||||
##===----------------------------------------------------------------------===##
|
||||
##
|
||||
## 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(CXKCP STATIC
|
||||
"FIPS202-opt64/KeccakHash.c"
|
||||
"FIPS202-opt64/KeccakP-1600-opt64.c"
|
||||
"FIPS202-opt64/KeccakSponge.c"
|
||||
"FIPS202-opt64/SimpleFIPS202.c"
|
||||
)
|
||||
|
||||
target_include_directories(CXKCP PUBLIC
|
||||
include)
|
||||
|
||||
target_compile_definitions(CXKCP PRIVATE
|
||||
$<$<PLATFORM_ID:Windows>:WIN32_LEAN_AND_MEAN>)
|
||||
target_link_libraries(CXKCP PUBLIC
|
||||
$<$<NOT:$<PLATFORM_ID:Darwin>>:dispatch>
|
||||
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
|
||||
SwiftASN1)
|
||||
set_target_properties(CXKCP PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/include;${CMAKE_Swift_MODULE_DIRECTORY}")
|
||||
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_CRYPTO_EXPORTS CXKCP)
|
||||
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
The eXtended Keccak Code Package (XKCP)
|
||||
https://github.com/XKCP/XKCP
|
||||
|
||||
Keccak, designed by Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche.
|
||||
|
||||
Implementation by the designers, hereby denoted as "the implementer".
|
||||
|
||||
For more information, feedback or questions, please refer to the Keccak Team website:
|
||||
https://keccak.team/
|
||||
|
||||
To the extent possible under law, the implementer has waived all copyright
|
||||
and related or neighboring rights to the source code in this file.
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
#include <string.h>
|
||||
#include "KeccakHash.h"
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
HashReturn Keccak_HashInitialize(Keccak_HashInstance *instance, unsigned int rate, unsigned int capacity, unsigned int hashbitlen, unsigned char delimitedSuffix)
|
||||
{
|
||||
HashReturn result;
|
||||
|
||||
if (delimitedSuffix == 0)
|
||||
return KECCAK_FAIL;
|
||||
result = (HashReturn)KeccakWidth1600_SpongeInitialize(&instance->sponge, rate, capacity);
|
||||
if (result != KECCAK_SUCCESS)
|
||||
return result;
|
||||
instance->fixedOutputLength = hashbitlen;
|
||||
instance->delimitedSuffix = delimitedSuffix;
|
||||
return KECCAK_SUCCESS;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
HashReturn Keccak_HashUpdate(Keccak_HashInstance *instance, const BitSequence *data, BitLength databitlen)
|
||||
{
|
||||
if ((databitlen % 8) == 0)
|
||||
return (HashReturn)KeccakWidth1600_SpongeAbsorb(&instance->sponge, data, databitlen/8);
|
||||
else {
|
||||
HashReturn ret = (HashReturn)KeccakWidth1600_SpongeAbsorb(&instance->sponge, data, databitlen/8);
|
||||
if (ret == KECCAK_SUCCESS) {
|
||||
/* The last partial byte is assumed to be aligned on the least significant bits */
|
||||
unsigned char lastByte = data[databitlen/8];
|
||||
/* Concatenate the last few bits provided here with those of the suffix */
|
||||
unsigned short delimitedLastBytes = (unsigned short)((unsigned short)(lastByte & ((1 << (databitlen % 8)) - 1)) | ((unsigned short)instance->delimitedSuffix << (databitlen % 8)));
|
||||
if ((delimitedLastBytes & 0xFF00) == 0x0000) {
|
||||
instance->delimitedSuffix = delimitedLastBytes & 0xFF;
|
||||
}
|
||||
else {
|
||||
unsigned char oneByte[1];
|
||||
oneByte[0] = delimitedLastBytes & 0xFF;
|
||||
ret = (HashReturn)KeccakWidth1600_SpongeAbsorb(&instance->sponge, oneByte, 1);
|
||||
instance->delimitedSuffix = (delimitedLastBytes >> 8) & 0xFF;
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
HashReturn Keccak_HashFinal(Keccak_HashInstance *instance, BitSequence *hashval)
|
||||
{
|
||||
HashReturn ret = (HashReturn)KeccakWidth1600_SpongeAbsorbLastFewBits(&instance->sponge, instance->delimitedSuffix);
|
||||
if (ret == KECCAK_SUCCESS)
|
||||
return (HashReturn)KeccakWidth1600_SpongeSqueeze(&instance->sponge, hashval, instance->fixedOutputLength/8);
|
||||
else
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
HashReturn Keccak_HashSqueeze(Keccak_HashInstance *instance, BitSequence *data, BitLength databitlen)
|
||||
{
|
||||
if ((databitlen % 8) != 0)
|
||||
return KECCAK_FAIL;
|
||||
return (HashReturn)KeccakWidth1600_SpongeSqueeze(&instance->sponge, data, databitlen/8);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
/*
|
||||
The eXtended Keccak Code Package (XKCP)
|
||||
https://github.com/XKCP/XKCP
|
||||
|
||||
Keccak, designed by Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche.
|
||||
|
||||
Implementation by the designers, hereby denoted as "the implementer".
|
||||
|
||||
For more information, feedback or questions, please refer to the Keccak Team website:
|
||||
https://keccak.team/
|
||||
|
||||
To the extent possible under law, the implementer has waived all copyright
|
||||
and related or neighboring rights to the source code in this file.
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
#ifndef _KeccakHashInterface_h_
|
||||
#define _KeccakHashInterface_h_
|
||||
|
||||
#include "config.h"
|
||||
#ifdef XKCP_has_KeccakP1600
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include "KeccakSponge.h"
|
||||
|
||||
#ifndef _Keccak_BitTypes_
|
||||
#define _Keccak_BitTypes_
|
||||
typedef uint8_t BitSequence;
|
||||
|
||||
typedef size_t BitLength;
|
||||
#endif
|
||||
|
||||
typedef enum { KECCAK_SUCCESS = 0, KECCAK_FAIL = 1, KECCAK_BAD_HASHLEN = 2 } HashReturn;
|
||||
|
||||
typedef struct {
|
||||
KeccakWidth1600_SpongeInstance sponge;
|
||||
unsigned int fixedOutputLength;
|
||||
unsigned char delimitedSuffix;
|
||||
} Keccak_HashInstance;
|
||||
|
||||
/**
|
||||
* Function to initialize the Keccak[r, c] sponge function instance used in sequential hashing mode.
|
||||
* @param hashInstance Pointer to the hash instance to be initialized.
|
||||
* @param rate The value of the rate r.
|
||||
* @param capacity The value of the capacity c.
|
||||
* @param hashbitlen The desired number of output bits,
|
||||
* or 0 for an arbitrarily-long output.
|
||||
* @param delimitedSuffix Bits that will be automatically appended to the end
|
||||
* of the input message, as in domain separation.
|
||||
* This is a byte containing from 0 to 7 bits
|
||||
* formatted like the @a delimitedData parameter of
|
||||
* the Keccak_SpongeAbsorbLastFewBits() function.
|
||||
* @pre One must have r+c=1600 and the rate a multiple of 8 bits in this implementation.
|
||||
* @return KECCAK_SUCCESS if successful, KECCAK_FAIL otherwise.
|
||||
*/
|
||||
HashReturn Keccak_HashInitialize(Keccak_HashInstance *hashInstance, unsigned int rate, unsigned int capacity, unsigned int hashbitlen, unsigned char delimitedSuffix);
|
||||
|
||||
/** Macro to initialize a SHAKE128 instance as specified in the FIPS 202 standard.
|
||||
*/
|
||||
#define Keccak_HashInitialize_SHAKE128(hashInstance) Keccak_HashInitialize(hashInstance, 1344, 256, 0, 0x1F)
|
||||
|
||||
/** Macro to initialize a SHAKE256 instance as specified in the FIPS 202 standard.
|
||||
*/
|
||||
#define Keccak_HashInitialize_SHAKE256(hashInstance) Keccak_HashInitialize(hashInstance, 1088, 512, 0, 0x1F)
|
||||
|
||||
/** Macro to initialize a SHA3-224 instance as specified in the FIPS 202 standard.
|
||||
*/
|
||||
#define Keccak_HashInitialize_SHA3_224(hashInstance) Keccak_HashInitialize(hashInstance, 1152, 448, 224, 0x06)
|
||||
|
||||
/** Macro to initialize a SHA3-256 instance as specified in the FIPS 202 standard.
|
||||
*/
|
||||
#define Keccak_HashInitialize_SHA3_256(hashInstance) Keccak_HashInitialize(hashInstance, 1088, 512, 256, 0x06)
|
||||
|
||||
/** Macro to initialize a SHA3-384 instance as specified in the FIPS 202 standard.
|
||||
*/
|
||||
#define Keccak_HashInitialize_SHA3_384(hashInstance) Keccak_HashInitialize(hashInstance, 832, 768, 384, 0x06)
|
||||
|
||||
/** Macro to initialize a SHA3-512 instance as specified in the FIPS 202 standard.
|
||||
*/
|
||||
#define Keccak_HashInitialize_SHA3_512(hashInstance) Keccak_HashInitialize(hashInstance, 576, 1024, 512, 0x06)
|
||||
|
||||
/**
|
||||
* Function to give input data to be absorbed.
|
||||
* @param hashInstance Pointer to the hash instance initialized by Keccak_HashInitialize().
|
||||
* @param data Pointer to the input data.
|
||||
* When @a databitLen is not a multiple of 8, the last bits of data must be
|
||||
* in the least significant bits of the last byte (little-endian convention).
|
||||
* In this case, the (8 - @a databitLen mod 8) most significant bits
|
||||
* of the last byte are ignored.
|
||||
* @param databitLen The number of input bits provided in the input data.
|
||||
* @pre In the previous call to Keccak_HashUpdate(), databitlen was a multiple of 8.
|
||||
* @return KECCAK_SUCCESS if successful, KECCAK_FAIL otherwise.
|
||||
*/
|
||||
HashReturn Keccak_HashUpdate(Keccak_HashInstance *hashInstance, const BitSequence *data, BitLength databitlen);
|
||||
|
||||
/**
|
||||
* Function to call after all input blocks have been input and to get
|
||||
* output bits if the length was specified when calling Keccak_HashInitialize().
|
||||
* @param hashInstance Pointer to the hash instance initialized by Keccak_HashInitialize().
|
||||
* If @a hashbitlen was not 0 in the call to Keccak_HashInitialize(), the number of
|
||||
* output bits is equal to @a hashbitlen.
|
||||
* If @a hashbitlen was 0 in the call to Keccak_HashInitialize(), the output bits
|
||||
* must be extracted using the Keccak_HashSqueeze() function.
|
||||
* @param hashval Pointer to the buffer where to store the output data.
|
||||
* @return KECCAK_SUCCESS if successful, KECCAK_FAIL otherwise.
|
||||
*/
|
||||
HashReturn Keccak_HashFinal(Keccak_HashInstance *hashInstance, BitSequence *hashval);
|
||||
|
||||
/**
|
||||
* Function to squeeze output data.
|
||||
* @param hashInstance Pointer to the hash instance initialized by Keccak_HashInitialize().
|
||||
* @param data Pointer to the buffer where to store the output data.
|
||||
* @param databitlen The number of output bits desired (must be a multiple of 8).
|
||||
* @pre Keccak_HashFinal() must have been already called.
|
||||
* @pre @a databitlen is a multiple of 8.
|
||||
* @return KECCAK_SUCCESS if successful, KECCAK_FAIL otherwise.
|
||||
*/
|
||||
HashReturn Keccak_HashSqueeze(Keccak_HashInstance *hashInstance, BitSequence *data, BitLength databitlen);
|
||||
|
||||
#else
|
||||
#error This requires an implementation of Keccak-p[1600]
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,758 @@
|
||||
/*
|
||||
The eXtended Keccak Code Package (XKCP)
|
||||
https://github.com/XKCP/XKCP
|
||||
|
||||
The Keccak-p permutations, designed by Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche.
|
||||
|
||||
Implementation by Gilles Van Assche and Ronny Van Keer, hereby denoted as "the implementer".
|
||||
|
||||
For more information, feedback or questions, please refer to the Keccak Team website:
|
||||
https://keccak.team/
|
||||
|
||||
To the extent possible under law, the implementer has waived all copyright
|
||||
and related or neighboring rights to the source code in this file.
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
#define declareABCDE \
|
||||
uint64_t Aba, Abe, Abi, Abo, Abu; \
|
||||
uint64_t Aga, Age, Agi, Ago, Agu; \
|
||||
uint64_t Aka, Ake, Aki, Ako, Aku; \
|
||||
uint64_t Ama, Ame, Ami, Amo, Amu; \
|
||||
uint64_t Asa, Ase, Asi, Aso, Asu; \
|
||||
uint64_t Bba, Bbe, Bbi, Bbo, Bbu; \
|
||||
uint64_t Bga, Bge, Bgi, Bgo, Bgu; \
|
||||
uint64_t Bka, Bke, Bki, Bko, Bku; \
|
||||
uint64_t Bma, Bme, Bmi, Bmo, Bmu; \
|
||||
uint64_t Bsa, Bse, Bsi, Bso, Bsu; \
|
||||
uint64_t Ca, Ce, Ci, Co, Cu; \
|
||||
uint64_t Da, De, Di, Do, Du; \
|
||||
uint64_t Eba, Ebe, Ebi, Ebo, Ebu; \
|
||||
uint64_t Ega, Ege, Egi, Ego, Egu; \
|
||||
uint64_t Eka, Eke, Eki, Eko, Eku; \
|
||||
uint64_t Ema, Eme, Emi, Emo, Emu; \
|
||||
uint64_t Esa, Ese, Esi, Eso, Esu; \
|
||||
|
||||
#define prepareTheta \
|
||||
Ca = Aba^Aga^Aka^Ama^Asa; \
|
||||
Ce = Abe^Age^Ake^Ame^Ase; \
|
||||
Ci = Abi^Agi^Aki^Ami^Asi; \
|
||||
Co = Abo^Ago^Ako^Amo^Aso; \
|
||||
Cu = Abu^Agu^Aku^Amu^Asu; \
|
||||
|
||||
#ifdef UseBebigokimisa
|
||||
/* --- Code for round, with prepare-theta (lane complementing pattern 'bebigokimisa') */
|
||||
/* --- 64-bit lanes mapped to 64-bit words */
|
||||
#define thetaRhoPiChiIotaPrepareTheta(i, A, E) \
|
||||
Da = Cu^ROL64(Ce, 1); \
|
||||
De = Ca^ROL64(Ci, 1); \
|
||||
Di = Ce^ROL64(Co, 1); \
|
||||
Do = Ci^ROL64(Cu, 1); \
|
||||
Du = Co^ROL64(Ca, 1); \
|
||||
\
|
||||
A##ba ^= Da; \
|
||||
Bba = A##ba; \
|
||||
A##ge ^= De; \
|
||||
Bbe = ROL64(A##ge, 44); \
|
||||
A##ki ^= Di; \
|
||||
Bbi = ROL64(A##ki, 43); \
|
||||
A##mo ^= Do; \
|
||||
Bbo = ROL64(A##mo, 21); \
|
||||
A##su ^= Du; \
|
||||
Bbu = ROL64(A##su, 14); \
|
||||
E##ba = Bba ^( Bbe | Bbi ); \
|
||||
E##ba ^= KeccakF1600RoundConstants[i]; \
|
||||
Ca = E##ba; \
|
||||
E##be = Bbe ^((~Bbi)| Bbo ); \
|
||||
Ce = E##be; \
|
||||
E##bi = Bbi ^( Bbo & Bbu ); \
|
||||
Ci = E##bi; \
|
||||
E##bo = Bbo ^( Bbu | Bba ); \
|
||||
Co = E##bo; \
|
||||
E##bu = Bbu ^( Bba & Bbe ); \
|
||||
Cu = E##bu; \
|
||||
\
|
||||
A##bo ^= Do; \
|
||||
Bga = ROL64(A##bo, 28); \
|
||||
A##gu ^= Du; \
|
||||
Bge = ROL64(A##gu, 20); \
|
||||
A##ka ^= Da; \
|
||||
Bgi = ROL64(A##ka, 3); \
|
||||
A##me ^= De; \
|
||||
Bgo = ROL64(A##me, 45); \
|
||||
A##si ^= Di; \
|
||||
Bgu = ROL64(A##si, 61); \
|
||||
E##ga = Bga ^( Bge | Bgi ); \
|
||||
Ca ^= E##ga; \
|
||||
E##ge = Bge ^( Bgi & Bgo ); \
|
||||
Ce ^= E##ge; \
|
||||
E##gi = Bgi ^( Bgo |(~Bgu)); \
|
||||
Ci ^= E##gi; \
|
||||
E##go = Bgo ^( Bgu | Bga ); \
|
||||
Co ^= E##go; \
|
||||
E##gu = Bgu ^( Bga & Bge ); \
|
||||
Cu ^= E##gu; \
|
||||
\
|
||||
A##be ^= De; \
|
||||
Bka = ROL64(A##be, 1); \
|
||||
A##gi ^= Di; \
|
||||
Bke = ROL64(A##gi, 6); \
|
||||
A##ko ^= Do; \
|
||||
Bki = ROL64(A##ko, 25); \
|
||||
A##mu ^= Du; \
|
||||
Bko = ROL64(A##mu, 8); \
|
||||
A##sa ^= Da; \
|
||||
Bku = ROL64(A##sa, 18); \
|
||||
E##ka = Bka ^( Bke | Bki ); \
|
||||
Ca ^= E##ka; \
|
||||
E##ke = Bke ^( Bki & Bko ); \
|
||||
Ce ^= E##ke; \
|
||||
E##ki = Bki ^((~Bko)& Bku ); \
|
||||
Ci ^= E##ki; \
|
||||
E##ko = (~Bko)^( Bku | Bka ); \
|
||||
Co ^= E##ko; \
|
||||
E##ku = Bku ^( Bka & Bke ); \
|
||||
Cu ^= E##ku; \
|
||||
\
|
||||
A##bu ^= Du; \
|
||||
Bma = ROL64(A##bu, 27); \
|
||||
A##ga ^= Da; \
|
||||
Bme = ROL64(A##ga, 36); \
|
||||
A##ke ^= De; \
|
||||
Bmi = ROL64(A##ke, 10); \
|
||||
A##mi ^= Di; \
|
||||
Bmo = ROL64(A##mi, 15); \
|
||||
A##so ^= Do; \
|
||||
Bmu = ROL64(A##so, 56); \
|
||||
E##ma = Bma ^( Bme & Bmi ); \
|
||||
Ca ^= E##ma; \
|
||||
E##me = Bme ^( Bmi | Bmo ); \
|
||||
Ce ^= E##me; \
|
||||
E##mi = Bmi ^((~Bmo)| Bmu ); \
|
||||
Ci ^= E##mi; \
|
||||
E##mo = (~Bmo)^( Bmu & Bma ); \
|
||||
Co ^= E##mo; \
|
||||
E##mu = Bmu ^( Bma | Bme ); \
|
||||
Cu ^= E##mu; \
|
||||
\
|
||||
A##bi ^= Di; \
|
||||
Bsa = ROL64(A##bi, 62); \
|
||||
A##go ^= Do; \
|
||||
Bse = ROL64(A##go, 55); \
|
||||
A##ku ^= Du; \
|
||||
Bsi = ROL64(A##ku, 39); \
|
||||
A##ma ^= Da; \
|
||||
Bso = ROL64(A##ma, 41); \
|
||||
A##se ^= De; \
|
||||
Bsu = ROL64(A##se, 2); \
|
||||
E##sa = Bsa ^((~Bse)& Bsi ); \
|
||||
Ca ^= E##sa; \
|
||||
E##se = (~Bse)^( Bsi | Bso ); \
|
||||
Ce ^= E##se; \
|
||||
E##si = Bsi ^( Bso & Bsu ); \
|
||||
Ci ^= E##si; \
|
||||
E##so = Bso ^( Bsu | Bsa ); \
|
||||
Co ^= E##so; \
|
||||
E##su = Bsu ^( Bsa & Bse ); \
|
||||
Cu ^= E##su; \
|
||||
\
|
||||
|
||||
/* --- Code for round (lane complementing pattern 'bebigokimisa') */
|
||||
/* --- 64-bit lanes mapped to 64-bit words */
|
||||
#define thetaRhoPiChiIota(i, A, E) \
|
||||
Da = Cu^ROL64(Ce, 1); \
|
||||
De = Ca^ROL64(Ci, 1); \
|
||||
Di = Ce^ROL64(Co, 1); \
|
||||
Do = Ci^ROL64(Cu, 1); \
|
||||
Du = Co^ROL64(Ca, 1); \
|
||||
\
|
||||
A##ba ^= Da; \
|
||||
Bba = A##ba; \
|
||||
A##ge ^= De; \
|
||||
Bbe = ROL64(A##ge, 44); \
|
||||
A##ki ^= Di; \
|
||||
Bbi = ROL64(A##ki, 43); \
|
||||
A##mo ^= Do; \
|
||||
Bbo = ROL64(A##mo, 21); \
|
||||
A##su ^= Du; \
|
||||
Bbu = ROL64(A##su, 14); \
|
||||
E##ba = Bba ^( Bbe | Bbi ); \
|
||||
E##ba ^= KeccakF1600RoundConstants[i]; \
|
||||
E##be = Bbe ^((~Bbi)| Bbo ); \
|
||||
E##bi = Bbi ^( Bbo & Bbu ); \
|
||||
E##bo = Bbo ^( Bbu | Bba ); \
|
||||
E##bu = Bbu ^( Bba & Bbe ); \
|
||||
\
|
||||
A##bo ^= Do; \
|
||||
Bga = ROL64(A##bo, 28); \
|
||||
A##gu ^= Du; \
|
||||
Bge = ROL64(A##gu, 20); \
|
||||
A##ka ^= Da; \
|
||||
Bgi = ROL64(A##ka, 3); \
|
||||
A##me ^= De; \
|
||||
Bgo = ROL64(A##me, 45); \
|
||||
A##si ^= Di; \
|
||||
Bgu = ROL64(A##si, 61); \
|
||||
E##ga = Bga ^( Bge | Bgi ); \
|
||||
E##ge = Bge ^( Bgi & Bgo ); \
|
||||
E##gi = Bgi ^( Bgo |(~Bgu)); \
|
||||
E##go = Bgo ^( Bgu | Bga ); \
|
||||
E##gu = Bgu ^( Bga & Bge ); \
|
||||
\
|
||||
A##be ^= De; \
|
||||
Bka = ROL64(A##be, 1); \
|
||||
A##gi ^= Di; \
|
||||
Bke = ROL64(A##gi, 6); \
|
||||
A##ko ^= Do; \
|
||||
Bki = ROL64(A##ko, 25); \
|
||||
A##mu ^= Du; \
|
||||
Bko = ROL64(A##mu, 8); \
|
||||
A##sa ^= Da; \
|
||||
Bku = ROL64(A##sa, 18); \
|
||||
E##ka = Bka ^( Bke | Bki ); \
|
||||
E##ke = Bke ^( Bki & Bko ); \
|
||||
E##ki = Bki ^((~Bko)& Bku ); \
|
||||
E##ko = (~Bko)^( Bku | Bka ); \
|
||||
E##ku = Bku ^( Bka & Bke ); \
|
||||
\
|
||||
A##bu ^= Du; \
|
||||
Bma = ROL64(A##bu, 27); \
|
||||
A##ga ^= Da; \
|
||||
Bme = ROL64(A##ga, 36); \
|
||||
A##ke ^= De; \
|
||||
Bmi = ROL64(A##ke, 10); \
|
||||
A##mi ^= Di; \
|
||||
Bmo = ROL64(A##mi, 15); \
|
||||
A##so ^= Do; \
|
||||
Bmu = ROL64(A##so, 56); \
|
||||
E##ma = Bma ^( Bme & Bmi ); \
|
||||
E##me = Bme ^( Bmi | Bmo ); \
|
||||
E##mi = Bmi ^((~Bmo)| Bmu ); \
|
||||
E##mo = (~Bmo)^( Bmu & Bma ); \
|
||||
E##mu = Bmu ^( Bma | Bme ); \
|
||||
\
|
||||
A##bi ^= Di; \
|
||||
Bsa = ROL64(A##bi, 62); \
|
||||
A##go ^= Do; \
|
||||
Bse = ROL64(A##go, 55); \
|
||||
A##ku ^= Du; \
|
||||
Bsi = ROL64(A##ku, 39); \
|
||||
A##ma ^= Da; \
|
||||
Bso = ROL64(A##ma, 41); \
|
||||
A##se ^= De; \
|
||||
Bsu = ROL64(A##se, 2); \
|
||||
E##sa = Bsa ^((~Bse)& Bsi ); \
|
||||
E##se = (~Bse)^( Bsi | Bso ); \
|
||||
E##si = Bsi ^( Bso & Bsu ); \
|
||||
E##so = Bso ^( Bsu | Bsa ); \
|
||||
E##su = Bsu ^( Bsa & Bse ); \
|
||||
\
|
||||
|
||||
#else /* UseBebigokimisa */
|
||||
/* --- Code for round, with prepare-theta */
|
||||
/* --- 64-bit lanes mapped to 64-bit words */
|
||||
#define thetaRhoPiChiIotaPrepareTheta(i, A, E) \
|
||||
Da = Cu^ROL64(Ce, 1); \
|
||||
De = Ca^ROL64(Ci, 1); \
|
||||
Di = Ce^ROL64(Co, 1); \
|
||||
Do = Ci^ROL64(Cu, 1); \
|
||||
Du = Co^ROL64(Ca, 1); \
|
||||
\
|
||||
A##ba ^= Da; \
|
||||
Bba = A##ba; \
|
||||
A##ge ^= De; \
|
||||
Bbe = ROL64(A##ge, 44); \
|
||||
A##ki ^= Di; \
|
||||
Bbi = ROL64(A##ki, 43); \
|
||||
A##mo ^= Do; \
|
||||
Bbo = ROL64(A##mo, 21); \
|
||||
A##su ^= Du; \
|
||||
Bbu = ROL64(A##su, 14); \
|
||||
E##ba = Bba ^((~Bbe)& Bbi ); \
|
||||
E##ba ^= KeccakF1600RoundConstants[i]; \
|
||||
Ca = E##ba; \
|
||||
E##be = Bbe ^((~Bbi)& Bbo ); \
|
||||
Ce = E##be; \
|
||||
E##bi = Bbi ^((~Bbo)& Bbu ); \
|
||||
Ci = E##bi; \
|
||||
E##bo = Bbo ^((~Bbu)& Bba ); \
|
||||
Co = E##bo; \
|
||||
E##bu = Bbu ^((~Bba)& Bbe ); \
|
||||
Cu = E##bu; \
|
||||
\
|
||||
A##bo ^= Do; \
|
||||
Bga = ROL64(A##bo, 28); \
|
||||
A##gu ^= Du; \
|
||||
Bge = ROL64(A##gu, 20); \
|
||||
A##ka ^= Da; \
|
||||
Bgi = ROL64(A##ka, 3); \
|
||||
A##me ^= De; \
|
||||
Bgo = ROL64(A##me, 45); \
|
||||
A##si ^= Di; \
|
||||
Bgu = ROL64(A##si, 61); \
|
||||
E##ga = Bga ^((~Bge)& Bgi ); \
|
||||
Ca ^= E##ga; \
|
||||
E##ge = Bge ^((~Bgi)& Bgo ); \
|
||||
Ce ^= E##ge; \
|
||||
E##gi = Bgi ^((~Bgo)& Bgu ); \
|
||||
Ci ^= E##gi; \
|
||||
E##go = Bgo ^((~Bgu)& Bga ); \
|
||||
Co ^= E##go; \
|
||||
E##gu = Bgu ^((~Bga)& Bge ); \
|
||||
Cu ^= E##gu; \
|
||||
\
|
||||
A##be ^= De; \
|
||||
Bka = ROL64(A##be, 1); \
|
||||
A##gi ^= Di; \
|
||||
Bke = ROL64(A##gi, 6); \
|
||||
A##ko ^= Do; \
|
||||
Bki = ROL64(A##ko, 25); \
|
||||
A##mu ^= Du; \
|
||||
Bko = ROL64(A##mu, 8); \
|
||||
A##sa ^= Da; \
|
||||
Bku = ROL64(A##sa, 18); \
|
||||
E##ka = Bka ^((~Bke)& Bki ); \
|
||||
Ca ^= E##ka; \
|
||||
E##ke = Bke ^((~Bki)& Bko ); \
|
||||
Ce ^= E##ke; \
|
||||
E##ki = Bki ^((~Bko)& Bku ); \
|
||||
Ci ^= E##ki; \
|
||||
E##ko = Bko ^((~Bku)& Bka ); \
|
||||
Co ^= E##ko; \
|
||||
E##ku = Bku ^((~Bka)& Bke ); \
|
||||
Cu ^= E##ku; \
|
||||
\
|
||||
A##bu ^= Du; \
|
||||
Bma = ROL64(A##bu, 27); \
|
||||
A##ga ^= Da; \
|
||||
Bme = ROL64(A##ga, 36); \
|
||||
A##ke ^= De; \
|
||||
Bmi = ROL64(A##ke, 10); \
|
||||
A##mi ^= Di; \
|
||||
Bmo = ROL64(A##mi, 15); \
|
||||
A##so ^= Do; \
|
||||
Bmu = ROL64(A##so, 56); \
|
||||
E##ma = Bma ^((~Bme)& Bmi ); \
|
||||
Ca ^= E##ma; \
|
||||
E##me = Bme ^((~Bmi)& Bmo ); \
|
||||
Ce ^= E##me; \
|
||||
E##mi = Bmi ^((~Bmo)& Bmu ); \
|
||||
Ci ^= E##mi; \
|
||||
E##mo = Bmo ^((~Bmu)& Bma ); \
|
||||
Co ^= E##mo; \
|
||||
E##mu = Bmu ^((~Bma)& Bme ); \
|
||||
Cu ^= E##mu; \
|
||||
\
|
||||
A##bi ^= Di; \
|
||||
Bsa = ROL64(A##bi, 62); \
|
||||
A##go ^= Do; \
|
||||
Bse = ROL64(A##go, 55); \
|
||||
A##ku ^= Du; \
|
||||
Bsi = ROL64(A##ku, 39); \
|
||||
A##ma ^= Da; \
|
||||
Bso = ROL64(A##ma, 41); \
|
||||
A##se ^= De; \
|
||||
Bsu = ROL64(A##se, 2); \
|
||||
E##sa = Bsa ^((~Bse)& Bsi ); \
|
||||
Ca ^= E##sa; \
|
||||
E##se = Bse ^((~Bsi)& Bso ); \
|
||||
Ce ^= E##se; \
|
||||
E##si = Bsi ^((~Bso)& Bsu ); \
|
||||
Ci ^= E##si; \
|
||||
E##so = Bso ^((~Bsu)& Bsa ); \
|
||||
Co ^= E##so; \
|
||||
E##su = Bsu ^((~Bsa)& Bse ); \
|
||||
Cu ^= E##su; \
|
||||
\
|
||||
|
||||
/* --- Code for round */
|
||||
/* --- 64-bit lanes mapped to 64-bit words */
|
||||
#define thetaRhoPiChiIota(i, A, E) \
|
||||
Da = Cu^ROL64(Ce, 1); \
|
||||
De = Ca^ROL64(Ci, 1); \
|
||||
Di = Ce^ROL64(Co, 1); \
|
||||
Do = Ci^ROL64(Cu, 1); \
|
||||
Du = Co^ROL64(Ca, 1); \
|
||||
\
|
||||
A##ba ^= Da; \
|
||||
Bba = A##ba; \
|
||||
A##ge ^= De; \
|
||||
Bbe = ROL64(A##ge, 44); \
|
||||
A##ki ^= Di; \
|
||||
Bbi = ROL64(A##ki, 43); \
|
||||
A##mo ^= Do; \
|
||||
Bbo = ROL64(A##mo, 21); \
|
||||
A##su ^= Du; \
|
||||
Bbu = ROL64(A##su, 14); \
|
||||
E##ba = Bba ^((~Bbe)& Bbi ); \
|
||||
E##ba ^= KeccakF1600RoundConstants[i]; \
|
||||
E##be = Bbe ^((~Bbi)& Bbo ); \
|
||||
E##bi = Bbi ^((~Bbo)& Bbu ); \
|
||||
E##bo = Bbo ^((~Bbu)& Bba ); \
|
||||
E##bu = Bbu ^((~Bba)& Bbe ); \
|
||||
\
|
||||
A##bo ^= Do; \
|
||||
Bga = ROL64(A##bo, 28); \
|
||||
A##gu ^= Du; \
|
||||
Bge = ROL64(A##gu, 20); \
|
||||
A##ka ^= Da; \
|
||||
Bgi = ROL64(A##ka, 3); \
|
||||
A##me ^= De; \
|
||||
Bgo = ROL64(A##me, 45); \
|
||||
A##si ^= Di; \
|
||||
Bgu = ROL64(A##si, 61); \
|
||||
E##ga = Bga ^((~Bge)& Bgi ); \
|
||||
E##ge = Bge ^((~Bgi)& Bgo ); \
|
||||
E##gi = Bgi ^((~Bgo)& Bgu ); \
|
||||
E##go = Bgo ^((~Bgu)& Bga ); \
|
||||
E##gu = Bgu ^((~Bga)& Bge ); \
|
||||
\
|
||||
A##be ^= De; \
|
||||
Bka = ROL64(A##be, 1); \
|
||||
A##gi ^= Di; \
|
||||
Bke = ROL64(A##gi, 6); \
|
||||
A##ko ^= Do; \
|
||||
Bki = ROL64(A##ko, 25); \
|
||||
A##mu ^= Du; \
|
||||
Bko = ROL64(A##mu, 8); \
|
||||
A##sa ^= Da; \
|
||||
Bku = ROL64(A##sa, 18); \
|
||||
E##ka = Bka ^((~Bke)& Bki ); \
|
||||
E##ke = Bke ^((~Bki)& Bko ); \
|
||||
E##ki = Bki ^((~Bko)& Bku ); \
|
||||
E##ko = Bko ^((~Bku)& Bka ); \
|
||||
E##ku = Bku ^((~Bka)& Bke ); \
|
||||
\
|
||||
A##bu ^= Du; \
|
||||
Bma = ROL64(A##bu, 27); \
|
||||
A##ga ^= Da; \
|
||||
Bme = ROL64(A##ga, 36); \
|
||||
A##ke ^= De; \
|
||||
Bmi = ROL64(A##ke, 10); \
|
||||
A##mi ^= Di; \
|
||||
Bmo = ROL64(A##mi, 15); \
|
||||
A##so ^= Do; \
|
||||
Bmu = ROL64(A##so, 56); \
|
||||
E##ma = Bma ^((~Bme)& Bmi ); \
|
||||
E##me = Bme ^((~Bmi)& Bmo ); \
|
||||
E##mi = Bmi ^((~Bmo)& Bmu ); \
|
||||
E##mo = Bmo ^((~Bmu)& Bma ); \
|
||||
E##mu = Bmu ^((~Bma)& Bme ); \
|
||||
\
|
||||
A##bi ^= Di; \
|
||||
Bsa = ROL64(A##bi, 62); \
|
||||
A##go ^= Do; \
|
||||
Bse = ROL64(A##go, 55); \
|
||||
A##ku ^= Du; \
|
||||
Bsi = ROL64(A##ku, 39); \
|
||||
A##ma ^= Da; \
|
||||
Bso = ROL64(A##ma, 41); \
|
||||
A##se ^= De; \
|
||||
Bsu = ROL64(A##se, 2); \
|
||||
E##sa = Bsa ^((~Bse)& Bsi ); \
|
||||
E##se = Bse ^((~Bsi)& Bso ); \
|
||||
E##si = Bsi ^((~Bso)& Bsu ); \
|
||||
E##so = Bso ^((~Bsu)& Bsa ); \
|
||||
E##su = Bsu ^((~Bsa)& Bse ); \
|
||||
\
|
||||
|
||||
#endif /* UseBebigokimisa */
|
||||
|
||||
#define copyFromState(X, state) \
|
||||
X##ba = state[ 0]; \
|
||||
X##be = state[ 1]; \
|
||||
X##bi = state[ 2]; \
|
||||
X##bo = state[ 3]; \
|
||||
X##bu = state[ 4]; \
|
||||
X##ga = state[ 5]; \
|
||||
X##ge = state[ 6]; \
|
||||
X##gi = state[ 7]; \
|
||||
X##go = state[ 8]; \
|
||||
X##gu = state[ 9]; \
|
||||
X##ka = state[10]; \
|
||||
X##ke = state[11]; \
|
||||
X##ki = state[12]; \
|
||||
X##ko = state[13]; \
|
||||
X##ku = state[14]; \
|
||||
X##ma = state[15]; \
|
||||
X##me = state[16]; \
|
||||
X##mi = state[17]; \
|
||||
X##mo = state[18]; \
|
||||
X##mu = state[19]; \
|
||||
X##sa = state[20]; \
|
||||
X##se = state[21]; \
|
||||
X##si = state[22]; \
|
||||
X##so = state[23]; \
|
||||
X##su = state[24]; \
|
||||
|
||||
#define copyToState(state, X) \
|
||||
state[ 0] = X##ba; \
|
||||
state[ 1] = X##be; \
|
||||
state[ 2] = X##bi; \
|
||||
state[ 3] = X##bo; \
|
||||
state[ 4] = X##bu; \
|
||||
state[ 5] = X##ga; \
|
||||
state[ 6] = X##ge; \
|
||||
state[ 7] = X##gi; \
|
||||
state[ 8] = X##go; \
|
||||
state[ 9] = X##gu; \
|
||||
state[10] = X##ka; \
|
||||
state[11] = X##ke; \
|
||||
state[12] = X##ki; \
|
||||
state[13] = X##ko; \
|
||||
state[14] = X##ku; \
|
||||
state[15] = X##ma; \
|
||||
state[16] = X##me; \
|
||||
state[17] = X##mi; \
|
||||
state[18] = X##mo; \
|
||||
state[19] = X##mu; \
|
||||
state[20] = X##sa; \
|
||||
state[21] = X##se; \
|
||||
state[22] = X##si; \
|
||||
state[23] = X##so; \
|
||||
state[24] = X##su; \
|
||||
|
||||
#define copyStateVariables(X, Y) \
|
||||
X##ba = Y##ba; \
|
||||
X##be = Y##be; \
|
||||
X##bi = Y##bi; \
|
||||
X##bo = Y##bo; \
|
||||
X##bu = Y##bu; \
|
||||
X##ga = Y##ga; \
|
||||
X##ge = Y##ge; \
|
||||
X##gi = Y##gi; \
|
||||
X##go = Y##go; \
|
||||
X##gu = Y##gu; \
|
||||
X##ka = Y##ka; \
|
||||
X##ke = Y##ke; \
|
||||
X##ki = Y##ki; \
|
||||
X##ko = Y##ko; \
|
||||
X##ku = Y##ku; \
|
||||
X##ma = Y##ma; \
|
||||
X##me = Y##me; \
|
||||
X##mi = Y##mi; \
|
||||
X##mo = Y##mo; \
|
||||
X##mu = Y##mu; \
|
||||
X##sa = Y##sa; \
|
||||
X##se = Y##se; \
|
||||
X##si = Y##si; \
|
||||
X##so = Y##so; \
|
||||
X##su = Y##su; \
|
||||
|
||||
#if (PLATFORM_BYTE_ORDER == IS_LITTLE_ENDIAN)
|
||||
#define HTOLE64(x) (x)
|
||||
#else
|
||||
/*
|
||||
* Big Endian platforms macro to swap data.
|
||||
*
|
||||
* NOTE: we cannot directly use the 64-bit input
|
||||
* of the following macro because of possible alignment
|
||||
* constraints (on some platforms such as Sparc or MIPS,
|
||||
* dereferencing an uint64_t on a buffer not aligned on the
|
||||
* word size will induce a 'bus error'). Instead, we read and
|
||||
* swap the data byte per byte.
|
||||
*/
|
||||
#define HTOLE64(x) \
|
||||
( ((uint64_t) (((uint8_t*)&(x))[ 7]) << 56 ) \
|
||||
| ((uint64_t) (((uint8_t*)&(x))[ 6]) << 48 ) \
|
||||
| ((uint64_t) (((uint8_t*)&(x))[ 5]) << 40 ) \
|
||||
| ((uint64_t) (((uint8_t*)&(x))[ 4]) << 32 ) \
|
||||
| ((uint64_t) (((uint8_t*)&(x))[ 3]) << 24 ) \
|
||||
| ((uint64_t) (((uint8_t*)&(x))[ 2]) << 16 ) \
|
||||
| ((uint64_t) (((uint8_t*)&(x))[ 1]) << 8 ) \
|
||||
| ((uint64_t) (((uint8_t*)&(x))[ 0])))
|
||||
#endif
|
||||
|
||||
#define addInput(X, input, laneCount) \
|
||||
if (laneCount == 21) { \
|
||||
X##ba ^= HTOLE64(input[ 0]); \
|
||||
X##be ^= HTOLE64(input[ 1]); \
|
||||
X##bi ^= HTOLE64(input[ 2]); \
|
||||
X##bo ^= HTOLE64(input[ 3]); \
|
||||
X##bu ^= HTOLE64(input[ 4]); \
|
||||
X##ga ^= HTOLE64(input[ 5]); \
|
||||
X##ge ^= HTOLE64(input[ 6]); \
|
||||
X##gi ^= HTOLE64(input[ 7]); \
|
||||
X##go ^= HTOLE64(input[ 8]); \
|
||||
X##gu ^= HTOLE64(input[ 9]); \
|
||||
X##ka ^= HTOLE64(input[10]); \
|
||||
X##ke ^= HTOLE64(input[11]); \
|
||||
X##ki ^= HTOLE64(input[12]); \
|
||||
X##ko ^= HTOLE64(input[13]); \
|
||||
X##ku ^= HTOLE64(input[14]); \
|
||||
X##ma ^= HTOLE64(input[15]); \
|
||||
X##me ^= HTOLE64(input[16]); \
|
||||
X##mi ^= HTOLE64(input[17]); \
|
||||
X##mo ^= HTOLE64(input[18]); \
|
||||
X##mu ^= HTOLE64(input[19]); \
|
||||
X##sa ^= HTOLE64(input[20]); \
|
||||
} \
|
||||
else if (laneCount < 16) { \
|
||||
if (laneCount < 8) { \
|
||||
if (laneCount < 4) { \
|
||||
if (laneCount < 2) { \
|
||||
if (laneCount < 1) { \
|
||||
} \
|
||||
else { \
|
||||
X##ba ^= HTOLE64(input[ 0]); \
|
||||
} \
|
||||
} \
|
||||
else { \
|
||||
X##ba ^= HTOLE64(input[ 0]); \
|
||||
X##be ^= HTOLE64(input[ 1]); \
|
||||
if (laneCount < 3) { \
|
||||
} \
|
||||
else { \
|
||||
X##bi ^= HTOLE64(input[ 2]); \
|
||||
} \
|
||||
} \
|
||||
} \
|
||||
else { \
|
||||
X##ba ^= HTOLE64(input[ 0]); \
|
||||
X##be ^= HTOLE64(input[ 1]); \
|
||||
X##bi ^= HTOLE64(input[ 2]); \
|
||||
X##bo ^= HTOLE64(input[ 3]); \
|
||||
if (laneCount < 6) { \
|
||||
if (laneCount < 5) { \
|
||||
} \
|
||||
else { \
|
||||
X##bu ^= HTOLE64(input[ 4]); \
|
||||
} \
|
||||
} \
|
||||
else { \
|
||||
X##bu ^= HTOLE64(input[ 4]); \
|
||||
X##ga ^= HTOLE64(input[ 5]); \
|
||||
if (laneCount < 7) { \
|
||||
} \
|
||||
else { \
|
||||
X##ge ^= HTOLE64(input[ 6]); \
|
||||
} \
|
||||
} \
|
||||
} \
|
||||
} \
|
||||
else { \
|
||||
X##ba ^= HTOLE64(input[ 0]); \
|
||||
X##be ^= HTOLE64(input[ 1]); \
|
||||
X##bi ^= HTOLE64(input[ 2]); \
|
||||
X##bo ^= HTOLE64(input[ 3]); \
|
||||
X##bu ^= HTOLE64(input[ 4]); \
|
||||
X##ga ^= HTOLE64(input[ 5]); \
|
||||
X##ge ^= HTOLE64(input[ 6]); \
|
||||
X##gi ^= HTOLE64(input[ 7]); \
|
||||
if (laneCount < 12) { \
|
||||
if (laneCount < 10) { \
|
||||
if (laneCount < 9) { \
|
||||
} \
|
||||
else { \
|
||||
X##go ^= HTOLE64(input[ 8]); \
|
||||
} \
|
||||
} \
|
||||
else { \
|
||||
X##go ^= HTOLE64(input[ 8]); \
|
||||
X##gu ^= HTOLE64(input[ 9]); \
|
||||
if (laneCount < 11) { \
|
||||
} \
|
||||
else { \
|
||||
X##ka ^= HTOLE64(input[10]); \
|
||||
} \
|
||||
} \
|
||||
} \
|
||||
else { \
|
||||
X##go ^= HTOLE64(input[ 8]); \
|
||||
X##gu ^= HTOLE64(input[ 9]); \
|
||||
X##ka ^= HTOLE64(input[10]); \
|
||||
X##ke ^= HTOLE64(input[11]); \
|
||||
if (laneCount < 14) { \
|
||||
if (laneCount < 13) { \
|
||||
} \
|
||||
else { \
|
||||
X##ki ^= HTOLE64(input[12]); \
|
||||
} \
|
||||
} \
|
||||
else { \
|
||||
X##ki ^= HTOLE64(input[12]); \
|
||||
X##ko ^= HTOLE64(input[13]); \
|
||||
if (laneCount < 15) { \
|
||||
} \
|
||||
else { \
|
||||
X##ku ^= HTOLE64(input[14]); \
|
||||
} \
|
||||
} \
|
||||
} \
|
||||
} \
|
||||
} \
|
||||
else { \
|
||||
X##ba ^= HTOLE64(input[ 0]); \
|
||||
X##be ^= HTOLE64(input[ 1]); \
|
||||
X##bi ^= HTOLE64(input[ 2]); \
|
||||
X##bo ^= HTOLE64(input[ 3]); \
|
||||
X##bu ^= HTOLE64(input[ 4]); \
|
||||
X##ga ^= HTOLE64(input[ 5]); \
|
||||
X##ge ^= HTOLE64(input[ 6]); \
|
||||
X##gi ^= HTOLE64(input[ 7]); \
|
||||
X##go ^= HTOLE64(input[ 8]); \
|
||||
X##gu ^= HTOLE64(input[ 9]); \
|
||||
X##ka ^= HTOLE64(input[10]); \
|
||||
X##ke ^= HTOLE64(input[11]); \
|
||||
X##ki ^= HTOLE64(input[12]); \
|
||||
X##ko ^= HTOLE64(input[13]); \
|
||||
X##ku ^= HTOLE64(input[14]); \
|
||||
X##ma ^= HTOLE64(input[15]); \
|
||||
if (laneCount < 24) { \
|
||||
if (laneCount < 20) { \
|
||||
if (laneCount < 18) { \
|
||||
if (laneCount < 17) { \
|
||||
} \
|
||||
else { \
|
||||
X##me ^= HTOLE64(input[16]); \
|
||||
} \
|
||||
} \
|
||||
else { \
|
||||
X##me ^= HTOLE64(input[16]); \
|
||||
X##mi ^= HTOLE64(input[17]); \
|
||||
if (laneCount < 19) { \
|
||||
} \
|
||||
else { \
|
||||
X##mo ^= HTOLE64(input[18]); \
|
||||
} \
|
||||
} \
|
||||
} \
|
||||
else { \
|
||||
X##me ^= HTOLE64(input[16]); \
|
||||
X##mi ^= HTOLE64(input[17]); \
|
||||
X##mo ^= HTOLE64(input[18]); \
|
||||
X##mu ^= HTOLE64(input[19]); \
|
||||
if (laneCount < 22) { \
|
||||
if (laneCount < 21) { \
|
||||
} \
|
||||
else { \
|
||||
X##sa ^= HTOLE64(input[20]); \
|
||||
} \
|
||||
} \
|
||||
else { \
|
||||
X##sa ^= HTOLE64(input[20]); \
|
||||
X##se ^= HTOLE64(input[21]); \
|
||||
if (laneCount < 23) { \
|
||||
} \
|
||||
else { \
|
||||
X##si ^= HTOLE64(input[22]); \
|
||||
} \
|
||||
} \
|
||||
} \
|
||||
} \
|
||||
else { \
|
||||
X##me ^= HTOLE64(input[16]); \
|
||||
X##mi ^= HTOLE64(input[17]); \
|
||||
X##mo ^= HTOLE64(input[18]); \
|
||||
X##mu ^= HTOLE64(input[19]); \
|
||||
X##sa ^= HTOLE64(input[20]); \
|
||||
X##se ^= HTOLE64(input[21]); \
|
||||
X##si ^= HTOLE64(input[22]); \
|
||||
X##so ^= HTOLE64(input[23]); \
|
||||
if (laneCount < 25) { \
|
||||
} \
|
||||
else { \
|
||||
X##su ^= HTOLE64(input[24]); \
|
||||
} \
|
||||
} \
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
The eXtended Keccak Code Package (XKCP)
|
||||
https://github.com/XKCP/XKCP
|
||||
|
||||
The Keccak-p permutations, designed by Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche.
|
||||
|
||||
Implementation by Gilles Van Assche and Ronny Van Keer, hereby denoted as "the implementer".
|
||||
|
||||
For more information, feedback or questions, please refer to the Keccak Team website:
|
||||
https://keccak.team/
|
||||
|
||||
To the extent possible under law, the implementer has waived all copyright
|
||||
and related or neighboring rights to the source code in this file.
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
|
||||
---
|
||||
|
||||
Please refer to SnP-documentation.h for more details.
|
||||
*/
|
||||
|
||||
#ifndef _KeccakP_1600_SnP_h_
|
||||
#define _KeccakP_1600_SnP_h_
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "brg_endian.h"
|
||||
#include "KeccakP-1600-opt64-config.h"
|
||||
|
||||
typedef struct {
|
||||
uint64_t A[25];
|
||||
} KeccakP1600_plain64_state;
|
||||
|
||||
typedef KeccakP1600_plain64_state KeccakP1600_state;
|
||||
|
||||
#define KeccakP1600_implementation "generic 64-bit optimized implementation (" KeccakP1600_implementation_config ")"
|
||||
#define KeccakF1600_FastLoop_supported
|
||||
#define KeccakP1600_12rounds_FastLoop_supported
|
||||
|
||||
#define KeccakP1600_StaticInitialize()
|
||||
void KeccakP1600_Initialize(KeccakP1600_plain64_state *state);
|
||||
#if (PLATFORM_BYTE_ORDER == IS_LITTLE_ENDIAN)
|
||||
#define KeccakP1600_AddByte(state, byte, offset) \
|
||||
((unsigned char*)(state))[(offset)] ^= (byte)
|
||||
#else
|
||||
void KeccakP1600_AddByte(KeccakP1600_plain64_state *state, unsigned char data, unsigned int offset);
|
||||
#endif
|
||||
void KeccakP1600_AddBytes(KeccakP1600_plain64_state *state, const unsigned char *data, unsigned int offset, unsigned int length);
|
||||
void KeccakP1600_OverwriteBytes(KeccakP1600_plain64_state *state, const unsigned char *data, unsigned int offset, unsigned int length);
|
||||
void KeccakP1600_OverwriteWithZeroes(KeccakP1600_plain64_state *state, unsigned int byteCount);
|
||||
void KeccakP1600_Permute_Nrounds(KeccakP1600_plain64_state *state, unsigned int nrounds);
|
||||
void KeccakP1600_Permute_12rounds(KeccakP1600_plain64_state *state);
|
||||
void KeccakP1600_Permute_24rounds(KeccakP1600_plain64_state *state);
|
||||
void KeccakP1600_ExtractBytes(const KeccakP1600_plain64_state *state, unsigned char *data, unsigned int offset, unsigned int length);
|
||||
void KeccakP1600_ExtractAndAddBytes(const KeccakP1600_plain64_state *state, const unsigned char *input, unsigned char *output, unsigned int offset, unsigned int length);
|
||||
size_t KeccakF1600_FastLoop_Absorb(KeccakP1600_plain64_state *state, unsigned int laneCount, const unsigned char *data, size_t dataByteLen);
|
||||
size_t KeccakP1600_12rounds_FastLoop_Absorb(KeccakP1600_plain64_state *state, unsigned int laneCount, const unsigned char *data, size_t dataByteLen);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,6 @@
|
||||
/*
|
||||
This file defines some parameters of the implementation in the parent directory.
|
||||
*/
|
||||
|
||||
#define KeccakP1600_implementation_config "all rounds unrolled"
|
||||
#define KeccakP1600_fullUnrolling
|
||||
@@ -0,0 +1,565 @@
|
||||
/*
|
||||
The eXtended Keccak Code Package (XKCP)
|
||||
https://github.com/XKCP/XKCP
|
||||
|
||||
The Keccak-p permutations, designed by Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche.
|
||||
|
||||
Implementation by Gilles Van Assche and Ronny Van Keer, hereby denoted as "the implementer".
|
||||
|
||||
For more information, feedback or questions, please refer to the Keccak Team website:
|
||||
https://keccak.team/
|
||||
|
||||
To the extent possible under law, the implementer has waived all copyright
|
||||
and related or neighboring rights to the source code in this file.
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
|
||||
---
|
||||
|
||||
This file implements Keccak-p[1600] in a SnP-compatible way.
|
||||
Please refer to SnP-documentation.h for more details.
|
||||
|
||||
This implementation comes with KeccakP-1600-SnP.h in the same folder.
|
||||
Please refer to LowLevel.build for the exact list of other files it must be combined with.
|
||||
*/
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include "brg_endian.h"
|
||||
#include "KeccakP-1600-SnP.h"
|
||||
|
||||
#if defined(KeccakP1600_useLaneComplementing)
|
||||
#define UseBebigokimisa
|
||||
#endif
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
#define ROL64(a, offset) _rotl64(a, offset)
|
||||
#elif defined(KeccakP1600_useSHLD)
|
||||
#define ROL64(x,N) ({ \
|
||||
register uint64_t __out; \
|
||||
register uint64_t __in = x; \
|
||||
__asm__ ("shld %2,%0,%0" : "=r"(__out) : "0"(__in), "i"(N)); \
|
||||
__out; \
|
||||
})
|
||||
#else
|
||||
#define ROL64(a, offset) ((((uint64_t)a) << offset) ^ (((uint64_t)a) >> (64-offset)))
|
||||
#endif
|
||||
|
||||
#include "KeccakP-1600-64.macros"
|
||||
#ifdef KeccakP1600_fullUnrolling
|
||||
#define FullUnrolling
|
||||
#else
|
||||
#define Unrolling KeccakP1600_unrolling
|
||||
#endif
|
||||
#include "KeccakP-1600-unrolling.macros"
|
||||
#include "SnP-Relaned.h"
|
||||
|
||||
static const uint64_t KeccakF1600RoundConstants[24] = {
|
||||
0x0000000000000001ULL,
|
||||
0x0000000000008082ULL,
|
||||
0x800000000000808aULL,
|
||||
0x8000000080008000ULL,
|
||||
0x000000000000808bULL,
|
||||
0x0000000080000001ULL,
|
||||
0x8000000080008081ULL,
|
||||
0x8000000000008009ULL,
|
||||
0x000000000000008aULL,
|
||||
0x0000000000000088ULL,
|
||||
0x0000000080008009ULL,
|
||||
0x000000008000000aULL,
|
||||
0x000000008000808bULL,
|
||||
0x800000000000008bULL,
|
||||
0x8000000000008089ULL,
|
||||
0x8000000000008003ULL,
|
||||
0x8000000000008002ULL,
|
||||
0x8000000000000080ULL,
|
||||
0x000000000000800aULL,
|
||||
0x800000008000000aULL,
|
||||
0x8000000080008081ULL,
|
||||
0x8000000000008080ULL,
|
||||
0x0000000080000001ULL,
|
||||
0x8000000080008008ULL };
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
void KeccakP1600_Initialize(KeccakP1600_plain64_state *state)
|
||||
{
|
||||
memset(state, 0, 200);
|
||||
#ifdef KeccakP1600_useLaneComplementing
|
||||
state->A[ 1] = ~(uint64_t)0;
|
||||
state->A[ 2] = ~(uint64_t)0;
|
||||
state->A[ 8] = ~(uint64_t)0;
|
||||
state->A[12] = ~(uint64_t)0;
|
||||
state->A[17] = ~(uint64_t)0;
|
||||
state->A[20] = ~(uint64_t)0;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
void KeccakP1600_AddBytesInLane(KeccakP1600_plain64_state *state, unsigned int lanePosition, const unsigned char *data, unsigned int offset, unsigned int length)
|
||||
{
|
||||
#if (PLATFORM_BYTE_ORDER == IS_LITTLE_ENDIAN)
|
||||
uint64_t lane;
|
||||
if (length == 0)
|
||||
return;
|
||||
if (length == 1)
|
||||
lane = data[0];
|
||||
else {
|
||||
lane = 0;
|
||||
memcpy(&lane, data, length);
|
||||
}
|
||||
lane <<= offset*8;
|
||||
#else
|
||||
uint64_t lane = 0;
|
||||
unsigned int i;
|
||||
for(i=0; i<length; i++)
|
||||
lane |= ((uint64_t)data[i]) << ((i+offset)*8);
|
||||
#endif
|
||||
state->A[lanePosition] ^= lane;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
void KeccakP1600_AddLanes(KeccakP1600_plain64_state *state, const unsigned char *data, unsigned int laneCount)
|
||||
{
|
||||
#if (PLATFORM_BYTE_ORDER == IS_LITTLE_ENDIAN)
|
||||
unsigned int i = 0;
|
||||
#ifdef NO_MISALIGNED_ACCESSES
|
||||
/* If either pointer is misaligned, fall back to byte-wise xor. */
|
||||
if (((((uintptr_t)state) & 7) != 0) || ((((uintptr_t)data) & 7) != 0)) {
|
||||
for (i = 0; i < laneCount * 8; i++) {
|
||||
((unsigned char*)state)[i] ^= data[i];
|
||||
}
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
/* Otherwise... */
|
||||
for( ; (i+8)<=laneCount; i+=8) {
|
||||
state->A[i+0] ^= ((uint64_t*)data)[i+0];
|
||||
state->A[i+1] ^= ((uint64_t*)data)[i+1];
|
||||
state->A[i+2] ^= ((uint64_t*)data)[i+2];
|
||||
state->A[i+3] ^= ((uint64_t*)data)[i+3];
|
||||
state->A[i+4] ^= ((uint64_t*)data)[i+4];
|
||||
state->A[i+5] ^= ((uint64_t*)data)[i+5];
|
||||
state->A[i+6] ^= ((uint64_t*)data)[i+6];
|
||||
state->A[i+7] ^= ((uint64_t*)data)[i+7];
|
||||
}
|
||||
for( ; (i+4)<=laneCount; i+=4) {
|
||||
state->A[i+0] ^= ((uint64_t*)data)[i+0];
|
||||
state->A[i+1] ^= ((uint64_t*)data)[i+1];
|
||||
state->A[i+2] ^= ((uint64_t*)data)[i+2];
|
||||
state->A[i+3] ^= ((uint64_t*)data)[i+3];
|
||||
}
|
||||
for( ; (i+2)<=laneCount; i+=2) {
|
||||
state->A[i+0] ^= ((uint64_t*)data)[i+0];
|
||||
state->A[i+1] ^= ((uint64_t*)data)[i+1];
|
||||
}
|
||||
if (i<laneCount) {
|
||||
state->A[i+0] ^= ((uint64_t*)data)[i+0];
|
||||
}
|
||||
}
|
||||
#else
|
||||
unsigned int i;
|
||||
const uint8_t *curData = data;
|
||||
for(i=0; i<laneCount; i++, curData+=8) {
|
||||
uint64_t lane = (uint64_t)curData[0]
|
||||
| ((uint64_t)curData[1] << 8)
|
||||
| ((uint64_t)curData[2] << 16)
|
||||
| ((uint64_t)curData[3] << 24)
|
||||
| ((uint64_t)curData[4] << 32)
|
||||
| ((uint64_t)curData[5] << 40)
|
||||
| ((uint64_t)curData[6] << 48)
|
||||
| ((uint64_t)curData[7] << 56);
|
||||
state->A[i] ^= lane;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
#if (PLATFORM_BYTE_ORDER != IS_LITTLE_ENDIAN)
|
||||
void KeccakP1600_AddByte(KeccakP1600_plain64_state *state, unsigned char byte, unsigned int offset)
|
||||
{
|
||||
uint64_t lane = byte;
|
||||
lane <<= (offset%8)*8;
|
||||
state->A[offset/8] ^= lane;
|
||||
}
|
||||
#endif
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
void KeccakP1600_AddBytes(KeccakP1600_plain64_state *state, const unsigned char *data, unsigned int offset, unsigned int length)
|
||||
{
|
||||
SnP_AddBytes(state, data, offset, length, KeccakP1600_AddLanes, KeccakP1600_AddBytesInLane, 8);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
void KeccakP1600_OverwriteBytesInLane(KeccakP1600_plain64_state *state, unsigned int lanePosition, const unsigned char *data, unsigned int offset, unsigned int length)
|
||||
{
|
||||
#if (PLATFORM_BYTE_ORDER == IS_LITTLE_ENDIAN)
|
||||
#ifdef KeccakP1600_useLaneComplementing
|
||||
if ((lanePosition == 1) || (lanePosition == 2) || (lanePosition == 8) || (lanePosition == 12) || (lanePosition == 17) || (lanePosition == 20)) {
|
||||
unsigned int i;
|
||||
for(i=0; i<length; i++)
|
||||
((unsigned char*)state)[lanePosition*8+offset+i] = ~data[i];
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
memcpy((unsigned char*)state+lanePosition*8+offset, data, length);
|
||||
}
|
||||
#else
|
||||
uint64_t lane = state->A[lanePosition];
|
||||
unsigned int i;
|
||||
for(i=0; i<length; i++) {
|
||||
lane &= ~((uint64_t)0xFF << ((offset+i)*8));
|
||||
#ifdef KeccakP1600_useLaneComplementing
|
||||
if ((lanePosition == 1) || (lanePosition == 2) || (lanePosition == 8) || (lanePosition == 12) || (lanePosition == 17) || (lanePosition == 20))
|
||||
lane |= (uint64_t)(data[i] ^ 0xFF) << ((offset+i)*8);
|
||||
else
|
||||
#endif
|
||||
lane |= (uint64_t)data[i] << ((offset+i)*8);
|
||||
}
|
||||
state->A[lanePosition] = lane;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
void KeccakP1600_OverwriteLanes(KeccakP1600_plain64_state *state, const unsigned char *data, unsigned int laneCount)
|
||||
{
|
||||
#if (PLATFORM_BYTE_ORDER == IS_LITTLE_ENDIAN)
|
||||
#ifdef KeccakP1600_useLaneComplementing
|
||||
unsigned int lanePosition;
|
||||
|
||||
for(lanePosition=0; lanePosition<laneCount; lanePosition++)
|
||||
if ((lanePosition == 1) || (lanePosition == 2) || (lanePosition == 8) || (lanePosition == 12) || (lanePosition == 17) || (lanePosition == 20))
|
||||
state->A[lanePosition] = ~((const uint64_t*)data)[lanePosition];
|
||||
else
|
||||
state->A[lanePosition] = ((const uint64_t*)data)[lanePosition];
|
||||
#else
|
||||
memcpy(state, data, laneCount*8);
|
||||
#endif
|
||||
#else
|
||||
unsigned int lanePosition;
|
||||
const uint8_t *curData = data;
|
||||
for(lanePosition=0; lanePosition<laneCount; lanePosition++, curData+=8) {
|
||||
uint64_t lane = (uint64_t)curData[0]
|
||||
| ((uint64_t)curData[1] << 8)
|
||||
| ((uint64_t)curData[2] << 16)
|
||||
| ((uint64_t)curData[3] << 24)
|
||||
| ((uint64_t)curData[4] << 32)
|
||||
| ((uint64_t)curData[5] << 40)
|
||||
| ((uint64_t)curData[6] << 48)
|
||||
| ((uint64_t)curData[7] << 56);
|
||||
#ifdef KeccakP1600_useLaneComplementing
|
||||
if ((lanePosition == 1) || (lanePosition == 2) || (lanePosition == 8) || (lanePosition == 12) || (lanePosition == 17) || (lanePosition == 20))
|
||||
state->A[lanePosition] = ~lane;
|
||||
else
|
||||
#endif
|
||||
state->A[lanePosition] = lane;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
void KeccakP1600_OverwriteBytes(KeccakP1600_plain64_state *state, const unsigned char *data, unsigned int offset, unsigned int length)
|
||||
{
|
||||
SnP_OverwriteBytes(state, data, offset, length, KeccakP1600_OverwriteLanes, KeccakP1600_OverwriteBytesInLane, 8);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
void KeccakP1600_OverwriteWithZeroes(KeccakP1600_plain64_state *state, unsigned int byteCount)
|
||||
{
|
||||
#if (PLATFORM_BYTE_ORDER == IS_LITTLE_ENDIAN)
|
||||
#ifdef KeccakP1600_useLaneComplementing
|
||||
unsigned int lanePosition;
|
||||
|
||||
for(lanePosition=0; lanePosition<byteCount/8; lanePosition++)
|
||||
if ((lanePosition == 1) || (lanePosition == 2) || (lanePosition == 8) || (lanePosition == 12) || (lanePosition == 17) || (lanePosition == 20))
|
||||
state->A[lanePosition] = ~0;
|
||||
else
|
||||
state->A[lanePosition] = 0;
|
||||
if (byteCount%8 != 0) {
|
||||
lanePosition = byteCount/8;
|
||||
if ((lanePosition == 1) || (lanePosition == 2) || (lanePosition == 8) || (lanePosition == 12) || (lanePosition == 17) || (lanePosition == 20))
|
||||
memset((unsigned char*)state+lanePosition*8, 0xFF, byteCount%8);
|
||||
else
|
||||
memset((unsigned char*)state+lanePosition*8, 0, byteCount%8);
|
||||
}
|
||||
#else
|
||||
memset(state, 0, byteCount);
|
||||
#endif
|
||||
#else
|
||||
unsigned int i, j;
|
||||
for(i=0; i<byteCount; i+=8) {
|
||||
unsigned int lanePosition = i/8;
|
||||
if (i+8 <= byteCount) {
|
||||
#ifdef KeccakP1600_useLaneComplementing
|
||||
if ((lanePosition == 1) || (lanePosition == 2) || (lanePosition == 8) || (lanePosition == 12) || (lanePosition == 17) || (lanePosition == 20))
|
||||
state->A[lanePosition] = ~(uint64_t)0;
|
||||
else
|
||||
#endif
|
||||
state->A[lanePosition] = 0;
|
||||
}
|
||||
else {
|
||||
uint64_t lane = state->A[lanePosition];
|
||||
for(j=0; j<byteCount%8; j++) {
|
||||
#ifdef KeccakP1600_useLaneComplementing
|
||||
if ((lanePosition == 1) || (lanePosition == 2) || (lanePosition == 8) || (lanePosition == 12) || (lanePosition == 17) || (lanePosition == 20))
|
||||
lane |= (uint64_t)0xFF << (j*8);
|
||||
else
|
||||
#endif
|
||||
lane &= ~((uint64_t)0xFF << (j*8));
|
||||
}
|
||||
state->A[lanePosition] = lane;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
void KeccakP1600_Permute_Nrounds(KeccakP1600_plain64_state *state, unsigned int nr)
|
||||
{
|
||||
declareABCDE
|
||||
unsigned int i;
|
||||
uint64_t *stateAsLanes = state->A;
|
||||
|
||||
copyFromState(A, stateAsLanes)
|
||||
roundsN(nr)
|
||||
copyToState(stateAsLanes, A)
|
||||
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
void KeccakP1600_Permute_24rounds(KeccakP1600_plain64_state *state)
|
||||
{
|
||||
declareABCDE
|
||||
#ifndef KeccakP1600_fullUnrolling
|
||||
unsigned int i;
|
||||
#endif
|
||||
uint64_t *stateAsLanes = state->A;
|
||||
|
||||
copyFromState(A, stateAsLanes)
|
||||
rounds24
|
||||
copyToState(stateAsLanes, A)
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
void KeccakP1600_Permute_12rounds(KeccakP1600_plain64_state *state)
|
||||
{
|
||||
declareABCDE
|
||||
#ifndef KeccakP1600_fullUnrolling
|
||||
unsigned int i;
|
||||
#endif
|
||||
uint64_t *stateAsLanes = state->A;
|
||||
|
||||
copyFromState(A, stateAsLanes)
|
||||
rounds12
|
||||
copyToState(stateAsLanes, A)
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
void KeccakP1600_ExtractBytesInLane(const KeccakP1600_plain64_state *state, unsigned int lanePosition, unsigned char *data, unsigned int offset, unsigned int length)
|
||||
{
|
||||
uint64_t lane = state->A[lanePosition];
|
||||
#ifdef KeccakP1600_useLaneComplementing
|
||||
if ((lanePosition == 1) || (lanePosition == 2) || (lanePosition == 8) || (lanePosition == 12) || (lanePosition == 17) || (lanePosition == 20))
|
||||
lane = ~lane;
|
||||
#endif
|
||||
#if (PLATFORM_BYTE_ORDER == IS_LITTLE_ENDIAN)
|
||||
{
|
||||
uint64_t lane1[1];
|
||||
lane1[0] = lane;
|
||||
memcpy(data, (uint8_t*)lane1+offset, length);
|
||||
}
|
||||
#else
|
||||
unsigned int i;
|
||||
lane >>= offset*8;
|
||||
for(i=0; i<length; i++) {
|
||||
data[i] = lane & 0xFF;
|
||||
lane >>= 8;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
#if (PLATFORM_BYTE_ORDER != IS_LITTLE_ENDIAN)
|
||||
static void fromWordToBytes(uint8_t *bytes, const uint64_t word)
|
||||
{
|
||||
unsigned int i;
|
||||
|
||||
for(i=0; i<(64/8); i++)
|
||||
bytes[i] = (word >> (8*i)) & 0xFF;
|
||||
}
|
||||
#endif
|
||||
|
||||
void KeccakP1600_ExtractLanes(const KeccakP1600_plain64_state *state, unsigned char *data, unsigned int laneCount)
|
||||
{
|
||||
#if (PLATFORM_BYTE_ORDER == IS_LITTLE_ENDIAN)
|
||||
memcpy(data, state, laneCount*8);
|
||||
#else
|
||||
unsigned int i;
|
||||
|
||||
for(i=0; i<laneCount; i++)
|
||||
fromWordToBytes(data+(i*8), ((const uint64_t*)state)[i]);
|
||||
#endif
|
||||
#ifdef KeccakP1600_useLaneComplementing
|
||||
if (laneCount > 1) {
|
||||
((uint64_t*)data)[ 1] = ~((uint64_t*)data)[ 1];
|
||||
if (laneCount > 2) {
|
||||
((uint64_t*)data)[ 2] = ~((uint64_t*)data)[ 2];
|
||||
if (laneCount > 8) {
|
||||
((uint64_t*)data)[ 8] = ~((uint64_t*)data)[ 8];
|
||||
if (laneCount > 12) {
|
||||
((uint64_t*)data)[12] = ~((uint64_t*)data)[12];
|
||||
if (laneCount > 17) {
|
||||
((uint64_t*)data)[17] = ~((uint64_t*)data)[17];
|
||||
if (laneCount > 20) {
|
||||
((uint64_t*)data)[20] = ~((uint64_t*)data)[20];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
void KeccakP1600_ExtractBytes(const KeccakP1600_plain64_state *state, unsigned char *data, unsigned int offset, unsigned int length)
|
||||
{
|
||||
SnP_ExtractBytes(state, data, offset, length, KeccakP1600_ExtractLanes, KeccakP1600_ExtractBytesInLane, 8);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
void KeccakP1600_ExtractAndAddBytesInLane(const KeccakP1600_plain64_state *state, unsigned int lanePosition, const unsigned char *input, unsigned char *output, unsigned int offset, unsigned int length)
|
||||
{
|
||||
uint64_t lane = state->A[lanePosition];
|
||||
#ifdef KeccakP1600_useLaneComplementing
|
||||
if ((lanePosition == 1) || (lanePosition == 2) || (lanePosition == 8) || (lanePosition == 12) || (lanePosition == 17) || (lanePosition == 20))
|
||||
lane = ~lane;
|
||||
#endif
|
||||
#if (PLATFORM_BYTE_ORDER == IS_LITTLE_ENDIAN)
|
||||
{
|
||||
unsigned int i;
|
||||
uint64_t lane1[1];
|
||||
lane1[0] = lane;
|
||||
for(i=0; i<length; i++)
|
||||
output[i] = input[i] ^ ((uint8_t*)lane1)[offset+i];
|
||||
}
|
||||
#else
|
||||
unsigned int i;
|
||||
lane >>= offset*8;
|
||||
for(i=0; i<length; i++) {
|
||||
output[i] = input[i] ^ (lane & 0xFF);
|
||||
lane >>= 8;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
void KeccakP1600_ExtractAndAddLanes(const KeccakP1600_plain64_state *state, const unsigned char *input, unsigned char *output, unsigned int laneCount)
|
||||
{
|
||||
unsigned int i;
|
||||
#if (PLATFORM_BYTE_ORDER != IS_LITTLE_ENDIAN)
|
||||
unsigned char temp[8];
|
||||
unsigned int j;
|
||||
#endif
|
||||
|
||||
for(i=0; i<laneCount; i++) {
|
||||
#if (PLATFORM_BYTE_ORDER == IS_LITTLE_ENDIAN)
|
||||
((uint64_t*)output)[i] = ((uint64_t*)input)[i] ^ ((const uint64_t*)state)[i];
|
||||
#else
|
||||
fromWordToBytes(temp, ((const uint64_t*)state)[i]);
|
||||
for(j=0; j<8; j++)
|
||||
output[i*8+j] = input[i*8+j] ^ temp[j];
|
||||
#endif
|
||||
}
|
||||
#ifdef KeccakP1600_useLaneComplementing
|
||||
if (laneCount > 1) {
|
||||
((uint64_t*)output)[ 1] = ~((uint64_t*)output)[ 1];
|
||||
if (laneCount > 2) {
|
||||
((uint64_t*)output)[ 2] = ~((uint64_t*)output)[ 2];
|
||||
if (laneCount > 8) {
|
||||
((uint64_t*)output)[ 8] = ~((uint64_t*)output)[ 8];
|
||||
if (laneCount > 12) {
|
||||
((uint64_t*)output)[12] = ~((uint64_t*)output)[12];
|
||||
if (laneCount > 17) {
|
||||
((uint64_t*)output)[17] = ~((uint64_t*)output)[17];
|
||||
if (laneCount > 20) {
|
||||
((uint64_t*)output)[20] = ~((uint64_t*)output)[20];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
void KeccakP1600_ExtractAndAddBytes(const KeccakP1600_plain64_state *state, const unsigned char *input, unsigned char *output, unsigned int offset, unsigned int length)
|
||||
{
|
||||
SnP_ExtractAndAddBytes(state, input, output, offset, length, KeccakP1600_ExtractAndAddLanes, KeccakP1600_ExtractAndAddBytesInLane, 8);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
size_t KeccakF1600_FastLoop_Absorb(KeccakP1600_plain64_state *state, unsigned int laneCount, const unsigned char *data, size_t dataByteLen)
|
||||
{
|
||||
size_t originalDataByteLen = dataByteLen;
|
||||
declareABCDE
|
||||
#ifndef KeccakP1600_fullUnrolling
|
||||
unsigned int i;
|
||||
#endif
|
||||
uint64_t *stateAsLanes = state->A;
|
||||
uint64_t *inDataAsLanes = (uint64_t*)data;
|
||||
|
||||
copyFromState(A, stateAsLanes)
|
||||
while(dataByteLen >= laneCount*8) {
|
||||
addInput(A, inDataAsLanes, laneCount)
|
||||
rounds24
|
||||
inDataAsLanes += laneCount;
|
||||
dataByteLen -= laneCount*8;
|
||||
}
|
||||
copyToState(stateAsLanes, A)
|
||||
return originalDataByteLen - dataByteLen;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
size_t KeccakP1600_12rounds_FastLoop_Absorb(KeccakP1600_plain64_state *state, unsigned int laneCount, const unsigned char *data, size_t dataByteLen)
|
||||
{
|
||||
size_t originalDataByteLen = dataByteLen;
|
||||
declareABCDE
|
||||
#ifndef KeccakP1600_fullUnrolling
|
||||
unsigned int i;
|
||||
#endif
|
||||
uint64_t *stateAsLanes = state->A;
|
||||
uint64_t *inDataAsLanes = (uint64_t*)data;
|
||||
|
||||
copyFromState(A, stateAsLanes)
|
||||
while(dataByteLen >= laneCount*8) {
|
||||
addInput(A, inDataAsLanes, laneCount)
|
||||
rounds12
|
||||
inDataAsLanes += laneCount;
|
||||
dataByteLen -= laneCount*8;
|
||||
}
|
||||
copyToState(stateAsLanes, A)
|
||||
return originalDataByteLen - dataByteLen;
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
/*
|
||||
The eXtended Keccak Code Package (XKCP)
|
||||
https://github.com/XKCP/XKCP
|
||||
|
||||
The Keccak-p permutations, designed by Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche.
|
||||
|
||||
Implementation by Gilles Van Assche and Ronny Van Keer, hereby denoted as "the implementer".
|
||||
|
||||
For more information, feedback or questions, please refer to the Keccak Team website:
|
||||
https://keccak.team/
|
||||
|
||||
To the extent possible under law, the implementer has waived all copyright
|
||||
and related or neighboring rights to the source code in this file.
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
#if (defined(FullUnrolling))
|
||||
#define rounds24 \
|
||||
prepareTheta \
|
||||
thetaRhoPiChiIotaPrepareTheta( 0, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta( 1, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta( 2, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta( 3, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta( 4, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta( 5, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta( 6, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta( 7, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta( 8, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta( 9, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(10, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(11, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(12, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(13, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(14, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(15, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(16, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(17, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(18, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(19, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(20, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(21, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(22, A, E) \
|
||||
thetaRhoPiChiIota(23, E, A) \
|
||||
|
||||
#define rounds12 \
|
||||
prepareTheta \
|
||||
thetaRhoPiChiIotaPrepareTheta(12, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(13, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(14, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(15, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(16, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(17, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(18, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(19, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(20, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(21, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(22, A, E) \
|
||||
thetaRhoPiChiIota(23, E, A) \
|
||||
|
||||
#define rounds6 \
|
||||
prepareTheta \
|
||||
thetaRhoPiChiIotaPrepareTheta(18, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(19, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(20, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(21, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(22, A, E) \
|
||||
thetaRhoPiChiIota(23, E, A) \
|
||||
|
||||
#define rounds4 \
|
||||
prepareTheta \
|
||||
thetaRhoPiChiIotaPrepareTheta(20, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(21, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(22, A, E) \
|
||||
thetaRhoPiChiIota(23, E, A) \
|
||||
|
||||
#elif (Unrolling == 12)
|
||||
#define rounds24 \
|
||||
prepareTheta \
|
||||
for(i=0; i<24; i+=12) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+ 1, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+ 2, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+ 3, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+ 4, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+ 5, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+ 6, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+ 7, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+ 8, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+ 9, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+10, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+11, E, A) \
|
||||
} \
|
||||
|
||||
#define rounds12 \
|
||||
prepareTheta \
|
||||
thetaRhoPiChiIotaPrepareTheta(12, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(13, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(14, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(15, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(16, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(17, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(18, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(19, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(20, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(21, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(22, A, E) \
|
||||
thetaRhoPiChiIota(23, E, A) \
|
||||
|
||||
#define rounds6 \
|
||||
prepareTheta \
|
||||
thetaRhoPiChiIotaPrepareTheta(18, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(19, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(20, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(21, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(22, A, E) \
|
||||
thetaRhoPiChiIota(23, E, A) \
|
||||
|
||||
#define rounds4 \
|
||||
prepareTheta \
|
||||
thetaRhoPiChiIotaPrepareTheta(20, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(21, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(22, A, E) \
|
||||
thetaRhoPiChiIota(23, E, A) \
|
||||
|
||||
#elif (Unrolling == 6)
|
||||
#define rounds24 \
|
||||
prepareTheta \
|
||||
for(i=0; i<24; i+=6) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+1, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+2, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+3, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+4, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+5, E, A) \
|
||||
} \
|
||||
|
||||
#define rounds12 \
|
||||
prepareTheta \
|
||||
for(i=12; i<24; i+=6) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+1, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+2, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+3, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+4, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+5, E, A) \
|
||||
} \
|
||||
|
||||
#define rounds6 \
|
||||
prepareTheta \
|
||||
thetaRhoPiChiIotaPrepareTheta(18, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(19, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(20, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(21, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(22, A, E) \
|
||||
thetaRhoPiChiIota(23, E, A) \
|
||||
|
||||
#define rounds4 \
|
||||
prepareTheta \
|
||||
thetaRhoPiChiIotaPrepareTheta(20, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(21, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(22, A, E) \
|
||||
thetaRhoPiChiIota(23, E, A) \
|
||||
|
||||
#elif (Unrolling == 4)
|
||||
#define rounds24 \
|
||||
prepareTheta \
|
||||
for(i=0; i<24; i+=4) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+1, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+2, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+3, E, A) \
|
||||
} \
|
||||
|
||||
#define rounds12 \
|
||||
prepareTheta \
|
||||
for(i=12; i<24; i+=4) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+1, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+2, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+3, E, A) \
|
||||
} \
|
||||
|
||||
#define rounds6 \
|
||||
prepareTheta \
|
||||
for(i=18; i<24; i+=2) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+1, E, A) \
|
||||
} \
|
||||
|
||||
#define rounds4 \
|
||||
prepareTheta \
|
||||
thetaRhoPiChiIotaPrepareTheta(20, A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(21, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(22, A, E) \
|
||||
thetaRhoPiChiIota(23, E, A) \
|
||||
|
||||
#elif (Unrolling == 3)
|
||||
#define rounds24 \
|
||||
prepareTheta \
|
||||
for(i=0; i<24; i+=3) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+1, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+2, A, E) \
|
||||
copyStateVariables(A, E) \
|
||||
} \
|
||||
|
||||
#define rounds12 \
|
||||
prepareTheta \
|
||||
for(i=12; i<24; i+=3) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+1, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+2, A, E) \
|
||||
copyStateVariables(A, E) \
|
||||
} \
|
||||
|
||||
#define rounds6 \
|
||||
prepareTheta \
|
||||
for(i=18; i<24; i+=3) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+1, E, A) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+2, A, E) \
|
||||
copyStateVariables(A, E) \
|
||||
} \
|
||||
|
||||
#define rounds4 \
|
||||
prepareTheta \
|
||||
for(i=20; i<24; i+=2) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+1, E, A) \
|
||||
} \
|
||||
|
||||
#elif (Unrolling == 2)
|
||||
#define rounds24 \
|
||||
prepareTheta \
|
||||
for(i=0; i<24; i+=2) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+1, E, A) \
|
||||
} \
|
||||
|
||||
#define rounds12 \
|
||||
prepareTheta \
|
||||
for(i=12; i<24; i+=2) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+1, E, A) \
|
||||
} \
|
||||
|
||||
#define rounds6 \
|
||||
prepareTheta \
|
||||
for(i=18; i<24; i+=2) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+1, E, A) \
|
||||
} \
|
||||
|
||||
#define rounds4 \
|
||||
prepareTheta \
|
||||
for(i=20; i<24; i+=2) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+1, E, A) \
|
||||
} \
|
||||
|
||||
#elif (Unrolling == 1)
|
||||
#define rounds24 \
|
||||
prepareTheta \
|
||||
for(i=0; i<24; i++) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
copyStateVariables(A, E) \
|
||||
} \
|
||||
|
||||
#define rounds12 \
|
||||
prepareTheta \
|
||||
for(i=12; i<24; i++) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
copyStateVariables(A, E) \
|
||||
} \
|
||||
|
||||
#define rounds6 \
|
||||
prepareTheta \
|
||||
for(i=18; i<24; i++) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
copyStateVariables(A, E) \
|
||||
} \
|
||||
|
||||
#define rounds4 \
|
||||
prepareTheta \
|
||||
for(i=20; i<24; i++) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
copyStateVariables(A, E) \
|
||||
} \
|
||||
|
||||
#else
|
||||
#error "Unrolling is not correctly specified!"
|
||||
#endif
|
||||
|
||||
#define roundsN(__nrounds) \
|
||||
prepareTheta \
|
||||
i = 24 - (__nrounds); \
|
||||
if ((i&1) != 0) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i, A, E) \
|
||||
copyStateVariables(A, E) \
|
||||
++i; \
|
||||
} \
|
||||
for( /* empty */; i<24; i+=2) { \
|
||||
thetaRhoPiChiIotaPrepareTheta(i , A, E) \
|
||||
thetaRhoPiChiIotaPrepareTheta(i+1, E, A) \
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
The eXtended Keccak Code Package (XKCP)
|
||||
https://github.com/XKCP/XKCP
|
||||
|
||||
Keccak, designed by Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche.
|
||||
|
||||
Implementation by the designers, hereby denoted as "the implementer".
|
||||
|
||||
For more information, feedback or questions, please refer to the Keccak Team website:
|
||||
https://keccak.team/
|
||||
|
||||
To the extent possible under law, the implementer has waived all copyright
|
||||
and related or neighboring rights to the source code in this file.
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
#include "KeccakSponge.h"
|
||||
|
||||
#ifdef KeccakReference
|
||||
#include "displayIntermediateValues.h"
|
||||
#endif
|
||||
|
||||
#ifdef XKCP_has_KeccakP200
|
||||
#include "KeccakP-200-SnP.h"
|
||||
|
||||
#define prefix KeccakWidth200
|
||||
#define SnP KeccakP200
|
||||
#define SnP_width 200
|
||||
#define SnP_Permute KeccakP200_Permute_18rounds
|
||||
#if defined(KeccakF200_FastLoop_supported)
|
||||
#define SnP_FastLoop_Absorb KeccakF200_FastLoop_Absorb
|
||||
#endif
|
||||
#include "KeccakSponge.inc"
|
||||
#undef prefix
|
||||
#undef SnP
|
||||
#undef SnP_width
|
||||
#undef SnP_Permute
|
||||
#undef SnP_FastLoop_Absorb
|
||||
#endif
|
||||
|
||||
#ifdef XKCP_has_KeccakP400
|
||||
#include "KeccakP-400-SnP.h"
|
||||
|
||||
#define prefix KeccakWidth400
|
||||
#define SnP KeccakP400
|
||||
#define SnP_width 400
|
||||
#define SnP_Permute KeccakP400_Permute_20rounds
|
||||
#if defined(KeccakF400_FastLoop_supported)
|
||||
#define SnP_FastLoop_Absorb KeccakF400_FastLoop_Absorb
|
||||
#endif
|
||||
#include "KeccakSponge.inc"
|
||||
#undef prefix
|
||||
#undef SnP
|
||||
#undef SnP_width
|
||||
#undef SnP_Permute
|
||||
#undef SnP_FastLoop_Absorb
|
||||
#endif
|
||||
|
||||
#ifdef XKCP_has_KeccakP800
|
||||
#include "KeccakP-800-SnP.h"
|
||||
|
||||
#define prefix KeccakWidth800
|
||||
#define SnP KeccakP800
|
||||
#define SnP_width 800
|
||||
#define SnP_Permute KeccakP800_Permute_22rounds
|
||||
#if defined(KeccakF800_FastLoop_supported)
|
||||
#define SnP_FastLoop_Absorb KeccakF800_FastLoop_Absorb
|
||||
#endif
|
||||
#include "KeccakSponge.inc"
|
||||
#undef prefix
|
||||
#undef SnP
|
||||
#undef SnP_width
|
||||
#undef SnP_Permute
|
||||
#undef SnP_FastLoop_Absorb
|
||||
#endif
|
||||
|
||||
#ifdef XKCP_has_KeccakP1600
|
||||
#include "KeccakP-1600-SnP.h"
|
||||
|
||||
#define prefix KeccakWidth1600
|
||||
#define SnP KeccakP1600
|
||||
#define SnP_state KeccakP1600_state
|
||||
#define SnP_width 1600
|
||||
#define SnP_Permute KeccakP1600_Permute_24rounds
|
||||
#if defined(KeccakF1600_FastLoop_supported)
|
||||
#define SnP_FastLoop_Absorb KeccakF1600_FastLoop_Absorb
|
||||
#endif
|
||||
#include "KeccakSponge.inc"
|
||||
#undef prefix
|
||||
#undef SnP
|
||||
#undef SnP_state
|
||||
#undef SnP_width
|
||||
#undef SnP_Permute
|
||||
#undef SnP_FastLoop_Absorb
|
||||
#endif
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
The eXtended Keccak Code Package (XKCP)
|
||||
https://github.com/XKCP/XKCP
|
||||
|
||||
Keccak, designed by Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche.
|
||||
|
||||
Implementation by the designers, hereby denoted as "the implementer".
|
||||
|
||||
For more information, feedback or questions, please refer to the Keccak Team website:
|
||||
https://keccak.team/
|
||||
|
||||
To the extent possible under law, the implementer has waived all copyright
|
||||
and related or neighboring rights to the source code in this file.
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
#ifndef _KeccakSponge_h_
|
||||
#define _KeccakSponge_h_
|
||||
|
||||
/* For the documentation, please follow the link: */
|
||||
/* #include "KeccakSponge-documentation.h" */
|
||||
|
||||
#include <string.h>
|
||||
#include "align.h"
|
||||
#include "config.h"
|
||||
|
||||
#define XKCP_DeclareSpongeStructure(prefix, state_t) \
|
||||
typedef struct prefix##_SpongeInstanceStruct { \
|
||||
state_t state; \
|
||||
unsigned int rate; \
|
||||
unsigned int byteIOIndex; \
|
||||
int squeezing; \
|
||||
} prefix##_SpongeInstance;
|
||||
|
||||
#define XKCP_DeclareSpongeFunctions(prefix) \
|
||||
int prefix##_Sponge(unsigned int rate, unsigned int capacity, const unsigned char *input, size_t inputByteLen, unsigned char suffix, unsigned char *output, size_t outputByteLen); \
|
||||
int prefix##_SpongeInitialize(prefix##_SpongeInstance *spongeInstance, unsigned int rate, unsigned int capacity); \
|
||||
int prefix##_SpongeAbsorb(prefix##_SpongeInstance *spongeInstance, const unsigned char *data, size_t dataByteLen); \
|
||||
int prefix##_SpongeAbsorbLastFewBits(prefix##_SpongeInstance *spongeInstance, unsigned char delimitedData); \
|
||||
int prefix##_SpongeSqueeze(prefix##_SpongeInstance *spongeInstance, unsigned char *data, size_t dataByteLen);
|
||||
|
||||
#ifdef XKCP_has_KeccakP200
|
||||
#include "KeccakP-200-SnP.h"
|
||||
XKCP_DeclareSpongeStructure(KeccakWidth200, KeccakP200_stateSizeInBytes, KeccakP200_stateAlignment)
|
||||
XKCP_DeclareSpongeFunctions(KeccakWidth200)
|
||||
#define XKCP_has_Sponge_Keccak_width200
|
||||
#endif
|
||||
|
||||
#ifdef XKCP_has_KeccakP400
|
||||
#include "KeccakP-400-SnP.h"
|
||||
XKCP_DeclareSpongeStructure(KeccakWidth400, KeccakP400_stateSizeInBytes, KeccakP400_stateAlignment)
|
||||
XKCP_DeclareSpongeFunctions(KeccakWidth400)
|
||||
#define XKCP_has_Sponge_Keccak_width400
|
||||
#endif
|
||||
|
||||
#ifdef XKCP_has_KeccakP800
|
||||
#include "KeccakP-800-SnP.h"
|
||||
XKCP_DeclareSpongeStructure(KeccakWidth800, KeccakP800_stateSizeInBytes, KeccakP800_stateAlignment)
|
||||
XKCP_DeclareSpongeFunctions(KeccakWidth800)
|
||||
#define XKCP_has_Sponge_Keccak_width800
|
||||
#endif
|
||||
|
||||
#ifdef XKCP_has_KeccakP1600
|
||||
#include "KeccakP-1600-SnP.h"
|
||||
XKCP_DeclareSpongeStructure(KeccakWidth1600, KeccakP1600_state)
|
||||
XKCP_DeclareSpongeFunctions(KeccakWidth1600)
|
||||
#define XKCP_has_Sponge_Keccak_width1600
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,312 @@
|
||||
/*
|
||||
The eXtended Keccak Code Package (XKCP)
|
||||
https://github.com/XKCP/XKCP
|
||||
|
||||
Keccak, designed by Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche.
|
||||
|
||||
Implementation by the designers, hereby denoted as "the implementer".
|
||||
|
||||
For more information, feedback or questions, please refer to the Keccak Team website:
|
||||
https://keccak.team/
|
||||
|
||||
To the extent possible under law, the implementer has waived all copyright
|
||||
and related or neighboring rights to the source code in this file.
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
#define JOIN0(a, b) a ## b
|
||||
#define JOIN(a, b) JOIN0(a, b)
|
||||
|
||||
#define Sponge JOIN(prefix, _Sponge)
|
||||
#define SpongeInstance JOIN(prefix, _SpongeInstance)
|
||||
#define SpongeInitialize JOIN(prefix, _SpongeInitialize)
|
||||
#define SpongeAbsorb JOIN(prefix, _SpongeAbsorb)
|
||||
#define SpongeAbsorbLastFewBits JOIN(prefix, _SpongeAbsorbLastFewBits)
|
||||
#define SpongeSqueeze JOIN(prefix, _SpongeSqueeze)
|
||||
|
||||
#define SnP_StaticInitialize JOIN(SnP, _StaticInitialize)
|
||||
#define SnP_Initialize JOIN(SnP, _Initialize)
|
||||
#define SnP_AddByte JOIN(SnP, _AddByte)
|
||||
#define SnP_AddBytes JOIN(SnP, _AddBytes)
|
||||
#define SnP_ExtractBytes JOIN(SnP, _ExtractBytes)
|
||||
|
||||
int Sponge(unsigned int rate, unsigned int capacity, const unsigned char *input, size_t inputByteLen, unsigned char suffix, unsigned char *output, size_t outputByteLen)
|
||||
{
|
||||
SnP_state state;
|
||||
unsigned int partialBlock;
|
||||
const unsigned char *curInput = input;
|
||||
unsigned char *curOutput = output;
|
||||
unsigned int rateInBytes = rate/8;
|
||||
|
||||
if (rate+capacity != SnP_width)
|
||||
return 1;
|
||||
if ((rate <= 0) || (rate > SnP_width) || ((rate % 8) != 0))
|
||||
return 1;
|
||||
if (suffix == 0)
|
||||
return 1;
|
||||
|
||||
/* Initialize the state */
|
||||
SnP_StaticInitialize();
|
||||
SnP_Initialize(&state);
|
||||
|
||||
/* First, absorb whole blocks */
|
||||
#ifdef SnP_FastLoop_Absorb
|
||||
if (((rateInBytes % (SnP_width/200)) == 0) && (inputByteLen >= rateInBytes)) {
|
||||
/* fast lane: whole lane rate */
|
||||
size_t j;
|
||||
j = SnP_FastLoop_Absorb(&state, rateInBytes/(SnP_width/200), curInput, inputByteLen);
|
||||
curInput += j;
|
||||
inputByteLen -= j;
|
||||
}
|
||||
#endif
|
||||
while(inputByteLen >= (size_t)rateInBytes) {
|
||||
#ifdef KeccakReference
|
||||
displayBytes(1, "Block to be absorbed", curInput, rateInBytes);
|
||||
#endif
|
||||
SnP_AddBytes(&state, curInput, 0, rateInBytes);
|
||||
SnP_Permute(&state);
|
||||
curInput += rateInBytes;
|
||||
inputByteLen -= rateInBytes;
|
||||
}
|
||||
|
||||
/* Then, absorb what remains */
|
||||
partialBlock = (unsigned int)inputByteLen;
|
||||
#ifdef KeccakReference
|
||||
displayBytes(1, "Block to be absorbed (part)", curInput, partialBlock);
|
||||
#endif
|
||||
SnP_AddBytes(&state, curInput, 0, partialBlock);
|
||||
|
||||
/* Finally, absorb the suffix */
|
||||
#ifdef KeccakReference
|
||||
{
|
||||
unsigned char delimitedData1[1];
|
||||
delimitedData1[0] = suffix;
|
||||
displayBytes(1, "Block to be absorbed (last few bits + first bit of padding)", delimitedData1, 1);
|
||||
}
|
||||
#endif
|
||||
/* Last few bits, whose delimiter coincides with first bit of padding */
|
||||
SnP_AddByte(&state, suffix, partialBlock);
|
||||
/* If the first bit of padding is at position rate-1, we need a whole new block for the second bit of padding */
|
||||
if ((suffix >= 0x80) && (partialBlock == (rateInBytes-1)))
|
||||
SnP_Permute(&state);
|
||||
/* Second bit of padding */
|
||||
SnP_AddByte(&state, 0x80, rateInBytes-1);
|
||||
#ifdef KeccakReference
|
||||
{
|
||||
unsigned char block[SnP_width/8];
|
||||
memset(block, 0, SnP_width/8);
|
||||
block[rateInBytes-1] = 0x80;
|
||||
displayBytes(1, "Second bit of padding", block, rateInBytes);
|
||||
}
|
||||
#endif
|
||||
SnP_Permute(&state);
|
||||
#ifdef KeccakReference
|
||||
displayText(1, "--- Switching to squeezing phase ---");
|
||||
#endif
|
||||
|
||||
/* First, output whole blocks */
|
||||
while(outputByteLen > (size_t)rateInBytes) {
|
||||
SnP_ExtractBytes(&state, curOutput, 0, rateInBytes);
|
||||
SnP_Permute(&state);
|
||||
#ifdef KeccakReference
|
||||
displayBytes(1, "Squeezed block", curOutput, rateInBytes);
|
||||
#endif
|
||||
curOutput += rateInBytes;
|
||||
outputByteLen -= rateInBytes;
|
||||
}
|
||||
|
||||
/* Finally, output what remains */
|
||||
partialBlock = (unsigned int)outputByteLen;
|
||||
SnP_ExtractBytes(&state, curOutput, 0, partialBlock);
|
||||
#ifdef KeccakReference
|
||||
displayBytes(1, "Squeezed block (part)", curOutput, partialBlock);
|
||||
#endif
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
/* ---------------------------------------------------------------- */
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
int SpongeInitialize(SpongeInstance *instance, unsigned int rate, unsigned int capacity)
|
||||
{
|
||||
if (rate+capacity != SnP_width)
|
||||
return 1;
|
||||
if ((rate <= 0) || (rate > SnP_width) || ((rate % 8) != 0))
|
||||
return 1;
|
||||
SnP_StaticInitialize();
|
||||
SnP_Initialize(&instance->state);
|
||||
instance->rate = rate;
|
||||
instance->byteIOIndex = 0;
|
||||
instance->squeezing = 0;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
int SpongeAbsorb(SpongeInstance *instance, const unsigned char *data, size_t dataByteLen)
|
||||
{
|
||||
size_t i, j;
|
||||
unsigned int partialBlock;
|
||||
const unsigned char *curData;
|
||||
unsigned int rateInBytes = instance->rate/8;
|
||||
|
||||
if (instance->squeezing)
|
||||
return 1; /* Too late for additional input */
|
||||
|
||||
i = 0;
|
||||
curData = data;
|
||||
while(i < dataByteLen) {
|
||||
if ((instance->byteIOIndex == 0) && (dataByteLen-i >= rateInBytes)) {
|
||||
#ifdef SnP_FastLoop_Absorb
|
||||
/* processing full blocks first */
|
||||
if ((rateInBytes % (SnP_width/200)) == 0) {
|
||||
/* fast lane: whole lane rate */
|
||||
j = SnP_FastLoop_Absorb(&instance->state, rateInBytes/(SnP_width/200), curData, dataByteLen - i);
|
||||
i += j;
|
||||
curData += j;
|
||||
}
|
||||
else {
|
||||
#endif
|
||||
for(j=dataByteLen-i; j>=rateInBytes; j-=rateInBytes) {
|
||||
#ifdef KeccakReference
|
||||
displayBytes(1, "Block to be absorbed", curData, rateInBytes);
|
||||
#endif
|
||||
SnP_AddBytes(&instance->state, curData, 0, rateInBytes);
|
||||
SnP_Permute(&instance->state);
|
||||
curData+=rateInBytes;
|
||||
}
|
||||
i = dataByteLen - j;
|
||||
#ifdef SnP_FastLoop_Absorb
|
||||
}
|
||||
#endif
|
||||
}
|
||||
else {
|
||||
/* normal lane: using the message queue */
|
||||
if (dataByteLen-i > rateInBytes-instance->byteIOIndex)
|
||||
partialBlock = rateInBytes-instance->byteIOIndex;
|
||||
else
|
||||
partialBlock = (unsigned int)(dataByteLen - i);
|
||||
#ifdef KeccakReference
|
||||
displayBytes(1, "Block to be absorbed (part)", curData, partialBlock);
|
||||
#endif
|
||||
i += partialBlock;
|
||||
|
||||
SnP_AddBytes(&instance->state, curData, instance->byteIOIndex, partialBlock);
|
||||
curData += partialBlock;
|
||||
instance->byteIOIndex += partialBlock;
|
||||
if (instance->byteIOIndex == rateInBytes) {
|
||||
SnP_Permute(&instance->state);
|
||||
instance->byteIOIndex = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
int SpongeAbsorbLastFewBits(SpongeInstance *instance, unsigned char delimitedData)
|
||||
{
|
||||
unsigned int rateInBytes = instance->rate/8;
|
||||
|
||||
if (delimitedData == 0)
|
||||
return 1;
|
||||
if (instance->squeezing)
|
||||
return 1; /* Too late for additional input */
|
||||
|
||||
#ifdef KeccakReference
|
||||
{
|
||||
unsigned char delimitedData1[1];
|
||||
delimitedData1[0] = delimitedData;
|
||||
displayBytes(1, "Block to be absorbed (last few bits + first bit of padding)", delimitedData1, 1);
|
||||
}
|
||||
#endif
|
||||
/* Last few bits, whose delimiter coincides with first bit of padding */
|
||||
SnP_AddByte(&instance->state, delimitedData, instance->byteIOIndex);
|
||||
/* If the first bit of padding is at position rate-1, we need a whole new block for the second bit of padding */
|
||||
if ((delimitedData >= 0x80) && (instance->byteIOIndex == (rateInBytes-1)))
|
||||
SnP_Permute(&instance->state);
|
||||
/* Second bit of padding */
|
||||
SnP_AddByte(&instance->state, 0x80, rateInBytes-1);
|
||||
#ifdef KeccakReference
|
||||
{
|
||||
unsigned char block[SnP_width/8];
|
||||
memset(block, 0, SnP_width/8);
|
||||
block[rateInBytes-1] = 0x80;
|
||||
displayBytes(1, "Second bit of padding", block, rateInBytes);
|
||||
}
|
||||
#endif
|
||||
SnP_Permute(&instance->state);
|
||||
instance->byteIOIndex = 0;
|
||||
instance->squeezing = 1;
|
||||
#ifdef KeccakReference
|
||||
displayText(1, "--- Switching to squeezing phase ---");
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
int SpongeSqueeze(SpongeInstance *instance, unsigned char *data, size_t dataByteLen)
|
||||
{
|
||||
size_t i, j;
|
||||
unsigned int partialBlock;
|
||||
unsigned int rateInBytes = instance->rate/8;
|
||||
unsigned char *curData;
|
||||
|
||||
if (!instance->squeezing)
|
||||
SpongeAbsorbLastFewBits(instance, 0x01);
|
||||
|
||||
i = 0;
|
||||
curData = data;
|
||||
while(i < dataByteLen) {
|
||||
if ((instance->byteIOIndex == rateInBytes) && (dataByteLen-i >= rateInBytes)) {
|
||||
for(j=dataByteLen-i; j>=rateInBytes; j-=rateInBytes) {
|
||||
SnP_Permute(&instance->state);
|
||||
SnP_ExtractBytes(&instance->state, curData, 0, rateInBytes);
|
||||
#ifdef KeccakReference
|
||||
displayBytes(1, "Squeezed block", curData, rateInBytes);
|
||||
#endif
|
||||
curData+=rateInBytes;
|
||||
}
|
||||
i = dataByteLen - j;
|
||||
}
|
||||
else {
|
||||
/* normal lane: using the message queue */
|
||||
if (instance->byteIOIndex == rateInBytes) {
|
||||
SnP_Permute(&instance->state);
|
||||
instance->byteIOIndex = 0;
|
||||
}
|
||||
if (dataByteLen-i > rateInBytes-instance->byteIOIndex)
|
||||
partialBlock = rateInBytes-instance->byteIOIndex;
|
||||
else
|
||||
partialBlock = (unsigned int)(dataByteLen - i);
|
||||
i += partialBlock;
|
||||
|
||||
SnP_ExtractBytes(&instance->state, curData, instance->byteIOIndex, partialBlock);
|
||||
#ifdef KeccakReference
|
||||
displayBytes(1, "Squeezed block (part)", curData, partialBlock);
|
||||
#endif
|
||||
curData += partialBlock;
|
||||
instance->byteIOIndex += partialBlock;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- */
|
||||
|
||||
#undef Sponge
|
||||
#undef SpongeInstance
|
||||
#undef SpongeInitialize
|
||||
#undef SpongeAbsorb
|
||||
#undef SpongeAbsorbLastFewBits
|
||||
#undef SpongeSqueeze
|
||||
#undef SnP_StaticInitialize
|
||||
#undef SnP_Initialize
|
||||
#undef SnP_AddByte
|
||||
#undef SnP_AddBytes
|
||||
#undef SnP_ExtractBytes
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
The eXtended Keccak Code Package (XKCP)
|
||||
https://github.com/XKCP/XKCP
|
||||
|
||||
Keccak, designed by Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche.
|
||||
|
||||
Implementation by Gilles Van Assche, hereby denoted as "the implementer".
|
||||
|
||||
For more information, feedback or questions, please refer to the Keccak Team website:
|
||||
https://keccak.team/
|
||||
|
||||
To the extent possible under law, the implementer has waived all copyright
|
||||
and related or neighboring rights to the source code in this file.
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
#include "KeccakSponge.h"
|
||||
#include "SimpleFIPS202.h"
|
||||
|
||||
int SHAKE128(unsigned char *output, size_t outputByteLen, const unsigned char *input, size_t inputByteLen)
|
||||
{
|
||||
return KeccakWidth1600_Sponge(1344, 256, input, inputByteLen, 0x1F, output, outputByteLen);
|
||||
}
|
||||
|
||||
int SHAKE256(unsigned char *output, size_t outputByteLen, const unsigned char *input, size_t inputByteLen)
|
||||
{
|
||||
return KeccakWidth1600_Sponge(1088, 512, input, inputByteLen, 0x1F, output, outputByteLen);
|
||||
}
|
||||
|
||||
int SHA3_224(unsigned char *output, const unsigned char *input, size_t inputByteLen)
|
||||
{
|
||||
return KeccakWidth1600_Sponge(1152, 448, input, inputByteLen, 0x06, output, 224/8);
|
||||
}
|
||||
|
||||
int SHA3_256(unsigned char *output, const unsigned char *input, size_t inputByteLen)
|
||||
{
|
||||
return KeccakWidth1600_Sponge(1088, 512, input, inputByteLen, 0x06, output, 256/8);
|
||||
}
|
||||
|
||||
int SHA3_384(unsigned char *output, const unsigned char *input, size_t inputByteLen)
|
||||
{
|
||||
return KeccakWidth1600_Sponge( 832, 768, input, inputByteLen, 0x06, output, 384/8);
|
||||
}
|
||||
|
||||
int SHA3_512(unsigned char *output, const unsigned char *input, size_t inputByteLen)
|
||||
{
|
||||
return KeccakWidth1600_Sponge(576, 1024, input, inputByteLen, 0x06, output, 512/8);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
The eXtended Keccak Code Package (XKCP)
|
||||
https://github.com/XKCP/XKCP
|
||||
|
||||
Keccak, designed by Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche.
|
||||
|
||||
Implementation by Gilles Van Assche, hereby denoted as "the implementer".
|
||||
|
||||
For more information, feedback or questions, please refer to the Keccak Team website:
|
||||
https://keccak.team/
|
||||
|
||||
To the extent possible under law, the implementer has waived all copyright
|
||||
and related or neighboring rights to the source code in this file.
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
#ifndef _SimpleFIPS202_h_
|
||||
#define _SimpleFIPS202_h_
|
||||
|
||||
#include "config.h"
|
||||
#ifdef XKCP_has_KeccakP1600
|
||||
|
||||
#include <string.h>
|
||||
|
||||
/** Implementation of the SHAKE128 extendable output function (XOF) [FIPS 202].
|
||||
* @param output Pointer to the output buffer.
|
||||
* @param outputByteLen The desired number of output bytes.
|
||||
* @param input Pointer to the input message.
|
||||
* @param inputByteLen The length of the input message in bytes.
|
||||
* @return 0 if successful, 1 otherwise.
|
||||
*/
|
||||
int SHAKE128(unsigned char *output, size_t outputByteLen, const unsigned char *input, size_t inputByteLen);
|
||||
|
||||
/** Implementation of the SHAKE256 extendable output function (XOF) [FIPS 202].
|
||||
* @param output Pointer to the output buffer.
|
||||
* @param outputByteLen The desired number of output bytes.
|
||||
* @param input Pointer to the input message.
|
||||
* @param inputByteLen The length of the input message in bytes.
|
||||
* @return 0 if successful, 1 otherwise.
|
||||
*/
|
||||
int SHAKE256(unsigned char *output, size_t outputByteLen, const unsigned char *input, size_t inputByteLen);
|
||||
|
||||
/** Implementation of SHA3-224 [FIPS 202].
|
||||
* @param output Pointer to the output buffer (28 bytes).
|
||||
* @param input Pointer to the input message.
|
||||
* @param inputByteLen The length of the input message in bytes.
|
||||
* @return 0 if successful, 1 otherwise.
|
||||
*/
|
||||
int SHA3_224(unsigned char *output, const unsigned char *input, size_t inputByteLen);
|
||||
|
||||
/** Implementation of SHA3-256 [FIPS 202].
|
||||
* @param output Pointer to the output buffer (32 bytes).
|
||||
* @param input Pointer to the input message.
|
||||
* @param inputByteLen The length of the input message in bytes.
|
||||
* @return 0 if successful, 1 otherwise.
|
||||
*/
|
||||
int SHA3_256(unsigned char *output, const unsigned char *input, size_t inputByteLen);
|
||||
|
||||
/** Implementation of SHA3-384 [FIPS 202].
|
||||
* @param output Pointer to the output buffer (48 bytes).
|
||||
* @param input Pointer to the input message.
|
||||
* @param inputByteLen The length of the input message in bytes.
|
||||
* @return 0 if successful, 1 otherwise.
|
||||
*/
|
||||
int SHA3_384(unsigned char *output, const unsigned char *input, size_t inputByteLen);
|
||||
|
||||
/** Implementation of SHA3-512 [FIPS 202].
|
||||
* @param output Pointer to the output buffer (64 bytes).
|
||||
* @param input Pointer to the input message.
|
||||
* @param inputByteLen The length of the input message in bytes.
|
||||
* @return 0 if successful, 1 otherwise.
|
||||
*/
|
||||
int SHA3_512(unsigned char *output, const unsigned char *input, size_t inputByteLen);
|
||||
|
||||
#else
|
||||
#error This requires an implementation of Keccak-p[1600]
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,145 @@
|
||||
/*
|
||||
The eXtended Keccak Code Package (XKCP)
|
||||
https://github.com/XKCP/XKCP
|
||||
|
||||
Implementation by Gilles Van Assche and Ronny Van Keer, hereby denoted as "the implementer".
|
||||
|
||||
For more information, feedback or questions, please refer to the Keccak Team website:
|
||||
https://keccak.team/
|
||||
|
||||
To the extent possible under law, the implementer has waived all copyright
|
||||
and related or neighboring rights to the source code in this file.
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
|
||||
---
|
||||
|
||||
This file contains macros that help implement a permutation in a SnP-compatible way.
|
||||
It converts an implementation that implement state input/output functions
|
||||
in a lane-oriented fashion (i.e., using SnP_AddLanes() and SnP_AddBytesInLane,
|
||||
and similarly for Overwite, Extract and ExtractAndAdd) to the byte-oriented SnP.
|
||||
Please refer to SnP-documentation.h for more details.
|
||||
*/
|
||||
|
||||
#ifndef _SnP_Relaned_h_
|
||||
#define _SnP_Relaned_h_
|
||||
|
||||
#define SnP_AddBytes(state, data, offset, length, SnP_AddLanes, SnP_AddBytesInLane, SnP_laneLengthInBytes) \
|
||||
{ \
|
||||
if ((offset) == 0) { \
|
||||
SnP_AddLanes(state, data, (length)/SnP_laneLengthInBytes); \
|
||||
if ((length)%SnP_laneLengthInBytes > 0) \
|
||||
SnP_AddBytesInLane(state, \
|
||||
(length)/SnP_laneLengthInBytes, \
|
||||
(data)+((length)/SnP_laneLengthInBytes)*SnP_laneLengthInBytes, \
|
||||
0, \
|
||||
(length)%SnP_laneLengthInBytes); \
|
||||
} \
|
||||
else { \
|
||||
unsigned int _sizeLeft = (length); \
|
||||
unsigned int _lanePosition = (offset)/SnP_laneLengthInBytes; \
|
||||
unsigned int _offsetInLane = (offset)%SnP_laneLengthInBytes; \
|
||||
const unsigned char *_curData = (data); \
|
||||
while(_sizeLeft > 0) { \
|
||||
unsigned int _bytesInLane = SnP_laneLengthInBytes - _offsetInLane; \
|
||||
if (_bytesInLane > _sizeLeft) \
|
||||
_bytesInLane = _sizeLeft; \
|
||||
SnP_AddBytesInLane(state, _lanePosition, _curData, _offsetInLane, _bytesInLane); \
|
||||
_sizeLeft -= _bytesInLane; \
|
||||
_lanePosition++; \
|
||||
_offsetInLane = 0; \
|
||||
_curData += _bytesInLane; \
|
||||
} \
|
||||
} \
|
||||
}
|
||||
|
||||
#define SnP_OverwriteBytes(state, data, offset, length, SnP_OverwriteLanes, SnP_OverwriteBytesInLane, SnP_laneLengthInBytes) \
|
||||
{ \
|
||||
if ((offset) == 0) { \
|
||||
SnP_OverwriteLanes(state, data, (length)/SnP_laneLengthInBytes); \
|
||||
if ((length)%SnP_laneLengthInBytes > 0) \
|
||||
SnP_OverwriteBytesInLane(state, \
|
||||
(length)/SnP_laneLengthInBytes, \
|
||||
(data)+((length)/SnP_laneLengthInBytes)*SnP_laneLengthInBytes, \
|
||||
0, \
|
||||
(length)%SnP_laneLengthInBytes); \
|
||||
} \
|
||||
else { \
|
||||
unsigned int _sizeLeft = (length); \
|
||||
unsigned int _lanePosition = (offset)/SnP_laneLengthInBytes; \
|
||||
unsigned int _offsetInLane = (offset)%SnP_laneLengthInBytes; \
|
||||
const unsigned char *_curData = (data); \
|
||||
while(_sizeLeft > 0) { \
|
||||
unsigned int _bytesInLane = SnP_laneLengthInBytes - _offsetInLane; \
|
||||
if (_bytesInLane > _sizeLeft) \
|
||||
_bytesInLane = _sizeLeft; \
|
||||
SnP_OverwriteBytesInLane(state, _lanePosition, _curData, _offsetInLane, _bytesInLane); \
|
||||
_sizeLeft -= _bytesInLane; \
|
||||
_lanePosition++; \
|
||||
_offsetInLane = 0; \
|
||||
_curData += _bytesInLane; \
|
||||
} \
|
||||
} \
|
||||
}
|
||||
|
||||
#define SnP_ExtractBytes(state, data, offset, length, SnP_ExtractLanes, SnP_ExtractBytesInLane, SnP_laneLengthInBytes) \
|
||||
{ \
|
||||
if ((offset) == 0) { \
|
||||
SnP_ExtractLanes(state, data, (length)/SnP_laneLengthInBytes); \
|
||||
if ((length)%SnP_laneLengthInBytes > 0) \
|
||||
SnP_ExtractBytesInLane(state, \
|
||||
(length)/SnP_laneLengthInBytes, \
|
||||
(data)+((length)/SnP_laneLengthInBytes)*SnP_laneLengthInBytes, \
|
||||
0, \
|
||||
(length)%SnP_laneLengthInBytes); \
|
||||
} \
|
||||
else { \
|
||||
unsigned int _sizeLeft = (length); \
|
||||
unsigned int _lanePosition = (offset)/SnP_laneLengthInBytes; \
|
||||
unsigned int _offsetInLane = (offset)%SnP_laneLengthInBytes; \
|
||||
unsigned char *_curData = (data); \
|
||||
while(_sizeLeft > 0) { \
|
||||
unsigned int _bytesInLane = SnP_laneLengthInBytes - _offsetInLane; \
|
||||
if (_bytesInLane > _sizeLeft) \
|
||||
_bytesInLane = _sizeLeft; \
|
||||
SnP_ExtractBytesInLane(state, _lanePosition, _curData, _offsetInLane, _bytesInLane); \
|
||||
_sizeLeft -= _bytesInLane; \
|
||||
_lanePosition++; \
|
||||
_offsetInLane = 0; \
|
||||
_curData += _bytesInLane; \
|
||||
} \
|
||||
} \
|
||||
}
|
||||
|
||||
#define SnP_ExtractAndAddBytes(state, input, output, offset, length, SnP_ExtractAndAddLanes, SnP_ExtractAndAddBytesInLane, SnP_laneLengthInBytes) \
|
||||
{ \
|
||||
if ((offset) == 0) { \
|
||||
SnP_ExtractAndAddLanes(state, input, output, (length)/SnP_laneLengthInBytes); \
|
||||
if ((length)%SnP_laneLengthInBytes > 0) \
|
||||
SnP_ExtractAndAddBytesInLane(state, \
|
||||
(length)/SnP_laneLengthInBytes, \
|
||||
(input)+((length)/SnP_laneLengthInBytes)*SnP_laneLengthInBytes, \
|
||||
(output)+((length)/SnP_laneLengthInBytes)*SnP_laneLengthInBytes, \
|
||||
0, \
|
||||
(length)%SnP_laneLengthInBytes); \
|
||||
} \
|
||||
else { \
|
||||
unsigned int _sizeLeft = (length); \
|
||||
unsigned int _lanePosition = (offset)/SnP_laneLengthInBytes; \
|
||||
unsigned int _offsetInLane = (offset)%SnP_laneLengthInBytes; \
|
||||
const unsigned char *_curInput = (input); \
|
||||
unsigned char *_curOutput = (output); \
|
||||
while(_sizeLeft > 0) { \
|
||||
unsigned int _bytesInLane = SnP_laneLengthInBytes - _offsetInLane; \
|
||||
if (_bytesInLane > _sizeLeft) \
|
||||
_bytesInLane = _sizeLeft; \
|
||||
SnP_ExtractAndAddBytesInLane(state, _lanePosition, _curInput, _curOutput, _offsetInLane, _bytesInLane); \
|
||||
_sizeLeft -= _bytesInLane; \
|
||||
_lanePosition++; \
|
||||
_offsetInLane = 0; \
|
||||
_curInput += _bytesInLane; \
|
||||
_curOutput += _bytesInLane; \
|
||||
} \
|
||||
} \
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
The eXtended Keccak Code Package (XKCP)
|
||||
https://github.com/XKCP/XKCP
|
||||
|
||||
Implementation by Gilles Van Assche and Ronny Van Keer, hereby denoted as "the implementer".
|
||||
|
||||
For more information, feedback or questions, please refer to the Keccak Team website:
|
||||
https://keccak.team/
|
||||
|
||||
To the extent possible under law, the implementer has waived all copyright
|
||||
and related or neighboring rights to the source code in this file.
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
#ifndef _align_h_
|
||||
#define _align_h_
|
||||
|
||||
/* on Mac OS-X and possibly others, ALIGN(x) is defined in param.h, and -Werror chokes on the redef. */
|
||||
#ifdef ALIGN
|
||||
#undef ALIGN
|
||||
#endif
|
||||
|
||||
#if defined(__GNUC__)
|
||||
#define ALIGN(x) __attribute__ ((aligned(x)))
|
||||
#elif defined(_MSC_VER)
|
||||
#define ALIGN(x) __declspec(align(x))
|
||||
#elif defined(__ARMCC_VERSION)
|
||||
#define ALIGN(x) __align(x)
|
||||
#else
|
||||
#define ALIGN(x)
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,143 @@
|
||||
/*
|
||||
---------------------------------------------------------------------------
|
||||
Copyright (c) 1998-2008, Brian Gladman, Worcester, UK. All rights reserved.
|
||||
|
||||
LICENSE TERMS
|
||||
|
||||
The redistribution and use of this software (with or without changes)
|
||||
is allowed without the payment of fees or royalties provided that:
|
||||
|
||||
1. source code distributions include the above copyright notice, this
|
||||
list of conditions and the following disclaimer;
|
||||
|
||||
2. binary distributions include the above copyright notice, this list
|
||||
of conditions and the following disclaimer in their documentation;
|
||||
|
||||
3. the name of the copyright holder is not used to endorse products
|
||||
built using this software without specific written permission.
|
||||
|
||||
DISCLAIMER
|
||||
|
||||
This software is provided 'as is' with no explicit or implied warranties
|
||||
in respect of its properties, including, but not limited to, correctness
|
||||
and/or fitness for purpose.
|
||||
---------------------------------------------------------------------------
|
||||
Issue Date: 20/12/2007
|
||||
Changes for ARM 9/9/2010
|
||||
*/
|
||||
|
||||
#ifndef _BRG_ENDIAN_H
|
||||
#define _BRG_ENDIAN_H
|
||||
|
||||
#define IS_BIG_ENDIAN 4321 /* byte 0 is most significant (mc68k) */
|
||||
#define IS_LITTLE_ENDIAN 1234 /* byte 0 is least significant (i386) */
|
||||
|
||||
#if 0
|
||||
/* Include files where endian defines and byteswap functions may reside */
|
||||
#if defined( __sun )
|
||||
# include <sys/isa_defs.h>
|
||||
#elif defined( __FreeBSD__ ) || defined( __OpenBSD__ ) || defined( __NetBSD__ )
|
||||
# include <sys/endian.h>
|
||||
#elif defined( BSD ) && ( BSD >= 199103 ) || defined( __APPLE__ ) || \
|
||||
defined( __CYGWIN32__ ) || defined( __DJGPP__ ) || defined( __osf__ )
|
||||
# include <machine/endian.h>
|
||||
#elif defined( __linux__ ) || defined( __GNUC__ ) || defined( __GNU_LIBRARY__ )
|
||||
# if !defined( __MINGW32__ ) && !defined( _AIX )
|
||||
# include <endian.h>
|
||||
# if !defined( __BEOS__ )
|
||||
# include <byteswap.h>
|
||||
# endif
|
||||
# endif
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/* Now attempt to set the define for platform byte order using any */
|
||||
/* of the four forms SYMBOL, _SYMBOL, __SYMBOL & __SYMBOL__, which */
|
||||
/* seem to encompass most endian symbol definitions */
|
||||
|
||||
#if defined( BIG_ENDIAN ) && defined( LITTLE_ENDIAN )
|
||||
# if defined( BYTE_ORDER ) && BYTE_ORDER == BIG_ENDIAN
|
||||
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
|
||||
# elif defined( BYTE_ORDER ) && BYTE_ORDER == LITTLE_ENDIAN
|
||||
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
|
||||
# endif
|
||||
#elif defined( BIG_ENDIAN )
|
||||
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
|
||||
#elif defined( LITTLE_ENDIAN )
|
||||
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
|
||||
#endif
|
||||
|
||||
#if defined( _BIG_ENDIAN ) && defined( _LITTLE_ENDIAN )
|
||||
# if defined( _BYTE_ORDER ) && _BYTE_ORDER == _BIG_ENDIAN
|
||||
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
|
||||
# elif defined( _BYTE_ORDER ) && _BYTE_ORDER == _LITTLE_ENDIAN
|
||||
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
|
||||
# endif
|
||||
#elif defined( _BIG_ENDIAN )
|
||||
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
|
||||
#elif defined( _LITTLE_ENDIAN )
|
||||
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
|
||||
#endif
|
||||
|
||||
#if defined( __BIG_ENDIAN ) && defined( __LITTLE_ENDIAN )
|
||||
# if defined( __BYTE_ORDER ) && __BYTE_ORDER == __BIG_ENDIAN
|
||||
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
|
||||
# elif defined( __BYTE_ORDER ) && __BYTE_ORDER == __LITTLE_ENDIAN
|
||||
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
|
||||
# endif
|
||||
#elif defined( __BIG_ENDIAN )
|
||||
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
|
||||
#elif defined( __LITTLE_ENDIAN )
|
||||
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
|
||||
#endif
|
||||
|
||||
#if defined( __BIG_ENDIAN__ ) && defined( __LITTLE_ENDIAN__ )
|
||||
# if defined( __BYTE_ORDER__ ) && __BYTE_ORDER__ == __BIG_ENDIAN__
|
||||
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
|
||||
# elif defined( __BYTE_ORDER__ ) && __BYTE_ORDER__ == __LITTLE_ENDIAN__
|
||||
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
|
||||
# endif
|
||||
#elif defined( __BIG_ENDIAN__ )
|
||||
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
|
||||
#elif defined( __LITTLE_ENDIAN__ )
|
||||
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
|
||||
#endif
|
||||
|
||||
/* if the platform byte order could not be determined, then try to */
|
||||
/* set this define using common machine defines */
|
||||
#if !defined(PLATFORM_BYTE_ORDER)
|
||||
|
||||
#if defined( __alpha__ ) || defined( __alpha ) || defined( i386 ) || \
|
||||
defined( __i386__ ) || defined( _M_I86 ) || defined( _M_IX86 ) || \
|
||||
defined( __OS2__ ) || defined( sun386 ) || defined( __TURBOC__ ) || \
|
||||
defined( vax ) || defined( vms ) || defined( VMS ) || \
|
||||
defined( __VMS ) || defined( _M_X64 )
|
||||
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
|
||||
|
||||
#elif defined( AMIGA ) || defined( applec ) || defined( __AS400__ ) || \
|
||||
defined( _CRAY ) || defined( __hppa ) || defined( __hp9000 ) || \
|
||||
defined( ibm370 ) || defined( mc68000 ) || defined( m68k ) || \
|
||||
defined( __MRC__ ) || defined( __MVS__ ) || defined( __MWERKS__ ) || \
|
||||
defined( sparc ) || defined( __sparc) || defined( SYMANTEC_C ) || \
|
||||
defined( __VOS__ ) || defined( __TIGCC__ ) || defined( __TANDEM ) || \
|
||||
defined( THINK_C ) || defined( __VMCMS__ ) || defined( _AIX ) || \
|
||||
defined( __s390__ ) || defined( __s390x__ ) || defined( __zarch__ )
|
||||
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
|
||||
|
||||
#elif defined(__arm__)
|
||||
# ifdef __BIG_ENDIAN
|
||||
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
|
||||
# else
|
||||
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
|
||||
# endif
|
||||
#elif 1 /* **** EDIT HERE IF NECESSARY **** */
|
||||
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
|
||||
#elif 0 /* **** EDIT HERE IF NECESSARY **** */
|
||||
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
|
||||
#else
|
||||
# error Please edit lines 132 or 134 in brg_endian.h to set the platform byte order
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,5 @@
|
||||
/* File generated by ToTargetConfigFile.xsl */
|
||||
|
||||
#define XKCP_has_Sponge_Keccak
|
||||
#define XKCP_has_FIPS202
|
||||
#define XKCP_has_KeccakP1600
|
||||
File renamed without changes.
@@ -0,0 +1,22 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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_XKCP_H
|
||||
#define C_CRYPTO_XKCP_H
|
||||
|
||||
#include "../FIPS202-opt64/KeccakHash.h"
|
||||
#include "../FIPS202-opt64/KeccakSponge.h"
|
||||
#include "../FIPS202-opt64/SimpleFIPS202.h"
|
||||
|
||||
#endif // C_CRYPTO_XKCP_H
|
||||
@@ -0,0 +1,4 @@
|
||||
module CXKCP {
|
||||
header "CXKCP.h"
|
||||
export *
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
Vendored code from XKCP#master (heads/master-0-g11297f5):
|
||||
- FIPS202-opt64/align.h
|
||||
- FIPS202-opt64/brg_endian.h
|
||||
- FIPS202-opt64/config.h
|
||||
- FIPS202-opt64/KeccakHash.c
|
||||
- FIPS202-opt64/KeccakHash.h
|
||||
- FIPS202-opt64/KeccakP-1600-64.macros
|
||||
- FIPS202-opt64/KeccakP-1600-opt64-config.h
|
||||
- FIPS202-opt64/KeccakP-1600-opt64.c
|
||||
- FIPS202-opt64/KeccakP-1600-SnP.h
|
||||
- FIPS202-opt64/KeccakP-1600-unrolling.macros
|
||||
- FIPS202-opt64/KeccakSponge.c
|
||||
- FIPS202-opt64/KeccakSponge.h
|
||||
- FIPS202-opt64/KeccakSponge.inc
|
||||
- FIPS202-opt64/SimpleFIPS202.c
|
||||
- FIPS202-opt64/SimpleFIPS202.h
|
||||
- FIPS202-opt64/SnP-Relaned.h
|
||||
@@ -0,0 +1,29 @@
|
||||
##===----------------------------------------------------------------------===##
|
||||
##
|
||||
## This source file is part of the SwiftCrypto open source project
|
||||
##
|
||||
## Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors
|
||||
## Licensed under Apache License v2.0
|
||||
##
|
||||
## See LICENSE.txt for license information
|
||||
## See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
##
|
||||
## SPDX-License-Identifier: Apache-2.0
|
||||
##
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
add_library(CXKCPShims STATIC
|
||||
"shims.c"
|
||||
)
|
||||
|
||||
target_include_directories(CXKCPShims PUBLIC
|
||||
include
|
||||
$<TARGET_PROPERTY:CXKCP,INCLUDE_DIRECTORIES>)
|
||||
|
||||
target_link_libraries(CXKCPShims PUBLIC
|
||||
CXKCP)
|
||||
|
||||
set_target_properties(CXKCPShims PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_CRYPTO_EXPORTS CXKCPShims)
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSPrivacyTracking</key>
|
||||
<false/>
|
||||
<key>NSPrivacyAccessedAPITypes</key>
|
||||
<array/>
|
||||
<key>NSPrivacyCollectedDataTypes</key>
|
||||
<array/>
|
||||
<key>NSPrivacyTrackingDomains</key>
|
||||
<array/>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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_XKCP_SHIMS_H
|
||||
#define C_XKCP_SHIMS_H
|
||||
|
||||
// This is for instances when `swift package generate-xcodeproj` is used as CXKCP
|
||||
// is treated as a framework and requires the framework's name as a prefix.
|
||||
#if __has_include(<CXKCP/CXKCP.h>)
|
||||
#include <CXKCP/CXKCP.h>
|
||||
#else
|
||||
#include <CXKCP.h>
|
||||
#endif
|
||||
|
||||
#if defined(__cplusplus)
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
// MARK:- Macro wrapper shims
|
||||
// This section of the code handles shims that wrap XKCP macros as C functions.
|
||||
// This is done because Swift cannot call C macros directly, so we need to wrap
|
||||
// them in actual C functions to make them callable from Swift.
|
||||
//
|
||||
// The XKCP library defines initialization macros for different SHA-3 variants:
|
||||
// - Keccak_HashInitialize_SHA3_256
|
||||
// - Keccak_HashInitialize_SHA3_384
|
||||
// - Keccak_HashInitialize_SHA3_512
|
||||
//
|
||||
// These macros call Keccak_HashInitialize with specific parameters for each variant.
|
||||
|
||||
/**
|
||||
* Wrapper function for Keccak_HashInitialize_SHA3_256 macro.
|
||||
* Initializes a SHA3-256 hash instance.
|
||||
* @param hashInstance Pointer to the hash instance to be initialized.
|
||||
* @return KECCAK_SUCCESS if successful, KECCAK_FAIL otherwise.
|
||||
*/
|
||||
HashReturn CXKCPShims_Keccak_HashInitialize_SHA3_256(Keccak_HashInstance *hashInstance);
|
||||
|
||||
/**
|
||||
* Wrapper function for Keccak_HashInitialize_SHA3_384 macro.
|
||||
* Initializes a SHA3-384 hash instance.
|
||||
* @param hashInstance Pointer to the hash instance to be initialized.
|
||||
* @return KECCAK_SUCCESS if successful, KECCAK_FAIL otherwise.
|
||||
*/
|
||||
HashReturn CXKCPShims_Keccak_HashInitialize_SHA3_384(Keccak_HashInstance *hashInstance);
|
||||
|
||||
/**
|
||||
* Wrapper function for Keccak_HashInitialize_SHA3_512 macro.
|
||||
* Initializes a SHA3-512 hash instance.
|
||||
* @param hashInstance Pointer to the hash instance to be initialized.
|
||||
* @return KECCAK_SUCCESS if successful, KECCAK_FAIL otherwise.
|
||||
*/
|
||||
HashReturn CXKCPShims_Keccak_HashInitialize_SHA3_512(Keccak_HashInstance *hashInstance);
|
||||
|
||||
#if defined(__cplusplus)
|
||||
}
|
||||
#endif // defined(__cplusplus)
|
||||
|
||||
#endif // C_XKCP_SHIMS_H
|
||||
@@ -0,0 +1,4 @@
|
||||
module CXKCPShims {
|
||||
header "CXKCPShims.h"
|
||||
export *
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 <CXKCPShims.h>
|
||||
|
||||
// MARK:- Macro wrapper shims
|
||||
// This section of the code handles shims that wrap XKCP macros as C functions.
|
||||
// This is done because Swift cannot call C macros directly, so we need to wrap
|
||||
// them in actual C functions to make them callable from Swift.
|
||||
//
|
||||
// The XKCP library defines initialization macros for different SHA-3 variants:
|
||||
// - Keccak_HashInitialize_SHA3_256 -> Keccak_HashInitialize(hashInstance, 1088, 512, 256, 0x06)
|
||||
// - Keccak_HashInitialize_SHA3_384 -> Keccak_HashInitialize(hashInstance, 832, 768, 384, 0x06)
|
||||
// - Keccak_HashInitialize_SHA3_512 -> Keccak_HashInitialize(hashInstance, 576, 1024, 512, 0x06)
|
||||
|
||||
HashReturn CXKCPShims_Keccak_HashInitialize_SHA3_256(Keccak_HashInstance *hashInstance) {
|
||||
return Keccak_HashInitialize(hashInstance, 1088, 512, 256, 0x06);
|
||||
}
|
||||
|
||||
HashReturn CXKCPShims_Keccak_HashInitialize_SHA3_384(Keccak_HashInstance *hashInstance) {
|
||||
return Keccak_HashInitialize(hashInstance, 832, 768, 384, 0x06);
|
||||
}
|
||||
|
||||
HashReturn CXKCPShims_Keccak_HashInitialize_SHA3_512(Keccak_HashInstance *hashInstance) {
|
||||
return Keccak_HashInitialize(hashInstance, 576, 1024, 512, 0x06);
|
||||
}
|
||||
@@ -14,23 +14,30 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#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
|
||||
import Security
|
||||
#else
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
typealias AESGCMImpl = OpenSSLAESGCMImpl
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
public import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension AES {
|
||||
/// The Advanced Encryption Standard (AES) Galois Counter Mode (GCM) cipher
|
||||
/// suite.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum GCM: Cipher {
|
||||
public enum GCM: Cipher, Sendable {
|
||||
static let tagByteCount = 16
|
||||
static let defaultNonceByteCount = 12
|
||||
|
||||
@@ -41,12 +48,12 @@ extension AES {
|
||||
/// - Parameters:
|
||||
/// - message: The plaintext data to seal.
|
||||
/// - key: A cryptographic key used to seal the message.
|
||||
/// - nonce: The nonce the sealing process requires. If you don't provide a nonce, the method generates a random one by invoking ``AES.GCM.Nonce()``.
|
||||
/// - nonce: The nonce the sealing process requires. If you don't provide a nonce, the method generates a random one by invoking ``AES/GCM/Nonce/init()``.
|
||||
/// - authenticatedData: Additional data to be authenticated.
|
||||
///
|
||||
/// - Returns: The sealed message.
|
||||
public static func seal<Plaintext: DataProtocol, AuthenticatedData: DataProtocol>
|
||||
(_ message: Plaintext, using key: SymmetricKey, nonce: Nonce? = nil, authenticating authenticatedData: AuthenticatedData) throws -> SealedBox {
|
||||
(_ message: Plaintext, using key: SymmetricKey, nonce: Nonce? = nil, authenticating authenticatedData: AuthenticatedData) throws(CryptoKitMetaError) -> SealedBox {
|
||||
return try AESGCMImpl.seal(key: key, message: message, nonce: nonce, authenticatedData: authenticatedData)
|
||||
}
|
||||
|
||||
@@ -56,11 +63,11 @@ extension AES {
|
||||
/// - Parameters:
|
||||
/// - message: The plaintext data to seal.
|
||||
/// - key: A cryptographic key used to seal the message.
|
||||
/// - nonce: The nonce the sealing process requires. If you don't provide a nonce, the method generates a random one by invoking ``AES.GCM.Nonce()``.
|
||||
/// - nonce: The nonce the sealing process requires. If you don't provide a nonce, the method generates a random one by invoking ``AES/GCM/Nonce/init()``.
|
||||
///
|
||||
/// - Returns: The sealed message.
|
||||
public static func seal<Plaintext: DataProtocol>
|
||||
(_ message: Plaintext, using key: SymmetricKey, nonce: Nonce? = nil) throws -> SealedBox {
|
||||
(_ message: Plaintext, using key: SymmetricKey, nonce: Nonce? = nil) throws(CryptoKitMetaError) -> SealedBox {
|
||||
return try AESGCMImpl.seal(key: key, message: message, nonce: nonce, authenticatedData: Data?.none)
|
||||
}
|
||||
|
||||
@@ -76,7 +83,7 @@ extension AES {
|
||||
/// box, as long as the correct key is used and authentication succeeds.
|
||||
/// The call throws an error if decryption or authentication fail.
|
||||
public static func open<AuthenticatedData: DataProtocol>
|
||||
(_ sealedBox: SealedBox, using key: SymmetricKey, authenticating authenticatedData: AuthenticatedData) throws -> Data {
|
||||
(_ sealedBox: SealedBox, using key: SymmetricKey, authenticating authenticatedData: AuthenticatedData) throws(CryptoKitMetaError) -> Data {
|
||||
return try AESGCMImpl.open(key: key, sealedBox: sealedBox, authenticatedData: authenticatedData)
|
||||
}
|
||||
|
||||
@@ -89,7 +96,7 @@ extension AES {
|
||||
/// - Returns: The original plaintext message that was sealed in the
|
||||
/// box, as long as the correct key is used and authentication succeeds.
|
||||
/// The call throws an error if decryption or authentication fail.
|
||||
public static func open(_ sealedBox: SealedBox, using key: SymmetricKey) throws -> Data {
|
||||
public static func open(_ sealedBox: SealedBox, using key: SymmetricKey) throws(CryptoKitMetaError) -> Data {
|
||||
return try AESGCMImpl.open(key: key, sealedBox: sealedBox, authenticatedData: Data?.none)
|
||||
}
|
||||
}
|
||||
@@ -112,7 +119,7 @@ extension AES.GCM {
|
||||
/// The receiver uses another instance of the same cipher, like the
|
||||
/// ``open(_:using:)`` method, to open the box.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SealedBox: AEADSealedBox {
|
||||
public struct SealedBox: AEADSealedBox, Sendable {
|
||||
private let combinedRepresentation: Data
|
||||
private let nonceByteCount: Int
|
||||
|
||||
@@ -167,13 +174,17 @@ extension AES.GCM {
|
||||
/// - combined: The combined bytes of the nonce, encrypted data, and
|
||||
/// authentication tag.
|
||||
@inlinable
|
||||
public init<D: DataProtocol>(combined: D) throws {
|
||||
public init<D: DataProtocol>(combined: D) throws(CryptoKitMetaError) {
|
||||
// AES minimum nonce (12 bytes) + AES tag (16 bytes)
|
||||
// While we have these values in the internal APIs, we can't use it in inlinable code.
|
||||
let aesGCMOverhead = 12 + 16
|
||||
|
||||
if combined.count < aesGCMOverhead {
|
||||
#if hasFeature(Embedded)
|
||||
throw CryptoKitMetaError.cryptoKitError(underlyingError: CryptoKitError.incorrectParameterSize)
|
||||
#else
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
#endif
|
||||
}
|
||||
|
||||
self.init(combined: Data(combined))
|
||||
@@ -185,9 +196,9 @@ extension AES.GCM {
|
||||
/// - nonce: The nonce.
|
||||
/// - ciphertext: The encrypted data.
|
||||
/// - tag: The authentication tag.
|
||||
public init<C: DataProtocol, T: DataProtocol>(nonce: AES.GCM.Nonce, ciphertext: C, tag: T) throws {
|
||||
public init<C: DataProtocol, T: DataProtocol>(nonce: AES.GCM.Nonce, ciphertext: C, tag: T) throws(CryptoKitMetaError) {
|
||||
guard tag.count == AES.GCM.tagByteCount else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
throw error(CryptoKitError.incorrectParameterSize)
|
||||
}
|
||||
|
||||
let nonceByteCount = nonce.bytes.count
|
||||
|
||||
@@ -16,7 +16,11 @@
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
import CryptoBoringWrapper
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
enum OpenSSLAESGCMImpl {
|
||||
|
||||
@@ -17,7 +17,11 @@
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
import CryptoBoringWrapper
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension BoringSSLAEAD {
|
||||
|
||||
@@ -14,20 +14,28 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#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
|
||||
import Security
|
||||
#else
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
typealias ChaChaPolyImpl = OpenSSLChaChaPolyImpl
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
public import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
/// An implementation of the ChaCha20-Poly1305 cipher.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum ChaChaPoly: Cipher {
|
||||
public enum ChaChaPoly: Cipher, Sendable {
|
||||
static let tagByteCount = 16
|
||||
static let keyBitsCount = 256
|
||||
static let nonceByteCount = 12
|
||||
@@ -39,7 +47,7 @@ public enum ChaChaPoly: Cipher {
|
||||
/// - Parameters:
|
||||
/// - message: The plaintext data to seal.
|
||||
/// - key: A cryptographic key used to seal the message.
|
||||
/// - nonce: The nonce the sealing process requires. If you don't provide a nonce, the method generates a random one by invoking ``ChaChaPoly.Nonce()``.
|
||||
/// - nonce: The nonce the sealing process requires. If you don't provide a nonce, the method generates a random one by invoking ``ChaChaPoly/Nonce/init()``.
|
||||
/// - authenticatedData: Additional data to be authenticated.
|
||||
///
|
||||
/// - Returns: The sealed message.
|
||||
@@ -54,7 +62,7 @@ public enum ChaChaPoly: Cipher {
|
||||
/// - Parameters:
|
||||
/// - message: The plaintext data to seal.
|
||||
/// - key: A cryptographic key used to seal the message.
|
||||
/// - nonce: The nonce the sealing process requires. If you don't provide a nonce, the method generates a random one by invoking ``ChaChaPoly.Nonce()``.
|
||||
/// - nonce: The nonce the sealing process requires. If you don't provide a nonce, the method generates a random one by invoking ``ChaChaPoly/Nonce/init()``.
|
||||
///
|
||||
/// - Returns: The sealed message.
|
||||
public static func seal<Plaintext: DataProtocol>
|
||||
@@ -111,7 +119,7 @@ extension ChaChaPoly {
|
||||
/// ``open(_:using:)`` method, to open the box.
|
||||
@frozen
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SealedBox: AEADSealedBox {
|
||||
public struct SealedBox: AEADSealedBox, Sendable {
|
||||
/// A combined element composed of the tag, the nonce, and the
|
||||
/// ciphertext.
|
||||
///
|
||||
|
||||
@@ -14,10 +14,20 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
protocol AEADSealedBox {
|
||||
protocol AEADSealedBox: Sendable {
|
||||
associatedtype Nonce: Sequence
|
||||
/// The authentication tag
|
||||
var tag: Data { get }
|
||||
@@ -52,7 +62,7 @@ protocol Cipher {
|
||||
/// - Returns: The sealed box containing the ciphertext and authentication tag
|
||||
/// - Throws: An error occurred while encrypting or authenticating.
|
||||
static func seal<Plaintext: DataProtocol, AuthenticatedData: DataProtocol>
|
||||
(_ message: Plaintext, using key: SymmetricKey, nonce: Nonce?, authenticating: AuthenticatedData) throws -> SealedBox
|
||||
(_ message: Plaintext, using key: SymmetricKey, nonce: Nonce?, authenticating: AuthenticatedData) throws(CryptoKitMetaError) -> SealedBox
|
||||
|
||||
/// Opens the sealed box. This decrypts and verifies the authenticity of the message,
|
||||
/// and optionally verifies the authenticity of the authenticated data.
|
||||
@@ -65,6 +75,6 @@ protocol Cipher {
|
||||
/// - Returns: Returns the data, if the correct key is used and the authenticated data matches the one from the seal operation.
|
||||
/// - Throws: An error occurred while decrypting or authenticating.
|
||||
static func open<AuthenticatedData: DataProtocol>
|
||||
(_ sealedBox: SealedBox, using key: Key, authenticating: AuthenticatedData) throws -> Data
|
||||
(_ sealedBox: SealedBox, using key: Key, authenticating: AuthenticatedData) throws(CryptoKitMetaError) -> Data
|
||||
}
|
||||
#endif
|
||||
@@ -14,11 +14,22 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
public import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
#endif
|
||||
// MARK: - Generated file, do NOT edit
|
||||
// any edits of this file WILL be overwritten and thus discarded
|
||||
// see section `gyb` in `README` for details.
|
||||
|
||||
|
||||
|
||||
|
||||
// MARK: - AES.GCM + Nonce
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension AES.GCM {
|
||||
@@ -28,7 +39,7 @@ extension AES.GCM {
|
||||
/// that nonces are unique per call to encryption APIs in order to protect the
|
||||
/// integrity of the encryption.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct Nonce: ContiguousBytes, Sequence {
|
||||
public struct Nonce: ContiguousBytes, Sequence, Sendable {
|
||||
let bytes: Data
|
||||
|
||||
/// Creates a new random nonce.
|
||||
@@ -49,11 +60,11 @@ extension AES.GCM {
|
||||
/// ``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 has a length other than 12 bytes.
|
||||
public init<D: DataProtocol>(data: D) throws {
|
||||
/// - data: A data representation of the nonce.
|
||||
/// The initializer throws an error if the data has a length smaller than 12 bytes.
|
||||
public init<D: DataProtocol>(data: D) throws(CryptoKitMetaError) {
|
||||
if data.count < AES.GCM.defaultNonceByteCount {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
throw error(CryptoKitError.incorrectParameterSize)
|
||||
}
|
||||
|
||||
self.bytes = Data(data)
|
||||
@@ -70,10 +81,16 @@ extension AES.GCM {
|
||||
/// 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
|
||||
@@ -92,7 +109,7 @@ extension ChaChaPoly {
|
||||
/// that nonces are unique per call to encryption APIs in order to protect the
|
||||
/// integrity of the encryption.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct Nonce: ContiguousBytes, Sequence {
|
||||
public struct Nonce: ContiguousBytes, Sequence, Sendable {
|
||||
let bytes: Data
|
||||
|
||||
/// Creates a new random nonce.
|
||||
@@ -113,11 +130,11 @@ extension ChaChaPoly {
|
||||
/// ``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 has a length other than 12 bytes.
|
||||
public init<D: DataProtocol>(data: D) throws {
|
||||
/// - data: A 12-byte data representation of the nonce.
|
||||
/// The initializer throws an error if the data isn't 12 bytes long.
|
||||
public init<D: DataProtocol>(data: D) throws(CryptoKitMetaError) {
|
||||
if data.count != ChaChaPoly.nonceByteCount {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
throw error(CryptoKitError.incorrectParameterSize)
|
||||
}
|
||||
|
||||
self.bytes = Data(data)
|
||||
@@ -134,10 +151,16 @@ extension ChaChaPoly {
|
||||
/// 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
|
||||
|
||||
@@ -14,18 +14,35 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
#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"},{"name": "ChaChaPoly", "recommendedNonceSize": "ChaChaPoly.nonceByteCount", "nonceValidation": "!= ChaChaPoly.nonceByteCount"}]
|
||||
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
|
||||
@@ -35,7 +52,7 @@ extension ${name} {
|
||||
/// 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 {
|
||||
public struct Nonce: ContiguousBytes, Sequence, Sendable {
|
||||
let bytes: Data
|
||||
|
||||
/// Creates a new random nonce.
|
||||
@@ -56,11 +73,10 @@ extension ${name} {
|
||||
/// ``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 has a length other than 12 bytes.
|
||||
public init<D: DataProtocol>(data: D) throws {
|
||||
${dataDescription}
|
||||
public init<D: DataProtocol>(data: D) throws(CryptoKitMetaError) {
|
||||
if data.count ${nonceValidation} {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
throw error(CryptoKitError.incorrectParameterSize)
|
||||
}
|
||||
|
||||
self.bytes = Data(data)
|
||||
@@ -77,10 +93,16 @@ extension ${name} {
|
||||
/// 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
|
||||
|
||||
@@ -14,7 +14,16 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// This module implements "just enough" ASN.1. Specifically, we implement exactly enough ASN.1 DER parsing to handle
|
||||
// the following use-cases:
|
||||
@@ -130,20 +139,22 @@ extension ASN1 {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1ParserNode: Hashable { }
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1ParserNode: CustomStringConvertible {
|
||||
var description: String {
|
||||
return "ASN1.ASN1ParserNode(identifier: \(self.identifier), depth: \(self.depth), dataBytes: \(self.dataBytes?.count ?? 0))"
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Sequence, SequenceOf, and Set
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
/// Parse the node as an ASN.1 sequence.
|
||||
internal static func sequence<T>(_ node: ASN1Node, identifier: ASN1.ASN1Identifier, _ builder: (inout ASN1.ASN1NodeCollection.Iterator) throws -> T) throws -> T {
|
||||
internal static func sequence<T>(_ node: ASN1Node, identifier: ASN1.ASN1Identifier, _ builder: (inout ASN1.ASN1NodeCollection.Iterator) throws(CryptoKitMetaError) -> T) throws(CryptoKitMetaError) -> T {
|
||||
guard node.identifier == identifier, case .constructed(let nodes) = node.content else {
|
||||
throw CryptoKitASN1Error.unexpectedFieldType
|
||||
throw error(CryptoKitASN1Error.unexpectedFieldType)
|
||||
}
|
||||
|
||||
var iterator = nodes.makeIterator()
|
||||
@@ -151,31 +162,36 @@ extension ASN1 {
|
||||
let result = try builder(&iterator)
|
||||
|
||||
guard iterator.next() == nil else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
internal static func sequence<T: ASN1Parseable>(of: T.Type = T.self, identifier: ASN1.ASN1Identifier, rootNode: ASN1Node) throws -> [T] {
|
||||
internal static func sequence<T: ASN1Parseable>(of: T.Type = T.self, identifier: ASN1.ASN1Identifier, rootNode: ASN1Node) throws(CryptoKitMetaError) -> [T] {
|
||||
guard rootNode.identifier == identifier, case .constructed(let nodes) = rootNode.content else {
|
||||
throw CryptoKitASN1Error.unexpectedFieldType
|
||||
throw error(CryptoKitASN1Error.unexpectedFieldType)
|
||||
}
|
||||
|
||||
return try nodes.map { try T(asn1Encoded: $0) }
|
||||
var sequence = [T]()
|
||||
// sequence.reserveCapacity(?)
|
||||
for node in nodes {
|
||||
sequence.append(try T(asn1Encoded: node))
|
||||
}
|
||||
return sequence
|
||||
}
|
||||
|
||||
internal static func sequence<T: ASN1Parseable>(of: T.Type = T.self, identifier: ASN1.ASN1Identifier, nodes: inout ASN1.ASN1NodeCollection.Iterator) throws -> [T] {
|
||||
internal static func sequence<T: ASN1Parseable>(of: T.Type = T.self, identifier: ASN1.ASN1Identifier, nodes: inout ASN1.ASN1NodeCollection.Iterator) throws(CryptoKitMetaError) -> [T] {
|
||||
guard let node = nodes.next() else {
|
||||
// Not present, throw.
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
return try sequence(of: T.self, identifier: identifier, rootNode: node)
|
||||
}
|
||||
|
||||
/// Parse the node as an ASN.1 set.
|
||||
internal static func set<T>(_ node: ASN1Node, identifier: ASN1.ASN1Identifier, _ builder: (inout ASN1.ASN1NodeCollection.Iterator) throws -> T) throws -> T {
|
||||
internal static func set<T>(_ node: ASN1Node, identifier: ASN1.ASN1Identifier, _ builder: (inout ASN1.ASN1NodeCollection.Iterator) throws(CryptoKitMetaError) -> T) throws(CryptoKitMetaError) -> T {
|
||||
// Shhhh these two are secretly the same with identifier.
|
||||
return try sequence(node, identifier: identifier, builder)
|
||||
}
|
||||
@@ -187,7 +203,7 @@ extension ASN1 {
|
||||
/// Parses an optional explicitly tagged element. Throws on a tag mismatch, returns nil if the element simply isn't there.
|
||||
///
|
||||
/// Expects to be used with the `ASN1.sequence` helper function.
|
||||
internal static func optionalExplicitlyTagged<T>(_ nodes: inout ASN1.ASN1NodeCollection.Iterator, tagNumber: Int, tagClass: ASN1.ASN1Identifier.TagClass, _ builder: (ASN1Node) throws -> T) throws -> T? {
|
||||
internal static func optionalExplicitlyTagged<T>(_ nodes: inout ASN1.ASN1NodeCollection.Iterator, tagNumber: Int, tagClass: ASN1.ASN1Identifier.TagClass, _ builder: (ASN1Node) throws(CryptoKitMetaError) -> T) throws(CryptoKitMetaError) -> T? {
|
||||
var localNodesCopy = nodes
|
||||
guard let node = localNodesCopy.next() else {
|
||||
// Node not present, return nil.
|
||||
@@ -212,7 +228,7 @@ extension ASN1 {
|
||||
|
||||
var nodeIterator = nodes.makeIterator()
|
||||
guard let child = nodeIterator.next(), nodeIterator.next() == nil else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
return try builder(child)
|
||||
@@ -226,7 +242,7 @@ extension ASN1 {
|
||||
/// be replaced with its default.
|
||||
///
|
||||
/// Expects to be used with the `ASN1.sequence` helper function.
|
||||
internal static func decodeDefault<T: ASN1Parseable & Equatable>(_ nodes: inout ASN1.ASN1NodeCollection.Iterator, identifier: ASN1.ASN1Identifier, defaultValue: T, _ builder: (ASN1Node) throws -> T) throws -> T {
|
||||
internal static func decodeDefault<T: ASN1Parseable & Equatable>(_ nodes: inout ASN1.ASN1NodeCollection.Iterator, identifier: ASN1.ASN1Identifier, defaultValue: T, _ builder: (ASN1Node) throws(CryptoKitMetaError) -> T) throws(CryptoKitMetaError) -> T {
|
||||
// A weird trick here: we only want to consume the next node _if_ it has the right tag. To achieve that,
|
||||
// we work on a copy.
|
||||
var localNodesCopy = nodes
|
||||
@@ -247,18 +263,18 @@ extension ASN1 {
|
||||
// DER forbids encoding DEFAULT values at their default state.
|
||||
// We can lift this in BER.
|
||||
guard parsed != defaultValue else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
return parsed
|
||||
}
|
||||
|
||||
internal static func decodeDefaultExplicitlyTagged<T: ASN1Parseable & Equatable>(_ nodes: inout ASN1.ASN1NodeCollection.Iterator, tagNumber: Int, tagClass: ASN1.ASN1Identifier.TagClass, defaultValue: T, _ builder: (ASN1Node) throws -> T) throws -> T {
|
||||
internal static func decodeDefaultExplicitlyTagged<T: ASN1Parseable & Equatable>(_ nodes: inout ASN1.ASN1NodeCollection.Iterator, tagNumber: Int, tagClass: ASN1.ASN1Identifier.TagClass, defaultValue: T, _ builder: (ASN1Node) throws(CryptoKitMetaError) -> T) throws(CryptoKitMetaError) -> T {
|
||||
if let result = try optionalExplicitlyTagged(&nodes, tagNumber: tagNumber, tagClass: tagClass, builder) {
|
||||
guard result != defaultValue else {
|
||||
// DER forbids encoding DEFAULT values at their default state.
|
||||
// We can lift this in BER.
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
return result
|
||||
@@ -282,46 +298,46 @@ extension ASN1 {
|
||||
self.nodes = nodes
|
||||
}
|
||||
|
||||
fileprivate static func parse(_ data: ArraySlice<UInt8>) throws -> ASN1ParseResult {
|
||||
fileprivate static func parse(_ data: ArraySlice<UInt8>) throws(CryptoKitMetaError) -> ASN1ParseResult {
|
||||
var data = data
|
||||
var nodes = [ASN1ParserNode]()
|
||||
nodes.reserveCapacity(16)
|
||||
|
||||
try parseNode(from: &data, depth: 1, into: &nodes)
|
||||
guard data.count == 0 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
return ASN1ParseResult(nodes[...])
|
||||
}
|
||||
|
||||
/// Parses a single ASN.1 node from the data and appends it to the buffer. This may recursively
|
||||
/// call itself when there are child nodes for constructed nodes.
|
||||
private static func parseNode(from data: inout ArraySlice<UInt8>, depth: Int, into nodes: inout [ASN1ParserNode]) throws {
|
||||
private static func parseNode(from data: inout ArraySlice<UInt8>, depth: Int, into nodes: inout [ASN1ParserNode]) throws(CryptoKitMetaError) {
|
||||
guard depth <= ASN1.ASN1ParseResult.maximumNodeDepth else {
|
||||
// We defend ourselves against stack overflow by refusing to allocate more than 10 stack frames to
|
||||
// the parsing.
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
guard let rawIdentifier = data.popFirst() else {
|
||||
throw CryptoKitASN1Error.truncatedASN1Field
|
||||
throw error(CryptoKitASN1Error.truncatedASN1Field)
|
||||
}
|
||||
|
||||
let identifier = try ASN1Identifier(rawIdentifier: rawIdentifier)
|
||||
guard let wideLength = try data.readASN1Length() else {
|
||||
throw CryptoKitASN1Error.truncatedASN1Field
|
||||
throw error(CryptoKitASN1Error.truncatedASN1Field)
|
||||
}
|
||||
|
||||
// UInt is sometimes too large for us!
|
||||
guard let length = Int(exactly: wideLength) else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
var subData = data.prefix(length)
|
||||
data = data.dropFirst(length)
|
||||
|
||||
guard subData.count == length else {
|
||||
throw CryptoKitASN1Error.truncatedASN1Field
|
||||
throw error(CryptoKitASN1Error.truncatedASN1Field)
|
||||
}
|
||||
|
||||
if identifier.constructed {
|
||||
@@ -341,11 +357,11 @@ extension ASN1.ASN1ParseResult: Hashable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
static func parse(_ data: [UInt8]) throws -> ASN1Node {
|
||||
static func parse(_ data: [UInt8]) throws(CryptoKitMetaError) -> ASN1Node {
|
||||
return try parse(data[...])
|
||||
}
|
||||
|
||||
static func parse(_ data: ArraySlice<UInt8>) throws -> ASN1Node {
|
||||
static func parse(_ data: ArraySlice<UInt8>) throws(CryptoKitMetaError) -> ASN1Node {
|
||||
var result = try ASN1ParseResult.parse(data)
|
||||
|
||||
// There will always be at least one node if the above didn't throw, so we can safely just removeFirst here.
|
||||
@@ -471,48 +487,50 @@ extension ASN1 {
|
||||
}
|
||||
|
||||
/// Appends a single, non-constructed node to the content.
|
||||
mutating func appendPrimitiveNode(identifier: ASN1.ASN1Identifier, _ contentWriter: (inout [UInt8]) throws -> Void) rethrows {
|
||||
mutating func appendPrimitiveNode(identifier: ASN1.ASN1Identifier, _ contentWriter: (inout [UInt8]) throws(CryptoKitMetaError) -> Void) throws(CryptoKitMetaError) {
|
||||
assert(identifier.primitive)
|
||||
try self._appendNode(identifier: identifier) { try contentWriter(&$0.serializedBytes) }
|
||||
try self._appendNode(identifier: identifier) { coder throws(CryptoKitMetaError) in
|
||||
try contentWriter(&coder.serializedBytes)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func appendConstructedNode(identifier: ASN1.ASN1Identifier, _ contentWriter: (inout Serializer) throws -> Void) rethrows {
|
||||
mutating func appendConstructedNode(identifier: ASN1.ASN1Identifier, _ contentWriter: (inout Serializer) throws(CryptoKitMetaError) -> Void) throws(CryptoKitMetaError) {
|
||||
assert(identifier.constructed)
|
||||
try self._appendNode(identifier: identifier, contentWriter)
|
||||
}
|
||||
|
||||
mutating func serialize<T: ASN1Serializable>(_ node: T) throws {
|
||||
mutating func serialize<T: ASN1Serializable>(_ node: T) throws(CryptoKitMetaError) {
|
||||
try node.serialize(into: &self)
|
||||
}
|
||||
|
||||
mutating func serialize<T: ASN1Serializable>(_ node: T, explicitlyTaggedWithTagNumber tagNumber: Int, tagClass: ASN1.ASN1Identifier.TagClass) throws {
|
||||
return try self.serialize(explicitlyTaggedWithTagNumber: tagNumber, tagClass: tagClass) { coder in
|
||||
mutating func serialize<T: ASN1Serializable>(_ node: T, explicitlyTaggedWithTagNumber tagNumber: Int, tagClass: ASN1.ASN1Identifier.TagClass) throws(CryptoKitMetaError) {
|
||||
return try self.serialize(explicitlyTaggedWithTagNumber: tagNumber, tagClass: tagClass) { coder throws(CryptoKitMetaError) in
|
||||
try coder.serialize(node)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func serialize(explicitlyTaggedWithTagNumber tagNumber: Int, tagClass: ASN1.ASN1Identifier.TagClass, _ block: (inout Serializer) throws -> Void) rethrows {
|
||||
mutating func serialize(explicitlyTaggedWithTagNumber tagNumber: Int, tagClass: ASN1.ASN1Identifier.TagClass, _ block: (inout Serializer) throws(CryptoKitMetaError) -> Void) throws(CryptoKitMetaError) {
|
||||
let identifier = ASN1Identifier(explicitTagWithNumber: tagNumber, tagClass: tagClass)
|
||||
try self.appendConstructedNode(identifier: identifier) { coder in
|
||||
try self.appendConstructedNode(identifier: identifier) { coder throws(CryptoKitMetaError) in
|
||||
try block(&coder)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func serializeSequenceOf<Elements: Sequence>(_ elements: Elements, identifier: ASN1.ASN1Identifier = .sequence) throws where Elements.Element: ASN1Serializable {
|
||||
try self.appendConstructedNode(identifier: identifier) { coder in
|
||||
mutating func serializeSequenceOf<Elements: Sequence>(_ elements: Elements, identifier: ASN1.ASN1Identifier = .sequence) throws(CryptoKitMetaError) where Elements.Element: ASN1Serializable {
|
||||
try self.appendConstructedNode(identifier: identifier) { coder throws(CryptoKitMetaError) in
|
||||
for element in elements {
|
||||
try coder.serialize(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mutating func serialize(_ node: ASN1.ASN1Node) {
|
||||
mutating func serialize(_ node: ASN1.ASN1Node) throws(CryptoKitMetaError) {
|
||||
let identifier = node.identifier
|
||||
self._appendNode(identifier: identifier) { coder in
|
||||
try self._appendNode(identifier: identifier) { coder throws(CryptoKitMetaError) in
|
||||
switch node.content {
|
||||
case .constructed(let nodes):
|
||||
for node in nodes {
|
||||
coder.serialize(node)
|
||||
try coder.serialize(node)
|
||||
}
|
||||
case .primitive(let baseData):
|
||||
coder.serializedBytes.append(contentsOf: baseData)
|
||||
@@ -522,7 +540,7 @@ extension ASN1 {
|
||||
|
||||
// This is the base logical function that all other append methods are built on. This one has most of the logic, and doesn't
|
||||
// police what we expect to happen in the content writer.
|
||||
private mutating func _appendNode(identifier: ASN1.ASN1Identifier, _ contentWriter: (inout Serializer) throws -> Void) rethrows {
|
||||
private mutating func _appendNode(identifier: ASN1.ASN1Identifier, _ contentWriter: (inout Serializer) throws(CryptoKitMetaError) -> Void) throws(CryptoKitMetaError) {
|
||||
// This is a tricky game to play. We want to write the identifier and the length, but we don't know what the
|
||||
// length is here. To get around that, we _assume_ the length will be one byte, and let the writer write their content.
|
||||
// If it turns out to have been longer, we recalculate how many bytes we need and shuffle them in the buffer,
|
||||
@@ -570,31 +588,31 @@ extension ASN1 {
|
||||
// MARK: - Helpers
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal protocol ASN1Parseable {
|
||||
init(asn1Encoded: ASN1.ASN1Node) throws
|
||||
init(asn1Encoded: ASN1.ASN1Node) throws(CryptoKitMetaError)
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1Parseable {
|
||||
internal init(asn1Encoded sequenceNodeIterator: inout ASN1.ASN1NodeCollection.Iterator) throws {
|
||||
internal init(asn1Encoded sequenceNodeIterator: inout ASN1.ASN1NodeCollection.Iterator) throws(CryptoKitMetaError) {
|
||||
guard let node = sequenceNodeIterator.next() else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
self = try .init(asn1Encoded: node)
|
||||
}
|
||||
|
||||
internal init(asn1Encoded: [UInt8]) throws {
|
||||
internal init(asn1Encoded: [UInt8]) throws(CryptoKitMetaError) {
|
||||
self = try .init(asn1Encoded: ASN1.parse(asn1Encoded))
|
||||
}
|
||||
|
||||
internal init(asn1Encoded: ArraySlice<UInt8>) throws {
|
||||
internal init(asn1Encoded: ArraySlice<UInt8>) throws(CryptoKitMetaError) {
|
||||
self = try .init(asn1Encoded: ASN1.parse(asn1Encoded))
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal protocol ASN1Serializable {
|
||||
func serialize(into coder: inout ASN1.Serializer) throws
|
||||
func serialize(into coder: inout ASN1.Serializer) throws(CryptoKitMetaError)
|
||||
}
|
||||
|
||||
/// Covers ASN.1 types that may be implicitly tagged. Not all nodes can be!
|
||||
@@ -604,42 +622,42 @@ internal protocol ASN1ImplicitlyTaggable: ASN1Parseable, ASN1Serializable {
|
||||
/// any more specific tag definition.
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier { get }
|
||||
|
||||
init(asn1Encoded: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws
|
||||
init(asn1Encoded: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError)
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError)
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1ImplicitlyTaggable {
|
||||
internal init(asn1Encoded sequenceNodeIterator: inout ASN1.ASN1NodeCollection.Iterator,
|
||||
withIdentifier identifier: ASN1.ASN1Identifier = Self.defaultIdentifier) throws {
|
||||
withIdentifier identifier: ASN1.ASN1Identifier = Self.defaultIdentifier) throws(CryptoKitMetaError) {
|
||||
guard let node = sequenceNodeIterator.next() else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
self = try .init(asn1Encoded: node, withIdentifier: identifier)
|
||||
}
|
||||
|
||||
internal init(asn1Encoded: [UInt8], withIdentifier identifier: ASN1.ASN1Identifier = Self.defaultIdentifier) throws {
|
||||
internal init(asn1Encoded: [UInt8], withIdentifier identifier: ASN1.ASN1Identifier = Self.defaultIdentifier) throws(CryptoKitMetaError) {
|
||||
self = try .init(asn1Encoded: ASN1.parse(asn1Encoded), withIdentifier: identifier)
|
||||
}
|
||||
|
||||
internal init(asn1Encoded: ArraySlice<UInt8>, withIdentifier identifier: ASN1.ASN1Identifier = Self.defaultIdentifier) throws {
|
||||
internal init(asn1Encoded: ArraySlice<UInt8>, withIdentifier identifier: ASN1.ASN1Identifier = Self.defaultIdentifier) throws(CryptoKitMetaError) {
|
||||
self = try .init(asn1Encoded: ASN1.parse(asn1Encoded), withIdentifier: identifier)
|
||||
}
|
||||
|
||||
init(asn1Encoded: ASN1.ASN1Node) throws {
|
||||
init(asn1Encoded: ASN1.ASN1Node) throws(CryptoKitMetaError) {
|
||||
try self.init(asn1Encoded: asn1Encoded, withIdentifier: Self.defaultIdentifier)
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer) throws {
|
||||
func serialize(into coder: inout ASN1.Serializer) throws(CryptoKitMetaError) {
|
||||
try self.serialize(into: &coder, withIdentifier: Self.defaultIdentifier)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ArraySlice where Element == UInt8 {
|
||||
fileprivate mutating func readASN1Length() throws -> UInt? {
|
||||
fileprivate mutating func readASN1Length() throws(CryptoKitMetaError) -> UInt? {
|
||||
guard let firstByte = self.popFirst() else {
|
||||
return nil
|
||||
}
|
||||
@@ -647,7 +665,7 @@ extension ArraySlice where Element == UInt8 {
|
||||
switch firstByte {
|
||||
case 0x80:
|
||||
// Indefinite form. Unsupported.
|
||||
throw CryptoKitASN1Error.unsupportedFieldLength
|
||||
throw error(CryptoKitASN1Error.unsupportedFieldLength)
|
||||
case let val where val & 0x80 == 0x80:
|
||||
// Top bit is set, this is the long form. The remaining 7 bits of this octet
|
||||
// determine how long the length field is.
|
||||
@@ -666,16 +684,16 @@ extension ArraySlice where Element == UInt8 {
|
||||
switch requiredBits {
|
||||
case 0...7:
|
||||
// For 0 to 7 bits, the long form is unacceptable and we require the short.
|
||||
throw CryptoKitASN1Error.unsupportedFieldLength
|
||||
throw error(CryptoKitASN1Error.unsupportedFieldLength)
|
||||
case 8...:
|
||||
// For 8 or more bits, fieldLength should be the minimum required.
|
||||
let requiredBytes = (requiredBits + 7) / 8
|
||||
if fieldLength > requiredBytes {
|
||||
throw CryptoKitASN1Error.unsupportedFieldLength
|
||||
throw error(CryptoKitASN1Error.unsupportedFieldLength)
|
||||
}
|
||||
default:
|
||||
// This is not reachable, but we'll error anyway.
|
||||
throw CryptoKitASN1Error.unsupportedFieldLength
|
||||
throw error(CryptoKitASN1Error.unsupportedFieldLength)
|
||||
}
|
||||
|
||||
return length
|
||||
@@ -688,9 +706,9 @@ extension ArraySlice where Element == UInt8 {
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension FixedWidthInteger {
|
||||
internal init<Bytes: Collection>(bigEndianBytes bytes: Bytes) throws where Bytes.Element == UInt8 {
|
||||
internal init<Bytes: Collection>(bigEndianBytes bytes: Bytes) throws(CryptoKitMetaError) where Bytes.Element == UInt8 {
|
||||
guard bytes.count <= (Self.bitWidth / 8) else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
self = 0
|
||||
|
||||
@@ -14,7 +14,16 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
@@ -29,28 +38,28 @@ extension ASN1 {
|
||||
struct ASN1Any: ASN1Parseable, ASN1Serializable, Hashable {
|
||||
fileprivate var serializedBytes: ArraySlice<UInt8>
|
||||
|
||||
init<ASN1Type: ASN1Serializable>(erasing: ASN1Type) throws {
|
||||
init<ASN1Type: ASN1Serializable>(erasing: ASN1Type) throws(CryptoKitMetaError) {
|
||||
var serializer = ASN1.Serializer()
|
||||
try erasing.serialize(into: &serializer)
|
||||
self.serializedBytes = ArraySlice(serializer.serializedBytes)
|
||||
}
|
||||
|
||||
init<ASN1Type: ASN1ImplicitlyTaggable>(erasing: ASN1Type, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
init<ASN1Type: ASN1ImplicitlyTaggable>(erasing: ASN1Type, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
var serializer = ASN1.Serializer()
|
||||
try erasing.serialize(into: &serializer, withIdentifier: identifier)
|
||||
self.serializedBytes = ArraySlice(serializer.serializedBytes)
|
||||
}
|
||||
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node) {
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node) throws(CryptoKitMetaError) {
|
||||
// This is a bit sad: we just re-serialize this data. In an ideal world
|
||||
// we'd update the parse representation so that all nodes can point at their
|
||||
// complete backing storage, but for now this is better.
|
||||
var serializer = ASN1.Serializer()
|
||||
serializer.serialize(rootNode)
|
||||
try serializer.serialize(rootNode)
|
||||
self.serializedBytes = ArraySlice(serializer.serializedBytes)
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer) throws {
|
||||
func serialize(into coder: inout ASN1.Serializer) throws(CryptoKitMetaError) {
|
||||
// Dangerous to just reach in there like this, but it's the right way to serialize this.
|
||||
coder.serializedBytes.append(contentsOf: self.serializedBytes)
|
||||
}
|
||||
@@ -59,14 +68,14 @@ extension ASN1 {
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1Parseable {
|
||||
init(asn1Any: ASN1.ASN1Any) throws {
|
||||
init(asn1Any: ASN1.ASN1Any) throws(CryptoKitMetaError) {
|
||||
try self.init(asn1Encoded: asn1Any.serializedBytes)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1ImplicitlyTaggable {
|
||||
init(asn1Any: ASN1.ASN1Any, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
init(asn1Any: ASN1.ASN1Any, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
try self.init(asn1Encoded: asn1Any.serializedBytes, withIdentifier: identifier)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,16 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
@@ -27,9 +36,9 @@ extension ASN1 {
|
||||
|
||||
var bytes: ArraySlice<UInt8>
|
||||
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
guard node.identifier == identifier else {
|
||||
throw CryptoKitASN1Error.unexpectedFieldType
|
||||
throw error(CryptoKitASN1Error.unexpectedFieldType)
|
||||
}
|
||||
|
||||
guard case .primitive(let content) = node.content else {
|
||||
@@ -39,7 +48,7 @@ extension ASN1 {
|
||||
// The initial octet explains how many of the bits in the _final_ octet are not part of the bitstring.
|
||||
// The only value we support here is 0.
|
||||
guard content.first == 0 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
self.bytes = content.dropFirst()
|
||||
@@ -49,8 +58,8 @@ extension ASN1 {
|
||||
self.bytes = bytes
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
coder.appendPrimitiveNode(identifier: identifier) { bytes in
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
try coder.appendPrimitiveNode(identifier: identifier) { bytes in
|
||||
bytes.append(0)
|
||||
bytes.append(contentsOf: self.bytes)
|
||||
}
|
||||
@@ -63,9 +72,15 @@ extension ASN1.ASN1BitString: Hashable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1BitString: ContiguousBytes {
|
||||
#if hasFeature(Embedded)
|
||||
func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
#else
|
||||
func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -14,7 +14,16 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Bool: ASN1ImplicitlyTaggable {
|
||||
@@ -22,13 +31,13 @@ extension Bool: ASN1ImplicitlyTaggable {
|
||||
.boolean
|
||||
}
|
||||
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
guard node.identifier == identifier else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
guard case .primitive(let bytes) = node.content, bytes.count == 1 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
switch bytes[bytes.startIndex] {
|
||||
@@ -40,12 +49,12 @@ extension Bool: ASN1ImplicitlyTaggable {
|
||||
self = true
|
||||
default:
|
||||
// If we come to support BER then these values are all "true" as well.
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
coder.appendPrimitiveNode(identifier: identifier) { bytes in
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
try coder.appendPrimitiveNode(identifier: identifier) { bytes in
|
||||
if self {
|
||||
bytes.append(0xff)
|
||||
} else {
|
||||
|
||||
@@ -14,7 +14,16 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
@@ -59,10 +68,10 @@ extension ASN1 {
|
||||
}
|
||||
}
|
||||
|
||||
init(rawIdentifier: UInt8) throws {
|
||||
init(rawIdentifier: UInt8) throws(CryptoKitMetaError) {
|
||||
// We don't support multibyte identifiers, which are signalled when the bottom 5 bits are all 1.
|
||||
guard rawIdentifier & 0x1F != 0x1F else {
|
||||
throw CryptoKitASN1Error.invalidFieldIdentifier
|
||||
throw error(CryptoKitASN1Error.invalidFieldIdentifier)
|
||||
}
|
||||
|
||||
self.baseTag = rawIdentifier
|
||||
@@ -141,11 +150,13 @@ extension ASN1.ASN1Identifier {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1Identifier: Hashable { }
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1Identifier: CustomStringConvertible {
|
||||
var description: String {
|
||||
return "ASN1Identifier(\(self.baseTag))"
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -14,10 +14,19 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
/// A protocol that represents any internal object that can present itself as an INTEGER, or be parsed from
|
||||
/// an INTEGER.
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/// A protocol that represents any internal object that can present itself as a INTEGER, or be parsed from
|
||||
/// a INTEGER.
|
||||
///
|
||||
/// 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
|
||||
@@ -30,9 +39,9 @@ protocol ASN1IntegerRepresentable: ASN1ImplicitlyTaggable {
|
||||
/// parser will automatically handle padding with leading zero bytes as needed.
|
||||
static var isSigned: Bool { get }
|
||||
|
||||
init(asn1IntegerBytes: ArraySlice<UInt8>) throws
|
||||
init(asn1IntegerBytes: ArraySlice<UInt8>) throws(CryptoKitMetaError)
|
||||
|
||||
func withBigEndianIntegerBytes<ReturnType>(_ body: (IntegerBytes) throws -> ReturnType) rethrows -> 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, *)
|
||||
@@ -41,9 +50,9 @@ extension ASN1IntegerRepresentable {
|
||||
.integer
|
||||
}
|
||||
|
||||
internal init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
internal init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
guard node.identifier == identifier else {
|
||||
throw CryptoKitASN1Error.unexpectedFieldType
|
||||
throw error(CryptoKitASN1Error.unexpectedFieldType)
|
||||
}
|
||||
|
||||
guard case .primitive(var dataBytes) = node.content else {
|
||||
@@ -52,7 +61,7 @@ extension ASN1IntegerRepresentable {
|
||||
|
||||
// Zero bytes of integer is not an acceptable encoding.
|
||||
guard dataBytes.count > 0 else {
|
||||
throw CryptoKitASN1Error.invalidASN1IntegerEncoding
|
||||
throw error(CryptoKitASN1Error.invalidASN1IntegerEncoding)
|
||||
}
|
||||
|
||||
// 8.3.2 If the contents octets of an integer value encoding consist of more than one octet, then the bits of the first octet and bit 8 of the second octet:
|
||||
@@ -64,7 +73,7 @@ extension ASN1IntegerRepresentable {
|
||||
if let first = dataBytes.first, let second = dataBytes.dropFirst().first {
|
||||
if (first == 0xFF) && second.topBitSet ||
|
||||
(first == 0x00) && !second.topBitSet {
|
||||
throw CryptoKitASN1Error.invalidASN1IntegerEncoding
|
||||
throw error(CryptoKitASN1Error.invalidASN1IntegerEncoding)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,16 +83,16 @@ extension ASN1IntegerRepresentable {
|
||||
if first == 0x00 {
|
||||
dataBytes = dataBytes.dropFirst()
|
||||
} else if first & 0x80 == 0x80 {
|
||||
throw CryptoKitASN1Error.invalidASN1IntegerEncoding
|
||||
throw error(CryptoKitASN1Error.invalidASN1IntegerEncoding)
|
||||
}
|
||||
}
|
||||
|
||||
self = try Self(asn1IntegerBytes: dataBytes)
|
||||
}
|
||||
|
||||
internal func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
coder.appendPrimitiveNode(identifier: identifier) { bytes in
|
||||
self.withBigEndianIntegerBytes { integerBytes in
|
||||
internal func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
try coder.appendPrimitiveNode(identifier: identifier) { bytes throws(CryptoKitMetaError) in
|
||||
try self.withBigEndianIntegerBytes { integerBytes throws(CryptoKitMetaError) in
|
||||
// If the number of bytes is 0, we're encoding a zero. That actually _does_ require one byte.
|
||||
if integerBytes.count == 0 {
|
||||
bytes.append(0)
|
||||
@@ -106,7 +115,7 @@ extension ASN1IntegerRepresentable {
|
||||
// MARK: - Auto-conformance for FixedWidthInteger with fixed width magnitude.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1IntegerRepresentable where Self: FixedWidthInteger {
|
||||
init(asn1IntegerBytes bytes: ArraySlice<UInt8>) throws {
|
||||
init(asn1IntegerBytes bytes: ArraySlice<UInt8>) throws(CryptoKitMetaError) {
|
||||
// Defer to the FixedWidthInteger constructor.
|
||||
// There's a wrinkle here: if this is a signed integer, and the top bit of the data bytes was set,
|
||||
// then we need to 1-extend the bytes. This is because ASN.1 tries to delete redundant bytes that
|
||||
@@ -120,7 +129,7 @@ extension ASN1IntegerRepresentable where Self: FixedWidthInteger {
|
||||
}
|
||||
}
|
||||
|
||||
func withBigEndianIntegerBytes<ReturnType>(_ body: (IntegerBytesCollection<Self>) throws -> ReturnType) rethrows -> ReturnType {
|
||||
func withBigEndianIntegerBytes<ReturnType>(_ body: (IntegerBytesCollection<Self>) throws(CryptoKitMetaError) -> ReturnType) throws(CryptoKitMetaError) -> ReturnType {
|
||||
return try body(IntegerBytesCollection(self))
|
||||
}
|
||||
}
|
||||
@@ -205,24 +214,34 @@ extension IntegerBytesCollection.Index: Strideable {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Int8: ASN1IntegerRepresentable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension UInt8: ASN1IntegerRepresentable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Int16: ASN1IntegerRepresentable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension UInt16: ASN1IntegerRepresentable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Int32: ASN1IntegerRepresentable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension UInt32: ASN1IntegerRepresentable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Int64: ASN1IntegerRepresentable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension UInt64: ASN1IntegerRepresentable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Int: ASN1IntegerRepresentable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension UInt: ASN1IntegerRepresentable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
|
||||
@@ -14,7 +14,16 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
@@ -27,18 +36,18 @@ extension ASN1 {
|
||||
|
||||
init() { }
|
||||
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
guard node.identifier == identifier, case .primitive(let content) = node.content else {
|
||||
throw CryptoKitASN1Error.unexpectedFieldType
|
||||
throw error(CryptoKitASN1Error.unexpectedFieldType)
|
||||
}
|
||||
|
||||
guard content.count == 0 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) {
|
||||
coder.appendPrimitiveNode(identifier: identifier, { _ in })
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
try coder.appendPrimitiveNode(identifier: identifier, { _ in })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,16 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
@@ -27,9 +36,9 @@ extension ASN1 {
|
||||
|
||||
var bytes: ArraySlice<UInt8>
|
||||
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
guard node.identifier == identifier else {
|
||||
throw CryptoKitASN1Error.unexpectedFieldType
|
||||
throw error(CryptoKitASN1Error.unexpectedFieldType)
|
||||
}
|
||||
|
||||
guard case .primitive(let content) = node.content else {
|
||||
@@ -43,8 +52,8 @@ extension ASN1 {
|
||||
self.bytes = contentBytes
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
coder.appendPrimitiveNode(identifier: identifier) { bytes in
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
try coder.appendPrimitiveNode(identifier: identifier) { bytes in
|
||||
bytes.append(contentsOf: self.bytes)
|
||||
}
|
||||
}
|
||||
@@ -56,9 +65,15 @@ extension ASN1.ASN1OctetString: Hashable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1OctetString: ContiguousBytes {
|
||||
#if hasFeature(Embedded)
|
||||
func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
#else
|
||||
func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -14,21 +14,46 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
private func contents(of string: StaticString) -> ArraySlice<UInt8> {
|
||||
if string.hasPointerRepresentation {
|
||||
return ArraySlice(
|
||||
UnsafeBufferPointer(start: string.utf8Start, count: string.utf8CodeUnitCount)
|
||||
)
|
||||
} else {
|
||||
return string.withUTF8Buffer { ptr in
|
||||
// Here ptr points to a word-sized temporary value that holds the
|
||||
// UTF-8 representation of the single Unicode codepoint held in `string`.
|
||||
// We need to copy this because it's only valid inside the closure.
|
||||
ArraySlice(Array(ptr))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
/// A UTF8String is roughly what it sounds like. We note that all the string types are encoded as implicitly tagged
|
||||
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct ASN1UTF8String: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes, ExpressibleByStringLiteral {
|
||||
struct ASN1UTF8String: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.primitiveUTF8String
|
||||
}
|
||||
|
||||
var bytes: ArraySlice<UInt8>
|
||||
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
self.bytes = try ASN1OctetString(asn1Encoded: node, withIdentifier: identifier).bytes
|
||||
}
|
||||
|
||||
@@ -36,35 +61,43 @@ extension ASN1 {
|
||||
self.bytes = contentBytes
|
||||
}
|
||||
|
||||
init(stringLiteral value: StringLiteralType) {
|
||||
self.bytes = ArraySlice(value.utf8)
|
||||
#if hasFeature(Embedded)
|
||||
init(_ string: StaticString) {
|
||||
self.bytes = contents(of: string)
|
||||
}
|
||||
|
||||
#else
|
||||
init(_ string: String) {
|
||||
self.bytes = ArraySlice(string.utf8)
|
||||
}
|
||||
#endif
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
let octet = ASN1OctetString(contentBytes: self.bytes)
|
||||
try octet.serialize(into: &coder, withIdentifier: identifier)
|
||||
}
|
||||
|
||||
#if hasFeature(Embedded)
|
||||
func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
#else
|
||||
func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// We note that all the string types are encoded as implicitly tagged
|
||||
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct ASN1TeletexString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes, ExpressibleByStringLiteral {
|
||||
struct ASN1TeletexString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.primitiveTeletexString
|
||||
}
|
||||
|
||||
var bytes: ArraySlice<UInt8>
|
||||
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
self.bytes = try ASN1OctetString(asn1Encoded: node, withIdentifier: identifier).bytes
|
||||
}
|
||||
|
||||
@@ -72,35 +105,43 @@ extension ASN1 {
|
||||
self.bytes = contentBytes
|
||||
}
|
||||
|
||||
init(stringLiteral value: StringLiteralType) {
|
||||
self.bytes = ArraySlice(value.utf8)
|
||||
#if hasFeature(Embedded)
|
||||
init(_ string: StaticString) {
|
||||
self.bytes = contents(of: string)
|
||||
}
|
||||
|
||||
#else
|
||||
init(_ string: String) {
|
||||
self.bytes = ArraySlice(string.utf8)
|
||||
}
|
||||
#endif
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
let octet = ASN1OctetString(contentBytes: self.bytes)
|
||||
try octet.serialize(into: &coder, withIdentifier: identifier)
|
||||
}
|
||||
|
||||
#if hasFeature(Embedded)
|
||||
func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
#else
|
||||
func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// We note that all the string types are encoded as implicitly tagged
|
||||
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct ASN1PrintableString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes, ExpressibleByStringLiteral {
|
||||
struct ASN1PrintableString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.primitivePrintableString
|
||||
}
|
||||
|
||||
var bytes: ArraySlice<UInt8>
|
||||
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
self.bytes = try ASN1OctetString(asn1Encoded: node, withIdentifier: identifier).bytes
|
||||
}
|
||||
|
||||
@@ -108,35 +149,43 @@ extension ASN1 {
|
||||
self.bytes = contentBytes
|
||||
}
|
||||
|
||||
init(stringLiteral value: StringLiteralType) {
|
||||
self.bytes = ArraySlice(value.utf8)
|
||||
#if hasFeature(Embedded)
|
||||
init(_ string: StaticString) {
|
||||
self.bytes = contents(of: string)
|
||||
}
|
||||
|
||||
#else
|
||||
init(_ string: String) {
|
||||
self.bytes = ArraySlice(string.utf8)
|
||||
}
|
||||
#endif
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
let octet = ASN1OctetString(contentBytes: self.bytes)
|
||||
try octet.serialize(into: &coder, withIdentifier: identifier)
|
||||
}
|
||||
|
||||
#if hasFeature(Embedded)
|
||||
func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
#else
|
||||
func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// We note that all the string types are encoded as implicitly tagged
|
||||
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct ASN1UniversalString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes, ExpressibleByStringLiteral {
|
||||
struct ASN1UniversalString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.primitiveUniversalString
|
||||
}
|
||||
|
||||
var bytes: ArraySlice<UInt8>
|
||||
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
self.bytes = try ASN1OctetString(asn1Encoded: node, withIdentifier: identifier).bytes
|
||||
}
|
||||
|
||||
@@ -144,35 +193,43 @@ extension ASN1 {
|
||||
self.bytes = contentBytes
|
||||
}
|
||||
|
||||
init(stringLiteral value: StringLiteralType) {
|
||||
self.bytes = ArraySlice(value.utf8)
|
||||
#if hasFeature(Embedded)
|
||||
init(_ string: StaticString) {
|
||||
self.bytes = contents(of: string)
|
||||
}
|
||||
|
||||
#else
|
||||
init(_ string: String) {
|
||||
self.bytes = ArraySlice(string.utf8)
|
||||
}
|
||||
#endif
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
let octet = ASN1OctetString(contentBytes: self.bytes)
|
||||
try octet.serialize(into: &coder, withIdentifier: identifier)
|
||||
}
|
||||
|
||||
#if hasFeature(Embedded)
|
||||
func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
#else
|
||||
func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// We note that all the string types are encoded as implicitly tagged
|
||||
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct ASN1BMPString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes, ExpressibleByStringLiteral {
|
||||
struct ASN1BMPString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.primitiveBMPString
|
||||
}
|
||||
|
||||
var bytes: ArraySlice<UInt8>
|
||||
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
self.bytes = try ASN1OctetString(asn1Encoded: node, withIdentifier: identifier).bytes
|
||||
}
|
||||
|
||||
@@ -180,23 +237,69 @@ extension ASN1 {
|
||||
self.bytes = contentBytes
|
||||
}
|
||||
|
||||
init(stringLiteral value: StringLiteralType) {
|
||||
self.bytes = ArraySlice(value.utf8)
|
||||
#if hasFeature(Embedded)
|
||||
init(_ string: StaticString) {
|
||||
self.bytes = contents(of: string)
|
||||
}
|
||||
|
||||
#else
|
||||
init(_ string: String) {
|
||||
self.bytes = ArraySlice(string.utf8)
|
||||
}
|
||||
#endif
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
let octet = ASN1OctetString(contentBytes: self.bytes)
|
||||
try octet.serialize(into: &coder, withIdentifier: identifier)
|
||||
}
|
||||
|
||||
#if hasFeature(Embedded)
|
||||
func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
#else
|
||||
func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1TeletexString: ExpressibleByStringLiteral {
|
||||
public init(stringLiteral value: StringLiteralType) {
|
||||
self.bytes = ArraySlice(value.utf8)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1UTF8String: ExpressibleByStringLiteral {
|
||||
public init(stringLiteral value: StringLiteralType) {
|
||||
self.bytes = ArraySlice(value.utf8)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1PrintableString: ExpressibleByStringLiteral {
|
||||
public init(stringLiteral value: StringLiteralType) {
|
||||
self.bytes = ArraySlice(value.utf8)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1UniversalString: ExpressibleByStringLiteral {
|
||||
public init(stringLiteral value: StringLiteralType) {
|
||||
self.bytes = ArraySlice(value.utf8)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1BMPString: ExpressibleByStringLiteral {
|
||||
public init(stringLiteral value: StringLiteralType) {
|
||||
self.bytes = ArraySlice(value.utf8)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -15,11 +15,24 @@
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// For temporary purposes we pretend that ArraySlice is our "bigint" type. We don't really need anything else.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ArraySlice: ASN1Serializable where Element == UInt8 { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ArraySlice: ASN1Parseable where Element == UInt8 { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ArraySlice: ASN1ImplicitlyTaggable where Element == UInt8 { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
@@ -29,11 +42,11 @@ extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 {
|
||||
return false
|
||||
}
|
||||
|
||||
init(asn1IntegerBytes: ArraySlice<UInt8>) throws {
|
||||
init(asn1IntegerBytes: ArraySlice<UInt8>) throws(CryptoKitMetaError) {
|
||||
self = asn1IntegerBytes
|
||||
}
|
||||
|
||||
func withBigEndianIntegerBytes<ReturnType>(_ body: (ArraySlice<UInt8>) throws -> ReturnType) rethrows -> ReturnType {
|
||||
func withBigEndianIntegerBytes<ReturnType>(_ body: (ArraySlice<UInt8>) throws(CryptoKitMetaError) -> ReturnType) throws(CryptoKitMetaError) -> ReturnType {
|
||||
return try body(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,16 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
@@ -102,7 +111,7 @@ extension ASN1 {
|
||||
private var _seconds: Int
|
||||
private var _fractionalSeconds: Double
|
||||
|
||||
init(year: Int, month: Int, day: Int, hours: Int, minutes: Int, seconds: Int, fractionalSeconds: Double) throws {
|
||||
init(year: Int, month: Int, day: Int, hours: Int, minutes: Int, seconds: Int, fractionalSeconds: Double) throws(CryptoKitMetaError) {
|
||||
self._year = year
|
||||
self._month = month
|
||||
self._day = day
|
||||
@@ -114,9 +123,9 @@ extension ASN1 {
|
||||
try self.validate()
|
||||
}
|
||||
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
guard node.identifier == identifier else {
|
||||
throw CryptoKitASN1Error.unexpectedFieldType
|
||||
throw error(CryptoKitASN1Error.unexpectedFieldType)
|
||||
}
|
||||
|
||||
guard case .primitive(let content) = node.content else {
|
||||
@@ -126,33 +135,33 @@ extension ASN1 {
|
||||
self = try .parseDateBytes(content)
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
coder.appendPrimitiveNode(identifier: identifier) { bytes in
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
try coder.appendPrimitiveNode(identifier: identifier) { bytes in
|
||||
bytes.append(self)
|
||||
}
|
||||
}
|
||||
|
||||
private func validate() throws {
|
||||
private func validate() throws(CryptoKitMetaError) {
|
||||
// Validate that the structure is well-formed.
|
||||
guard self._year >= 0 && self._year <= 9999 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
// This also validates the month.
|
||||
guard let daysInMonth = ASN1.GeneralizedTime.daysInMonth(self._month, ofYear: self._year) else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
guard self._day >= 1 && self._day <= daysInMonth else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
guard self._hours >= 0 && self._hours < 24 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
guard self._minutes >= 0 && self._minutes < 60 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
// We allow leap seconds here, but don't validate it.
|
||||
@@ -160,12 +169,12 @@ extension ASN1 {
|
||||
// comparison here. We should consider whether this needs to be transformable
|
||||
// to `Date` or similar.
|
||||
guard self._seconds >= 0 && self._seconds <= 61 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
// Fractional seconds may not be negative and may not be 1 or more.
|
||||
guard self._fractionalSeconds >= 0 && self._fractionalSeconds < 1 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -173,7 +182,7 @@ extension ASN1 {
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.GeneralizedTime {
|
||||
fileprivate static func parseDateBytes(_ bytes: ArraySlice<UInt8>) throws -> ASN1.GeneralizedTime {
|
||||
fileprivate static func parseDateBytes(_ bytes: ArraySlice<UInt8>) throws(CryptoKitMetaError) -> ASN1.GeneralizedTime {
|
||||
var bytes = bytes
|
||||
|
||||
// First, there must always be a calendar date. No separators, 4
|
||||
@@ -181,7 +190,7 @@ extension ASN1.GeneralizedTime {
|
||||
guard let rawYear = bytes.readFourDigitDecimalInteger(),
|
||||
let rawMonth = bytes.readTwoDigitDecimalInteger(),
|
||||
let rawDay = bytes.readTwoDigitDecimalInteger() else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
// Next there must be a _time_. Per DER rules, this time must always go
|
||||
@@ -190,23 +199,23 @@ extension ASN1.GeneralizedTime {
|
||||
guard let rawHour = bytes.readTwoDigitDecimalInteger(),
|
||||
let rawMinutes = bytes.readTwoDigitDecimalInteger(),
|
||||
let rawSeconds = bytes.readTwoDigitDecimalInteger() else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
// There may be some fractional seconds.
|
||||
var fractionalSeconds: Double = 0
|
||||
if bytes.first == UInt8(ascii: ".") {
|
||||
if bytes.first == UInt8(46 /* "." */) {
|
||||
fractionalSeconds = try bytes.readFractionalSeconds()
|
||||
}
|
||||
|
||||
// The next character _must_ be Z, or the encoding is invalid.
|
||||
guard bytes.popFirst() == UInt8(ascii: "Z") else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
guard bytes.popFirst() == UInt8(90 /* "Z" */) else {
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
// Great! There better not be anything left.
|
||||
guard bytes.count == 0 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
return try ASN1.GeneralizedTime(year: rawYear,
|
||||
@@ -284,8 +293,8 @@ extension ArraySlice where Element == UInt8 {
|
||||
}
|
||||
|
||||
/// This may only be called if there's a leading period: we precondition on this fact.
|
||||
fileprivate mutating func readFractionalSeconds() throws -> Double {
|
||||
precondition(self.popFirst() == UInt8(ascii: "."))
|
||||
fileprivate mutating func readFractionalSeconds() throws(CryptoKitMetaError) -> Double {
|
||||
precondition(self.popFirst() == UInt8(46 /* "." */))
|
||||
|
||||
var numerator = 0
|
||||
var denominator = 1
|
||||
@@ -304,7 +313,7 @@ extension ArraySlice where Element == UInt8 {
|
||||
|
||||
// If the numerator overflows, we don't support the result.
|
||||
if multiplyOverflow || addingOverflow {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
numerator = newNumeratorWithAdded
|
||||
@@ -313,7 +322,7 @@ extension ArraySlice where Element == UInt8 {
|
||||
// Ok, we're either at the end or the next character is a Z. One final check: there may not have
|
||||
// been any trailing zeros here. This means the number may not be 0 mod 10.
|
||||
if numerator % 10 == 0 {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
return Double(numerator) / Double(denominator)
|
||||
@@ -332,26 +341,48 @@ extension Array where Element == UInt8 {
|
||||
|
||||
// Ok, tricky moment here. Is the fractional part non-zero? If it is, we need to write it out as well.
|
||||
if generalizedTime.fractionalSeconds != 0 {
|
||||
let stringified = String(generalizedTime.fractionalSeconds)
|
||||
assert(stringified.starts(with: "0."))
|
||||
|
||||
self.append(contentsOf: stringified.utf8.dropFirst(1))
|
||||
// Remove any trailing zeros from self, they are forbidden.
|
||||
while self.last == 0 {
|
||||
self = self.dropLast()
|
||||
}
|
||||
self._appendFractionalPart(generalizedTime.fractionalSeconds)
|
||||
}
|
||||
|
||||
self.append(UInt8(ascii: "Z"))
|
||||
self.append(UInt8(90 /* "Z" */))
|
||||
}
|
||||
|
||||
#if hasFeature(Embedded)
|
||||
private mutating func _appendFractionalPart(_ d: Double) {
|
||||
precondition(d > 0 && d < 1)
|
||||
let digitZero: UInt8 = 48 /* "0" */
|
||||
var d = d - d.rounded(.down)
|
||||
for _ in 0..<16 {
|
||||
d *= 10
|
||||
let x = d.rounded(.down)
|
||||
self.append(UInt8(x) + digitZero)
|
||||
d = d - x
|
||||
}
|
||||
while self.count > 1 && self.last == UInt8(48 /* "0" */) {
|
||||
self = self.dropLast()
|
||||
}
|
||||
}
|
||||
#else
|
||||
private mutating func _appendFractionalPart(_ d: Double) {
|
||||
precondition(d > 0 && d < 1)
|
||||
let stringified = String(d)
|
||||
assert(stringified.starts(with: "0."))
|
||||
|
||||
self.append(contentsOf: stringified.utf8.dropFirst(1))
|
||||
// Remove any trailing zeros from self, they are forbidden.
|
||||
while self.last == UInt8(48 /* "0" */) {
|
||||
self = self.dropLast()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
fileprivate mutating func appendFourDigitDecimal(_ number: Int) {
|
||||
assert(number >= 0 && number <= 9999)
|
||||
|
||||
// Each digit can be isolated by dividing by the place and then taking the result modulo 10.
|
||||
// This is annoyingly division heavy. There may be a better algorithm floating around.
|
||||
// Unchecked math is fine, there cannot be an overflow here.
|
||||
let asciiZero = UInt8(ascii: "0")
|
||||
let asciiZero = UInt8(48 /* "0" */)
|
||||
self.append(UInt8(truncatingIfNeeded: (number / 1000) % 10) &+ asciiZero)
|
||||
self.append(UInt8(truncatingIfNeeded: (number / 100) % 10) &+ asciiZero)
|
||||
self.append(UInt8(truncatingIfNeeded: (number / 10) % 10) &+ asciiZero)
|
||||
@@ -364,7 +395,7 @@ extension Array where Element == UInt8 {
|
||||
// Each digit can be isolated by dividing by the place and then taking the result modulo 10.
|
||||
// This is annoyingly division heavy. There may be a better algorithm floating around.
|
||||
// Unchecked math is fine, there cannot be an overflow here.
|
||||
let asciiZero = UInt8(ascii: "0")
|
||||
let asciiZero = UInt8(48 /* "0" */)
|
||||
self.append(UInt8(truncatingIfNeeded: (number / 10) % 10) &+ asciiZero)
|
||||
self.append(UInt8(truncatingIfNeeded: number % 10) &+ asciiZero)
|
||||
}
|
||||
@@ -373,7 +404,7 @@ extension Array where Element == UInt8 {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Int {
|
||||
fileprivate init?(fromDecimalASCII ascii: UInt8) {
|
||||
let asciiZero = UInt8(ascii: "0")
|
||||
let asciiZero = UInt8(48 /* "0" */)
|
||||
let zeroToNine = 0...9
|
||||
|
||||
// These are all coming from UInt8space, the subtraction cannot overflow.
|
||||
|
||||
@@ -14,7 +14,16 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
@@ -31,9 +40,9 @@ extension ASN1 {
|
||||
|
||||
private var oidComponents: [UInt]
|
||||
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
guard node.identifier == identifier else {
|
||||
throw CryptoKitASN1Error.unexpectedFieldType
|
||||
throw error(CryptoKitASN1Error.unexpectedFieldType)
|
||||
}
|
||||
|
||||
guard case .primitive(var content) = node.content else {
|
||||
@@ -67,7 +76,7 @@ extension ASN1 {
|
||||
}
|
||||
|
||||
guard subcomponents.count >= 2 else {
|
||||
throw CryptoKitASN1Error.invalidObjectIdentifier
|
||||
throw error(CryptoKitASN1Error.invalidObjectIdentifier)
|
||||
}
|
||||
|
||||
// Now we need to expand the subcomponents out. This means we need to undo the step above. The first component will be in the range 0..<40
|
||||
@@ -92,8 +101,8 @@ extension ASN1 {
|
||||
self.oidComponents = oidComponents
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
coder.appendPrimitiveNode(identifier: identifier) { bytes in
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
try coder.appendPrimitiveNode(identifier: identifier) { bytes in
|
||||
var components = self.oidComponents[...]
|
||||
guard let firstComponent = components.popFirst(), let secondComponent = components.popFirst() else {
|
||||
preconditionFailure("Invalid number of OID components: must be at least two!")
|
||||
@@ -191,11 +200,11 @@ extension ASN1.ASN1ObjectIdentifier {
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ArraySlice where Element == UInt8 {
|
||||
mutating fileprivate func readOIDSubidentifier() throws -> 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
|
||||
// because for us it shouldn't matter.
|
||||
guard let subidentifierEndIndex = self.firstIndex(where: { $0 & 0x80 == 0x00 }) else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
let oidSlice = self[self.startIndex ... subidentifierEndIndex]
|
||||
@@ -208,10 +217,10 @@ extension ArraySlice where Element == UInt8 {
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension UInt {
|
||||
fileprivate init<Bytes: Collection>(sevenBitBigEndianBytes bytes: Bytes) throws 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".
|
||||
guard ((bytes.count * 7) + 7) / 8 <= MemoryLayout<UInt>.size else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
self = 0
|
||||
|
||||
@@ -14,7 +14,16 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
@@ -40,8 +49,8 @@ extension ASN1 {
|
||||
self.s = s
|
||||
}
|
||||
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes throws(CryptoKitMetaError) in
|
||||
let r = try IntegerType(asn1Encoded: &nodes)
|
||||
let s = try IntegerType(asn1Encoded: &nodes)
|
||||
|
||||
@@ -49,8 +58,8 @@ extension ASN1 {
|
||||
}
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder throws(CryptoKitMetaError) in
|
||||
try coder.serialize(self.r)
|
||||
try coder.serialize(self.s)
|
||||
}
|
||||
|
||||
@@ -14,7 +14,16 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
|
||||
@@ -14,7 +14,15 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
@@ -50,11 +58,11 @@ extension ASN1 {
|
||||
|
||||
var privateKey: ASN1.SEC1PrivateKey
|
||||
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes throws(CryptoKitMetaError) in
|
||||
let version = try Int(asn1Encoded: &nodes)
|
||||
guard version == 0 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
let algorithm = try ASN1.RFC5480AlgorithmIdentifier(asn1Encoded: &nodes)
|
||||
@@ -66,14 +74,14 @@ extension ASN1 {
|
||||
let sec1PrivateKeyNode = try ASN1.parse(privateKeyBytes.bytes)
|
||||
let sec1PrivateKey = try ASN1.SEC1PrivateKey(asn1Encoded: sec1PrivateKeyNode)
|
||||
if let innerAlgorithm = sec1PrivateKey.algorithm, innerAlgorithm != algorithm {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
return try .init(algorithm: algorithm, privateKey: sec1PrivateKey)
|
||||
}
|
||||
}
|
||||
|
||||
private init(algorithm: ASN1.RFC5480AlgorithmIdentifier, privateKey: ASN1.SEC1PrivateKey) throws {
|
||||
private init(algorithm: ASN1.RFC5480AlgorithmIdentifier, privateKey: ASN1.SEC1PrivateKey) throws(CryptoKitMetaError) {
|
||||
self.privateKey = privateKey
|
||||
self.algorithm = algorithm
|
||||
}
|
||||
@@ -86,8 +94,8 @@ extension ASN1 {
|
||||
self.privateKey = ASN1.SEC1PrivateKey(privateKey: privateKey, algorithm: nil, publicKey: publicKey)
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder throws(CryptoKitMetaError) in
|
||||
try coder.serialize(0) // version
|
||||
try coder.serialize(self.algorithm)
|
||||
|
||||
|
||||
@@ -14,7 +14,16 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
@@ -38,18 +47,18 @@ extension ASN1 {
|
||||
|
||||
var publicKey: ASN1.ASN1BitString?
|
||||
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes throws(CryptoKitMetaError) in
|
||||
let version = try Int(asn1Encoded: &nodes)
|
||||
guard 1 == version else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
let privateKey = try ASN1OctetString(asn1Encoded: &nodes)
|
||||
let parameters = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in
|
||||
let parameters = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node throws(CryptoKitMetaError) in
|
||||
return try ASN1.ASN1ObjectIdentifier(asn1Encoded: node)
|
||||
}
|
||||
let publicKey = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { node in
|
||||
let publicKey = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { node throws(CryptoKitMetaError) in
|
||||
return try ASN1.ASN1BitString(asn1Encoded: node)
|
||||
}
|
||||
|
||||
@@ -57,10 +66,10 @@ extension ASN1 {
|
||||
}
|
||||
}
|
||||
|
||||
private init(privateKey: ASN1.ASN1OctetString, algorithm: ASN1.ASN1ObjectIdentifier?, publicKey: ASN1.ASN1BitString?) throws {
|
||||
private init(privateKey: ASN1.ASN1OctetString, algorithm: ASN1.ASN1ObjectIdentifier?, publicKey: ASN1.ASN1BitString?) throws(CryptoKitMetaError) {
|
||||
self.privateKey = privateKey
|
||||
self.publicKey = publicKey
|
||||
self.algorithm = try algorithm.map { algorithmOID in
|
||||
self.algorithm = try algorithm.map { algorithmOID throws(CryptoKitMetaError) in
|
||||
switch algorithmOID {
|
||||
case ASN1ObjectIdentifier.NamedCurves.secp256r1:
|
||||
return .ecdsaP256
|
||||
@@ -69,7 +78,7 @@ extension ASN1 {
|
||||
case ASN1ObjectIdentifier.NamedCurves.secp521r1:
|
||||
return .ecdsaP521
|
||||
default:
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,8 +89,8 @@ extension ASN1 {
|
||||
self.publicKey = ASN1BitString(bytes: publicKey[...])
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder throws(CryptoKitMetaError) in
|
||||
try coder.serialize(1) // version
|
||||
try coder.serialize(self.privateKey)
|
||||
|
||||
@@ -95,7 +104,7 @@ extension ASN1 {
|
||||
case .ecdsaP521:
|
||||
oid = ASN1ObjectIdentifier.NamedCurves.secp521r1
|
||||
default:
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
|
||||
try coder.serialize(oid, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific)
|
||||
|
||||
@@ -14,7 +14,16 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
@@ -28,14 +37,14 @@ extension ASN1 {
|
||||
|
||||
var key: ASN1.ASN1BitString
|
||||
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
// The SPKI block looks like this:
|
||||
//
|
||||
// SubjectPublicKeyInfo ::= SEQUENCE {
|
||||
// algorithm AlgorithmIdentifier,
|
||||
// subjectPublicKey BIT STRING
|
||||
// }
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes throws(CryptoKitMetaError) in
|
||||
let algorithmIdentifier = try ASN1.RFC5480AlgorithmIdentifier(asn1Encoded: &nodes)
|
||||
let key = try ASN1.ASN1BitString(asn1Encoded: &nodes)
|
||||
|
||||
@@ -53,8 +62,8 @@ extension ASN1 {
|
||||
self.key = ASN1BitString(bytes: key[...])
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder throws(CryptoKitMetaError) in
|
||||
try coder.serialize(self.algorithmIdentifier)
|
||||
try coder.serialize(self.key)
|
||||
}
|
||||
@@ -76,7 +85,7 @@ extension ASN1 {
|
||||
self.parameters = parameters
|
||||
}
|
||||
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
// The AlgorithmIdentifier block looks like this.
|
||||
//
|
||||
// AlgorithmIdentifier ::= SEQUENCE {
|
||||
@@ -91,17 +100,17 @@ extension ASN1 {
|
||||
// }
|
||||
//
|
||||
// We don't bother with helpers: we just try to decode it directly.
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes throws(CryptoKitMetaError) in
|
||||
let algorithmOID = try ASN1.ASN1ObjectIdentifier(asn1Encoded: &nodes)
|
||||
|
||||
let parameters = nodes.next().map { ASN1.ASN1Any(asn1Encoded: $0) }
|
||||
|
||||
let n = nodes.next()
|
||||
let parameters = if let n { try ASN1.ASN1Any(asn1Encoded: n) } else { nil as ASN1.ASN1Any? }
|
||||
return .init(algorithm: algorithmOID, parameters: parameters)
|
||||
}
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws(CryptoKitMetaError) {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder throws(CryptoKitMetaError) in
|
||||
try coder.serialize(self.algorithm)
|
||||
if let parameters = self.parameters {
|
||||
try coder.serialize(parameters)
|
||||
|
||||
@@ -43,6 +43,8 @@ add_library(Crypto
|
||||
"Digests/Digests.swift"
|
||||
"Digests/HashFunctions.swift"
|
||||
"Digests/HashFunctions_SHA2.swift"
|
||||
"Digests/HashFunctions_SHA3.swift"
|
||||
"Digests/XKCP/Digest_xkcp.swift"
|
||||
"HPKE/Ciphersuite/HPKE-AEAD.swift"
|
||||
"HPKE/Ciphersuite/HPKE-Ciphersuite.swift"
|
||||
"HPKE/Ciphersuite/HPKE-KDF.swift"
|
||||
@@ -60,10 +62,17 @@ add_library(Crypto
|
||||
"HPKE/Modes/HPKE-Modes.swift"
|
||||
"Insecure/Insecure.swift"
|
||||
"Insecure/Insecure_HashFunctions.swift"
|
||||
"KEM/BoringSSL/MLKEM_boring.swift"
|
||||
"KEM/BoringSSL/MLKEM_wrapper.swift"
|
||||
"KEM/BoringSSL/XWing_boring.swift"
|
||||
"KEM/KEM-Errors.swift"
|
||||
"KEM/KEM.swift"
|
||||
"KEM/MLKEM.swift"
|
||||
"KEM/XWing.swift"
|
||||
"Key Agreement/BoringSSL/ECDH_boring.swift"
|
||||
"Key Agreement/DH.swift"
|
||||
"Key Agreement/ECDH.swift"
|
||||
"Key Derivation/ANSIx963.swift"
|
||||
"Key Derivation/HKDF.swift"
|
||||
"Key Wrapping/AESWrap.swift"
|
||||
"Key Wrapping/BoringSSL/AESWrap_boring.swift"
|
||||
@@ -82,10 +91,14 @@ add_library(Crypto
|
||||
"Signatures/BoringSSL/ECDSASignature_boring.swift"
|
||||
"Signatures/BoringSSL/ECDSA_boring.swift"
|
||||
"Signatures/BoringSSL/EdDSA_boring.swift"
|
||||
"Signatures/BoringSSL/MLDSA_boring.swift"
|
||||
"Signatures/BoringSSL/MLDSA_wrapper.swift"
|
||||
"Signatures/ECDSA.swift"
|
||||
"Signatures/Ed25519.swift"
|
||||
"Signatures/MLDSA.swift"
|
||||
"Signatures/Signature.swift"
|
||||
"Util/BoringSSL/CryptoKitErrors_boring.swift"
|
||||
"Util/BoringSSL/Optional+withUnsafeBytes_boring.swift"
|
||||
"Util/BoringSSL/RNG_boring.swift"
|
||||
"Util/BoringSSL/SafeCompare_boring.swift"
|
||||
"Util/BoringSSL/Zeroization_boring.swift"
|
||||
@@ -106,13 +119,17 @@ endif()
|
||||
target_include_directories(Crypto PRIVATE
|
||||
$<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:CXKCPShims,INCLUDE_DIRECTORIES>)
|
||||
target_link_libraries(Crypto PUBLIC
|
||||
$<$<NOT:$<PLATFORM_ID:Darwin>>:dispatch>
|
||||
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
|
||||
CCryptoBoringSSL
|
||||
CCryptoBoringSSLShims
|
||||
CryptoBoringWrapper)
|
||||
CryptoBoringWrapper
|
||||
CXKCP
|
||||
CXKCPShims)
|
||||
target_compile_options(Crypto PRIVATE ${SWIFT_CRYPTO_COMPILE_OPTIONS})
|
||||
set_target_properties(Crypto PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
|
||||
@@ -66,4 +66,59 @@ public enum CryptoKitASN1Error: Equatable, Error, Hashable {
|
||||
/// The string doesn’t parse as a PEM document.
|
||||
case invalidPEMDocument
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
enum RSAPSSSPKIErrors: Error {
|
||||
case invalidPSSOID
|
||||
case missingParameters
|
||||
case incorrectHashFunction
|
||||
case incorrectMGF
|
||||
case missingMGFHashFunction
|
||||
case incorrectMGFHashFunction
|
||||
case invalidSaltLength
|
||||
}
|
||||
|
||||
#if hasFeature(Embedded)
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct RSAPSSSPKIError: Error {
|
||||
internal var error: RSAPSSSPKIErrors
|
||||
}
|
||||
#else
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct RSAPSSSPKIError: Error {
|
||||
internal var error: RSAPSSSPKIErrors
|
||||
}
|
||||
#endif
|
||||
|
||||
#if hasFeature(Embedded)
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum CryptoKitMetaError: Error {
|
||||
case cryptoKitError(underlyingError: CryptoKitError)
|
||||
case asn1Error(underlyingError: CryptoKitASN1Error)
|
||||
case rsapssspkiError(underlyingError: RSAPSSSPKIError)
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal func error(_ error: CryptoKitError) -> CryptoKitMetaError {
|
||||
.cryptoKitError(underlyingError: error)
|
||||
}
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal func error(_ error: CryptoKitASN1Error) -> CryptoKitMetaError {
|
||||
.asn1Error(underlyingError: error)
|
||||
}
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal func error(_ error: RSAPSSSPKIErrors) -> CryptoKitMetaError {
|
||||
.rsapssspkiError(underlyingError: RSAPSSSPKIError(error: error))
|
||||
}
|
||||
#else /* !hasFeature(Embedded) */
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public typealias CryptoKitMetaError = any Error
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal func error(_ error: CryptoKitError) -> CryptoKitError { error }
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal func error(_ error: CryptoKitASN1Error) -> CryptoKitASN1Error { error }
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal func error(_ error: RSAPSSSPKIErrors) -> RSAPSSSPKIErrors { error }
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -47,7 +47,8 @@ extension Insecure.MD5: BoringSSLBackedHashFunction {
|
||||
}
|
||||
|
||||
static func finalize(_ context: inout MD5_CTX, digest: UnsafeMutableRawBufferPointer) -> Bool {
|
||||
CCryptoBoringSSL_MD5_Final(digest.baseAddress, &context) == 1
|
||||
guard let baseAddress = digest.baseAddress, digest.count == Self.digestSize else { return false }
|
||||
return CCryptoBoringSSL_MD5_Final(baseAddress, &context) == 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,7 +71,8 @@ extension Insecure.SHA1: BoringSSLBackedHashFunction {
|
||||
}
|
||||
|
||||
static func finalize(_ context: inout SHA_CTX, digest: UnsafeMutableRawBufferPointer) -> Bool {
|
||||
CCryptoBoringSSL_SHA1_Final(digest.baseAddress, &context) == 1
|
||||
guard let baseAddress = digest.baseAddress, digest.count == Self.digestSize else { return false }
|
||||
return CCryptoBoringSSL_SHA1_Final(baseAddress, &context) == 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,7 +95,8 @@ extension SHA256: BoringSSLBackedHashFunction {
|
||||
}
|
||||
|
||||
static func finalize(_ context: inout SHA256_CTX, digest: UnsafeMutableRawBufferPointer) -> Bool {
|
||||
CCryptoBoringSSL_SHA256_Final(digest.baseAddress, &context) == 1
|
||||
guard let baseAddress = digest.baseAddress, digest.count == Self.digestSize else { return false }
|
||||
return CCryptoBoringSSL_SHA256_Final(baseAddress, &context) == 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,7 +119,8 @@ extension SHA384: BoringSSLBackedHashFunction {
|
||||
}
|
||||
|
||||
static func finalize(_ context: inout SHA512_CTX, digest: UnsafeMutableRawBufferPointer) -> Bool {
|
||||
CCryptoBoringSSL_SHA384_Final(digest.baseAddress, &context) == 1
|
||||
guard let baseAddress = digest.baseAddress, digest.count == Self.digestSize else { return false }
|
||||
return CCryptoBoringSSL_SHA384_Final(baseAddress, &context) == 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,12 +143,13 @@ extension SHA512: BoringSSLBackedHashFunction {
|
||||
}
|
||||
|
||||
static func finalize(_ context: inout SHA512_CTX, digest: UnsafeMutableRawBufferPointer) -> Bool {
|
||||
CCryptoBoringSSL_SHA512_Final(digest.baseAddress, &context) == 1
|
||||
guard let baseAddress = digest.baseAddress, digest.count == Self.digestSize else { return false }
|
||||
return CCryptoBoringSSL_SHA512_Final(baseAddress, &context) == 1
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct OpenSSLDigestImpl<H: BoringSSLBackedHashFunction> {
|
||||
struct OpenSSLDigestImpl<H: BoringSSLBackedHashFunction>: @unchecked Sendable {
|
||||
private var context: DigestContext<H>
|
||||
|
||||
init() {
|
||||
|
||||
@@ -14,14 +14,34 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
public import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if hasFeature(Embedded)
|
||||
/// A type that represents the output of a hash.
|
||||
@preconcurrency
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol Digest: Hashable, ContiguousBytes, CustomStringConvertible, Sequence where Element == UInt8 {
|
||||
public protocol Digest: Hashable, Sendable, ContiguousBytes, Sequence where Element == UInt8 {
|
||||
/// The number of bytes in the digest.
|
||||
static var byteCount: Int { get }
|
||||
}
|
||||
#else // hasFeature(Embedded)
|
||||
/// A type that represents the output of a hash.
|
||||
@preconcurrency
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol Digest: Hashable, Sendable, ContiguousBytes, CustomStringConvertible, Sequence where Element == UInt8 {
|
||||
/// The number of bytes in the digest.
|
||||
static var byteCount: Int { get }
|
||||
}
|
||||
#endif // hasFeature(Embedded)
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
protocol DigestPrivate: Digest {
|
||||
@@ -84,9 +104,15 @@ extension Digest {
|
||||
return safeCompare(lhs, rhs.regions.first!)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Digest {
|
||||
public var description: String {
|
||||
return "\(Self.self): \(Array(self).hexString)"
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -18,6 +18,8 @@
|
||||
// any edits of this file WILL be overwritten and thus discarded
|
||||
// see section `gyb` in `README` for details.
|
||||
|
||||
|
||||
|
||||
// MARK: - SHA256Digest + DigestPrivate
|
||||
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 256-bit digest.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
@@ -49,6 +51,7 @@ public struct SHA256Digest: DigestPrivate {
|
||||
/// 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,
|
||||
@@ -56,6 +59,15 @@ public struct SHA256Digest: DigestPrivate {
|
||||
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]()
|
||||
@@ -63,14 +75,16 @@ public struct SHA256Digest: DigestPrivate {
|
||||
array.appendByte(bytes.1)
|
||||
array.appendByte(bytes.2)
|
||||
array.appendByte(bytes.3)
|
||||
return array.prefix(upTo: SHA256Digest.byteCount)
|
||||
return array.prefix(SHA256Digest.byteCount)
|
||||
}
|
||||
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// A human-readable description of the digest.
|
||||
public var description: String {
|
||||
return "\("SHA256") digest: \(toArray().hexString)"
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/// Hashes the essential components of the digest by feeding them into the
|
||||
/// given hash function.
|
||||
///
|
||||
@@ -120,6 +134,7 @@ public struct SHA384Digest: DigestPrivate {
|
||||
/// 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,
|
||||
@@ -127,6 +142,15 @@ public struct SHA384Digest: DigestPrivate {
|
||||
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]()
|
||||
@@ -136,14 +160,16 @@ public struct SHA384Digest: DigestPrivate {
|
||||
array.appendByte(bytes.3)
|
||||
array.appendByte(bytes.4)
|
||||
array.appendByte(bytes.5)
|
||||
return array.prefix(upTo: SHA384Digest.byteCount)
|
||||
return array.prefix(SHA384Digest.byteCount)
|
||||
}
|
||||
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// A human-readable description of the digest.
|
||||
public var description: String {
|
||||
return "\("SHA384") digest: \(toArray().hexString)"
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/// Hashes the essential components of the digest by feeding them into the
|
||||
/// given hash function.
|
||||
///
|
||||
@@ -193,6 +219,7 @@ public struct SHA512Digest: DigestPrivate {
|
||||
/// 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,
|
||||
@@ -200,6 +227,15 @@ public struct SHA512Digest: DigestPrivate {
|
||||
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]()
|
||||
@@ -211,14 +247,16 @@ public struct SHA512Digest: DigestPrivate {
|
||||
array.appendByte(bytes.5)
|
||||
array.appendByte(bytes.6)
|
||||
array.appendByte(bytes.7)
|
||||
return array.prefix(upTo: SHA512Digest.byteCount)
|
||||
return array.prefix(SHA512Digest.byteCount)
|
||||
}
|
||||
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// A human-readable description of the digest.
|
||||
public var description: String {
|
||||
return "\("SHA512") digest: \(toArray().hexString)"
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/// Hashes the essential components of the digest by feeding them into the
|
||||
/// given hash function.
|
||||
///
|
||||
@@ -269,6 +307,7 @@ public struct SHA1Digest: DigestPrivate {
|
||||
/// 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,
|
||||
@@ -276,20 +315,31 @@ public struct SHA1Digest: DigestPrivate {
|
||||
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)
|
||||
array.appendByte(bytes.1)
|
||||
array.appendByte(bytes.2)
|
||||
return array.prefix(upTo: SHA1Digest.byteCount)
|
||||
return array.prefix(SHA1Digest.byteCount)
|
||||
}
|
||||
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// A human-readable description of the digest.
|
||||
public var description: String {
|
||||
return "\("SHA1") digest: \(toArray().hexString)"
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/// Hashes the essential components of the digest by feeding them into the
|
||||
/// given hash function.
|
||||
///
|
||||
@@ -340,6 +390,7 @@ public struct MD5Digest: DigestPrivate {
|
||||
/// 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,
|
||||
@@ -347,19 +398,30 @@ public struct MD5Digest: DigestPrivate {
|
||||
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)
|
||||
array.appendByte(bytes.1)
|
||||
return array.prefix(upTo: MD5Digest.byteCount)
|
||||
return array.prefix(MD5Digest.byteCount)
|
||||
}
|
||||
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// A human-readable description of the digest.
|
||||
public var description: String {
|
||||
return "\("MD5") digest: \(toArray().hexString)"
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/// Hashes the essential components of the digest by feeding them into the
|
||||
/// given hash function.
|
||||
///
|
||||
@@ -377,4 +439,258 @@ public struct MD5Digest: DigestPrivate {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#if !CRYPTOKIT_IN_SEP
|
||||
|
||||
// MARK: - SHA3_256Digest + DigestPrivate
|
||||
/// The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a 256-bit digest.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA3_256Digest: DigestPrivate {
|
||||
let bytes: (UInt64, UInt64, UInt64, UInt64)
|
||||
|
||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
||||
guard bufferPointer.count == 32 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var bytes = (UInt64(0), UInt64(0), 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 32
|
||||
}
|
||||
|
||||
/// 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)
|
||||
array.appendByte(bytes.1)
|
||||
array.appendByte(bytes.2)
|
||||
array.appendByte(bytes.3)
|
||||
return array.prefix(upTo: SHA3_256Digest.byteCount)
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// A human-readable description of the digest.
|
||||
public var description: String {
|
||||
return "\("SHA3_256") 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 ``SHA3_256/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) }
|
||||
}
|
||||
}
|
||||
// MARK: - SHA3_384Digest + DigestPrivate
|
||||
/// The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a 384-bit digest.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA3_384Digest: DigestPrivate {
|
||||
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
|
||||
|
||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
||||
guard bufferPointer.count == 48 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), 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 48
|
||||
}
|
||||
|
||||
/// 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)
|
||||
array.appendByte(bytes.1)
|
||||
array.appendByte(bytes.2)
|
||||
array.appendByte(bytes.3)
|
||||
array.appendByte(bytes.4)
|
||||
array.appendByte(bytes.5)
|
||||
return array.prefix(upTo: SHA3_384Digest.byteCount)
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// A human-readable description of the digest.
|
||||
public var description: String {
|
||||
return "\("SHA3_384") 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 ``SHA3_384/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) }
|
||||
}
|
||||
}
|
||||
// MARK: - SHA3_512Digest + DigestPrivate
|
||||
/// The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a 512-bit digest.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA3_512Digest: DigestPrivate {
|
||||
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
|
||||
|
||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
||||
guard bufferPointer.count == 64 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||
targetPtr.copyMemory(from: bufferPointer)
|
||||
}
|
||||
self.bytes = bytes
|
||||
}
|
||||
|
||||
/// The number of bytes in the digest.
|
||||
public static var byteCount: Int {
|
||||
return 64
|
||||
}
|
||||
|
||||
/// 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)
|
||||
array.appendByte(bytes.1)
|
||||
array.appendByte(bytes.2)
|
||||
array.appendByte(bytes.3)
|
||||
array.appendByte(bytes.4)
|
||||
array.appendByte(bytes.5)
|
||||
array.appendByte(bytes.6)
|
||||
array.appendByte(bytes.7)
|
||||
return array.prefix(upTo: SHA3_512Digest.byteCount)
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// A human-readable description of the digest.
|
||||
public var description: String {
|
||||
return "\("SHA3_512") 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 ``SHA3_512/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) }
|
||||
}
|
||||
}
|
||||
#endif // !CRYPTOKIT_IN_SEP
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -17,9 +17,15 @@
|
||||
// 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},{"name":"SHA1", "count":20, "prefix":"Insecure "},{"name":"MD5", "count":16, "prefix":"Insecure "}]
|
||||
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"]
|
||||
@@ -73,6 +79,7 @@ public struct ${name}Digest: DigestPrivate {
|
||||
/// 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,
|
||||
@@ -80,6 +87,15 @@ public struct ${name}Digest: DigestPrivate {
|
||||
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]()
|
||||
@@ -87,14 +103,16 @@ public struct ${name}Digest: DigestPrivate {
|
||||
% for index in range(wordsCount-1):
|
||||
array.appendByte(bytes.${index+1})
|
||||
% end
|
||||
return array.prefix(upTo: ${name}Digest.byteCount)
|
||||
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.
|
||||
///
|
||||
@@ -113,4 +131,107 @@ public struct ${name}Digest: DigestPrivate {
|
||||
}
|
||||
${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
|
||||
@@ -14,15 +14,27 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
typealias DigestImpl = CoreCryptoDigestImpl
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
typealias DigestImplSHA3 = CoreCryptoDigestImpl
|
||||
#else
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
typealias DigestImpl = OpenSSLDigestImpl
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
typealias DigestImplSHA3 = XKCPDigestImpl
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
public import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/// A type that performs cryptographically secure hashing.
|
||||
///
|
||||
@@ -42,11 +54,12 @@ import Foundation
|
||||
/// authentication code (MAC) like ``HMAC`` instead. MACs rely on hashing, but
|
||||
/// incorporate a secret cryptographic key into the digest computation. Only a
|
||||
/// user that has the key can generate a valid MAC.
|
||||
@preconcurrency
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol HashFunction {
|
||||
public protocol HashFunction: Sendable {
|
||||
/// The number of bytes that represents the hash function’s internal state.
|
||||
static var blockByteCount: Int { get }
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#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
|
||||
@@ -111,7 +124,7 @@ extension HashFunction {
|
||||
return hasher.finalize()
|
||||
}
|
||||
|
||||
/// Computes the SHA1 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.
|
||||
///
|
||||
/// Use this method if all your data fits into a single data instance. If
|
||||
|
||||
@@ -14,6 +14,21 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
||||
/// 256-bit digest.
|
||||
///
|
||||
/// The ``SHA2_256`` hash implements the ``HashFunction`` protocol for the
|
||||
/// specific case of SHA-2 hashing with a 256-bit digest (``SHA256Digest``).
|
||||
/// Larger digests take more space but are more secure.
|
||||
///
|
||||
/// You can compute the digest by calling the static ``hash(data:)`` method
|
||||
/// once. Alternatively, if the data that you want to hash is too large to fit
|
||||
/// in memory, you can compute the digest iteratively by creating a new hash
|
||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||
/// data, and then calling the ``finalize()`` method to get the result.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public typealias SHA2_256 = SHA256
|
||||
|
||||
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
||||
/// 256-bit digest.
|
||||
///
|
||||
@@ -27,19 +42,11 @@
|
||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||
/// data, and then calling the ``finalize()`` method to get the result.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA256: HashFunctionImplementationDetails {
|
||||
public struct SHA256: HashFunctionImplementationDetails, Sendable {
|
||||
/// The number of bytes that represents the hash function’s internal state.
|
||||
public static var blockByteCount: Int {
|
||||
get { 64 }
|
||||
|
||||
set { fatalError("Cannot set SHA256.blockByteCount") }
|
||||
}
|
||||
public static let blockByteCount: Int = 64
|
||||
/// The number of bytes in a SHA256 digest.
|
||||
public static var byteCount: Int {
|
||||
get { 32 }
|
||||
|
||||
set { fatalError("Cannot set SHA256.byteCount") }
|
||||
}
|
||||
public static let byteCount: Int = 32
|
||||
/// The digest type for a SHA256 hash function.
|
||||
public typealias Digest = SHA256Digest
|
||||
|
||||
@@ -59,9 +66,6 @@ public struct SHA256: HashFunctionImplementationDetails {
|
||||
impl = DigestImpl()
|
||||
}
|
||||
|
||||
// Once https://github.com/apple/swift-evolution/pull/910 is landed,
|
||||
// we will be able to implement `init` here and remove the duplicate code.
|
||||
|
||||
/// Incrementally updates the hash function with the contents of the buffer.
|
||||
///
|
||||
/// Call this method one or more times to provide data to the hash function
|
||||
@@ -97,6 +101,21 @@ public struct SHA256: HashFunctionImplementationDetails {
|
||||
}
|
||||
}
|
||||
|
||||
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
||||
/// 384-bit digest.
|
||||
///
|
||||
/// The ``SHA2_384`` hash implements the ``HashFunction`` protocol for the
|
||||
/// specific case of SHA-2 hashing with a 384-bit digest (``SHA384Digest``).
|
||||
/// Larger digests take more space but are more secure.
|
||||
///
|
||||
/// You can compute the digest by calling the static ``hash(data:)`` method
|
||||
/// once. Alternatively, if the data that you want to hash is too large to fit
|
||||
/// in memory, you can compute the digest iteratively by creating a new hash
|
||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||
/// data, and then calling the ``finalize()`` method to get the result.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public typealias SHA2_384 = SHA384
|
||||
|
||||
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
||||
/// 384-bit digest.
|
||||
///
|
||||
@@ -110,19 +129,11 @@ public struct SHA256: HashFunctionImplementationDetails {
|
||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||
/// data, and then calling the ``finalize()`` method to get the result.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA384: HashFunctionImplementationDetails {
|
||||
public struct SHA384: HashFunctionImplementationDetails, Sendable {
|
||||
/// The number of bytes that represents the hash function’s internal state.
|
||||
public static var blockByteCount: Int {
|
||||
get { 128 }
|
||||
|
||||
set { fatalError("Cannot set SHA384.blockByteCount") }
|
||||
}
|
||||
public static let blockByteCount: Int = 128
|
||||
/// The number of bytes in a SHA384 digest.
|
||||
public static var byteCount: Int {
|
||||
get { 48 }
|
||||
|
||||
set { fatalError("Cannot set SHA384.byteCount") }
|
||||
}
|
||||
public static let byteCount: Int = 48
|
||||
|
||||
/// The digest type for a SHA384 hash function.
|
||||
public typealias Digest = SHA384Digest
|
||||
@@ -143,9 +154,6 @@ public struct SHA384: HashFunctionImplementationDetails {
|
||||
impl = DigestImpl()
|
||||
}
|
||||
|
||||
// Once https://github.com/apple/swift-evolution/pull/910 is landed,
|
||||
// we will be able to implement `init` here and remove the duplicate code.
|
||||
|
||||
/// Incrementally updates the hash function with the contents of the buffer.
|
||||
///
|
||||
/// Call this method one or more times to provide data to the hash function
|
||||
@@ -181,6 +189,21 @@ public struct SHA384: HashFunctionImplementationDetails {
|
||||
}
|
||||
}
|
||||
|
||||
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
||||
/// 512-bit digest.
|
||||
///
|
||||
/// The ``SHA2_512`` hash implements the ``HashFunction`` protocol for the
|
||||
/// specific case of SHA-2 hashing with a 512-bit digest (``SHA512Digest``).
|
||||
/// Larger digests take more space but are more secure.
|
||||
///
|
||||
/// You can compute the digest by calling the static ``hash(data:)`` method
|
||||
/// once. Alternatively, if the data that you want to hash is too large to fit
|
||||
/// in memory, you can compute the digest iteratively by creating a new hash
|
||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||
/// data, and then calling the ``finalize()`` method to get the result.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public typealias SHA2_512 = SHA512
|
||||
|
||||
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
||||
/// 512-bit digest.
|
||||
///
|
||||
@@ -194,19 +217,11 @@ public struct SHA384: HashFunctionImplementationDetails {
|
||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||
/// data, and then calling the ``finalize()`` method to get the result.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA512: HashFunctionImplementationDetails {
|
||||
public struct SHA512: HashFunctionImplementationDetails, Sendable {
|
||||
/// The number of bytes that represents the hash function’s internal state.
|
||||
public static var blockByteCount: Int {
|
||||
get { 128 }
|
||||
|
||||
set { fatalError("Cannot set SHA512.blockByteCount") }
|
||||
}
|
||||
public static let blockByteCount: Int = 128
|
||||
/// The number of bytes in a SHA512 digest.
|
||||
public static var byteCount: Int {
|
||||
get { 64 }
|
||||
|
||||
set { fatalError("Cannot set SHA512.byteCount") }
|
||||
}
|
||||
public static let byteCount: Int = 64
|
||||
/// The digest type for a SHA512 hash function.
|
||||
public typealias Digest = SHA512Digest
|
||||
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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_IN_SEP
|
||||
/// An implementation of Secure Hashing Algorithm 3 (SHA-3) hashing with a 256-bit digest.
|
||||
///
|
||||
/// The ``SHA3_256`` hash implements the ``HashFunction`` protocol for the
|
||||
/// specific case of SHA-3 hashing with a 256-bit digest (``SHA3_256Digest``).
|
||||
/// Larger digests take more space but are more secure.
|
||||
///
|
||||
/// Applications can compute the digest by calling the static ``hash(data:)``
|
||||
/// method once. Alternatively, if the data to hash is too large to fit in memory,
|
||||
/// applications can compute the digest iteratively by creating a new hash
|
||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||
/// data, and then calling the ``finalize()`` method to get the result.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA3_256: HashFunctionImplementationDetails, Sendable {
|
||||
/// The number of bytes that represents the hash function’s internal state.
|
||||
public static let blockByteCount: Int = 136
|
||||
/// The number of bytes in a SHA3-256 digest.
|
||||
public static let byteCount: Int = 32
|
||||
/// The digest type for a SHA3-256 hash function.
|
||||
public typealias Digest = SHA3_256Digest
|
||||
|
||||
var impl: DigestImplSHA3<SHA3_256>
|
||||
|
||||
/// Creates a SHA3-256 hash function.
|
||||
///
|
||||
/// Initialize a new hash function by calling this method if you want to
|
||||
/// hash data iteratively, such as when you don’t have a buffer large enough
|
||||
/// to hold all the data at once. Provide data blocks to the hash function
|
||||
/// using the ``update(data:)`` or ``update(bufferPointer:)`` method. After
|
||||
/// providing all the data, call ``finalize()`` to get the digest.
|
||||
///
|
||||
/// If your data fits into a single buffer, you can use the ``hash(data:)``
|
||||
/// method instead, to compute the digest in a single call.
|
||||
public init() {
|
||||
impl = DigestImplSHA3()
|
||||
}
|
||||
|
||||
/// Incrementally updates the hash function with the contents of the buffer.
|
||||
///
|
||||
/// Call this method one or more times to provide data to the hash function
|
||||
/// in blocks. After providing the last block of data, call the
|
||||
/// ``finalize()`` method to get the computed digest. Don’t call the update
|
||||
/// method again after finalizing the hash function.
|
||||
///
|
||||
/// - Note: Typically, it’s safer to use an instance of
|
||||
/// <doc://com.apple.documentation/documentation/foundation/data>, or some
|
||||
/// other type that conforms to the
|
||||
/// <doc://com.apple.documentation/documentation/foundation/dataprotocol>,
|
||||
/// to hold your data. When possible, use the ``update(data:)`` method
|
||||
/// instead.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bufferPointer: A pointer to the next block of data for the ongoing
|
||||
/// digest calculation.
|
||||
public mutating func update(bufferPointer: UnsafeRawBufferPointer) {
|
||||
impl.update(data: bufferPointer)
|
||||
}
|
||||
|
||||
/// Finalizes the hash function and returns the computed digest.
|
||||
///
|
||||
/// Call this method after you provide the hash function with all the data
|
||||
/// to hash by making one or more calls to the ``update(data:)`` or
|
||||
/// ``update(bufferPointer:)`` method. After finalizing the hash function,
|
||||
/// discard it. To compute a new digest, create a new hash function with a
|
||||
/// call to the ``init()`` method.
|
||||
///
|
||||
/// - Returns: The computed digest of the data.
|
||||
public func finalize() -> Self.Digest {
|
||||
return impl.finalize()
|
||||
}
|
||||
}
|
||||
|
||||
/// An implementation of Secure Hashing Algorithm 3 (SHA-3) hashing with a 384-bit digest.
|
||||
///
|
||||
/// The ``SHA3_384`` hash implements the ``HashFunction`` protocol for the
|
||||
/// specific case of SHA-3 hashing with a 384-bit digest (``SHA3_384Digest``).
|
||||
/// Larger digests take more space but are more secure.
|
||||
///
|
||||
/// Applications can compute the digest by calling the static ``hash(data:)``
|
||||
/// method once. Alternatively, if the data to hash is too large to fit in memory,
|
||||
/// applications can compute the digest iteratively by creating a new hash
|
||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||
/// data, and then calling the ``finalize()`` method to get the result.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA3_384: HashFunctionImplementationDetails, Sendable {
|
||||
/// The number of bytes that represents the hash function’s internal state.
|
||||
public static let blockByteCount: Int = 104
|
||||
/// The number of bytes in a SHA3-384 digest.
|
||||
public static let byteCount: Int = 48
|
||||
/// The digest type for a SHA3-384 hash function.
|
||||
public typealias Digest = SHA3_384Digest
|
||||
|
||||
var impl: DigestImplSHA3<SHA3_384>
|
||||
|
||||
/// Creates a SHA3-384 hash function.
|
||||
///
|
||||
/// Initialize a new hash function by calling this method if you want to
|
||||
/// hash data iteratively, such as when you don’t have a buffer large enough
|
||||
/// to hold all the data at once. Provide data blocks to the hash function
|
||||
/// using the ``update(data:)`` or ``update(bufferPointer:)`` method. After
|
||||
/// providing all the data, call ``finalize()`` to get the digest.
|
||||
///
|
||||
/// If your data fits into a single buffer, you can use the ``hash(data:)``
|
||||
/// method instead, to compute the digest in a single call.
|
||||
public init() {
|
||||
impl = DigestImplSHA3()
|
||||
}
|
||||
|
||||
/// Incrementally updates the hash function with the contents of the buffer.
|
||||
///
|
||||
/// Call this method one or more times to provide data to the hash function
|
||||
/// in blocks. After providing the last block of data, call the
|
||||
/// ``finalize()`` method to get the computed digest. Don’t call the update
|
||||
/// method again after finalizing the hash function.
|
||||
///
|
||||
/// - Note: Typically, it’s safer to use an instance of
|
||||
/// <doc://com.apple.documentation/documentation/foundation/data>, or some
|
||||
/// other type that conforms to the
|
||||
/// <doc://com.apple.documentation/documentation/foundation/dataprotocol>,
|
||||
/// to hold your data. When possible, use the ``update(data:)`` method
|
||||
/// instead.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bufferPointer: A pointer to the next block of data for the ongoing
|
||||
/// digest calculation.
|
||||
public mutating func update(bufferPointer: UnsafeRawBufferPointer) {
|
||||
impl.update(data: bufferPointer)
|
||||
}
|
||||
|
||||
/// Finalizes the hash function and returns the computed digest.
|
||||
///
|
||||
/// Call this method after you provide the hash function with all the data
|
||||
/// to hash by making one or more calls to the ``update(data:)`` or
|
||||
/// ``update(bufferPointer:)`` method. After finalizing the hash function,
|
||||
/// discard it. To compute a new digest, create a new hash function with a
|
||||
/// call to the ``init()`` method.
|
||||
///
|
||||
/// - Returns: The computed digest of the data.
|
||||
public func finalize() -> Self.Digest {
|
||||
return impl.finalize()
|
||||
}
|
||||
}
|
||||
|
||||
/// An implementation of Secure Hashing Algorithm 3 (SHA-3) hashing with a 512-bit digest.
|
||||
///
|
||||
/// The ``SHA3_512`` hash implements the ``HashFunction`` protocol for the
|
||||
/// specific case of SHA-3 hashing with a 512-bit digest (``SHA3_512Digest``).
|
||||
/// Larger digests take more space but are more secure.
|
||||
///
|
||||
/// Applications can compute the digest by calling the static ``hash(data:)``
|
||||
/// method once. Alternatively, if the data to hash is too large to fit in memory,
|
||||
/// applications can compute the digest iteratively by creating a new hash
|
||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||
/// data, and then calling the ``finalize()`` method to get the result.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA3_512: HashFunctionImplementationDetails, Sendable {
|
||||
/// The number of bytes that represents the hash function’s internal state.
|
||||
public static let blockByteCount: Int = 72
|
||||
/// The number of bytes in a SHA3-512 digest.
|
||||
public static let byteCount: Int = 64
|
||||
/// The digest type for a SHA3-512 hash function.
|
||||
public typealias Digest = SHA3_512Digest
|
||||
|
||||
var impl: DigestImplSHA3<SHA3_512>
|
||||
|
||||
/// Creates a SHA3-512 hash function.
|
||||
///
|
||||
/// Initialize a new hash function by calling this method if you want to
|
||||
/// hash data iteratively, such as when you don’t have a buffer large enough
|
||||
/// to hold all the data at once. Provide data blocks to the hash function
|
||||
/// using the ``update(data:)`` or ``update(bufferPointer:)`` method. After
|
||||
/// providing all the data, call ``finalize()`` to get the digest.
|
||||
///
|
||||
/// If your data fits into a single buffer, you can use the ``hash(data:)``
|
||||
/// method instead, to compute the digest in a single call.
|
||||
public init() {
|
||||
impl = DigestImplSHA3()
|
||||
}
|
||||
|
||||
/// Incrementally updates the hash function with the contents of the buffer.
|
||||
///
|
||||
/// Call this method one or more times to provide data to the hash function
|
||||
/// in blocks. After providing the last block of data, call the
|
||||
/// ``finalize()`` method to get the computed digest. Don’t call the update
|
||||
/// method again after finalizing the hash function.
|
||||
///
|
||||
/// - Note: Typically, it’s safer to use an instance of
|
||||
/// <doc://com.apple.documentation/documentation/foundation/data>, or some
|
||||
/// other type that conforms to the
|
||||
/// <doc://com.apple.documentation/documentation/foundation/dataprotocol>,
|
||||
/// to hold your data. When possible, use the ``update(data:)`` method
|
||||
/// instead.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bufferPointer: A pointer to the next block of data for the ongoing
|
||||
/// digest calculation.
|
||||
public mutating func update(bufferPointer: UnsafeRawBufferPointer) {
|
||||
impl.update(data: bufferPointer)
|
||||
}
|
||||
|
||||
/// Finalizes the hash function and returns the computed digest.
|
||||
///
|
||||
/// Call this method after you provide the hash function with all the data
|
||||
/// to hash by making one or more calls to the ``update(data:)`` or
|
||||
/// ``update(bufferPointer:)`` method. After finalizing the hash function,
|
||||
/// discard it. To compute a new digest, create a new hash function with a
|
||||
/// call to the ``init()`` method.
|
||||
///
|
||||
/// - Returns: The computed digest of the data.
|
||||
public func finalize() -> Self.Digest {
|
||||
return impl.finalize()
|
||||
}
|
||||
}
|
||||
#endif // !CRYPTOKIT_IN_SEP
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -0,0 +1,160 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
@_implementationOnly import CXKCP
|
||||
@_implementationOnly import CXKCPShims
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
protocol XKCPBackedHashFunction: HashFunctionImplementationDetails {
|
||||
associatedtype Context
|
||||
static var digestSize: Int { get }
|
||||
static func initialize() -> Context?
|
||||
static func update(_ context: inout Context, data: UnsafeRawBufferPointer) -> Bool
|
||||
static func finalize(_ context: inout Context, digest: UnsafeMutableRawBufferPointer) -> Bool
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension SHA3_256: XKCPBackedHashFunction {
|
||||
static var digestSize: Int { 32 }
|
||||
|
||||
static func initialize() -> Keccak_HashInstance? {
|
||||
var context = Keccak_HashInstance()
|
||||
guard CXKCPShims_Keccak_HashInitialize_SHA3_256(&context) == KECCAK_SUCCESS else {
|
||||
return nil
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
static func update(_ context: inout Keccak_HashInstance, data: UnsafeRawBufferPointer) -> Bool {
|
||||
guard let baseAddress = data.baseAddress else { return true }
|
||||
return Keccak_HashUpdate(&context, baseAddress, data.count * 8) == KECCAK_SUCCESS
|
||||
}
|
||||
|
||||
static func finalize(_ context: inout Keccak_HashInstance, digest: UnsafeMutableRawBufferPointer) -> Bool {
|
||||
guard let baseAddress = digest.baseAddress, digest.count == Self.digestSize else { return false }
|
||||
return Keccak_HashFinal(&context, baseAddress) == KECCAK_SUCCESS
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension SHA3_384: XKCPBackedHashFunction {
|
||||
static var digestSize: Int { 48 }
|
||||
|
||||
static func initialize() -> Keccak_HashInstance? {
|
||||
var context = Keccak_HashInstance()
|
||||
guard CXKCPShims_Keccak_HashInitialize_SHA3_384(&context) == KECCAK_SUCCESS else {
|
||||
return nil
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
static func update(_ context: inout Keccak_HashInstance, data: UnsafeRawBufferPointer) -> Bool {
|
||||
guard let baseAddress = data.baseAddress else { return true }
|
||||
return Keccak_HashUpdate(&context, baseAddress, data.count * 8) == KECCAK_SUCCESS
|
||||
}
|
||||
|
||||
static func finalize(_ context: inout Keccak_HashInstance, digest: UnsafeMutableRawBufferPointer) -> Bool {
|
||||
guard let baseAddress = digest.baseAddress, digest.count == Self.digestSize else { return false }
|
||||
return Keccak_HashFinal(&context, baseAddress) == KECCAK_SUCCESS
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension SHA3_512: XKCPBackedHashFunction {
|
||||
static var digestSize: Int { 64 }
|
||||
|
||||
static func initialize() -> Keccak_HashInstance? {
|
||||
var context = Keccak_HashInstance()
|
||||
guard CXKCPShims_Keccak_HashInitialize_SHA3_512(&context) == KECCAK_SUCCESS else {
|
||||
return nil
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
static func update(_ context: inout Keccak_HashInstance, data: UnsafeRawBufferPointer) -> Bool {
|
||||
guard let baseAddress = data.baseAddress else { return true }
|
||||
return Keccak_HashUpdate(&context, baseAddress, data.count * 8) == KECCAK_SUCCESS
|
||||
}
|
||||
|
||||
static func finalize(_ context: inout Keccak_HashInstance, digest: UnsafeMutableRawBufferPointer) -> Bool {
|
||||
guard let baseAddress = digest.baseAddress, digest.count == Self.digestSize else { return false }
|
||||
return Keccak_HashFinal(&context, baseAddress) == KECCAK_SUCCESS
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct XKCPDigestImpl<H: XKCPBackedHashFunction>: @unchecked Sendable {
|
||||
private var context: XKCPDigestContext<H>
|
||||
|
||||
init() {
|
||||
self.context = XKCPDigestContext()
|
||||
}
|
||||
|
||||
internal mutating func update(data: UnsafeRawBufferPointer) {
|
||||
if !isKnownUniquelyReferenced(&self.context) {
|
||||
self.context = XKCPDigestContext(copying: self.context)
|
||||
}
|
||||
self.context.update(data: data)
|
||||
}
|
||||
|
||||
internal func finalize() -> H.Digest {
|
||||
self.context.finalize()
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
private final class XKCPDigestContext<H: XKCPBackedHashFunction> {
|
||||
private var context: H.Context
|
||||
|
||||
init() {
|
||||
guard let context = H.initialize() else {
|
||||
preconditionFailure("Unable to initialize digest state")
|
||||
}
|
||||
self.context = context
|
||||
}
|
||||
|
||||
init(copying original: XKCPDigestContext) {
|
||||
self.context = original.context
|
||||
}
|
||||
|
||||
func update(data: UnsafeRawBufferPointer) {
|
||||
guard H.update(&self.context, data: data) else {
|
||||
preconditionFailure("Unable to update digest state")
|
||||
}
|
||||
}
|
||||
|
||||
func finalize() -> H.Digest {
|
||||
var copyContext = self.context
|
||||
defer {
|
||||
withUnsafeMutablePointer(to: ©Context) { $0.zeroize() }
|
||||
}
|
||||
return withUnsafeTemporaryAllocation(byteCount: H.digestSize, alignment: 1) { digestPointer in
|
||||
defer {
|
||||
digestPointer.zeroize()
|
||||
}
|
||||
guard H.finalize(©Context, digest: digestPointer) else {
|
||||
preconditionFailure("Unable to finalize digest state")
|
||||
}
|
||||
// We force unwrap here because if the digest size is wrong it's an internal error.
|
||||
return H.Digest(bufferPointer: UnsafeRawBufferPointer(digestPointer))!
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
withUnsafeMutablePointer(to: &self.context) { $0.zeroize() }
|
||||
}
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -14,14 +14,23 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension HPKE {
|
||||
/// The authenticated encryption with associated data (AEAD) algorithms to use in HPKE.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum AEAD: CaseIterable, Hashable {
|
||||
public enum AEAD: CaseIterable, Hashable, Sendable {
|
||||
/// An Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 128 bits.
|
||||
case AES_GCM_128
|
||||
/// An Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 256 bits.
|
||||
@@ -33,7 +42,9 @@ extension HPKE {
|
||||
/// In export-only mode, HPKE negotiates key derivation, but you can't use it to encrypt or decrypt data.
|
||||
case exportOnly
|
||||
|
||||
internal var value: UInt16 {
|
||||
/// Return the AEAD algorithm identifier as defined in section 7.3 of [RFC 9180](https://www.ietf.org/rfc/rfc9180.pdf).
|
||||
@_spi(HPKEAlgID)
|
||||
public var value: UInt16 {
|
||||
switch self {
|
||||
case .AES_GCM_128: return 0x0001
|
||||
case .AES_GCM_256: return 0x0002
|
||||
@@ -46,7 +57,9 @@ extension HPKE {
|
||||
return self == .exportOnly
|
||||
}
|
||||
|
||||
internal var keyByteCount: Int {
|
||||
/// Return the AEAD key size in bytes
|
||||
@_spi(HPKEAlgID)
|
||||
public var keyByteCount: Int {
|
||||
switch self {
|
||||
case .AES_GCM_128:
|
||||
return 16
|
||||
@@ -59,7 +72,9 @@ extension HPKE {
|
||||
}
|
||||
}
|
||||
|
||||
internal var nonceByteCount: Int {
|
||||
/// Return the AEAD nonce size in bytes
|
||||
@_spi(HPKEAlgID)
|
||||
public var nonceByteCount: Int {
|
||||
switch self {
|
||||
case .AES_GCM_128, .AES_GCM_256, .chaChaPoly:
|
||||
return 12
|
||||
@@ -68,7 +83,9 @@ extension HPKE {
|
||||
}
|
||||
}
|
||||
|
||||
internal var tagByteCount: Int {
|
||||
/// Return the AEAD tag size in bytes
|
||||
@_spi(HPKEAlgID)
|
||||
public var tagByteCount: Int {
|
||||
switch self {
|
||||
case .AES_GCM_128, .AES_GCM_256, .chaChaPoly:
|
||||
return 16
|
||||
@@ -81,7 +98,8 @@ extension HPKE {
|
||||
return I2OSP(value: Int(self.value), outputByteCount: 2)
|
||||
}
|
||||
|
||||
internal func seal<D: DataProtocol, AD: DataProtocol>(_ message: D, authenticating aad: AD, nonce: Data, using key: SymmetricKey) throws -> Data {
|
||||
@_spi(MLS)
|
||||
public func seal<D: DataProtocol, AD: DataProtocol>(_ message: D, authenticating aad: AD, nonce: Data, using key: SymmetricKey) throws -> Data {
|
||||
switch self {
|
||||
case .chaChaPoly:
|
||||
return try ChaChaPoly.seal(message, using: key, nonce: ChaChaPoly.Nonce(data: nonce), authenticating: aad).combined.dropFirst(nonce.count)
|
||||
@@ -90,7 +108,8 @@ extension HPKE {
|
||||
}
|
||||
}
|
||||
|
||||
internal func open<C: DataProtocol, AD: DataProtocol>(_ ct: C, nonce: Data, authenticating aad: AD, using key: SymmetricKey) throws -> Data {
|
||||
@_spi(MLS)
|
||||
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 {
|
||||
throw HPKE.Errors.expectedPSK
|
||||
}
|
||||
|
||||
@@ -14,19 +14,28 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension HPKE {
|
||||
/// Cipher suites to use in hybrid public key encryption.
|
||||
/// Cipher suites to use in hybrid public key encryption (HPKE).
|
||||
///
|
||||
/// HPKE cipher suites identify the authenticated encryption with additional data (AEAD) algorithm for encrypting
|
||||
/// and decrypting messages, the key derivation function (KDF) for deriving the shared key, and the key encapsulation
|
||||
/// mechanism (KEM) for sharing the symmetric key. The sender and recipient of encrypted messages need to use the
|
||||
/// same cipher suite.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct Ciphersuite {
|
||||
public struct Ciphersuite: Sendable {
|
||||
/// A cipher suite for HPKE that uses NIST P-256 elliptic curve key agreement, SHA-2 key derivation
|
||||
/// with a 256-bit digest, and the Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 256 bits.
|
||||
public static let P256_SHA256_AES_GCM_256 = Ciphersuite(kem: .P256_HKDF_SHA256, kdf: .HKDF_SHA256, aead: .AES_GCM_256)
|
||||
@@ -39,7 +48,10 @@ extension HPKE {
|
||||
/// A cipher suite for HPKE that uses X25519 elliptic curve key agreement, SHA-2 key derivation
|
||||
/// with a 256-bit digest, and the ChaCha20 stream cipher with the Poly1305 message authentication code.
|
||||
public static let Curve25519_SHA256_ChachaPoly = Ciphersuite(kem: .Curve25519_HKDF_SHA256, kdf: .HKDF_SHA256, aead: .chaChaPoly)
|
||||
|
||||
/// A cipher suite for HPKE that uses the X-Wing KEM (ML-KEM-768 with X25519), 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.
|
||||
public static let XWingMLKEM768X25519_SHA256_AES_GCM_256 = Ciphersuite(kem: .XWingMLKEM768X25519, kdf: .HKDF_SHA256, aead: .AES_GCM_256)
|
||||
|
||||
fileprivate static let ciphersuiteLabel = Data("HPKE".utf8)
|
||||
|
||||
/// The key encapsulation mechanism (KEM) for encapsulating the symmetric key.
|
||||
|
||||
@@ -14,22 +14,32 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension HPKE {
|
||||
/// The key derivation functions to use in HPKE.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum KDF: CaseIterable, Hashable {
|
||||
public enum KDF: CaseIterable, Hashable, Sendable {
|
||||
/// An HMAC-based key derivation function that uses SHA-2 hashing with a 256-bit digest.
|
||||
case HKDF_SHA256
|
||||
/// An HMAC-based key derivation function that uses SHA-2 hashing with a 384-bit digest.
|
||||
case HKDF_SHA384
|
||||
/// An HMAC-based key derivation function that uses SHA-2 hashing with a 512-bit digest.
|
||||
case HKDF_SHA512
|
||||
|
||||
/// Assigned value
|
||||
internal var value: UInt16 {
|
||||
|
||||
/// Return the KDF algorithm identifier as defined in section 7.2 of [RFC 9180](https://www.ietf.org/rfc/rfc9180.pdf).
|
||||
@_spi(HPKEAlgID)
|
||||
public var value: UInt16 {
|
||||
switch self {
|
||||
case .HKDF_SHA256: return 0x0001
|
||||
case .HKDF_SHA384: return 0x0002
|
||||
@@ -63,7 +73,8 @@ extension HPKE {
|
||||
/// - ikm: The initial key material the derivation function uses to derive a key.
|
||||
///
|
||||
/// - Returns: A pseudorandom, cryptographically strong key in the form of a hashed authentication code.
|
||||
func extract<S: DataProtocol>(salt: S, ikm: SymmetricKey) -> SymmetricKey {
|
||||
@_spi(MLS)
|
||||
public func extract<S: DataProtocol>(salt: S, ikm: SymmetricKey) -> SymmetricKey {
|
||||
switch self {
|
||||
case .HKDF_SHA256:
|
||||
return SymmetricKey(data: HKDF<SHA256>.extract(inputKeyMaterial: ikm, salt: salt))
|
||||
@@ -85,7 +96,8 @@ extension HPKE {
|
||||
/// - outputByteCount: The length in bytes of the resulting symmetric key.
|
||||
///
|
||||
/// - Returns: The derived symmetric key.
|
||||
func expand(prk: SymmetricKey, info: Data, outputByteCount: Int) -> SymmetricKey {
|
||||
@_spi(MLS)
|
||||
public func expand(prk: SymmetricKey, info: Data, outputByteCount: Int) -> SymmetricKey {
|
||||
switch self {
|
||||
case .HKDF_SHA256:
|
||||
return SymmetricKey(data: HKDF<SHA256>.expand(pseudoRandomKey: prk, info: info, outputByteCount: outputByteCount))
|
||||
|
||||
@@ -14,7 +14,17 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
private let suiteIDLabel = Data("KEM".utf8)
|
||||
@@ -27,7 +37,7 @@ extension HPKE {
|
||||
pkRm: Data, pkSm: Data? = nil, kem: HPKE.KEM, kdf: HPKE.KDF) -> SymmetricKey {
|
||||
var suiteID = suiteIDLabel
|
||||
suiteID.append(kem.identifier)
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#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
|
||||
@@ -40,7 +50,7 @@ extension HPKE {
|
||||
var context = Data()
|
||||
context.append(enc)
|
||||
context.append(pkRm)
|
||||
if let pkSm = pkSm { context.append(pkSm) }
|
||||
if let pkSm { context.append(pkSm) }
|
||||
return context
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,17 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
private let protocolLabel = Data("HPKE-v1".utf8)
|
||||
|
||||
@@ -14,15 +14,44 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
#if os(Windows)
|
||||
import ucrt
|
||||
#elseif canImport(Darwin)
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#elseif canImport(WASILibc)
|
||||
import WASILibc
|
||||
#endif
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal func I2OSP(value: Int, outputByteCount: Int) -> Data {
|
||||
precondition(outputByteCount > 0, "Cannot I2OSP with no output length.")
|
||||
precondition(value >= 0, "I2OSP requires a non-null value.")
|
||||
|
||||
#if !CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
let requiredBytes = Int(ceil(log2(Double(max(value, 1) + 1)) / 8))
|
||||
#else
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
let requiredBytes = Int((log2_bridge(Double(max(value, 1) + 1)) / 8).rounded(.up))
|
||||
#endif
|
||||
|
||||
precondition(outputByteCount >= requiredBytes)
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
|
||||
@@ -14,11 +14,21 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/// A type that ``HPKE`` uses to encode the public key.
|
||||
@preconcurrency
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol HPKEPublicKeySerialization {
|
||||
public protocol HPKEPublicKeySerialization: Sendable {
|
||||
/// Creates a public key from an encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -35,35 +45,58 @@ public protocol HPKEPublicKeySerialization {
|
||||
}
|
||||
|
||||
/// A type that represents the public key in a Diffie-Hellman key exchange.
|
||||
@preconcurrency
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol HPKEDiffieHellmanPublicKey: HPKEPublicKeySerialization where EphemeralPrivateKey.PublicKey == Self {
|
||||
public protocol HPKEDiffieHellmanPublicKey: HPKEPublicKeySerialization, Sendable where EphemeralPrivateKey.PublicKey == Self {
|
||||
/// The type of the ephemeral private key.
|
||||
associatedtype EphemeralPrivateKey: HPKEDiffieHellmanPrivateKeyGeneration
|
||||
}
|
||||
|
||||
/// A type that represents the private key in a Diffie-Hellman key exchange.
|
||||
|
||||
/// A type that represents the public key in HPKE
|
||||
@preconcurrency
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol HPKEDiffieHellmanPrivateKey: DiffieHellmanKeyAgreement where PublicKey: HPKEDiffieHellmanPublicKey {}
|
||||
public protocol HPKEKEMPublicKey: KEMPublicKey, HPKEPublicKeySerialization where EphemeralPrivateKey.PublicKey == Self {
|
||||
/// The type of the ephemeral private key.
|
||||
associatedtype EphemeralPrivateKey: HPKEKEMPrivateKeyGeneration
|
||||
}
|
||||
|
||||
/// A type that represents the private key in a Diffie-Hellman key exchange.
|
||||
@preconcurrency
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol HPKEDiffieHellmanPrivateKey: Sendable, DiffieHellmanKeyAgreement where PublicKey: HPKEDiffieHellmanPublicKey {}
|
||||
|
||||
/// A type that represents the private key in HPKE.
|
||||
@preconcurrency
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol HPKEKEMPrivateKey: Sendable, KEMPrivateKey where PublicKey: HPKEKEMPublicKey {}
|
||||
|
||||
/// A type that represents the generation of private keys in a Diffie-Hellman key exchange.
|
||||
@preconcurrency
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol HPKEDiffieHellmanPrivateKeyGeneration: HPKEDiffieHellmanPrivateKey {
|
||||
public protocol HPKEDiffieHellmanPrivateKeyGeneration: HPKEDiffieHellmanPrivateKey, Sendable {
|
||||
/// Creates a private key generator.
|
||||
init()
|
||||
}
|
||||
|
||||
/// A type that represents the generation of private keys in HPKE
|
||||
@preconcurrency
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol HPKEKEMPrivateKeyGeneration: HPKEKEMPrivateKey, Sendable {
|
||||
/// Creates a private key generator.
|
||||
init() throws
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension HPKE {
|
||||
/// A container for Diffie-Hellman key encapsulation mechanisms (KEMs).
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum DHKEM {
|
||||
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 {
|
||||
let kem: HPKE.KEM
|
||||
let key: DHPK
|
||||
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
typealias EncapsulationResult = CryptoKit.KEM.EncapsulationResult
|
||||
#else
|
||||
typealias EncapsulationResult = Crypto.KEM.EncapsulationResult
|
||||
|
||||
@@ -14,7 +14,17 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
public import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Curve25519.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {}
|
||||
|
||||
@@ -14,9 +14,16 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
public import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension P256.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
||||
|
||||
@@ -14,13 +14,30 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension HPKE {
|
||||
/// The key encapsulation mechanisms to use in HPKE.
|
||||
///
|
||||
/// The module-lattice key encapsulation mechanism (ML-KEM) is designed to offer increased security in situations
|
||||
/// where an adversary uses a quantum computer.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum KEM: CaseIterable, Hashable {
|
||||
public enum KEM: CaseIterable, Hashable, Sendable {
|
||||
public static var allCases: [HPKE.KEM] {
|
||||
var cases = [KEM.P256_HKDF_SHA256, KEM.P384_HKDF_SHA384, KEM.P521_HKDF_SHA512, KEM.Curve25519_HKDF_SHA256]
|
||||
cases.append(KEM.XWingMLKEM768X25519)
|
||||
return cases
|
||||
}
|
||||
|
||||
/// A key encapsulation mechanism using NIST P-256 elliptic curve key agreement
|
||||
/// and SHA-2 hashing with a 256-bit digest.
|
||||
case P256_HKDF_SHA256
|
||||
@@ -33,22 +50,29 @@ extension HPKE {
|
||||
/// A key encapsulation mechanism using X25519 elliptic curve key agreement
|
||||
/// and SHA-2 hashing with a 256-bit digest.
|
||||
case Curve25519_HKDF_SHA256
|
||||
|
||||
internal var value: UInt16 {
|
||||
/// A key encapsulation mechanism using the X-Wing (ML-KEM-768 with X25519) key encapsulation mechanism
|
||||
/// and SHA-2 hashing with a 256-bit digest.
|
||||
case XWingMLKEM768X25519
|
||||
|
||||
/// Return the KEM algorithm identifier as defined in section 7.1 of [RFC 9180](https://www.ietf.org/rfc/rfc9180.pdf).
|
||||
@_spi(HPKEAlgID)
|
||||
public var value: UInt16 {
|
||||
switch self {
|
||||
case .P256_HKDF_SHA256: return 0x0010
|
||||
case .P384_HKDF_SHA384: return 0x0011
|
||||
case .P521_HKDF_SHA512: return 0x0012
|
||||
case .Curve25519_HKDF_SHA256: return 0x0020
|
||||
case .P256_HKDF_SHA256: return 0x0010
|
||||
case .P384_HKDF_SHA384: return 0x0011
|
||||
case .P521_HKDF_SHA512: return 0x0012
|
||||
case .Curve25519_HKDF_SHA256: return 0x0020
|
||||
case .XWingMLKEM768X25519: return 0x647a // https://datatracker.ietf.org/doc/html/draft-connolly-cfrg-xwing-kem-06#name-iana-considerations
|
||||
}
|
||||
}
|
||||
|
||||
internal var kdf: HPKE.KDF {
|
||||
switch self {
|
||||
case .P256_HKDF_SHA256: return .HKDF_SHA256
|
||||
case .P384_HKDF_SHA384: return .HKDF_SHA384
|
||||
case .P521_HKDF_SHA512: return .HKDF_SHA512
|
||||
case .Curve25519_HKDF_SHA256: return .HKDF_SHA256
|
||||
case .P256_HKDF_SHA256: return .HKDF_SHA256
|
||||
case .P384_HKDF_SHA384: return .HKDF_SHA384
|
||||
case .P521_HKDF_SHA512: return .HKDF_SHA512
|
||||
case .Curve25519_HKDF_SHA256: return .HKDF_SHA256
|
||||
case .XWingMLKEM768X25519: return .HKDF_SHA256
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,10 +82,23 @@ extension HPKE {
|
||||
|
||||
internal var nSecret: UInt16 {
|
||||
switch self {
|
||||
case .P256_HKDF_SHA256: return 32
|
||||
case .P384_HKDF_SHA384: return 48
|
||||
case .P521_HKDF_SHA512: return 64
|
||||
case .Curve25519_HKDF_SHA256: return 32
|
||||
case .P256_HKDF_SHA256: return 32
|
||||
case .P384_HKDF_SHA384: return 48
|
||||
case .P521_HKDF_SHA512: return 64
|
||||
case .Curve25519_HKDF_SHA256: return 32
|
||||
case .XWingMLKEM768X25519: return 32
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the size of the encapsulation in bytes
|
||||
@_spi(HPKEAlgID)
|
||||
public var nEnc: UInt16 {
|
||||
switch self {
|
||||
case .P256_HKDF_SHA256: return 65
|
||||
case .P384_HKDF_SHA384: return 97
|
||||
case .P521_HKDF_SHA512: return 133
|
||||
case .Curve25519_HKDF_SHA256: return 32
|
||||
case .XWingMLKEM768X25519: return 1120
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,16 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension HPKE {
|
||||
|
||||
@@ -14,7 +14,15 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/// A container for hybrid public key encryption (HPKE) operations.
|
||||
///
|
||||
@@ -46,10 +54,14 @@ import Foundation
|
||||
/// ### Handling errors
|
||||
/// - ``Errors``
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum HPKE {}
|
||||
public enum HPKE: Sendable {}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension HPKE {
|
||||
/// Static constant used to store the fixed-string label for the HPKE export API
|
||||
/// See: https://datatracker.ietf.org/doc/html/rfc9180#name-secret-export
|
||||
fileprivate static let exportLabel = Data("sec".utf8)
|
||||
|
||||
/// A type that represents the sending side of an HPKE message exchange.
|
||||
///
|
||||
/// To create encrypted messages, initialize a `Sender` specifying the appropriate cipher suite,
|
||||
@@ -59,11 +71,11 @@ extension HPKE {
|
||||
/// same order as the `Sender`, using the same encryption mode, cipher suite, and key schedule information
|
||||
/// (`info`), as well as the `Sender`'s ``encapsulatedKey``.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct Sender {
|
||||
public struct Sender: Sendable {
|
||||
private var context: Context
|
||||
/// The encapsulated symmetric key that the recipient uses to decrypt messages.
|
||||
public let encapsulatedKey: Data
|
||||
|
||||
|
||||
/// The exporter secret.
|
||||
internal var exporterSecret: SymmetricKey {
|
||||
return context.keySchedule.exporterSecret
|
||||
@@ -77,13 +89,13 @@ extension HPKE {
|
||||
public func exportSecret<Context: DataProtocol>(context: Context, outputByteCount: Int) throws -> SymmetricKey {
|
||||
precondition(outputByteCount > 0);
|
||||
return LabeledExpand(prk: self.exporterSecret,
|
||||
label: Data("sec".utf8),
|
||||
label: exportLabel,
|
||||
info: context,
|
||||
outputByteCount: UInt16(outputByteCount),
|
||||
suiteID: self.context.keySchedule.ciphersuite.identifier,
|
||||
kdf: self.context.keySchedule.ciphersuite.kdf)
|
||||
}
|
||||
|
||||
|
||||
/// Creates a sender in base mode.
|
||||
///
|
||||
/// The `Sender` encrypts messages in base mode with a symmetric encryption key it derives using a key derivation function (KDF).
|
||||
@@ -100,7 +112,24 @@ extension HPKE {
|
||||
self.context = try Context(senderRoleWithCiphersuite: ciphersuite, mode: .base, psk: nil, pskID: nil, pkR: recipientKey, info: info)
|
||||
self.encapsulatedKey = context.encapsulated
|
||||
}
|
||||
|
||||
|
||||
/// Creates a sender in base mode.
|
||||
///
|
||||
/// The `Sender` encrypts messages in base mode with a symmetric encryption key it derives using a key derivation function (KDF).
|
||||
/// The KDF uses the key schedule data in `info` as input to generate the key.
|
||||
/// The `Sender` encapsulates the derived key using the recipient's public key.
|
||||
/// You access the encapsulated key using ``encapsulatedKey``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - recipientKey: The recipient's public key for encrypting the messages.
|
||||
/// - ciphersuite: The cipher suite that defines the cryptographic algorithms to use.
|
||||
/// - info: Data that the key derivation function uses to compute the symmetric key material. The sender and the recipient need to use the same `info` data.
|
||||
/// - Note: The system throws errors from ``CryptoKit/HPKE/Errors`` when it encounters them.
|
||||
public init<PK: HPKEKEMPublicKey>(recipientKey: PK, ciphersuite: Ciphersuite, info: Data) throws {
|
||||
self.context = try Context(senderRoleWithCiphersuite: ciphersuite, mode: .base, psk: nil, pskID: nil, pkR: recipientKey, info: info)
|
||||
self.encapsulatedKey = context.encapsulated
|
||||
}
|
||||
|
||||
/// Creates a sender in preshared key (PSK) mode.
|
||||
///
|
||||
/// The `Sender` encrypts messages in PSK mode using a symmetric encryption key that the sender and recipient both know in advance, in combination with a key it derives using a key derivation function (KDF) and
|
||||
@@ -197,15 +226,15 @@ extension HPKE {
|
||||
/// (`info` data).
|
||||
/// Use a separate `Recipient` instance for each stream of messages.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct Recipient {
|
||||
public struct Recipient: Sendable {
|
||||
|
||||
private var context: Context
|
||||
|
||||
|
||||
/// The exporter secret.
|
||||
internal var exporterSecret: SymmetricKey {
|
||||
return context.keySchedule.exporterSecret
|
||||
}
|
||||
|
||||
|
||||
/// Exports a secret given domain-separation context and the desired output length.
|
||||
/// - Parameters:
|
||||
/// - context: Application-specific information providing context on the use of this key.
|
||||
@@ -214,12 +243,26 @@ extension HPKE {
|
||||
public func exportSecret<Context: DataProtocol>(context: Context, outputByteCount: Int) throws -> SymmetricKey {
|
||||
precondition(outputByteCount > 0);
|
||||
return LabeledExpand(prk: self.exporterSecret,
|
||||
label: Data("sec".utf8),
|
||||
label: exportLabel,
|
||||
info: context,
|
||||
outputByteCount: UInt16(outputByteCount),
|
||||
suiteID: self.context.keySchedule.ciphersuite.identifier,
|
||||
kdf: self.context.keySchedule.ciphersuite.kdf)
|
||||
}
|
||||
|
||||
/// Creates a recipient in base mode.
|
||||
///
|
||||
/// The `Receiver` decrypts messages in base mode using the encapsulated key with the key schedule information (`info` data).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - privateKey: The recipient's private key for decrypting the incoming messages.
|
||||
/// - ciphersuite: The cipher suite that defines the cryptographic algorithms to use.
|
||||
/// - info: Data that the key derivation function uses to compute the symmetric key material. The sender and the recipient need to use the same `info` data.
|
||||
/// - encapsulatedKey: The encapsulated symmetric key that the sender provides.
|
||||
/// - Note: The system throws errors from ``CryptoKit/HPKE/Errors`` when it encounters them.
|
||||
public init<SK: HPKEDiffieHellmanPrivateKey>(privateKey: SK, ciphersuite: Ciphersuite, info: Data, encapsulatedKey: Data) throws {
|
||||
self.context = try Context(recipientRoleWithCiphersuite: ciphersuite, mode: .base, enc: encapsulatedKey, psk: nil, pskID: nil, skR: privateKey, info: info, pkS: nil)
|
||||
}
|
||||
|
||||
/// Creates a recipient in base mode.
|
||||
///
|
||||
@@ -231,7 +274,7 @@ extension HPKE {
|
||||
/// - info: Data that the key derivation function uses to compute the symmetric key material. The sender and the recipient need to use the same `info` data.
|
||||
/// - encapsulatedKey: The encapsulated symmetric key that the sender provides.
|
||||
/// - Note: The system throws errors from ``CryptoKit/HPKE/Errors`` when it encounters them.
|
||||
public init<SK: HPKEDiffieHellmanPrivateKey>(privateKey: SK, ciphersuite: Ciphersuite, info: Data, encapsulatedKey: Data) throws {
|
||||
public init<SK: HPKEKEMPrivateKey>(privateKey: SK, ciphersuite: Ciphersuite, info: Data, encapsulatedKey: Data) throws {
|
||||
self.context = try Context(recipientRoleWithCiphersuite: ciphersuite, mode: .base, enc: encapsulatedKey, psk: nil, pskID: nil, skR: privateKey, info: info, pkS: nil)
|
||||
}
|
||||
|
||||
|
||||
@@ -14,12 +14,21 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension HPKE {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct Context {
|
||||
struct Context: Sendable {
|
||||
var keySchedule: KeySchedule
|
||||
var encapsulated: Data
|
||||
|
||||
@@ -31,7 +40,14 @@ extension HPKE {
|
||||
self.keySchedule = try KeySchedule(mode: mode,
|
||||
sharedSecret: encapsulationResult.sharedSecret, info: info, psk: psk, pskID: pskID, ciphersuite: ciphersuite)
|
||||
}
|
||||
|
||||
|
||||
init<PublicKey: HPKEKEMPublicKey>(senderRoleWithCiphersuite ciphersuite: Ciphersuite, mode: Mode, psk: SymmetricKey?, pskID: Data?, pkR: PublicKey, info: Data) throws {
|
||||
let encapsulationResult = try pkR.encapsulate()
|
||||
encapsulated = encapsulationResult.encapsulated
|
||||
self.keySchedule = try KeySchedule(mode: mode,
|
||||
sharedSecret: encapsulationResult.sharedSecret, info: info, psk: psk, pskID: pskID, ciphersuite: ciphersuite)
|
||||
}
|
||||
|
||||
init<SK: HPKEDiffieHellmanPrivateKey>(senderRoleWithCiphersuite ciphersuite: Ciphersuite, mode: Mode, psk: SymmetricKey?, pskID: Data?, pkR: SK.PublicKey, info: Data, skS: SK) throws {
|
||||
|
||||
let skSKEM = try HPKE.DHKEM.PrivateKey(skS, kem: ciphersuite.kem)
|
||||
@@ -47,7 +63,7 @@ extension HPKE {
|
||||
let skRKEM = try HPKE.DHKEM.PrivateKey(skR, kem: ciphersuite.kem)
|
||||
|
||||
let sharedSecret: SymmetricKey
|
||||
if let pkS = pkS {
|
||||
if let pkS {
|
||||
sharedSecret = try skRKEM.decapsulate(enc, authenticating: pkS)
|
||||
} else {
|
||||
sharedSecret = try skRKEM.decapsulate(enc)
|
||||
@@ -57,6 +73,11 @@ extension HPKE {
|
||||
self.keySchedule = try KeySchedule(mode: mode, sharedSecret: sharedSecret, info: info, psk: psk, pskID: pskID, ciphersuite: ciphersuite)
|
||||
}
|
||||
|
||||
init<PrivateKey: HPKEKEMPrivateKey>(recipientRoleWithCiphersuite ciphersuite: Ciphersuite, mode: Mode, enc: Data, psk: SymmetricKey?, pskID: Data?, skR: PrivateKey, info: Data, pkS: PrivateKey.PublicKey?) throws {
|
||||
let sharedSecret = try skR.decapsulate(enc)
|
||||
self.encapsulated = enc
|
||||
self.keySchedule = try KeySchedule(mode: mode, sharedSecret: sharedSecret, info: info, psk: psk, pskID: pskID, ciphersuite: ciphersuite)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,12 +14,21 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension HPKE {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal struct KeySchedule {
|
||||
internal struct KeySchedule: Sendable {
|
||||
fileprivate static let pksIDHashLabel = Data("psk_id_hash".utf8)
|
||||
fileprivate static let infoHashLabel = Data("info_hash".utf8)
|
||||
fileprivate static let secretLabel = Data("secret".utf8)
|
||||
@@ -103,8 +112,19 @@ extension HPKE {
|
||||
self.ciphersuite = ciphersuite
|
||||
}
|
||||
|
||||
var maxSequenceNumber: UInt64 {
|
||||
get {
|
||||
let nonceBitCount = UInt64(self.ciphersuite.aead.nonceByteCount * 8)
|
||||
if (nonceBitCount >= 64) {
|
||||
return UInt64.max
|
||||
}
|
||||
|
||||
return ((UInt64(1) << nonceBitCount) - 1)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func incrementSequenceNumber() throws {
|
||||
if self.sequenceNumber >= ((1 << (self.ciphersuite.aead.nonceByteCount)) - 1) {
|
||||
if self.sequenceNumber >= maxSequenceNumber {
|
||||
throw HPKE.Errors.outOfRangeSequenceNumber
|
||||
}
|
||||
sequenceNumber += 1
|
||||
|
||||
@@ -20,5 +20,5 @@
|
||||
/// but the framework provides them for backward compatibility with older
|
||||
/// services that require them. For new services, avoid these algorithms.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum Insecure {}
|
||||
public enum Insecure: Sendable {}
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -33,21 +33,13 @@ extension Insecure {
|
||||
/// that require it. For new services, prefer one of the secure hashes, like
|
||||
/// ``SHA512``.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA1: HashFunctionImplementationDetails {
|
||||
public struct SHA1: HashFunctionImplementationDetails, Sendable {
|
||||
/// The number of bytes that represents the hash function’s internal
|
||||
/// state.
|
||||
public static var blockByteCount: Int {
|
||||
get { 64 }
|
||||
|
||||
set { fatalError("Cannot set SHA1.blockByteCount") }
|
||||
}
|
||||
public static let blockByteCount: Int = 64
|
||||
|
||||
/// The number of bytes in a SHA1 digest.
|
||||
public static var byteCount: Int {
|
||||
get { 20 }
|
||||
|
||||
set { fatalError("Cannot set SHA1.byteCount") }
|
||||
}
|
||||
public static let byteCount: Int = 20
|
||||
|
||||
/// The digest type for a SHA1 hash function.
|
||||
public typealias Digest = Insecure.SHA1Digest
|
||||
@@ -122,20 +114,12 @@ extension Insecure {
|
||||
/// that require it. For new services, prefer one of the secure hashes, like
|
||||
/// ``SHA512``.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct MD5: HashFunctionImplementationDetails {
|
||||
public struct MD5: HashFunctionImplementationDetails, Sendable {
|
||||
/// The number of bytes that represents the hash function’s internal
|
||||
/// state.
|
||||
public static var blockByteCount: Int {
|
||||
get { 64 }
|
||||
|
||||
set { fatalError("Cannot set MD5.blockByteCount") }
|
||||
}
|
||||
public static let blockByteCount: Int = 64
|
||||
/// The number of bytes in an MD5 digest.
|
||||
public static var byteCount: Int {
|
||||
get { 16 }
|
||||
|
||||
set { fatalError("Cannot set MD5.byteCount") }
|
||||
}
|
||||
public static let byteCount: Int = 16
|
||||
|
||||
/// The digest type for a MD5 hash function.
|
||||
public typealias Digest = Insecure.MD5Digest
|
||||
|
||||
@@ -0,0 +1,571 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2024-2025 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// MARK: - Generated file, do NOT edit
|
||||
// any edits of this file WILL be overwritten and thus discarded
|
||||
// see section `gyb` in `README` for details.
|
||||
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM768 {
|
||||
/// A ML-KEM-768 private key.
|
||||
struct InternalPrivateKey: @unchecked Sendable, KEMPrivateKey {
|
||||
private var backing: Backing
|
||||
|
||||
/// Initialize a ML-KEM-768 private key from a random seed.
|
||||
init() {
|
||||
self.backing = Backing()
|
||||
}
|
||||
|
||||
/// Generate a ML-KEM-768 private key from a random seed.
|
||||
///
|
||||
/// - Returns: The generated private key.
|
||||
static func generate() -> MLKEM768.InternalPrivateKey {
|
||||
.init()
|
||||
}
|
||||
|
||||
/// Initialize a ML-KEM-768 private key from a seed.
|
||||
///
|
||||
/// - Parameter seedRepresentation: The seed to use to generate the private key.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectKeySize` if the seed is not 64 bytes long.
|
||||
init(seedRepresentation: some DataProtocol) throws {
|
||||
self.backing = try Backing(seedRepresentation: seedRepresentation)
|
||||
}
|
||||
|
||||
/// The seed from which this private key was generated.
|
||||
var seedRepresentation: Data {
|
||||
self.backing.seed
|
||||
}
|
||||
|
||||
/// The public key associated with this private key.
|
||||
var publicKey: InternalPublicKey {
|
||||
self.backing.publicKey
|
||||
}
|
||||
|
||||
/// Decapsulate a shared secret and create a symmetric key.
|
||||
///
|
||||
/// - Parameter encapsulated: The encapsulated shared secret.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectParameterSize` if the encapsulated shared secret is not 1088 bytes long.
|
||||
///
|
||||
/// - Returns: The symmetric key.
|
||||
func decapsulate(_ encapsulated: some DataProtocol) throws -> SymmetricKey {
|
||||
try self.backing.decapsulate(encapsulated)
|
||||
}
|
||||
|
||||
fileprivate final class Backing {
|
||||
var key: MLKEM768_private_key
|
||||
var seed: Data
|
||||
|
||||
/// Initialize a ML-KEM-768 private key from a random seed.
|
||||
init() {
|
||||
self.key = .init()
|
||||
self.seed = Data()
|
||||
|
||||
self.seed = withUnsafeTemporaryAllocation(
|
||||
of: UInt8.self,
|
||||
capacity: MLKEM.seedByteCount
|
||||
) { seedPtr in
|
||||
withUnsafeTemporaryAllocation(
|
||||
of: UInt8.self,
|
||||
capacity: MLKEM768.InternalPublicKey.byteCount
|
||||
) { publicKeyPtr in
|
||||
CCryptoBoringSSL_MLKEM768_generate_key(
|
||||
publicKeyPtr.baseAddress,
|
||||
seedPtr.baseAddress,
|
||||
&self.key
|
||||
)
|
||||
|
||||
return Data(bytes: seedPtr.baseAddress!, count: MLKEM.seedByteCount)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Initialize a ML-KEM-768 private key from a seed.
|
||||
///
|
||||
/// - Parameter seedRepresentation: The seed to use to generate the private key.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectKeySize` if the seed is not 64 bytes long.
|
||||
init(seedRepresentation: some DataProtocol) throws {
|
||||
guard seedRepresentation.count == MLKEM.seedByteCount else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
self.key = .init()
|
||||
self.seed = Data(seedRepresentation)
|
||||
|
||||
guard
|
||||
self.seed.withUnsafeBytes({ seedPtr in
|
||||
CCryptoBoringSSL_MLKEM768_private_key_from_seed(
|
||||
&self.key,
|
||||
seedPtr.baseAddress,
|
||||
seedPtr.count
|
||||
)
|
||||
}) == 1
|
||||
else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
}
|
||||
|
||||
/// The public key associated with this private key.
|
||||
var publicKey: InternalPublicKey {
|
||||
InternalPublicKey(privateKeyBacking: self)
|
||||
}
|
||||
|
||||
/// Decapsulate a shared secret and create a symmetric key.
|
||||
///
|
||||
/// - Parameter encapsulated: The encapsulated shared secret.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectParameterSize` if the encapsulated shared secret is not 1088 bytes long.
|
||||
///
|
||||
/// - Returns: The symmetric key.
|
||||
func decapsulate(_ encapsulated: some DataProtocol) throws -> SymmetricKey {
|
||||
guard encapsulated.count == MLKEM768.ciphertextByteCount else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount)
|
||||
|
||||
let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in
|
||||
let bytes: ContiguousBytes =
|
||||
encapsulated.regions.count == 1
|
||||
? encapsulated.regions.first!
|
||||
: Array(encapsulated)
|
||||
return bytes.withUnsafeBytes { encapsulatedPtr in
|
||||
CCryptoBoringSSL_MLKEM768_decap(
|
||||
symmetricKeyDataPtr.baseAddress,
|
||||
encapsulatedPtr.baseAddress,
|
||||
encapsulatedPtr.count,
|
||||
&self.key
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
return SymmetricKey(data: symmetricKeyData)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM768 {
|
||||
/// A ML-KEM-768 public key.
|
||||
struct InternalPublicKey: @unchecked Sendable, KEMPublicKey {
|
||||
private var backing: Backing
|
||||
|
||||
fileprivate init(privateKeyBacking: InternalPrivateKey.Backing) {
|
||||
self.backing = Backing(privateKeyBacking: privateKeyBacking)
|
||||
}
|
||||
|
||||
/// Initialize a ML-KEM-768 public key from a raw representation.
|
||||
///
|
||||
/// - Parameter rawRepresentation: The public key bytes.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectKeySize` if the raw representation is not the correct size.
|
||||
init(rawRepresentation: some DataProtocol) throws {
|
||||
self.backing = try Backing(rawRepresentation: rawRepresentation)
|
||||
}
|
||||
|
||||
/// The raw binary representation of the public key.
|
||||
var rawRepresentation: Data {
|
||||
self.backing.rawRepresentation
|
||||
}
|
||||
|
||||
/// Encapsulate a shared secret.
|
||||
///
|
||||
/// - Returns: The shared secret and its encapsulated version.
|
||||
func encapsulate() -> KEM.EncapsulationResult {
|
||||
self.backing.encapsulate()
|
||||
}
|
||||
|
||||
/// The size of the public key in bytes.
|
||||
static let byteCount = Backing.byteCount
|
||||
|
||||
fileprivate final class Backing {
|
||||
var key: MLKEM768_public_key
|
||||
|
||||
init(privateKeyBacking: InternalPrivateKey.Backing) {
|
||||
self.key = .init()
|
||||
CCryptoBoringSSL_MLKEM768_public_from_private(&self.key, &privateKeyBacking.key)
|
||||
}
|
||||
|
||||
/// Initialize a ML-KEM-768 public key from a raw representation.
|
||||
///
|
||||
/// - Parameter rawRepresentation: The public key bytes.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectKeySize` if the raw representation is not the correct size.
|
||||
init(rawRepresentation: some DataProtocol) throws {
|
||||
guard rawRepresentation.count == MLKEM768.InternalPublicKey.byteCount else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
self.key = .init()
|
||||
|
||||
let bytes: ContiguousBytes =
|
||||
rawRepresentation.regions.count == 1
|
||||
? rawRepresentation.regions.first!
|
||||
: Array(rawRepresentation)
|
||||
try bytes.withUnsafeBytes { rawBuffer in
|
||||
try rawBuffer.withMemoryRebound(to: UInt8.self) { buffer in
|
||||
var cbs = CBS(data: buffer.baseAddress, len: buffer.count)
|
||||
guard CCryptoBoringSSL_MLKEM768_parse_public_key(&self.key, &cbs) == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw binary representation of the public key.
|
||||
var rawRepresentation: Data {
|
||||
var cbb = CBB()
|
||||
// The following BoringSSL functions can only fail on allocation failure, which we define as impossible.
|
||||
CCryptoBoringSSL_CBB_init(&cbb, MLKEM768.InternalPublicKey.Backing.byteCount)
|
||||
defer { CCryptoBoringSSL_CBB_cleanup(&cbb) }
|
||||
CCryptoBoringSSL_MLKEM768_marshal_public_key(&cbb, &self.key)
|
||||
return Data(bytes: CCryptoBoringSSL_CBB_data(&cbb), count: CCryptoBoringSSL_CBB_len(&cbb))
|
||||
}
|
||||
|
||||
/// Encapsulate a shared secret.
|
||||
///
|
||||
/// - Returns: The shared secret and its encapsulated version.
|
||||
func encapsulate() -> KEM.EncapsulationResult {
|
||||
withUnsafeTemporaryAllocation(
|
||||
of: UInt8.self,
|
||||
capacity: MLKEM768.ciphertextByteCount
|
||||
) { encapsulatedPtr in
|
||||
withUnsafeTemporaryAllocation(
|
||||
of: UInt8.self,
|
||||
capacity: MLKEM.sharedSecretByteCount
|
||||
) { secretPtr in
|
||||
CCryptoBoringSSL_MLKEM768_encap(
|
||||
encapsulatedPtr.baseAddress,
|
||||
secretPtr.baseAddress,
|
||||
&self.key
|
||||
)
|
||||
|
||||
return KEM.EncapsulationResult(
|
||||
sharedSecret: SymmetricKey(
|
||||
data: Data(bytes: secretPtr.baseAddress!, count: MLKEM.sharedSecretByteCount)
|
||||
),
|
||||
encapsulated: Data(
|
||||
bytes: encapsulatedPtr.baseAddress!,
|
||||
count: MLKEM768.ciphertextByteCount
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The size of the public key in bytes.
|
||||
static let byteCount = Int(MLKEM768_PUBLIC_KEY_BYTES)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM768 {
|
||||
/// The size of the encapsulated shared secret in bytes.
|
||||
private static let ciphertextByteCount = Int(MLKEM768_CIPHERTEXT_BYTES)
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM1024 {
|
||||
/// A ML-KEM-1024 private key.
|
||||
struct InternalPrivateKey: @unchecked Sendable, KEMPrivateKey {
|
||||
private var backing: Backing
|
||||
|
||||
/// Initialize a ML-KEM-1024 private key from a random seed.
|
||||
init() {
|
||||
self.backing = Backing()
|
||||
}
|
||||
|
||||
/// Generate a ML-KEM-1024 private key from a random seed.
|
||||
///
|
||||
/// - Returns: The generated private key.
|
||||
static func generate() -> MLKEM1024.InternalPrivateKey {
|
||||
.init()
|
||||
}
|
||||
|
||||
/// Initialize a ML-KEM-1024 private key from a seed.
|
||||
///
|
||||
/// - Parameter seedRepresentation: The seed to use to generate the private key.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectKeySize` if the seed is not 64 bytes long.
|
||||
init(seedRepresentation: some DataProtocol) throws {
|
||||
self.backing = try Backing(seedRepresentation: seedRepresentation)
|
||||
}
|
||||
|
||||
/// The seed from which this private key was generated.
|
||||
var seedRepresentation: Data {
|
||||
self.backing.seed
|
||||
}
|
||||
|
||||
/// The public key associated with this private key.
|
||||
var publicKey: InternalPublicKey {
|
||||
self.backing.publicKey
|
||||
}
|
||||
|
||||
/// Decapsulate a shared secret and create a symmetric key.
|
||||
///
|
||||
/// - Parameter encapsulated: The encapsulated shared secret.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectParameterSize` if the encapsulated shared secret is not 1088 bytes long.
|
||||
///
|
||||
/// - Returns: The symmetric key.
|
||||
func decapsulate(_ encapsulated: some DataProtocol) throws -> SymmetricKey {
|
||||
try self.backing.decapsulate(encapsulated)
|
||||
}
|
||||
|
||||
fileprivate final class Backing {
|
||||
var key: MLKEM1024_private_key
|
||||
var seed: Data
|
||||
|
||||
/// Initialize a ML-KEM-1024 private key from a random seed.
|
||||
init() {
|
||||
self.key = .init()
|
||||
self.seed = Data()
|
||||
|
||||
self.seed = withUnsafeTemporaryAllocation(
|
||||
of: UInt8.self,
|
||||
capacity: MLKEM.seedByteCount
|
||||
) { seedPtr in
|
||||
withUnsafeTemporaryAllocation(
|
||||
of: UInt8.self,
|
||||
capacity: MLKEM1024.InternalPublicKey.byteCount
|
||||
) { publicKeyPtr in
|
||||
CCryptoBoringSSL_MLKEM1024_generate_key(
|
||||
publicKeyPtr.baseAddress,
|
||||
seedPtr.baseAddress,
|
||||
&self.key
|
||||
)
|
||||
|
||||
return Data(bytes: seedPtr.baseAddress!, count: MLKEM.seedByteCount)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Initialize a ML-KEM-1024 private key from a seed.
|
||||
///
|
||||
/// - Parameter seedRepresentation: The seed to use to generate the private key.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectKeySize` if the seed is not 64 bytes long.
|
||||
init(seedRepresentation: some DataProtocol) throws {
|
||||
guard seedRepresentation.count == MLKEM.seedByteCount else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
self.key = .init()
|
||||
self.seed = Data(seedRepresentation)
|
||||
|
||||
guard
|
||||
self.seed.withUnsafeBytes({ seedPtr in
|
||||
CCryptoBoringSSL_MLKEM1024_private_key_from_seed(
|
||||
&self.key,
|
||||
seedPtr.baseAddress,
|
||||
seedPtr.count
|
||||
)
|
||||
}) == 1
|
||||
else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
}
|
||||
|
||||
/// The public key associated with this private key.
|
||||
var publicKey: InternalPublicKey {
|
||||
InternalPublicKey(privateKeyBacking: self)
|
||||
}
|
||||
|
||||
/// Decapsulate a shared secret and create a symmetric key.
|
||||
///
|
||||
/// - Parameter encapsulated: The encapsulated shared secret.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectParameterSize` if the encapsulated shared secret is not 1088 bytes long.
|
||||
///
|
||||
/// - Returns: The symmetric key.
|
||||
func decapsulate(_ encapsulated: some DataProtocol) throws -> SymmetricKey {
|
||||
guard encapsulated.count == MLKEM1024.ciphertextByteCount else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount)
|
||||
|
||||
let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in
|
||||
let bytes: ContiguousBytes =
|
||||
encapsulated.regions.count == 1
|
||||
? encapsulated.regions.first!
|
||||
: Array(encapsulated)
|
||||
return bytes.withUnsafeBytes { encapsulatedPtr in
|
||||
CCryptoBoringSSL_MLKEM1024_decap(
|
||||
symmetricKeyDataPtr.baseAddress,
|
||||
encapsulatedPtr.baseAddress,
|
||||
encapsulatedPtr.count,
|
||||
&self.key
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
return SymmetricKey(data: symmetricKeyData)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM1024 {
|
||||
/// A ML-KEM-1024 public key.
|
||||
struct InternalPublicKey: @unchecked Sendable, KEMPublicKey {
|
||||
private var backing: Backing
|
||||
|
||||
fileprivate init(privateKeyBacking: InternalPrivateKey.Backing) {
|
||||
self.backing = Backing(privateKeyBacking: privateKeyBacking)
|
||||
}
|
||||
|
||||
/// Initialize a ML-KEM-1024 public key from a raw representation.
|
||||
///
|
||||
/// - Parameter rawRepresentation: The public key bytes.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectKeySize` if the raw representation is not the correct size.
|
||||
init(rawRepresentation: some DataProtocol) throws {
|
||||
self.backing = try Backing(rawRepresentation: rawRepresentation)
|
||||
}
|
||||
|
||||
/// The raw binary representation of the public key.
|
||||
var rawRepresentation: Data {
|
||||
self.backing.rawRepresentation
|
||||
}
|
||||
|
||||
/// Encapsulate a shared secret.
|
||||
///
|
||||
/// - Returns: The shared secret and its encapsulated version.
|
||||
func encapsulate() -> KEM.EncapsulationResult {
|
||||
self.backing.encapsulate()
|
||||
}
|
||||
|
||||
/// The size of the public key in bytes.
|
||||
static let byteCount = Backing.byteCount
|
||||
|
||||
fileprivate final class Backing {
|
||||
var key: MLKEM1024_public_key
|
||||
|
||||
init(privateKeyBacking: InternalPrivateKey.Backing) {
|
||||
self.key = .init()
|
||||
CCryptoBoringSSL_MLKEM1024_public_from_private(&self.key, &privateKeyBacking.key)
|
||||
}
|
||||
|
||||
/// Initialize a ML-KEM-1024 public key from a raw representation.
|
||||
///
|
||||
/// - Parameter rawRepresentation: The public key bytes.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectKeySize` if the raw representation is not the correct size.
|
||||
init(rawRepresentation: some DataProtocol) throws {
|
||||
guard rawRepresentation.count == MLKEM1024.InternalPublicKey.byteCount else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
self.key = .init()
|
||||
|
||||
let bytes: ContiguousBytes =
|
||||
rawRepresentation.regions.count == 1
|
||||
? rawRepresentation.regions.first!
|
||||
: Array(rawRepresentation)
|
||||
try bytes.withUnsafeBytes { rawBuffer in
|
||||
try rawBuffer.withMemoryRebound(to: UInt8.self) { buffer in
|
||||
var cbs = CBS(data: buffer.baseAddress, len: buffer.count)
|
||||
guard CCryptoBoringSSL_MLKEM1024_parse_public_key(&self.key, &cbs) == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw binary representation of the public key.
|
||||
var rawRepresentation: Data {
|
||||
var cbb = CBB()
|
||||
// The following BoringSSL functions can only fail on allocation failure, which we define as impossible.
|
||||
CCryptoBoringSSL_CBB_init(&cbb, MLKEM1024.InternalPublicKey.Backing.byteCount)
|
||||
defer { CCryptoBoringSSL_CBB_cleanup(&cbb) }
|
||||
CCryptoBoringSSL_MLKEM1024_marshal_public_key(&cbb, &self.key)
|
||||
return Data(bytes: CCryptoBoringSSL_CBB_data(&cbb), count: CCryptoBoringSSL_CBB_len(&cbb))
|
||||
}
|
||||
|
||||
/// Encapsulate a shared secret.
|
||||
///
|
||||
/// - Returns: The shared secret and its encapsulated version.
|
||||
func encapsulate() -> KEM.EncapsulationResult {
|
||||
withUnsafeTemporaryAllocation(
|
||||
of: UInt8.self,
|
||||
capacity: MLKEM1024.ciphertextByteCount
|
||||
) { encapsulatedPtr in
|
||||
withUnsafeTemporaryAllocation(
|
||||
of: UInt8.self,
|
||||
capacity: MLKEM.sharedSecretByteCount
|
||||
) { secretPtr in
|
||||
CCryptoBoringSSL_MLKEM1024_encap(
|
||||
encapsulatedPtr.baseAddress,
|
||||
secretPtr.baseAddress,
|
||||
&self.key
|
||||
)
|
||||
|
||||
return KEM.EncapsulationResult(
|
||||
sharedSecret: SymmetricKey(
|
||||
data: Data(bytes: secretPtr.baseAddress!, count: MLKEM.sharedSecretByteCount)
|
||||
),
|
||||
encapsulated: Data(
|
||||
bytes: encapsulatedPtr.baseAddress!,
|
||||
count: MLKEM1024.ciphertextByteCount
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The size of the public key in bytes.
|
||||
static let byteCount = Int(MLKEM1024_PUBLIC_KEY_BYTES)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM1024 {
|
||||
/// The size of the encapsulated shared secret in bytes.
|
||||
private static let ciphertextByteCount = Int(MLKEM1024_CIPHERTEXT_BYTES)
|
||||
}
|
||||
|
||||
enum MLKEM {
|
||||
/// The size of the seed in bytes.
|
||||
static let seedByteCount = 64
|
||||
|
||||
// The size of the shared secret in bytes.
|
||||
static let sharedSecretByteCount = 32
|
||||
}
|
||||
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -0,0 +1,309 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2024-2025 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// MARK: - Generated file, do NOT edit
|
||||
// any edits of this file WILL be overwritten and thus discarded
|
||||
// see section `gyb` in `README` for details.
|
||||
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
%{
|
||||
parameter_sets = ["768", "1024"]
|
||||
}%
|
||||
% for parameter_set in parameter_sets:
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM${parameter_set} {
|
||||
/// A ML-KEM-${parameter_set} private key.
|
||||
struct InternalPrivateKey: @unchecked Sendable, KEMPrivateKey {
|
||||
private var backing: Backing
|
||||
|
||||
/// Initialize a ML-KEM-${parameter_set} private key from a random seed.
|
||||
init() {
|
||||
self.backing = Backing()
|
||||
}
|
||||
|
||||
/// Generate a ML-KEM-${parameter_set} private key from a random seed.
|
||||
///
|
||||
/// - Returns: The generated private key.
|
||||
static func generate() -> MLKEM${parameter_set}.InternalPrivateKey {
|
||||
.init()
|
||||
}
|
||||
|
||||
/// Initialize a ML-KEM-${parameter_set} private key from a seed.
|
||||
///
|
||||
/// - Parameter seedRepresentation: The seed to use to generate the private key.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectKeySize` if the seed is not 64 bytes long.
|
||||
init(seedRepresentation: some DataProtocol) throws {
|
||||
self.backing = try Backing(seedRepresentation: seedRepresentation)
|
||||
}
|
||||
|
||||
/// The seed from which this private key was generated.
|
||||
var seedRepresentation: Data {
|
||||
self.backing.seed
|
||||
}
|
||||
|
||||
/// The public key associated with this private key.
|
||||
var publicKey: InternalPublicKey {
|
||||
self.backing.publicKey
|
||||
}
|
||||
|
||||
/// Decapsulate a shared secret and create a symmetric key.
|
||||
///
|
||||
/// - Parameter encapsulated: The encapsulated shared secret.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectParameterSize` if the encapsulated shared secret is not 1088 bytes long.
|
||||
///
|
||||
/// - Returns: The symmetric key.
|
||||
func decapsulate(_ encapsulated: some DataProtocol) throws -> SymmetricKey {
|
||||
try self.backing.decapsulate(encapsulated)
|
||||
}
|
||||
|
||||
fileprivate final class Backing {
|
||||
var key: MLKEM${parameter_set}_private_key
|
||||
var seed: Data
|
||||
|
||||
/// Initialize a ML-KEM-${parameter_set} private key from a random seed.
|
||||
init() {
|
||||
self.key = .init()
|
||||
self.seed = Data()
|
||||
|
||||
self.seed = withUnsafeTemporaryAllocation(
|
||||
of: UInt8.self,
|
||||
capacity: MLKEM.seedByteCount
|
||||
) { seedPtr in
|
||||
withUnsafeTemporaryAllocation(
|
||||
of: UInt8.self,
|
||||
capacity: MLKEM${parameter_set}.InternalPublicKey.byteCount
|
||||
) { publicKeyPtr in
|
||||
CCryptoBoringSSL_MLKEM${parameter_set}_generate_key(
|
||||
publicKeyPtr.baseAddress,
|
||||
seedPtr.baseAddress,
|
||||
&self.key
|
||||
)
|
||||
|
||||
return Data(bytes: seedPtr.baseAddress!, count: MLKEM.seedByteCount)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Initialize a ML-KEM-${parameter_set} private key from a seed.
|
||||
///
|
||||
/// - Parameter seedRepresentation: The seed to use to generate the private key.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectKeySize` if the seed is not 64 bytes long.
|
||||
init(seedRepresentation: some DataProtocol) throws {
|
||||
guard seedRepresentation.count == MLKEM.seedByteCount else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
self.key = .init()
|
||||
self.seed = Data(seedRepresentation)
|
||||
|
||||
guard
|
||||
self.seed.withUnsafeBytes({ seedPtr in
|
||||
CCryptoBoringSSL_MLKEM${parameter_set}_private_key_from_seed(
|
||||
&self.key,
|
||||
seedPtr.baseAddress,
|
||||
seedPtr.count
|
||||
)
|
||||
}) == 1
|
||||
else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
}
|
||||
|
||||
/// The public key associated with this private key.
|
||||
var publicKey: InternalPublicKey {
|
||||
InternalPublicKey(privateKeyBacking: self)
|
||||
}
|
||||
|
||||
/// Decapsulate a shared secret and create a symmetric key.
|
||||
///
|
||||
/// - Parameter encapsulated: The encapsulated shared secret.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectParameterSize` if the encapsulated shared secret is not 1088 bytes long.
|
||||
///
|
||||
/// - Returns: The symmetric key.
|
||||
func decapsulate(_ encapsulated: some DataProtocol) throws -> SymmetricKey {
|
||||
guard encapsulated.count == MLKEM${parameter_set}.ciphertextByteCount else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount)
|
||||
|
||||
let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in
|
||||
let bytes: ContiguousBytes =
|
||||
encapsulated.regions.count == 1
|
||||
? encapsulated.regions.first!
|
||||
: Array(encapsulated)
|
||||
return bytes.withUnsafeBytes { encapsulatedPtr in
|
||||
CCryptoBoringSSL_MLKEM${parameter_set}_decap(
|
||||
symmetricKeyDataPtr.baseAddress,
|
||||
encapsulatedPtr.baseAddress,
|
||||
encapsulatedPtr.count,
|
||||
&self.key
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
return SymmetricKey(data: symmetricKeyData)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM${parameter_set} {
|
||||
/// A ML-KEM-${parameter_set} public key.
|
||||
struct InternalPublicKey: @unchecked Sendable, KEMPublicKey {
|
||||
private var backing: Backing
|
||||
|
||||
fileprivate init(privateKeyBacking: InternalPrivateKey.Backing) {
|
||||
self.backing = Backing(privateKeyBacking: privateKeyBacking)
|
||||
}
|
||||
|
||||
/// Initialize a ML-KEM-${parameter_set} public key from a raw representation.
|
||||
///
|
||||
/// - Parameter rawRepresentation: The public key bytes.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectKeySize` if the raw representation is not the correct size.
|
||||
init(rawRepresentation: some DataProtocol) throws {
|
||||
self.backing = try Backing(rawRepresentation: rawRepresentation)
|
||||
}
|
||||
|
||||
/// The raw binary representation of the public key.
|
||||
var rawRepresentation: Data {
|
||||
self.backing.rawRepresentation
|
||||
}
|
||||
|
||||
/// Encapsulate a shared secret.
|
||||
///
|
||||
/// - Returns: The shared secret and its encapsulated version.
|
||||
func encapsulate() -> KEM.EncapsulationResult {
|
||||
self.backing.encapsulate()
|
||||
}
|
||||
|
||||
/// The size of the public key in bytes.
|
||||
static let byteCount = Backing.byteCount
|
||||
|
||||
fileprivate final class Backing {
|
||||
var key: MLKEM${parameter_set}_public_key
|
||||
|
||||
init(privateKeyBacking: InternalPrivateKey.Backing) {
|
||||
self.key = .init()
|
||||
CCryptoBoringSSL_MLKEM${parameter_set}_public_from_private(&self.key, &privateKeyBacking.key)
|
||||
}
|
||||
|
||||
/// Initialize a ML-KEM-${parameter_set} public key from a raw representation.
|
||||
///
|
||||
/// - Parameter rawRepresentation: The public key bytes.
|
||||
///
|
||||
/// - Throws: `CryptoKitError.incorrectKeySize` if the raw representation is not the correct size.
|
||||
init(rawRepresentation: some DataProtocol) throws {
|
||||
guard rawRepresentation.count == MLKEM${parameter_set}.InternalPublicKey.byteCount else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
self.key = .init()
|
||||
|
||||
let bytes: ContiguousBytes =
|
||||
rawRepresentation.regions.count == 1
|
||||
? rawRepresentation.regions.first!
|
||||
: Array(rawRepresentation)
|
||||
try bytes.withUnsafeBytes { rawBuffer in
|
||||
try rawBuffer.withMemoryRebound(to: UInt8.self) { buffer in
|
||||
var cbs = CBS(data: buffer.baseAddress, len: buffer.count)
|
||||
guard CCryptoBoringSSL_MLKEM${parameter_set}_parse_public_key(&self.key, &cbs) == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw binary representation of the public key.
|
||||
var rawRepresentation: Data {
|
||||
var cbb = CBB()
|
||||
// The following BoringSSL functions can only fail on allocation failure, which we define as impossible.
|
||||
CCryptoBoringSSL_CBB_init(&cbb, MLKEM${parameter_set}.InternalPublicKey.Backing.byteCount)
|
||||
defer { CCryptoBoringSSL_CBB_cleanup(&cbb) }
|
||||
CCryptoBoringSSL_MLKEM${parameter_set}_marshal_public_key(&cbb, &self.key)
|
||||
return Data(bytes: CCryptoBoringSSL_CBB_data(&cbb), count: CCryptoBoringSSL_CBB_len(&cbb))
|
||||
}
|
||||
|
||||
/// Encapsulate a shared secret.
|
||||
///
|
||||
/// - Returns: The shared secret and its encapsulated version.
|
||||
func encapsulate() -> KEM.EncapsulationResult {
|
||||
withUnsafeTemporaryAllocation(
|
||||
of: UInt8.self,
|
||||
capacity: MLKEM${parameter_set}.ciphertextByteCount
|
||||
) { encapsulatedPtr in
|
||||
withUnsafeTemporaryAllocation(
|
||||
of: UInt8.self,
|
||||
capacity: MLKEM.sharedSecretByteCount
|
||||
) { secretPtr in
|
||||
CCryptoBoringSSL_MLKEM${parameter_set}_encap(
|
||||
encapsulatedPtr.baseAddress,
|
||||
secretPtr.baseAddress,
|
||||
&self.key
|
||||
)
|
||||
|
||||
return KEM.EncapsulationResult(
|
||||
sharedSecret: SymmetricKey(
|
||||
data: Data(bytes: secretPtr.baseAddress!, count: MLKEM.sharedSecretByteCount)
|
||||
),
|
||||
encapsulated: Data(
|
||||
bytes: encapsulatedPtr.baseAddress!,
|
||||
count: MLKEM${parameter_set}.ciphertextByteCount
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The size of the public key in bytes.
|
||||
static let byteCount = Int(MLKEM${parameter_set}_PUBLIC_KEY_BYTES)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM${parameter_set} {
|
||||
/// The size of the encapsulated shared secret in bytes.
|
||||
private static let ciphertextByteCount = Int(MLKEM${parameter_set}_CIPHERTEXT_BYTES)
|
||||
}
|
||||
% end
|
||||
|
||||
enum MLKEM {
|
||||
/// The size of the seed in bytes.
|
||||
static let seedByteCount = 64
|
||||
|
||||
// The size of the shared secret in bytes.
|
||||
static let sharedSecretByteCount = 32
|
||||
}
|
||||
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -0,0 +1,292 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
protocol BoringSSLBackedMLKEMPrivateKey: Sendable {
|
||||
associatedtype InteriorPublicKey: BoringSSLBackedMLKEMPublicKey
|
||||
|
||||
static func generatePrivateKey() throws -> Self
|
||||
|
||||
static func generateWithSeed(_ seed: Data) throws -> Self
|
||||
|
||||
init<Bytes: DataProtocol>(seedRepresentation: Bytes, publicKeyRawRepresentation: Data?) throws
|
||||
|
||||
init<Bytes: DataProtocol>(seedRepresentation: Bytes, publicKeyHash: SHA3_256Digest?) throws
|
||||
|
||||
var seedRepresentation: Data { get }
|
||||
|
||||
func decapsulate<Bytes: DataProtocol>(_ encapsulated: Bytes) throws -> SymmetricKey
|
||||
|
||||
var interiorPublicKey: InteriorPublicKey { get }
|
||||
|
||||
var integrityCheckedRepresentation: Data { get }
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension BoringSSLBackedMLKEMPrivateKey {
|
||||
func decapsulate<Bytes: DataProtocol>(encapsulated: Bytes) throws -> SymmetricKey {
|
||||
try self.decapsulate(encapsulated)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
protocol BoringSSLBackedMLKEMPublicKey: Sendable {
|
||||
init<Bytes: DataProtocol>(rawRepresentation: Bytes) throws
|
||||
|
||||
var rawRepresentation: Data { get }
|
||||
|
||||
func encapsulate() throws -> KEM.EncapsulationResult
|
||||
|
||||
func encapsulateWithSeed(_ encapSeed: Data) throws -> KEM.EncapsulationResult
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
protocol BoringSSLBackedMLKEMOuterPublicKey: Sendable {
|
||||
init(rawRepresentation: Data) throws
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
protocol BoringSSLBackedMLKEMParameters {
|
||||
associatedtype BackingPrivateKey: BoringSSLBackedMLKEMPrivateKey
|
||||
where BackingPrivateKey.InteriorPublicKey == BackingPublicKey
|
||||
associatedtype BackingPublicKey: BoringSSLBackedMLKEMPublicKey
|
||||
associatedtype PublicKey: BoringSSLBackedMLKEMOuterPublicKey
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM768: BoringSSLBackedMLKEMParameters {
|
||||
typealias BackingPrivateKey = MLKEM768.InternalPrivateKey
|
||||
typealias BackingPublicKey = MLKEM768.InternalPublicKey
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM768.PublicKey: BoringSSLBackedMLKEMOuterPublicKey {}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM768.InternalPrivateKey: BoringSSLBackedMLKEMPrivateKey {
|
||||
static func generatePrivateKey() throws -> Self {
|
||||
.generate()
|
||||
}
|
||||
|
||||
static func generateWithSeed(_ seed: Data) throws -> Self {
|
||||
let seed = Array(seed)
|
||||
var fullSeed: [UInt8] = []
|
||||
fullSeed.reserveCapacity(MLKEM.seedByteCount)
|
||||
|
||||
for i in 0..<MLKEM.seedByteCount {
|
||||
fullSeed.append(seed[i % seed.count])
|
||||
}
|
||||
|
||||
return try .init(seedRepresentation: fullSeed)
|
||||
}
|
||||
|
||||
init<Bytes>(seedRepresentation: Bytes, publicKeyRawRepresentation: Data?) throws where Bytes: DataProtocol {
|
||||
let publicKeyHash = publicKeyRawRepresentation.map {
|
||||
SHA3_256.hash(data: $0)
|
||||
}
|
||||
self = try .init(seedRepresentation: seedRepresentation, publicKeyHash: publicKeyHash)
|
||||
}
|
||||
|
||||
init<Bytes: DataProtocol>(seedRepresentation: Bytes, publicKeyHash: SHA3_256Digest?) throws {
|
||||
self = try .init(seedRepresentation: seedRepresentation)
|
||||
let generatedHash = SHA3_256.hash(data: self.publicKey.rawRepresentation)
|
||||
if let publicKeyHash, generatedHash != publicKeyHash {
|
||||
throw KEM.Errors.publicKeyMismatchDuringInitialization
|
||||
}
|
||||
}
|
||||
|
||||
var integrityCheckedRepresentation: Data {
|
||||
var representation = self.seedRepresentation
|
||||
SHA3_256.hash(data: self.publicKey.rawRepresentation).withUnsafeBytes {
|
||||
representation.append(contentsOf: $0)
|
||||
}
|
||||
return representation
|
||||
}
|
||||
|
||||
var interiorPublicKey: MLKEM768.InternalPublicKey {
|
||||
self.publicKey
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM768.InternalPublicKey: BoringSSLBackedMLKEMPublicKey {
|
||||
func encapsulateWithSeed(_ encapSeed: Data) throws -> KEM.EncapsulationResult {
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM1024: BoringSSLBackedMLKEMParameters {
|
||||
typealias BackingPrivateKey = MLKEM1024.InternalPrivateKey
|
||||
typealias BackingPublicKey = MLKEM1024.InternalPublicKey
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM1024.PublicKey: BoringSSLBackedMLKEMOuterPublicKey {}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM1024.InternalPrivateKey: BoringSSLBackedMLKEMPrivateKey {
|
||||
static func generatePrivateKey() throws -> Self {
|
||||
.generate()
|
||||
}
|
||||
|
||||
static func generateWithSeed(_ seed: Data) throws -> Self {
|
||||
let seed = Array(seed)
|
||||
var fullSeed: [UInt8] = []
|
||||
fullSeed.reserveCapacity(MLKEM.seedByteCount)
|
||||
|
||||
for i in 0..<MLKEM.seedByteCount {
|
||||
fullSeed.append(seed[i % seed.count])
|
||||
}
|
||||
|
||||
return try .init(seedRepresentation: fullSeed)
|
||||
}
|
||||
|
||||
init<Bytes>(seedRepresentation: Bytes, publicKeyRawRepresentation: Data?) throws where Bytes: DataProtocol {
|
||||
let publicKeyHash = publicKeyRawRepresentation.map {
|
||||
SHA3_256.hash(data: $0)
|
||||
}
|
||||
self = try .init(seedRepresentation: seedRepresentation, publicKeyHash: publicKeyHash)
|
||||
}
|
||||
|
||||
init<Bytes: DataProtocol>(seedRepresentation: Bytes, publicKeyHash: SHA3_256Digest?) throws {
|
||||
self = try .init(seedRepresentation: seedRepresentation)
|
||||
let generatedHash = SHA3_256.hash(data: self.publicKey.rawRepresentation)
|
||||
if let publicKeyHash, generatedHash != publicKeyHash {
|
||||
throw KEM.Errors.publicKeyMismatchDuringInitialization
|
||||
}
|
||||
}
|
||||
|
||||
var integrityCheckedRepresentation: Data {
|
||||
var representation = self.seedRepresentation
|
||||
SHA3_256.hash(data: self.publicKey.rawRepresentation).withUnsafeBytes {
|
||||
representation.append(contentsOf: $0)
|
||||
}
|
||||
return representation
|
||||
}
|
||||
|
||||
var interiorPublicKey: MLKEM1024.InternalPublicKey {
|
||||
self.publicKey
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM1024.InternalPublicKey: BoringSSLBackedMLKEMPublicKey {
|
||||
func encapsulateWithSeed(_ encapSeed: Data) throws -> KEM.EncapsulationResult {
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct OpenSSLMLKEMPublicKeyImpl<Parameters: BoringSSLBackedMLKEMParameters>: BoringSSLBackedMLKEMPublicKey, Sendable {
|
||||
private var backing: Parameters.BackingPublicKey
|
||||
|
||||
init(backing: Parameters.BackingPublicKey) {
|
||||
self.backing = backing
|
||||
}
|
||||
|
||||
init<Bytes>(rawRepresentation: Bytes) throws where Bytes: DataProtocol {
|
||||
self.backing = try .init(rawRepresentation: rawRepresentation)
|
||||
}
|
||||
|
||||
var rawRepresentation: Data {
|
||||
self.backing.rawRepresentation
|
||||
}
|
||||
|
||||
func encapsulate() throws -> KEM.EncapsulationResult {
|
||||
try self.backing.encapsulate()
|
||||
}
|
||||
|
||||
func encapsulateWithSeed(_ encapSeed: Data) throws -> KEM.EncapsulationResult {
|
||||
try self.backing.encapsulateWithSeed(encapSeed)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct OpenSSLMLKEMPrivateKeyImpl<Parameters: BoringSSLBackedMLKEMParameters>: BoringSSLBackedMLKEMPrivateKey, Sendable
|
||||
{
|
||||
typealias InteriorPublicKey = OpenSSLMLKEMPublicKeyImpl<Parameters>
|
||||
|
||||
private var backing: Parameters.BackingPrivateKey
|
||||
|
||||
init(backing: Parameters.BackingPrivateKey) {
|
||||
self.backing = backing
|
||||
}
|
||||
|
||||
static func generatePrivateKey() throws -> Self {
|
||||
try Self(backing: .generatePrivateKey())
|
||||
}
|
||||
|
||||
static func generateWithSeed(_ seed: Data) throws -> Self {
|
||||
try Self(backing: .generateWithSeed(seed))
|
||||
}
|
||||
|
||||
init<Bytes: DataProtocol>(
|
||||
seedRepresentation: Bytes,
|
||||
publicKeyRawRepresentation: Data?
|
||||
) throws {
|
||||
self.backing = try .init(
|
||||
seedRepresentation: seedRepresentation,
|
||||
publicKeyRawRepresentation: publicKeyRawRepresentation
|
||||
)
|
||||
}
|
||||
|
||||
init<Bytes: DataProtocol>(
|
||||
seedRepresentation: Bytes,
|
||||
publicKeyHash: SHA3_256Digest?
|
||||
) throws {
|
||||
self.backing = try .init(
|
||||
seedRepresentation: seedRepresentation,
|
||||
publicKeyHash: publicKeyHash
|
||||
)
|
||||
}
|
||||
|
||||
var seedRepresentation: Data {
|
||||
self.backing.seedRepresentation
|
||||
}
|
||||
|
||||
func decapsulate<Bytes>(_ encapsulated: Bytes) throws -> SymmetricKey where Bytes: DataProtocol {
|
||||
try self.backing.decapsulate(encapsulated)
|
||||
}
|
||||
|
||||
var interiorPublicKey: InteriorPublicKey {
|
||||
.init(backing: self.backing.interiorPublicKey)
|
||||
}
|
||||
|
||||
var publicKey: Parameters.PublicKey {
|
||||
get {
|
||||
try! .init(rawRepresentation: self.interiorPublicKey.rawRepresentation)
|
||||
}
|
||||
}
|
||||
|
||||
var integrityCheckedRepresentation: Data {
|
||||
self.backing.integrityCheckedRepresentation
|
||||
}
|
||||
|
||||
static var seedSize: Int {
|
||||
MLKEM.seedByteCount
|
||||
}
|
||||
}
|
||||
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -0,0 +1,256 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct OpenSSLXWingPublicKeyImpl: Sendable {
|
||||
private var publicKeyBytes: Data
|
||||
|
||||
fileprivate init(publicKeyBytes: Data) {
|
||||
self.publicKeyBytes = publicKeyBytes
|
||||
}
|
||||
|
||||
init<D: ContiguousBytes>(rawRepresentation: D) throws {
|
||||
self.publicKeyBytes = try rawRepresentation.withUnsafeBytes {
|
||||
guard $0.count == XWING_PUBLIC_KEY_BYTES else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
return Data($0)
|
||||
}
|
||||
}
|
||||
|
||||
var rawRepresentation: Data {
|
||||
self.publicKeyBytes
|
||||
}
|
||||
|
||||
func encapsulate() throws -> KEM.EncapsulationResult {
|
||||
try self.encapsulateWithOptionalEntropy(entropy: nil)
|
||||
}
|
||||
|
||||
func encapsulateWithOptionalEntropy(entropy: [UInt8]?) throws -> KEM.EncapsulationResult {
|
||||
let (sharedSecret, encapsulatedSecret) = try self.publicKeyBytes.withUnsafeBytes { publicKeyBuffer in
|
||||
try withUnsafeTemporaryAllocation(byteCount: Int(XWING_CIPHERTEXT_BYTES), alignment: 1) {
|
||||
ciphertextBuffer in
|
||||
let sharedSecret = try SymmetricKey(unsafeUninitializedCapacity: Int(XWING_SHARED_SECRET_BYTES)) {
|
||||
sharedSecretBuffer,
|
||||
count in
|
||||
let rc: CInt
|
||||
|
||||
if let entropy {
|
||||
rc = CCryptoBoringSSL_XWING_encap_external_entropy(
|
||||
ciphertextBuffer.baseAddress,
|
||||
sharedSecretBuffer.baseAddress,
|
||||
publicKeyBuffer.baseAddress,
|
||||
entropy
|
||||
)
|
||||
} else {
|
||||
rc = CCryptoBoringSSL_XWING_encap(
|
||||
ciphertextBuffer.baseAddress,
|
||||
sharedSecretBuffer.baseAddress,
|
||||
publicKeyBuffer.baseAddress
|
||||
)
|
||||
}
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
count = Int(XWING_SHARED_SECRET_BYTES)
|
||||
}
|
||||
let encapsulatedSecret = Data(ciphertextBuffer)
|
||||
return (sharedSecret, encapsulatedSecret)
|
||||
}
|
||||
}
|
||||
|
||||
return .init(sharedSecret: sharedSecret, encapsulated: encapsulatedSecret)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct OpenSSLXWingPrivateKeyImpl: Sendable {
|
||||
private var backing: Backing
|
||||
|
||||
var seedRepresentation: Data {
|
||||
self.backing.seedRepresentation
|
||||
}
|
||||
|
||||
var integrityCheckedRepresentation: Data {
|
||||
self.backing.integrityCheckedRepresentation
|
||||
}
|
||||
|
||||
init<D: ContiguousBytes>(bytes: D) throws {
|
||||
self.backing = try .init(bytes: bytes)
|
||||
}
|
||||
|
||||
init<D: DataProtocol>(seedRepresentation: D, publicKeyHash: SHA3_256Digest?) throws {
|
||||
self.backing = try .init(seedRepresentation: seedRepresentation, publicKeyHash: publicKeyHash)
|
||||
}
|
||||
|
||||
private init(_ backing: Backing) {
|
||||
self.backing = backing
|
||||
}
|
||||
|
||||
var dataRepresentation: Data {
|
||||
self.backing.dataRepresentation
|
||||
}
|
||||
|
||||
static func generate() throws -> Self {
|
||||
try Self(.generate())
|
||||
}
|
||||
|
||||
func decapsulate(_ encapsulated: Data) throws -> SymmetricKey {
|
||||
try self.backing.decapsulate(encapsulated)
|
||||
}
|
||||
|
||||
var publicKey: OpenSSLXWingPublicKeyImpl {
|
||||
OpenSSLXWingPublicKeyImpl(publicKeyBytes: self.backing.publicKey)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension OpenSSLXWingPrivateKeyImpl {
|
||||
final class Backing: @unchecked Sendable {
|
||||
private var privateKey: XWING_private_key
|
||||
|
||||
init(privateKey: XWING_private_key) {
|
||||
self.privateKey = privateKey
|
||||
}
|
||||
|
||||
init() throws {
|
||||
self.privateKey = .init()
|
||||
try withUnsafeTemporaryAllocation(byteCount: Int(XWING_PUBLIC_KEY_BYTES), alignment: 1) {
|
||||
let rc = CCryptoBoringSSL_XWING_generate_key($0.baseAddress, &self.privateKey)
|
||||
if rc != 1 {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init<D: ContiguousBytes>(bytes: D) throws {
|
||||
self.privateKey = .init()
|
||||
|
||||
// The first bytes are the private key (in "seed representation"), the latter bytes are the public key.
|
||||
try bytes.withUnsafeBytes { ptr in
|
||||
guard ptr.count == Int(XWING_PRIVATE_KEY_BYTES) + Int(XWING_PUBLIC_KEY_BYTES) else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
let privateKeyBytes = UnsafeRawBufferPointer(rebasing: ptr.prefix(Int(XWING_PRIVATE_KEY_BYTES)))
|
||||
let publicKeyBytes = UnsafeRawBufferPointer(rebasing: ptr.suffix(Int(XWING_PUBLIC_KEY_BYTES)))
|
||||
|
||||
var cbs = CBS()
|
||||
CCryptoBoringSSL_CBS_init(&cbs, privateKeyBytes.baseAddress, privateKeyBytes.count)
|
||||
|
||||
let rc = CCryptoBoringSSL_XWING_parse_private_key(&self.privateKey, &cbs)
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
// Matching CryptoKit, we only care that this _is_ a public key, not that it matches.
|
||||
let _ = try OpenSSLXWingPublicKeyImpl(rawRepresentation: publicKeyBytes)
|
||||
}
|
||||
}
|
||||
|
||||
init<D: DataProtocol>(seedRepresentation: D, publicKeyHash: SHA3_256Digest?) throws {
|
||||
self.privateKey = .init()
|
||||
|
||||
let seedRepresentation: ContiguousBytes =
|
||||
seedRepresentation.regions.count == 1 ? seedRepresentation.regions.first! : Array(seedRepresentation)
|
||||
|
||||
try seedRepresentation.withUnsafeBytes { privateKeyBytes in
|
||||
guard privateKeyBytes.count == Int(XWING_PRIVATE_KEY_BYTES) else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
var cbs = CBS()
|
||||
CCryptoBoringSSL_CBS_init(&cbs, privateKeyBytes.baseAddress, privateKeyBytes.count)
|
||||
|
||||
let rc = CCryptoBoringSSL_XWING_parse_private_key(&self.privateKey, &cbs)
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
}
|
||||
|
||||
if let publicKeyHash, publicKeyHash != self.publicKeyDigest {
|
||||
throw KEM.Errors.publicKeyMismatchDuringInitialization
|
||||
}
|
||||
}
|
||||
|
||||
var seedRepresentation: Data {
|
||||
withUnsafeTemporaryAllocation(byteCount: Int(XWING_PRIVATE_KEY_BYTES), alignment: 1) {
|
||||
var cbb = CBB()
|
||||
CCryptoBoringSSL_CBB_init_fixed(&cbb, $0.baseAddress, $0.count)
|
||||
let rc = CCryptoBoringSSL_XWING_marshal_private_key(&cbb, &self.privateKey)
|
||||
precondition(rc == 1)
|
||||
return Data($0.prefix(CCryptoBoringSSL_CBB_len(&cbb)))
|
||||
}
|
||||
}
|
||||
|
||||
var integrityCheckedRepresentation: Data {
|
||||
var representation = self.seedRepresentation
|
||||
self.publicKeyDigest.withUnsafeBytes {
|
||||
representation.append(contentsOf: $0)
|
||||
}
|
||||
return representation
|
||||
}
|
||||
|
||||
var dataRepresentation: Data {
|
||||
self.seedRepresentation + self.publicKey
|
||||
}
|
||||
|
||||
var publicKey: Data {
|
||||
withUnsafeTemporaryAllocation(byteCount: Int(XWING_PUBLIC_KEY_BYTES), alignment: 1) {
|
||||
let rc = CCryptoBoringSSL_XWING_public_from_private($0.baseAddress, &self.privateKey)
|
||||
precondition(rc == 1)
|
||||
return Data($0)
|
||||
}
|
||||
}
|
||||
|
||||
private var publicKeyDigest: SHA3_256Digest {
|
||||
withUnsafeTemporaryAllocation(byteCount: Int(XWING_PUBLIC_KEY_BYTES), alignment: 1) {
|
||||
let rc = CCryptoBoringSSL_XWING_public_from_private($0.baseAddress, &self.privateKey)
|
||||
precondition(rc == 1)
|
||||
return SHA3_256.hash(bufferPointer: UnsafeRawBufferPointer($0))
|
||||
}
|
||||
}
|
||||
|
||||
static func generate() throws -> Self {
|
||||
try Self()
|
||||
}
|
||||
|
||||
func decapsulate(_ encapsulated: Data) throws -> SymmetricKey {
|
||||
try SymmetricKey(unsafeUninitializedCapacity: Int(XWING_SHARED_SECRET_BYTES)) { sharedSecretBytes, count in
|
||||
try encapsulated.withUnsafeBytes { encapsulatedSecretBytes in
|
||||
let rc = CCryptoBoringSSL_XWING_decap(
|
||||
sharedSecretBytes.baseAddress,
|
||||
encapsulatedSecretBytes.baseAddress,
|
||||
&self.privateKey
|
||||
)
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
count = Int(XWING_SHARED_SECRET_BYTES)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -0,0 +1,41 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension KEM {
|
||||
/// Errors that CryptoKit throws when it encounters problems in key encapsulation mechanism (KEM) operations.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum Errors: Error {
|
||||
/// The public key CryptoKit receives when it initializes a key encapsulation operation doesn't match the expected value.
|
||||
case publicKeyMismatchDuringInitialization
|
||||
|
||||
/// The seed value supplied for deriving a key isn't valid.
|
||||
case invalidSeed
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -14,19 +14,31 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
/// A Key Encapsulation Mechanism
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
public import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/// A key encapsulation mechanism.
|
||||
///
|
||||
/// Use a key encapsulation mechanism (KEM) to protect a symmetric cryptographic key that you share with another party.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum KEM {
|
||||
/// The result of an encapsulation operation
|
||||
public enum KEM: Sendable {
|
||||
/// The result of a key encapsulation operation.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct EncapsulationResult {
|
||||
/// The shared secret
|
||||
public struct EncapsulationResult: Sendable {
|
||||
/// The shared secret.
|
||||
public let sharedSecret: SymmetricKey
|
||||
/// The encapsulated secret
|
||||
/// The encapsulated representation of the shared secret.
|
||||
public let encapsulated: Data
|
||||
|
||||
/// Initializes a key encapsulation result.
|
||||
public init(sharedSecret: SymmetricKey, encapsulated: Data) {
|
||||
self.sharedSecret = sharedSecret
|
||||
self.encapsulated = encapsulated
|
||||
@@ -34,29 +46,37 @@ public enum KEM {
|
||||
}
|
||||
}
|
||||
|
||||
/// A Key Encapsulation Mechanism's Public Key
|
||||
/// The public key for a key encapsulation mechanism.
|
||||
@preconcurrency
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol KEMPublicKey {
|
||||
/// Encapsulates the generated shared secret
|
||||
/// - Returns: The shared secret and its encapsulated version
|
||||
public protocol KEMPublicKey: Sendable {
|
||||
/// Generates and encapsulates a shared secret.
|
||||
///
|
||||
/// Share the encapsulated secret with the person who has the ``KEMPrivateKey``.
|
||||
/// They use ``KEMPrivateKey/decapsulate(_:)`` to recover the shared secret.
|
||||
/// - Returns: The shared secret, and its encapsulated version.
|
||||
func encapsulate() throws -> KEM.EncapsulationResult
|
||||
}
|
||||
|
||||
/// A Key Encapsulation Mechanism's Private Key
|
||||
/// The private key for a key encapsulation mechanism.
|
||||
@preconcurrency
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol KEMPrivateKey {
|
||||
public protocol KEMPrivateKey: Sendable {
|
||||
associatedtype PublicKey: KEMPublicKey
|
||||
|
||||
/// Generate a new random Private Key
|
||||
/// - Returns: The generated private key
|
||||
/// 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
|
||||
|
||||
/// Decapsulates the encapsulated shared secret
|
||||
/// - Parameter encapsulated: The encapsulated shared secret
|
||||
/// - Returns: The decapsulated shared secret
|
||||
/// 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.
|
||||
func decapsulate(_ encapsulated: Data) throws -> SymmetricKey
|
||||
|
||||
/// Returns the associated public key
|
||||
/// The associated public key.
|
||||
var publicKey: PublicKey { get }
|
||||
}
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -0,0 +1,286 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
|
||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
typealias MLKEMPublicKeyImpl = CoreCryptoMLKEMPublicKeyImpl
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
typealias MLKEMPrivateKeyImpl = CoreCryptoMLKEMPrivateKeyImpl
|
||||
#else
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
typealias MLKEMPublicKeyImpl = OpenSSLMLKEMPublicKeyImpl
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
typealias MLKEMPrivateKeyImpl = OpenSSLMLKEMPrivateKeyImpl
|
||||
#endif
|
||||
|
||||
|
||||
/// The Module-Lattice key encapsulation mechanism (KEM).
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum MLKEM768: Sendable {}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM768 {
|
||||
/// A public key you use to encapsulate shared secrets with the Module-Lattice key encapsulation mechanism.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct PublicKey: KEMPublicKey, Sendable {
|
||||
var impl: MLKEMPublicKeyImpl<MLKEM768>
|
||||
|
||||
/// 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 ``MLKEM768/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.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct PrivateKey: KEMPrivateKey {
|
||||
internal let impl: MLKEMPrivateKeyImpl<MLKEM768>
|
||||
|
||||
internal init(_ impl: MLKEMPrivateKeyImpl<MLKEM768>) {
|
||||
self.impl = impl
|
||||
}
|
||||
|
||||
/// Generates a new, random private key.
|
||||
public static func generate() throws -> MLKEM768.PrivateKey {
|
||||
let impl = try MLKEMPrivateKeyImpl<MLKEM768>.generatePrivateKey()
|
||||
return PrivateKey(impl)
|
||||
}
|
||||
|
||||
static func generateWithSeed(_ seed: Data) throws -> MLKEM768.PrivateKey {
|
||||
let impl = try MLKEMPrivateKeyImpl<MLKEM768>.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: MLKEM768.PublicKey?) throws {
|
||||
var publicKeyRawRepresentation: Data? = nil
|
||||
if publicKey != nil {
|
||||
publicKeyRawRepresentation = publicKey!.rawRepresentation
|
||||
}
|
||||
self.impl = try MLKEMPrivateKeyImpl<MLKEM768>(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 ``MLKEM768/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: MLKEM768.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<MLKEM768>.seedSize + 32 else {
|
||||
throw KEM.Errors.invalidSeed
|
||||
}
|
||||
let seed = Data(integrityCheckedRepresentation).subdata(in: 0..<MLKEMPrivateKeyImpl<MLKEM768>.seedSize)
|
||||
let publicKeyHashData = Data(integrityCheckedRepresentation).subdata(in: MLKEMPrivateKeyImpl<MLKEM768>.seedSize..<integrityCheckedRepresentation.count)
|
||||
let publicKeyHash = SHA3_256Digest(bytes: [UInt8](publicKeyHashData))
|
||||
|
||||
self.impl = try MLKEMPrivateKeyImpl<MLKEM768>(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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// The Module-Lattice key encapsulation mechanism (KEM).
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum MLKEM1024: Sendable {}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM1024 {
|
||||
/// A public key you use to encapsulate shared secrets with the Module-Lattice key encapsulation mechanism.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct PublicKey: KEMPublicKey, Sendable {
|
||||
var impl: MLKEMPublicKeyImpl<MLKEM1024>
|
||||
|
||||
/// 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 ``MLKEM1024/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.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct PrivateKey: KEMPrivateKey {
|
||||
internal let impl: MLKEMPrivateKeyImpl<MLKEM1024>
|
||||
|
||||
internal init(_ impl: MLKEMPrivateKeyImpl<MLKEM1024>) {
|
||||
self.impl = impl
|
||||
}
|
||||
|
||||
/// Generates a new, random private key.
|
||||
public static func generate() throws -> MLKEM1024.PrivateKey {
|
||||
let impl = try MLKEMPrivateKeyImpl<MLKEM1024>.generatePrivateKey()
|
||||
return PrivateKey(impl)
|
||||
}
|
||||
|
||||
static func generateWithSeed(_ seed: Data) throws -> MLKEM1024.PrivateKey {
|
||||
let impl = try MLKEMPrivateKeyImpl<MLKEM1024>.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: MLKEM1024.PublicKey?) throws {
|
||||
var publicKeyRawRepresentation: Data? = nil
|
||||
if publicKey != nil {
|
||||
publicKeyRawRepresentation = publicKey!.rawRepresentation
|
||||
}
|
||||
self.impl = try MLKEMPrivateKeyImpl<MLKEM1024>(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 ``MLKEM1024/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: MLKEM1024.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<MLKEM1024>.seedSize + 32 else {
|
||||
throw KEM.Errors.invalidSeed
|
||||
}
|
||||
let seed = Data(integrityCheckedRepresentation).subdata(in: 0..<MLKEMPrivateKeyImpl<MLKEM1024>.seedSize)
|
||||
let publicKeyHashData = Data(integrityCheckedRepresentation).subdata(in: MLKEMPrivateKeyImpl<MLKEM1024>.seedSize..<integrityCheckedRepresentation.count)
|
||||
let publicKeyHash = SHA3_256Digest(bytes: [UInt8](publicKeyHashData))
|
||||
|
||||
self.impl = try MLKEMPrivateKeyImpl<MLKEM1024>(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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -0,0 +1,162 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
@@ -0,0 +1,172 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
#if (!CRYPTO_IN_SWIFTPM_FORCE_BUILD_API) || CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
typealias XWingPublicKeyImpl = CoreCryptoXWingPublicKeyImpl
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
typealias XWingPrivateKeyImpl = CoreCryptoXWingPrivateKeyImpl
|
||||
#else
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
typealias XWingPublicKeyImpl = OpenSSLXWingPublicKeyImpl
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
typealias XWingPrivateKeyImpl = OpenSSLXWingPrivateKeyImpl
|
||||
#endif
|
||||
|
||||
/// The X-Wing (ML-KEM768 with X25519) Key Encapsulation Mechanism, defined in
|
||||
/// https://datatracker.ietf.org/doc/html/draft-connolly-cfrg-xwing-kem-06
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum XWingMLKEM768X25519: Sendable {}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension XWingMLKEM768X25519 {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct PublicKey: KEMPublicKey {
|
||||
var impl: XWingPublicKeyImpl
|
||||
|
||||
internal init(impl: XWingPublicKeyImpl) {
|
||||
self.impl = impl
|
||||
}
|
||||
|
||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws {
|
||||
self.impl = try .init(rawRepresentation: rawRepresentation)
|
||||
}
|
||||
|
||||
public var rawRepresentation: Data {
|
||||
get {
|
||||
self.impl.rawRepresentation
|
||||
}
|
||||
}
|
||||
|
||||
public func encapsulate() throws -> KEM.EncapsulationResult {
|
||||
return try self.impl.encapsulate()
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct PrivateKey: KEMPrivateKey {
|
||||
private var impl: XWingPrivateKeyImpl
|
||||
|
||||
public var seedRepresentation: Data {
|
||||
get {
|
||||
self.impl.seedRepresentation
|
||||
}
|
||||
}
|
||||
|
||||
public var integrityCheckedRepresentation: Data {
|
||||
get {
|
||||
self.impl.integrityCheckedRepresentation
|
||||
}
|
||||
}
|
||||
|
||||
internal init(impl: XWingPrivateKeyImpl) {
|
||||
self.impl = impl
|
||||
}
|
||||
|
||||
internal init<D: DataProtocol>(seedRepresentation: D, publicKeyHash: SHA3_256Digest?) throws {
|
||||
self.impl = try .init(seedRepresentation: seedRepresentation, publicKeyHash: publicKeyHash)
|
||||
}
|
||||
|
||||
public static func generate() throws -> XWingMLKEM768X25519.PrivateKey {
|
||||
return try Self(impl: XWingPrivateKeyImpl.generate())
|
||||
}
|
||||
|
||||
public func decapsulate(_ encapsulated: Data) throws -> SymmetricKey {
|
||||
try self.impl.decapsulate(encapsulated)
|
||||
}
|
||||
|
||||
public var publicKey: XWingMLKEM768X25519.PublicKey {
|
||||
get {
|
||||
XWingMLKEM768X25519.PublicKey(impl: self.impl.publicKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension XWingMLKEM768X25519.PrivateKey: HPKEKEMPrivateKeyGeneration {
|
||||
public init() throws {
|
||||
self = try Self.generate()
|
||||
}
|
||||
|
||||
public init<D: DataProtocol>(seedRepresentation: D, publicKey: XWingMLKEM768X25519.PublicKey?) throws {
|
||||
var publicKeyHash: SHA3_256Digest? = nil
|
||||
if publicKey != nil {
|
||||
publicKeyHash = SHA3_256.hash(data: publicKey!.rawRepresentation)
|
||||
}
|
||||
|
||||
self = try XWingMLKEM768X25519.PrivateKey.init(seedRepresentation: seedRepresentation, publicKeyHash: publicKeyHash)
|
||||
}
|
||||
|
||||
public init<D: DataProtocol>(integrityCheckedRepresentation: D) throws {
|
||||
let seed = integrityCheckedRepresentation.dropLast(32) // sizeof(SHA3-256 digest)
|
||||
let publicKeyHashBytes = integrityCheckedRepresentation.dropFirst(32)
|
||||
let publicKeyHash = SHA3_256Digest(bytes: [UInt8](publicKeyHashBytes))
|
||||
|
||||
self = try XWingMLKEM768X25519.PrivateKey.init(seedRepresentation: seed, publicKeyHash: publicKeyHash)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension XWingMLKEM768X25519.PublicKey: HPKEKEMPublicKey {
|
||||
/// The type of the ephemeral private key associated with this public key.
|
||||
public typealias EphemeralPrivateKey = XWingMLKEM768X25519.PrivateKey
|
||||
|
||||
static func validateCiphersuite(_ kem: HPKE.KEM) throws {
|
||||
switch kem {
|
||||
case .XWingMLKEM768X25519: do {}
|
||||
default: do {
|
||||
throw HPKE.Errors.inconsistentCiphersuiteAndKey
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an X-Wing public key for use with HPKE.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - serialization: The serialized bytes of the public key.
|
||||
/// - kem: The key encapsulation mechanism to use with the public key.
|
||||
///
|
||||
/// - Throws: ``CryptoKit/HPKE/Errors/inconsistentCiphersuiteAndKey`` if the key encapsulation mechanism requested is incompatible with this public key.
|
||||
public init<D>(_ serialization: D, kem: HPKE.KEM) throws where D: ContiguousBytes {
|
||||
try Self.validateCiphersuite(kem)
|
||||
try self.init(rawRepresentation: serialization)
|
||||
}
|
||||
|
||||
/// Creates a serialized representation of the public key.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - kem: The Key Encapsulation Mechanism to use with the public key.
|
||||
///
|
||||
/// - Throws: ``CryptoKit/HPKE/Errors/inconsistentCiphersuiteAndKey`` if the key encapsulation mechanism requested is incompatible with this public key.
|
||||
///
|
||||
/// - Returns: The serialized representation of the public key.
|
||||
public func hpkeRepresentation(kem: HPKE.KEM) throws -> Data {
|
||||
try Self.validateCiphersuite(kem)
|
||||
return self.rawRepresentation
|
||||
}
|
||||
|
||||
/// The type of the ephemeral private key associated with this public key.
|
||||
public typealias HPKEEphemeralPrivateKey = XWingMLKEM768X25519.PrivateKey
|
||||
}
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -14,13 +14,23 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
#if CRYPTOKIT_NO_ACCESS_TO_FOUNDATION
|
||||
public import SwiftSystem
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/// A Diffie-Hellman Key Agreement Key
|
||||
@preconcurrency
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol DiffieHellmanKeyAgreement {
|
||||
public protocol DiffieHellmanKeyAgreement: Sendable {
|
||||
/// The public key share type to perform the DH Key Agreement
|
||||
associatedtype PublicKey
|
||||
associatedtype PublicKey: Sendable
|
||||
var publicKey: PublicKey { get }
|
||||
|
||||
/// Performs a Diffie-Hellman Key Agreement.
|
||||
@@ -28,7 +38,7 @@ public protocol DiffieHellmanKeyAgreement {
|
||||
/// - Parameters:
|
||||
/// - publicKeyShare: The public key share.
|
||||
/// - Returns: The resulting key agreement result.
|
||||
func sharedSecretFromKeyAgreement(with publicKeyShare: PublicKey) throws -> SharedSecret
|
||||
func sharedSecretFromKeyAgreement(with publicKeyShare: PublicKey) throws(CryptoKitMetaError) -> SharedSecret
|
||||
}
|
||||
|
||||
/// A key agreement result from which you can derive a symmetric cryptographic
|
||||
@@ -37,7 +47,7 @@ public protocol DiffieHellmanKeyAgreement {
|
||||
/// Generate a shared secret by calling your private key’s
|
||||
/// `sharedSecretFromKeyAgreement(publicKeyShare:)` method with the public key
|
||||
/// from another party. The other party computes the same secret by passing your
|
||||
/// public key to the equivalent method on their own private key.
|
||||
/// public key to the the equivalent method on their own private key.
|
||||
///
|
||||
/// The shared secret isn’t suitable as a symmetric cryptographic key
|
||||
/// (``SymmetricKey``) by itself. However, you use it to generate a key by
|
||||
@@ -49,9 +59,13 @@ public protocol DiffieHellmanKeyAgreement {
|
||||
/// ``HMAC``, or for opening and closing a sealed box with a cipher like
|
||||
/// ``ChaChaPoly`` or ``AES``.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SharedSecret: ContiguousBytes {
|
||||
public struct SharedSecret: ContiguousBytes, Sendable {
|
||||
var ss: SecureBytes
|
||||
|
||||
|
||||
internal init(ss: SecureBytes){
|
||||
self.ss = ss
|
||||
}
|
||||
|
||||
/// Invokes the given closure with a buffer pointer covering the raw bytes
|
||||
/// of the shared secret.
|
||||
///
|
||||
@@ -60,9 +74,15 @@ public struct SharedSecret: ContiguousBytes {
|
||||
/// shared secret and returns the shared secret.
|
||||
///
|
||||
/// - Returns: The shared secret, as returned from the body closure.
|
||||
#if hasFeature(Embedded)
|
||||
public func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
|
||||
return try ss.withUnsafeBytes(body)
|
||||
}
|
||||
#else
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try ss.withUnsafeBytes(body)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Derives a symmetric encryption key from the secret using x9.63 key
|
||||
/// derivation.
|
||||
@@ -74,57 +94,10 @@ public struct SharedSecret: ContiguousBytes {
|
||||
///
|
||||
/// - Returns: The derived symmetric key.
|
||||
public func x963DerivedSymmetricKey<H: HashFunction, SI: DataProtocol>(using hashFunction: H.Type, sharedInfo: SI, outputByteCount: Int) -> SymmetricKey {
|
||||
// SEC1 defines 3 inputs to the KDF:
|
||||
//
|
||||
// 1. An octet string Z which is the shared secret value. That's `self` here.
|
||||
// 2. An integer `keydatalen` which is the length in octets of the keying data to be generated. Here that's `outputByteCount`.
|
||||
// 3. An optional octet string `SharedInfo` which consists of other shared data. Here, that's `sharedInfo`.
|
||||
//
|
||||
// We then need to perform the following steps:
|
||||
//
|
||||
// 1. Check that keydatalen < hashlen × (2³² − 1). If keydatalen ≥ hashlen × (2³² − 1), fail.
|
||||
// 2. Initiate a 4 octet, big-endian octet string Counter as 0x00000001.
|
||||
// 3. For i = 1 to ⌈keydatalen/hashlen⌉, do the following:
|
||||
// 1. Compute: Ki = Hash(Z || Counter || [SharedInfo]).
|
||||
// 2. Increment Counter.
|
||||
// 3. Increment i.
|
||||
// 4. Set K to be the leftmost keydatalen octets of: K1 || K2 || . . . || K⌈keydatalen/hashlen⌉.
|
||||
// 5. Output K.
|
||||
//
|
||||
// The loop in step 3 is not very Swifty, so instead we generate the counter directly.
|
||||
// Step 1: Check that keydatalen < hashlen × (2³² − 1).
|
||||
// We do this math in UInt64-space, because we'll overflow 32-bit integers.
|
||||
guard UInt64(outputByteCount) < (UInt64(H.Digest.byteCount) * UInt64(UInt32.max)) else {
|
||||
fatalError("Invalid parameter size")
|
||||
|
||||
return self.ss.withUnsafeBytes { ssBytes in
|
||||
return ANSIKDFx963<H>.deriveKey(inputKeyMaterial: SymmetricKey(data: ssBytes), info: sharedInfo, outputByteCount: outputByteCount)
|
||||
}
|
||||
|
||||
var key = SecureBytes()
|
||||
key.reserveCapacity(outputByteCount)
|
||||
|
||||
var remainingBytes = outputByteCount
|
||||
var counter = UInt32(1)
|
||||
|
||||
while remainingBytes > 0 {
|
||||
// 1. Compute: Ki = Hash(Z || Counter || [SharedInfo]).
|
||||
var hasher = H()
|
||||
hasher.update(self)
|
||||
hasher.update(counter.bigEndian)
|
||||
hasher.update(data: sharedInfo)
|
||||
let digest = hasher.finalize()
|
||||
|
||||
// 2. Increment Counter.
|
||||
counter += 1
|
||||
|
||||
// Append the bytes of the digest. We don't want to append more than the remaining number of bytes.
|
||||
let bytesToAppend = min(remainingBytes, H.Digest.byteCount)
|
||||
digest.withUnsafeBytes { digestPtr in
|
||||
key.append(digestPtr.prefix(bytesToAppend))
|
||||
}
|
||||
remainingBytes -= bytesToAppend
|
||||
}
|
||||
|
||||
precondition(key.count == outputByteCount)
|
||||
return SymmetricKey(data: key)
|
||||
}
|
||||
|
||||
/// Derives a symmetric encryption key from the secret using HKDF key
|
||||
@@ -155,7 +128,7 @@ extension SharedSecret: Hashable {
|
||||
|
||||
// We want to implement constant-time comparison for digests.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension SharedSecret: CustomStringConvertible, Equatable {
|
||||
extension SharedSecret: Equatable {
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
return safeCompare(lhs, rhs)
|
||||
}
|
||||
@@ -177,11 +150,16 @@ extension SharedSecret: CustomStringConvertible, Equatable {
|
||||
return safeCompare(lhs, rhs.regions.first!)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension SharedSecret: CustomStringConvertible {
|
||||
public var description: String {
|
||||
return "\(Self.self): \(ss.hexString)"
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension HashFunction {
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#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, *)
|
||||
@@ -26,7 +26,15 @@ typealias NISTCurvePublicKeyImpl = OpenSSLNISTCurvePublicKeyImpl
|
||||
typealias NISTCurvePrivateKeyImpl = OpenSSLNISTCurvePrivateKeyImpl
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
#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
|
||||
@@ -39,11 +47,11 @@ extension P256 {
|
||||
/// A mechanism used to create or verify a cryptographic signature using
|
||||
/// the NIST P-256 elliptic curve digital signature algorithm (ECDSA).
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum Signing {
|
||||
|
||||
public enum Signing: Sendable {
|
||||
|
||||
/// A P-256 public key used to verify cryptographic signatures.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct PublicKey: NISTECPublicKey {
|
||||
public struct PublicKey: NISTECPublicKey, Sendable {
|
||||
var impl: NISTCurvePublicKeyImpl<P256>
|
||||
|
||||
/// Creates a P-256 public key for signing from a collection of bytes.
|
||||
@@ -51,7 +59,7 @@ extension P256 {
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the key as a collection of
|
||||
/// contiguous bytes.
|
||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws {
|
||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(rawRepresentation: rawRepresentation)
|
||||
}
|
||||
|
||||
@@ -61,7 +69,7 @@ extension P256 {
|
||||
/// - Parameters:
|
||||
/// - compactRepresentation: A compact representation of the key
|
||||
/// as a collection of contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(compactRepresentation: compactRepresentation)
|
||||
}
|
||||
|
||||
@@ -70,7 +78,7 @@ extension P256 {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - x963Representation: An ANSI x9.63 representation of the key.
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(x963Representation: x963Representation)
|
||||
}
|
||||
|
||||
@@ -80,29 +88,31 @@ extension P256 {
|
||||
/// - Parameters:
|
||||
/// - compressedRepresentation: A compressed representation of the key as a collection
|
||||
/// of contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(compressedRepresentation: compressedRepresentation)
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// Creates a P-256 public key for signing from a Privacy-Enhanced Mail
|
||||
/// (PEM) representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pemRepresentation: A PEM representation of the key.
|
||||
public init(pemRepresentation: String) throws {
|
||||
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 P-256 public key for signing from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: A DER-encoded representation of the key.
|
||||
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
|
||||
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)
|
||||
@@ -134,16 +144,18 @@ extension P256 {
|
||||
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
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
||||
let impl: NISTCurvePrivateKeyImpl<P256>
|
||||
|
||||
/// Creates a random P-256 private key for signing.
|
||||
@@ -164,7 +176,7 @@ extension P256 {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - x963Representation: An ANSI x9.63 representation of the key.
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePrivateKeyImpl(x963: x963Representation)
|
||||
}
|
||||
|
||||
@@ -173,16 +185,17 @@ extension P256 {
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the key as a collection of
|
||||
/// contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePrivateKeyImpl(data: rawRepresentation)
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// Creates a P-256 private key for signing from a Privacy-Enhanced Mail
|
||||
/// PEM) representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pemRepresentation: A PEM representation of the key.
|
||||
public init(pemRepresentation: String) throws {
|
||||
public init(pemRepresentation: String) throws(CryptoKitMetaError) {
|
||||
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
|
||||
|
||||
switch pem.type {
|
||||
@@ -196,13 +209,14 @@ extension P256 {
|
||||
throw CryptoKitASN1Error.invalidPEMDocument
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Creates a P-256 private key for signing from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: A DER-encoded representation of the key.
|
||||
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
|
||||
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.
|
||||
@@ -242,11 +256,13 @@ extension P256 {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -258,11 +274,11 @@ extension P256 {
|
||||
/// performing NIST P-256 elliptic curve Diffie Hellman (ECDH) key
|
||||
/// exchange.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum KeyAgreement {
|
||||
|
||||
public enum KeyAgreement: Sendable {
|
||||
|
||||
/// A P-256 public key used for key agreement.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct PublicKey: NISTECPublicKey {
|
||||
public struct PublicKey: NISTECPublicKey, Sendable {
|
||||
var impl: NISTCurvePublicKeyImpl<P256>
|
||||
|
||||
/// Creates a P-256 public key for key agreement from a collection of bytes.
|
||||
@@ -270,7 +286,7 @@ extension P256 {
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the key as a collection of
|
||||
/// contiguous bytes.
|
||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws {
|
||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(rawRepresentation: rawRepresentation)
|
||||
}
|
||||
|
||||
@@ -280,7 +296,7 @@ extension P256 {
|
||||
/// - Parameters:
|
||||
/// - compactRepresentation: A compact representation of the key
|
||||
/// as a collection of contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(compactRepresentation: compactRepresentation)
|
||||
}
|
||||
|
||||
@@ -289,7 +305,7 @@ extension P256 {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - x963Representation: An ANSI x9.63 representation of the key.
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(x963Representation: x963Representation)
|
||||
}
|
||||
|
||||
@@ -299,29 +315,31 @@ extension P256 {
|
||||
/// - Parameters:
|
||||
/// - compressedRepresentation: A compressed representation of the key as a collection
|
||||
/// of contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(compressedRepresentation: compressedRepresentation)
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// Creates a P-256 public key for key agreement from a Privacy-Enhanced Mail
|
||||
/// (PEM) representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pemRepresentation: A PEM representation of the key.
|
||||
public init(pemRepresentation: String) throws {
|
||||
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 P-256 public key for key agreement from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: A DER-encoded representation of the key.
|
||||
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
|
||||
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)
|
||||
@@ -353,16 +371,18 @@ extension P256 {
|
||||
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
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
||||
let impl: NISTCurvePrivateKeyImpl<P256>
|
||||
|
||||
/// Creates a random P-256 private key for key agreement.
|
||||
@@ -383,7 +403,7 @@ extension P256 {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - x963Representation: An ANSI x9.63 representation of the key.
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePrivateKeyImpl(x963: x963Representation)
|
||||
}
|
||||
|
||||
@@ -392,16 +412,17 @@ extension P256 {
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the key as a collection of
|
||||
/// contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePrivateKeyImpl(data: rawRepresentation)
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// Creates a P-256 private key for key agreement from a Privacy-Enhanced Mail
|
||||
/// PEM) representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pemRepresentation: A PEM representation of the key.
|
||||
public init(pemRepresentation: String) throws {
|
||||
public init(pemRepresentation: String) throws(CryptoKitMetaError) {
|
||||
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
|
||||
|
||||
switch pem.type {
|
||||
@@ -415,13 +436,14 @@ extension P256 {
|
||||
throw CryptoKitASN1Error.invalidPEMDocument
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Creates a P-256 private key for key agreement from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: A DER-encoded representation of the key.
|
||||
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
|
||||
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.
|
||||
@@ -461,11 +483,13 @@ extension P256 {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -476,11 +500,11 @@ extension P384 {
|
||||
/// A mechanism used to create or verify a cryptographic signature using
|
||||
/// the NIST P-384 elliptic curve digital signature algorithm (ECDSA).
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum Signing {
|
||||
|
||||
public enum Signing: Sendable {
|
||||
|
||||
/// A P-384 public key used to verify cryptographic signatures.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct PublicKey: NISTECPublicKey {
|
||||
public struct PublicKey: NISTECPublicKey, Sendable {
|
||||
var impl: NISTCurvePublicKeyImpl<P384>
|
||||
|
||||
/// Creates a P-384 public key for signing from a collection of bytes.
|
||||
@@ -488,7 +512,7 @@ extension P384 {
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the key as a collection of
|
||||
/// contiguous bytes.
|
||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws {
|
||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(rawRepresentation: rawRepresentation)
|
||||
}
|
||||
|
||||
@@ -498,7 +522,7 @@ extension P384 {
|
||||
/// - Parameters:
|
||||
/// - compactRepresentation: A compact representation of the key
|
||||
/// as a collection of contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(compactRepresentation: compactRepresentation)
|
||||
}
|
||||
|
||||
@@ -507,7 +531,7 @@ extension P384 {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - x963Representation: An ANSI x9.63 representation of the key.
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(x963Representation: x963Representation)
|
||||
}
|
||||
|
||||
@@ -517,29 +541,31 @@ extension P384 {
|
||||
/// - Parameters:
|
||||
/// - compressedRepresentation: A compressed representation of the key as a collection
|
||||
/// of contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(compressedRepresentation: compressedRepresentation)
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// Creates a P-384 public key for signing from a Privacy-Enhanced Mail
|
||||
/// (PEM) representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pemRepresentation: A PEM representation of the key.
|
||||
public init(pemRepresentation: String) throws {
|
||||
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 P-384 public key for signing from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: A DER-encoded representation of the key.
|
||||
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
|
||||
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)
|
||||
@@ -571,16 +597,18 @@ extension P384 {
|
||||
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
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
||||
let impl: NISTCurvePrivateKeyImpl<P384>
|
||||
|
||||
/// Creates a random P-384 private key for signing.
|
||||
@@ -601,7 +629,7 @@ extension P384 {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - x963Representation: An ANSI x9.63 representation of the key.
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePrivateKeyImpl(x963: x963Representation)
|
||||
}
|
||||
|
||||
@@ -610,16 +638,17 @@ extension P384 {
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the key as a collection of
|
||||
/// contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePrivateKeyImpl(data: rawRepresentation)
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// Creates a P-384 private key for signing from a Privacy-Enhanced Mail
|
||||
/// PEM) representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pemRepresentation: A PEM representation of the key.
|
||||
public init(pemRepresentation: String) throws {
|
||||
public init(pemRepresentation: String) throws(CryptoKitMetaError) {
|
||||
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
|
||||
|
||||
switch pem.type {
|
||||
@@ -633,13 +662,14 @@ extension P384 {
|
||||
throw CryptoKitASN1Error.invalidPEMDocument
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Creates a P-384 private key for signing from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: A DER-encoded representation of the key.
|
||||
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
|
||||
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.
|
||||
@@ -679,11 +709,13 @@ extension P384 {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -695,11 +727,11 @@ extension P384 {
|
||||
/// performing NIST P-384 elliptic curve Diffie Hellman (ECDH) key
|
||||
/// exchange.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum KeyAgreement {
|
||||
|
||||
public enum KeyAgreement: Sendable {
|
||||
|
||||
/// A P-384 public key used for key agreement.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct PublicKey: NISTECPublicKey {
|
||||
public struct PublicKey: NISTECPublicKey, Sendable {
|
||||
var impl: NISTCurvePublicKeyImpl<P384>
|
||||
|
||||
/// Creates a P-384 public key for key agreement from a collection of bytes.
|
||||
@@ -707,7 +739,7 @@ extension P384 {
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the key as a collection of
|
||||
/// contiguous bytes.
|
||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws {
|
||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(rawRepresentation: rawRepresentation)
|
||||
}
|
||||
|
||||
@@ -717,7 +749,7 @@ extension P384 {
|
||||
/// - Parameters:
|
||||
/// - compactRepresentation: A compact representation of the key
|
||||
/// as a collection of contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(compactRepresentation: compactRepresentation)
|
||||
}
|
||||
|
||||
@@ -726,7 +758,7 @@ extension P384 {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - x963Representation: An ANSI x9.63 representation of the key.
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(x963Representation: x963Representation)
|
||||
}
|
||||
|
||||
@@ -736,29 +768,31 @@ extension P384 {
|
||||
/// - Parameters:
|
||||
/// - compressedRepresentation: A compressed representation of the key as a collection
|
||||
/// of contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(compressedRepresentation: compressedRepresentation)
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// Creates a P-384 public key for key agreement from a Privacy-Enhanced Mail
|
||||
/// (PEM) representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pemRepresentation: A PEM representation of the key.
|
||||
public init(pemRepresentation: String) throws {
|
||||
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 P-384 public key for key agreement from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: A DER-encoded representation of the key.
|
||||
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
|
||||
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)
|
||||
@@ -790,16 +824,18 @@ extension P384 {
|
||||
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
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
||||
let impl: NISTCurvePrivateKeyImpl<P384>
|
||||
|
||||
/// Creates a random P-384 private key for key agreement.
|
||||
@@ -820,7 +856,7 @@ extension P384 {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - x963Representation: An ANSI x9.63 representation of the key.
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePrivateKeyImpl(x963: x963Representation)
|
||||
}
|
||||
|
||||
@@ -829,16 +865,17 @@ extension P384 {
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the key as a collection of
|
||||
/// contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePrivateKeyImpl(data: rawRepresentation)
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// Creates a P-384 private key for key agreement from a Privacy-Enhanced Mail
|
||||
/// PEM) representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pemRepresentation: A PEM representation of the key.
|
||||
public init(pemRepresentation: String) throws {
|
||||
public init(pemRepresentation: String) throws(CryptoKitMetaError) {
|
||||
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
|
||||
|
||||
switch pem.type {
|
||||
@@ -852,13 +889,14 @@ extension P384 {
|
||||
throw CryptoKitASN1Error.invalidPEMDocument
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Creates a P-384 private key for key agreement from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: A DER-encoded representation of the key.
|
||||
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
|
||||
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.
|
||||
@@ -898,11 +936,13 @@ extension P384 {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -913,11 +953,11 @@ extension P521 {
|
||||
/// A mechanism used to create or verify a cryptographic signature using
|
||||
/// the NIST P-521 elliptic curve digital signature algorithm (ECDSA).
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum Signing {
|
||||
|
||||
public enum Signing: Sendable {
|
||||
|
||||
/// A P-521 public key used to verify cryptographic signatures.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct PublicKey: NISTECPublicKey {
|
||||
public struct PublicKey: NISTECPublicKey, Sendable {
|
||||
var impl: NISTCurvePublicKeyImpl<P521>
|
||||
|
||||
/// Creates a P-521 public key for signing from a collection of bytes.
|
||||
@@ -925,7 +965,7 @@ extension P521 {
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the key as a collection of
|
||||
/// contiguous bytes.
|
||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws {
|
||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(rawRepresentation: rawRepresentation)
|
||||
}
|
||||
|
||||
@@ -935,7 +975,7 @@ extension P521 {
|
||||
/// - Parameters:
|
||||
/// - compactRepresentation: A compact representation of the key
|
||||
/// as a collection of contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(compactRepresentation: compactRepresentation)
|
||||
}
|
||||
|
||||
@@ -944,7 +984,7 @@ extension P521 {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - x963Representation: An ANSI x9.63 representation of the key.
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(x963Representation: x963Representation)
|
||||
}
|
||||
|
||||
@@ -954,29 +994,31 @@ extension P521 {
|
||||
/// - Parameters:
|
||||
/// - compressedRepresentation: A compressed representation of the key as a collection
|
||||
/// of contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(compressedRepresentation: compressedRepresentation)
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// Creates a P-521 public key for signing from a Privacy-Enhanced Mail
|
||||
/// (PEM) representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pemRepresentation: A PEM representation of the key.
|
||||
public init(pemRepresentation: String) throws {
|
||||
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 P-521 public key for signing from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: A DER-encoded representation of the key.
|
||||
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
|
||||
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)
|
||||
@@ -1008,16 +1050,18 @@ extension P521 {
|
||||
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
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
||||
let impl: NISTCurvePrivateKeyImpl<P521>
|
||||
|
||||
/// Creates a random P-521 private key for signing.
|
||||
@@ -1038,7 +1082,7 @@ extension P521 {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - x963Representation: An ANSI x9.63 representation of the key.
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePrivateKeyImpl(x963: x963Representation)
|
||||
}
|
||||
|
||||
@@ -1047,16 +1091,17 @@ extension P521 {
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the key as a collection of
|
||||
/// contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePrivateKeyImpl(data: rawRepresentation)
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// Creates a P-521 private key for signing from a Privacy-Enhanced Mail
|
||||
/// PEM) representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pemRepresentation: A PEM representation of the key.
|
||||
public init(pemRepresentation: String) throws {
|
||||
public init(pemRepresentation: String) throws(CryptoKitMetaError) {
|
||||
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
|
||||
|
||||
switch pem.type {
|
||||
@@ -1070,13 +1115,14 @@ extension P521 {
|
||||
throw CryptoKitASN1Error.invalidPEMDocument
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Creates a P-521 private key for signing from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: A DER-encoded representation of the key.
|
||||
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
|
||||
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.
|
||||
@@ -1116,11 +1162,13 @@ extension P521 {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1132,11 +1180,11 @@ extension P521 {
|
||||
/// performing NIST P-521 elliptic curve Diffie Hellman (ECDH) key
|
||||
/// exchange.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum KeyAgreement {
|
||||
|
||||
public enum KeyAgreement: Sendable {
|
||||
|
||||
/// A P-521 public key used for key agreement.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct PublicKey: NISTECPublicKey {
|
||||
public struct PublicKey: NISTECPublicKey, Sendable {
|
||||
var impl: NISTCurvePublicKeyImpl<P521>
|
||||
|
||||
/// Creates a P-521 public key for key agreement from a collection of bytes.
|
||||
@@ -1144,7 +1192,7 @@ extension P521 {
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the key as a collection of
|
||||
/// contiguous bytes.
|
||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws {
|
||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(rawRepresentation: rawRepresentation)
|
||||
}
|
||||
|
||||
@@ -1154,7 +1202,7 @@ extension P521 {
|
||||
/// - Parameters:
|
||||
/// - compactRepresentation: A compact representation of the key
|
||||
/// as a collection of contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(compactRepresentation: compactRepresentation)
|
||||
}
|
||||
|
||||
@@ -1163,7 +1211,7 @@ extension P521 {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - x963Representation: An ANSI x9.63 representation of the key.
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(x963Representation: x963Representation)
|
||||
}
|
||||
|
||||
@@ -1173,29 +1221,31 @@ extension P521 {
|
||||
/// - Parameters:
|
||||
/// - compressedRepresentation: A compressed representation of the key as a collection
|
||||
/// of contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePublicKeyImpl(compressedRepresentation: compressedRepresentation)
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// Creates a P-521 public key for key agreement from a Privacy-Enhanced Mail
|
||||
/// (PEM) representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pemRepresentation: A PEM representation of the key.
|
||||
public init(pemRepresentation: String) throws {
|
||||
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 P-521 public key for key agreement from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: A DER-encoded representation of the key.
|
||||
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
|
||||
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)
|
||||
@@ -1227,16 +1277,18 @@ extension P521 {
|
||||
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
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
public struct PrivateKey: NISTECPrivateKey, Sendable {
|
||||
let impl: NISTCurvePrivateKeyImpl<P521>
|
||||
|
||||
/// Creates a random P-521 private key for key agreement.
|
||||
@@ -1257,7 +1309,7 @@ extension P521 {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - x963Representation: An ANSI x9.63 representation of the key.
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePrivateKeyImpl(x963: x963Representation)
|
||||
}
|
||||
|
||||
@@ -1266,16 +1318,17 @@ extension P521 {
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the key as a collection of
|
||||
/// contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws {
|
||||
public init<Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws(CryptoKitMetaError) {
|
||||
impl = try NISTCurvePrivateKeyImpl(data: rawRepresentation)
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// Creates a P-521 private key for key agreement from a Privacy-Enhanced Mail
|
||||
/// PEM) representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pemRepresentation: A PEM representation of the key.
|
||||
public init(pemRepresentation: String) throws {
|
||||
public init(pemRepresentation: String) throws(CryptoKitMetaError) {
|
||||
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
|
||||
|
||||
switch pem.type {
|
||||
@@ -1289,13 +1342,14 @@ extension P521 {
|
||||
throw CryptoKitASN1Error.invalidPEMDocument
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Creates a P-521 private key for key agreement from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: A DER-encoded representation of the key.
|
||||
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
|
||||
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.
|
||||
@@ -1335,11 +1389,13 @@ extension P521 {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1353,8 +1409,8 @@ extension P256.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
|
||||
/// - 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: P256.KeyAgreement.PublicKey) throws -> SharedSecret {
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
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)
|
||||
@@ -1370,8 +1426,8 @@ extension P384.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
|
||||
/// - 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: P384.KeyAgreement.PublicKey) throws -> SharedSecret {
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
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)
|
||||
@@ -1387,8 +1443,8 @@ extension P521.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
|
||||
/// - 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: P521.KeyAgreement.PublicKey) throws -> SharedSecret {
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
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)
|
||||
|
||||
Loaded 100 of 322 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user