mirror of
https://github.com/apple/swift-crypto
synced 2026-11-22 04:30:39 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e15b6234fe | ||
|
|
3280a5f728 | ||
|
|
1fa43495bc | ||
|
|
9f96b82711 | ||
|
|
281a92df6c | ||
|
|
32adcc5038 | ||
|
|
1586608eee | ||
|
|
f8fad2f95a | ||
|
|
6ff0a3b147 | ||
|
|
ab0beab369 | ||
|
|
57de8e7cb8 | ||
|
|
6a032cf17d | ||
|
|
404c818e35 | ||
|
|
47df2f1f6d | ||
|
|
c2cbadd726 | ||
|
|
deb49b961e | ||
|
|
0f6f68df04 | ||
|
|
1c80d3aff5 | ||
|
|
25847ff705 | ||
|
|
8c018d0882 | ||
|
|
a629920495 | ||
|
|
a9d1d5ab89 | ||
|
|
da9d28d69e | ||
|
|
f79a3ffbc0 | ||
|
|
fa2832e44b | ||
|
|
315a799ccc | ||
|
|
3ed653865a | ||
|
|
47d3869a72 | ||
|
|
c3d9fc8938 | ||
|
|
1ca42a1885 | ||
|
|
1b6b2e274e | ||
|
|
2d37b1192f | ||
|
|
c5b1d7f0cb | ||
|
|
476538ccb8 | ||
|
|
5ef6059b2b | ||
|
|
bb4ba815da | ||
|
|
fa308c07a6 | ||
|
|
a5a71cfcbc | ||
|
|
31611736b0 | ||
|
|
6f70fa9eab | ||
|
|
e8ed8867ec | ||
|
|
87a9e066d9 | ||
|
|
781478b4e0 | ||
|
|
bcd2b89f2a | ||
|
+6 |
431013afaf |
No files matched your search
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "swift-crypto",
|
||||
"image": "swift:latest",
|
||||
"features": {
|
||||
"ghcr.io/devcontainers/features/common-utils:2": {
|
||||
"installZsh": "false",
|
||||
"username": "vscode",
|
||||
"upgradePackages": "false"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/git:1": {
|
||||
"version": "latest"
|
||||
}
|
||||
},
|
||||
"capAdd": ["CAP_SYS_PTRACE"],
|
||||
"securityOpt": ["seccomp=unconfined"],
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"settings": {
|
||||
"swift.path": "/usr/bin",
|
||||
"lldb.library": "/usr/lib/liblldb.so"
|
||||
},
|
||||
"extensions": [
|
||||
"swiftlang.swift-vscode"
|
||||
]
|
||||
}
|
||||
},
|
||||
"remoteUser": "vscode"
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
name: Main
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
@@ -12,19 +15,19 @@ jobs:
|
||||
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
|
||||
with:
|
||||
linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_6_0_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_6_1_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_6_2_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_6_3_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_6_0_enabled: true
|
||||
windows_6_1_enabled: true
|
||||
windows_6_2_enabled: true
|
||||
windows_6_3_enabled: true
|
||||
windows_nightly_next_enabled: true
|
||||
windows_nightly_main_enabled: true
|
||||
windows_6_0_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_6_1_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_6_2_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_6_3_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
|
||||
@@ -32,9 +35,9 @@ jobs:
|
||||
name: Release builds
|
||||
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
|
||||
with:
|
||||
windows_6_0_enabled: true
|
||||
windows_6_1_enabled: true
|
||||
windows_6_2_enabled: true
|
||||
windows_6_3_enabled: true
|
||||
windows_nightly_next_enabled: true
|
||||
windows_nightly_main_enabled: true
|
||||
|
||||
@@ -52,3 +55,4 @@ jobs:
|
||||
with:
|
||||
runner_pool: nightly
|
||||
build_scheme: swift-crypto-Package
|
||||
swift_6_1_enabled: false
|
||||
@@ -1,5 +1,8 @@
|
||||
name: PR
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize]
|
||||
@@ -7,39 +10,35 @@ on:
|
||||
jobs:
|
||||
soundness:
|
||||
name: Soundness
|
||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
|
||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.13
|
||||
with:
|
||||
license_header_check_project_name: "SwiftCrypto"
|
||||
docs_check_enabled: false
|
||||
format_check_container_image: "swift:latest"
|
||||
|
||||
unit-tests:
|
||||
name: Unit tests
|
||||
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
|
||||
with:
|
||||
linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_6_0_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_6_1_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_6_2_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_6_2_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||
linux_6_3_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||
linux_nightly_next_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_6_0_enabled: true
|
||||
windows_6_1_enabled: true
|
||||
windows_6_2_enabled: true
|
||||
windows_6_3_enabled: true
|
||||
windows_nightly_next_enabled: true
|
||||
windows_nightly_main_enabled: true
|
||||
windows_6_0_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_6_1_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_6_2_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_6_2_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||
windows_6_3_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||
windows_nightly_next_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
|
||||
release-builds:
|
||||
name: Release builds
|
||||
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
|
||||
with:
|
||||
windows_6_0_enabled: true
|
||||
windows_6_1_enabled: true
|
||||
windows_6_2_enabled: true
|
||||
windows_6_3_enabled: true
|
||||
windows_nightly_next_enabled: true
|
||||
windows_nightly_main_enabled: true
|
||||
|
||||
@@ -49,19 +48,25 @@ jobs:
|
||||
|
||||
cmake-checks:
|
||||
name: CMake checks
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
swift_version: ["6.2", "6.3", "6.4"]
|
||||
uses: apple/swift-nio/.github/workflows/cmake_tests.yml@main
|
||||
with:
|
||||
update_cmake_lists_config: >-
|
||||
{
|
||||
"targets": [
|
||||
{ "name": "CCryptoBoringSSL", "type": "source", "exceptions": [] },
|
||||
{ "name": "CCryptoBoringSSLShims", "type": "source", "exceptions": [] },
|
||||
{ "name": "CryptoBoringWrapper", "type": "source", "exceptions": [] },
|
||||
{ "name": "CXKCP", "type": "source", "exceptions": [] },
|
||||
{ "name": "CXKCPShims", "type": "source", "exceptions": [] },
|
||||
{ "name": "Crypto", "type": "source", "exceptions": [] },
|
||||
{ "name": "_CryptoExtras", "type": "source", "exceptions": [] },
|
||||
{ "name": "CryptoExtras", "type": "source", "exceptions": [] },
|
||||
{ "name": "CCryptoBoringSSL", "type": "assembly", "exceptions": [ "*/AES/*.swift" ] }
|
||||
]
|
||||
}
|
||||
image: "swift:${{ matrix.swift_version }}"
|
||||
|
||||
macos-tests:
|
||||
name: macOS tests
|
||||
@@ -69,6 +74,7 @@ jobs:
|
||||
with:
|
||||
runner_pool: general
|
||||
build_scheme: swift-crypto-Package
|
||||
swift_6_1_enabled: false
|
||||
|
||||
static-sdk:
|
||||
name: Static SDK
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
name: PR label
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [labeled, unlabeled, opened, reopened, synchronize]
|
||||
@@ -11,7 +14,7 @@ jobs:
|
||||
timeout-minutes: 1
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Check for Semantic Version label
|
||||
|
||||
+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
|
||||
+82
-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,54 @@ 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/ArraySpanHelpers.swift
|
||||
Sources/Crypto/Util/Data+ArraySpan.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 +123,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 +136,39 @@ 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/SymmetricKeyTests/SymmetricKeyTests.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,10 +13,15 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
import Benchmark
|
||||
import Crypto
|
||||
import Foundation
|
||||
import _CryptoExtras
|
||||
import CryptoExtras
|
||||
|
||||
let benchmarks = {
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
let benchmarks: @Sendable () -> Void = {
|
||||
let defaultMetrics: [BenchmarkMetric] = [.mallocCountTotal, .cpuTotal]
|
||||
|
||||
Benchmark(
|
||||
@@ -203,4 +208,145 @@ let benchmarks = {
|
||||
blackHole(try key1.sharedSecretFromKeyAgreement(with: key2.publicKey))
|
||||
}
|
||||
}
|
||||
|
||||
Benchmark(
|
||||
"hmac-sha256-authenticate",
|
||||
configuration: Benchmark.Configuration(
|
||||
metrics: defaultMetrics,
|
||||
scalingFactor: .mega,
|
||||
maxDuration: .seconds(10_000_000),
|
||||
maxIterations: 5
|
||||
)
|
||||
) { benchmark in
|
||||
let key = SymmetricKey(size: .bits256)
|
||||
let message = Data(repeating: 0x41, count: 1024)
|
||||
|
||||
benchmark.startMeasurement()
|
||||
|
||||
for _ in benchmark.scaledIterations {
|
||||
blackHole(HMAC<SHA256>.authenticationCode(for: message, using: key))
|
||||
}
|
||||
}
|
||||
|
||||
Benchmark(
|
||||
"hkdf-sha256-derive",
|
||||
configuration: Benchmark.Configuration(
|
||||
metrics: defaultMetrics,
|
||||
scalingFactor: .kilo,
|
||||
maxDuration: .seconds(10_000_000),
|
||||
maxIterations: 10
|
||||
)
|
||||
) { benchmark in
|
||||
let inputKeyMaterial = SymmetricKey(size: .bits256)
|
||||
let salt = Data("benchmark salt".utf8)
|
||||
let info = Data("benchmark info".utf8)
|
||||
|
||||
benchmark.startMeasurement()
|
||||
|
||||
for _ in benchmark.scaledIterations {
|
||||
blackHole(
|
||||
HKDF<SHA256>.deriveKey(
|
||||
inputKeyMaterial: inputKeyMaterial,
|
||||
salt: salt,
|
||||
info: info,
|
||||
outputByteCount: 1024
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Benchmark(
|
||||
"aes-keywrap-unwrap",
|
||||
configuration: Benchmark.Configuration(
|
||||
metrics: defaultMetrics,
|
||||
scalingFactor: .mega,
|
||||
maxDuration: .seconds(10_000_000),
|
||||
maxIterations: 5
|
||||
)
|
||||
) { benchmark in
|
||||
let kek = SymmetricKey(size: .bits256)
|
||||
let wrapped = try AES.KeyWrap.wrap(SymmetricKey(size: .bits256), using: kek)
|
||||
|
||||
benchmark.startMeasurement()
|
||||
|
||||
for _ in benchmark.scaledIterations {
|
||||
blackHole(try AES.KeyWrap.unwrap(wrapped, using: kek))
|
||||
}
|
||||
}
|
||||
|
||||
if #available(macOS 26.0, *) {
|
||||
Benchmark(
|
||||
"mlkem768-decapsulate",
|
||||
configuration: Benchmark.Configuration(
|
||||
metrics: defaultMetrics,
|
||||
scalingFactor: .kilo,
|
||||
maxDuration: .seconds(10_000_000),
|
||||
maxIterations: 10
|
||||
)
|
||||
) { benchmark in
|
||||
let privateKey = try MLKEM768.PrivateKey()
|
||||
let encapsulated = try privateKey.publicKey.encapsulate().encapsulated
|
||||
|
||||
benchmark.startMeasurement()
|
||||
|
||||
for _ in benchmark.scaledIterations {
|
||||
blackHole(try privateKey.decapsulate(encapsulated))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Benchmark(
|
||||
"pbkdf2-sha256-derive",
|
||||
configuration: Benchmark.Configuration(
|
||||
metrics: defaultMetrics,
|
||||
scalingFactor: .kilo,
|
||||
maxDuration: .seconds(10_000_000),
|
||||
maxIterations: 10
|
||||
)
|
||||
) { benchmark in
|
||||
let password = Data("benchmark password".utf8)
|
||||
let salt = Data("benchmark salt".utf8)
|
||||
|
||||
benchmark.startMeasurement()
|
||||
|
||||
for _ in benchmark.scaledIterations {
|
||||
blackHole(
|
||||
try KDF.Insecure.PBKDF2.deriveKey(
|
||||
from: password,
|
||||
salt: salt,
|
||||
using: .sha256,
|
||||
outputByteCount: 32,
|
||||
unsafeUncheckedRounds: 1_000
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Benchmark(
|
||||
"scrypt-derive",
|
||||
configuration: Benchmark.Configuration(
|
||||
metrics: defaultMetrics,
|
||||
scalingFactor: .kilo,
|
||||
maxDuration: .seconds(10_000_000),
|
||||
maxIterations: 3
|
||||
)
|
||||
) { benchmark in
|
||||
let password = Data("benchmark password".utf8)
|
||||
let salt = Data("benchmark salt".utf8)
|
||||
|
||||
benchmark.startMeasurement()
|
||||
|
||||
for _ in benchmark.scaledIterations {
|
||||
blackHole(
|
||||
try KDF.Scrypt.deriveKey(
|
||||
from: password,
|
||||
salt: salt,
|
||||
outputByteCount: 32,
|
||||
rounds: 1 << 10,
|
||||
blockSize: 8,
|
||||
parallelism: 1
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// swift-tools-version:5.10
|
||||
// swift-tools-version:6.2
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
@@ -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: [
|
||||
|
||||
+7
-8
@@ -12,7 +12,7 @@
|
||||
##
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
cmake_minimum_required(VERSION 3.15.1)
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
|
||||
if(POLICY CMP0157)
|
||||
cmake_policy(SET CMP0157 NEW)
|
||||
@@ -25,18 +25,14 @@ list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules)
|
||||
|
||||
include(SwiftSupport)
|
||||
|
||||
if(CMAKE_VERSION VERSION_LESS 3.16 AND CMAKE_SYSTEM_NAME STREQUAL Windows)
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||
else()
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
endif()
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||
set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift)
|
||||
|
||||
set(SWIFT_CRYPTO_COMPILE_OPTIONS
|
||||
-package-name com.apple.swift-crypto
|
||||
-enable-experimental-feature Lifetimes
|
||||
)
|
||||
|
||||
option(BUILD_SHARED_LIBS "Build shared libraries by default" YES)
|
||||
@@ -78,5 +74,8 @@ if(NOT SwiftASN1_FOUND)
|
||||
FetchContent_MakeAvailable(ASN1)
|
||||
endif()
|
||||
|
||||
# Set after vending swift-asn1 so its targets keep their own language mode.
|
||||
set(CMAKE_Swift_LANGUAGE_VERSION 6)
|
||||
|
||||
add_subdirectory(Sources)
|
||||
add_subdirectory(cmake/modules)
|
||||
@@ -1,3 +0,0 @@
|
||||
# Code of Conduct
|
||||
|
||||
The code of conduct for this project can be found at https://swift.org/code-of-conduct.
|
||||
+30
-10
@@ -5,6 +5,18 @@ your contribution to Apple and the community, and agree by submitting the patch
|
||||
that your contributions are licensed under the Apache 2.0 license (see
|
||||
`LICENSE.txt`).
|
||||
|
||||
## AI tools
|
||||
|
||||
Human discourse is an essential part of open source development. To encourage
|
||||
productive collaboration between contributors and maintainers, please refrain
|
||||
from using AI tools for the following:
|
||||
|
||||
- Issues: titles, bodies, and comments.
|
||||
- Pull requests: titles, descriptions, and comments.
|
||||
|
||||
Contributors who feel more comfortable writing in another language may use
|
||||
automated translation tools, but must include their original content in their
|
||||
preferred language.
|
||||
|
||||
## How to submit a bug report
|
||||
|
||||
@@ -44,19 +56,27 @@ $ uname -a
|
||||
Linux beefy.machine 4.4.0-101-generic #124-Ubuntu SMP Fri Nov 10 18:29:59 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
|
||||
```
|
||||
|
||||
## Writing a Patch
|
||||
## Contributing a pull request
|
||||
|
||||
A good swift-crypto patch is:
|
||||
> [!IMPORTANT]
|
||||
> To ensure productive use of contributor and maintainer time and resources,
|
||||
> contributors must first agree their proposed change with a maintainer in an
|
||||
> issue. Pull requests opened without prior discussion may be closed without
|
||||
> review.
|
||||
|
||||
1. Concise, and contains as few changes as needed to achieve the end result.
|
||||
2. Tested, ensuring that any tests provided failed before the patch and pass after it.
|
||||
3. Documented, adding API documentation as needed to cover new functions and properties.
|
||||
4. Accompanied by a great commit message, using our commit message template.
|
||||
If there is no issue already tracking the problem or feature request, please
|
||||
file a new one using your own voice (see "AI tools" usage above).
|
||||
|
||||
Once an issue is assigned to you, follow these steps:
|
||||
|
||||
## How to contribute your work
|
||||
|
||||
Please open a pull request at https://github.com/apple/swift-crypto. Make sure the CI passes, and then wait for code review.
|
||||
- Prepare your change, keeping in mind that a good patch is:
|
||||
- Concise, and contains as few changes as needed to achieve the end result.
|
||||
- Tested, ensuring that any tests provided failed before the patch and pass
|
||||
after it.
|
||||
- Documented, adding API documentation as needed to cover new functions and
|
||||
properties.
|
||||
- Accompanied by a great commit message.
|
||||
- Open a pull request and wait for code review by the maintainers.
|
||||
|
||||
### How to update CMakeLists files
|
||||
|
||||
@@ -69,7 +89,7 @@ act --container-architecture linux/amd64 pull_request -j cmake-lists -W ./.githu
|
||||
|
||||
You can find the underlying script at https://github.com/apple/swift-nio/blob/main/scripts/update-cmake-lists.sh . Using the script directly is less straightforwards because it requires you to pass the JSON config from the `pull_request.yml` file into the script, such as:
|
||||
```
|
||||
curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/update-cmake-lists.sh | CONFIG_JSON='{"targets":[{"name":"CCryptoBoringSSL","type":"source","exceptions":[]},{"name":"CCryptoBoringSSLShims","type":"source","exceptions":[]},{"name":"CryptoBoringWrapper","type":"source","exceptions":[]},{"name":"Crypto","type":"source","exceptions":[]},{"name":"_CryptoExtras","type":"source","exceptions":[]},{"name":"CCryptoBoringSSL","type":"assembly","exceptions":["*/AES/*.swift"]}]}' bash
|
||||
curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/update-cmake-lists.sh | CONFIG_JSON='{"targets":[{"name":"CCryptoBoringSSL","type":"source","exceptions":[]},{"name":"CryptoBoringWrapper","type":"source","exceptions":[]},{"name":"Crypto","type":"source","exceptions":[]},{"name":"CryptoExtras","type":"source","exceptions":[]},{"name":"CCryptoBoringSSL","type":"assembly","exceptions":["*/AES/*.swift"]}]}' bash
|
||||
```
|
||||
|
||||
## API Evolution
|
||||
|
||||
+77
-58
@@ -1,4 +1,4 @@
|
||||
// swift-tools-version:5.10
|
||||
// swift-tools-version:6.2
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
@@ -26,52 +26,31 @@ import PackageDescription
|
||||
|
||||
import class Foundation.ProcessInfo
|
||||
|
||||
// To develop this on Apple platforms, set this to true
|
||||
let development = false
|
||||
// NOTE: To develop the the non-Darwin Crypto target on macOS, use a Dev Container.
|
||||
let nonDarwinPlatforms: [Platform] = [
|
||||
.linux,
|
||||
.android,
|
||||
.windows,
|
||||
.wasi,
|
||||
.openbsd,
|
||||
// The SwiftPM Platform symbol is not yet public but the underlying platform name is set.
|
||||
// -- https://github.com/swiftlang/swift-package-manager/blob/swift-6.2.3-RELEASE/Sources/PackageDescription/SupportedPlatforms.swift#L75
|
||||
.custom("freebsd"),
|
||||
]
|
||||
|
||||
// Ideally, we should use `.when(platforms:)` to set `swiftSettings` and
|
||||
// `dependencies` like on other platforms. However, `Platform.freebsd` is not
|
||||
// yet available, and therefore we guard the settings behind this boolean.
|
||||
#if os(FreeBSD)
|
||||
let isFreeBSD = true
|
||||
#else
|
||||
let isFreeBSD = false
|
||||
var swiftSettings: [SwiftSetting] = [
|
||||
.define("CRYPTO_IN_SWIFTPM"),
|
||||
.enableExperimentalFeature("Lifetimes"),
|
||||
.enableExperimentalFeature("SourceWarningControl"),
|
||||
]
|
||||
|
||||
// Only enable CheckImplementationOnly on 6.4 -- 6.3 has the feature, but produces many false positives.
|
||||
#if compiler(>=6.4)
|
||||
swiftSettings.append(.enableExperimentalFeature("CheckImplementationOnly"))
|
||||
#endif
|
||||
|
||||
let swiftSettings: [SwiftSetting]
|
||||
let dependencies: [Target.Dependency]
|
||||
if development || isFreeBSD {
|
||||
swiftSettings = [
|
||||
.define("CRYPTO_IN_SWIFTPM"),
|
||||
.define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API"),
|
||||
]
|
||||
dependencies = [
|
||||
"CCryptoBoringSSL",
|
||||
"CCryptoBoringSSLShims",
|
||||
"CryptoBoringWrapper",
|
||||
]
|
||||
} else {
|
||||
let platforms: [Platform] = [
|
||||
Platform.linux,
|
||||
Platform.android,
|
||||
Platform.windows,
|
||||
Platform.wasi,
|
||||
Platform.openbsd,
|
||||
]
|
||||
swiftSettings = [
|
||||
.define("CRYPTO_IN_SWIFTPM"),
|
||||
.define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API", .when(platforms: platforms)),
|
||||
]
|
||||
dependencies = [
|
||||
.target(name: "CCryptoBoringSSL", condition: .when(platforms: platforms)),
|
||||
.target(name: "CCryptoBoringSSLShims", condition: .when(platforms: platforms)),
|
||||
.target(name: "CryptoBoringWrapper", condition: .when(platforms: platforms)),
|
||||
]
|
||||
}
|
||||
|
||||
// This doesn't work when cross-compiling: the privacy manifest will be included in the Bundle and
|
||||
// Foundation will be linked. This is, however, strictly better than unconditionally adding the
|
||||
// resource.
|
||||
// A resource makes SwiftPM generate a `Bundle.module` accessor that imports Foundation, not just FoundationEssentials.
|
||||
// `canImport(Darwin)` checks the host, not the target, so cross-compiling from Darwin still adds the resource.
|
||||
#if canImport(Darwin)
|
||||
let privacyManifestExclude: [String] = []
|
||||
let privacyManifestResource: [PackageDescription.Resource] = [.copy("PrivacyInfo.xcprivacy")]
|
||||
@@ -85,7 +64,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 */
|
||||
@@ -122,11 +103,31 @@ let package = Package(
|
||||
.when(platforms: [Platform.wasi])
|
||||
),
|
||||
.define("OPENSSL_NO_ASM", .when(platforms: [Platform.wasi])),
|
||||
// BoringSSL is vendored verbatim; we don't fix its warnings. Xcode enables
|
||||
// -Wshorten-64-to-32 by default (SwiftPM does not), which produces dozens
|
||||
// of warnings. Silence that group here.
|
||||
.disableWarning("shorten-64-to-32"),
|
||||
]
|
||||
),
|
||||
.target(
|
||||
name: "CCryptoBoringSSLShims",
|
||||
dependencies: ["CCryptoBoringSSL"],
|
||||
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"),
|
||||
.disableWarning("macro-redefined"),
|
||||
]
|
||||
),
|
||||
.target(
|
||||
name: "CXKCPShims",
|
||||
dependencies: ["CXKCP"],
|
||||
exclude: privacyManifestExclude + [
|
||||
"CMakeLists.txt"
|
||||
],
|
||||
@@ -134,22 +135,25 @@ let package = Package(
|
||||
),
|
||||
.target(
|
||||
name: "Crypto",
|
||||
dependencies: dependencies,
|
||||
dependencies: [
|
||||
.target(name: "CCryptoBoringSSL", condition: .when(platforms: nonDarwinPlatforms)),
|
||||
.target(name: "CryptoBoringWrapper", condition: .when(platforms: nonDarwinPlatforms)),
|
||||
.target(name: "CXKCP", condition: .when(platforms: nonDarwinPlatforms)),
|
||||
.target(name: "CXKCPShims", condition: .when(platforms: nonDarwinPlatforms)),
|
||||
],
|
||||
exclude: privacyManifestExclude + [
|
||||
"vendored-sources.txt",
|
||||
"CMakeLists.txt",
|
||||
"AEADs/Nonces.swift.gyb",
|
||||
"Digests/Digests.swift.gyb",
|
||||
"Key Agreement/ECDH.swift.gyb",
|
||||
"Signatures/ECDSA.swift.gyb",
|
||||
"Signatures/BoringSSL/MLDSA_boring.swift.gyb",
|
||||
"KEM/BoringSSL/MLKEM_boring.swift.gyb",
|
||||
],
|
||||
resources: privacyManifestResource,
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.target(
|
||||
name: "_CryptoExtras",
|
||||
name: "CryptoExtras",
|
||||
dependencies: [
|
||||
"CCryptoBoringSSL",
|
||||
"CCryptoBoringSSLShims",
|
||||
"CryptoBoringWrapper",
|
||||
"Crypto",
|
||||
.product(name: "SwiftASN1", package: "swift-asn1"),
|
||||
@@ -160,29 +164,43 @@ let package = Package(
|
||||
resources: privacyManifestResource,
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.target(
|
||||
name: "_CryptoExtras",
|
||||
dependencies: [
|
||||
"CryptoExtras",
|
||||
],
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.target(
|
||||
name: "CryptoBoringWrapper",
|
||||
dependencies: [
|
||||
"CCryptoBoringSSL",
|
||||
"CCryptoBoringSSLShims",
|
||||
],
|
||||
exclude: privacyManifestExclude + [
|
||||
"CMakeLists.txt"
|
||||
],
|
||||
resources: privacyManifestResource
|
||||
resources: privacyManifestResource,
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.executableTarget(name: "crypto-shasum", dependencies: ["Crypto"]),
|
||||
.testTarget(
|
||||
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 +211,7 @@ let package = Package(
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.testTarget(name: "CryptoBoringWrapperTests", dependencies: ["CryptoBoringWrapper"]),
|
||||
.testTarget(name: "CXKCPTests", dependencies: ["CXKCP"]),
|
||||
],
|
||||
cxxLanguageStandard: .cxx17
|
||||
)
|
||||
|
||||
@@ -7,9 +7,9 @@ Swift Crypto is an open-source implementation of a substantial portion of the AP
|
||||
Swift Crypto is available as a Swift Package Manager package. To use it, add the following dependency in your `Package.swift`:
|
||||
|
||||
```swift
|
||||
// swift-crypto 1.x, 2.x and 3.x are almost API compatible, so most clients
|
||||
// swift-crypto 1.x, 2.x, 3.x, 4.x, and 5.x are almost API compatible, so most clients
|
||||
// should allow any of them
|
||||
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "4.0.0"),
|
||||
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "6.0.0"),
|
||||
```
|
||||
|
||||
and to your target, add `Crypto` to your dependencies. You can then `import Crypto` to get access to Swift Crypto's functionality.
|
||||
@@ -28,13 +28,14 @@ Swift Crypto compiles in two distinct modes depending on the platform for which
|
||||
|
||||
When building Swift Crypto for use on an Apple platform where CryptoKit is already available, Swift Crypto compiles its entire API surface down to nothing and simply re-exports the API of CryptoKit. This means that when using Apple platforms Swift Crypto simply delegates all work to the core implementation of CryptoKit, as though Swift Crypto was not even there.
|
||||
|
||||
When building Swift Crypto for use on Linux or Windows, Swift Crypto builds substantially more code. In particular, we build:
|
||||
When building Swift Crypto for use on other platforms, Swift Crypto builds substantially more code. In particular, we build:
|
||||
|
||||
1. A vendored copy of BoringSSL's libcrypto.
|
||||
2. The common API of Swift Crypto and CryptoKit.
|
||||
3. The backing implementation of this common API, which calls into BoringSSL.
|
||||
2. A vendored copy of XKCP's libXKCP.
|
||||
3. The common API of Swift Crypto and CryptoKit.
|
||||
4. The backing implementation of this common API, which calls into BoringSSL or XKCP.
|
||||
|
||||
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 BoringSSL/XKCP backing implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIs predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL/XKCP implementation of the library in your application, no matter the platform.
|
||||
|
||||
## Evolution
|
||||
|
||||
@@ -48,11 +49,11 @@ Note that Swift Crypto does not intend to support all possible cryptographic pri
|
||||
|
||||
### Code Organisation
|
||||
|
||||
Files in this repository are divided into two groups, based on whether they have a name that ends in `_boring` or are in a `BoringSSL` directory, or if they are not.
|
||||
Files in this repository are divided into two groups, based on whether they have a name that ends in `_boring`/`_xkcp` or are in a `BoringSSL`/`XKCP` directory, or if they are not.
|
||||
|
||||
Files that meet the above criteria are specific to the Swift Crypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or access a BoringSSL API, it needs to be marked this way.
|
||||
Files that meet the above criteria are specific to the Swift Crypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or `import CXKCP` or access a BoringSSL or XKCP API, it needs to be marked this way.
|
||||
|
||||
Files that do not have the `_boring` suffix are part of the public API of CryptoKit. Changing these requires passing a higher bar, as any change in these files must be accompanied by a change in CryptoKit itself.
|
||||
Files that do not have the `_boring` or `_xkcp` suffix are part of the public API of CryptoKit. Changing these requires passing a higher bar, as any change in these files must be accompanied by a change in CryptoKit itself.
|
||||
|
||||
## Contributing
|
||||
|
||||
@@ -108,7 +109,7 @@ If you believe you have identified a vulnerability in Swift Crypto, please [repo
|
||||
|
||||
### Swift versions
|
||||
|
||||
The most recent versions of Swift Crypto support Swift 5.7 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
|
||||
The most recent versions of Swift Crypto support Swift 6.2 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
|
||||
|
||||
Swift Crypto | Minimum Swift Version
|
||||
--------------------|----------------------
|
||||
@@ -119,7 +120,10 @@ Swift Crypto | Minimum Swift Version
|
||||
`3.1.0 ..< 3.3.0` | 5.7
|
||||
`3.3.0 ..< 3.8.0` | 5.8
|
||||
`3.9.0 ..< 3.13.0` | 5.9
|
||||
`3.13.0 ...` | 5.10
|
||||
`3.13.0 ..< 4.0.0` | 5.10
|
||||
`4.0.0 ..< 4.4.0` | 6.0
|
||||
`4.4.0 ..< 5.0.0` | 6.1
|
||||
`5.0.0 ...` | 6.2
|
||||
|
||||
### Compatibility
|
||||
|
||||
@@ -131,13 +135,23 @@ SemVer and Swift Crypto's Public API guarantees should result in a working progr
|
||||
|
||||
Swift Crypto 2.0.0 was released in September 2021. The only breaking change between Swift Crypto 2.0.0 and 1.0.0 was the addition of new cases in the `CryptoError` enumeration. For most users, then, it's safe to depend on either the 1.0.0 _or_ 2.0.0 series of releases.
|
||||
|
||||
Swift Crypto 3.0.0 was released in September 2023. Again the only breaking change was the addition of new cases in the `CryptoError` enumeration, so most users can safely depend on the 1.0.0, 2.0.0, or 3.0.0 series of releases.
|
||||
|
||||
Swift Crypto 4.0.0 was released in September 2025. Again the only breaking change was the addition of new cases in the `CryptoError` enumeration, so most users can safely depend on the 1.0.0, 2.0.0, 3.0.0, or 4.0.0 series of releases. Note that in this release `_CryptoExtras` was renamed to `CryptoExtras`. The old products and targets have been kept around for compatibility reasons, but users depending only on new code should use `CryptoExtras` not `_CryptoExtras`.
|
||||
|
||||
Swift Crypto 5.0.0 was released in September 2026. Because this version is only supported on Swift versions that support extensible enums, this release has mechanically marked all non-frozen public enums in CryptoKit as `@nonexhaustive`, which should mitigate the need for any future major releases of Swift Crypto. Most users will be able to depend on the 1.0.0, 2.0.0, 3.0.0, 4.0.0 or 5.0.0 series of releases.
|
||||
|
||||
To do so, please use the following dependency in your `Package.swift`:
|
||||
|
||||
```swift
|
||||
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "3.0.0"),
|
||||
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "6.0.0"),
|
||||
```
|
||||
|
||||
### Developing Swift Crypto on macOS
|
||||
|
||||
Swift Crypto normally defers to the OS implementation of CryptoKit on macOS. Naturally, this makes developing Swift Crypto on macOS tricky. To get Swift Crypto to build the open source implementation on macOS, in `Package.swift`, change `let development = false` to `let development = true`, as this will force Swift Crypto to build its public API.
|
||||
Swift Crypto normally defers to the OS implementation of CryptoKit on macOS. Naturally, this makes developing Swift Crypto on macOS tricky. To get Swift Crypto to build the open source implementation on macOS, in `Package.swift`, use a Linux container. A Dev Container config is provided in the repo to make this easier.
|
||||
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
This project contains source code from the BoringSSL and XKCP projects.
|
||||
@@ -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
|
||||
@@ -1,155 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#ifndef C_CRYPTO_BORINGSSL_SHIMS_H
|
||||
#define C_CRYPTO_BORINGSSL_SHIMS_H
|
||||
|
||||
// This is for instances when `swift package generate-xcodeproj` is used as CCryptoBoringSSL
|
||||
// is treated as a framework and requires the framework's name as a prefix.
|
||||
#if __has_include(<CCryptoBoringSSL/CCryptoBoringSSL.h>)
|
||||
#include <CCryptoBoringSSL/CCryptoBoringSSL.h>
|
||||
#else
|
||||
#include <CCryptoBoringSSL.h>
|
||||
#endif
|
||||
|
||||
#if defined(__cplusplus)
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
// MARK:- Pointer type shims
|
||||
// This section of the code handles shims that change uint8_t* pointers to
|
||||
// void *s. This is done because Swift does not have the rule that C does, that
|
||||
// pointers to uint8_t can safely alias any other pointer. That means that Swift
|
||||
// Unsafe[Mutable]RawPointer cannot be passed to uint8_t * APIs, which is very
|
||||
// awkward, so we shim these to avoid the need to call bindMemory in Swift (which is
|
||||
// wrong).
|
||||
//
|
||||
// Our relevant citation is: https://github.com/apple/swift-nio-extras/pull/56#discussion_r329330295.
|
||||
// We want this to land: https://bugs.swift.org/browse/SR-11087. Once that lands we can remove these
|
||||
// shims.
|
||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_init(EVP_AEAD_CTX *ctx, const EVP_AEAD *aead,
|
||||
const void *key, size_t key_len, size_t tag_len,
|
||||
ENGINE *impl);
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_seal_scatter(
|
||||
const EVP_AEAD_CTX *ctx,
|
||||
void *out,
|
||||
void *out_tag,
|
||||
size_t *out_tag_len,
|
||||
size_t max_out_tag_len,
|
||||
const void *nonce,
|
||||
size_t nonce_len,
|
||||
const void *in,
|
||||
size_t in_len,
|
||||
const void *extra_in,
|
||||
size_t extra_in_len,
|
||||
const void *ad,
|
||||
size_t ad_len);
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(const EVP_AEAD_CTX *ctx, void *out,
|
||||
const void *nonce, size_t nonce_len,
|
||||
const void *in, size_t in_len,
|
||||
const void *in_tag, size_t in_tag_len,
|
||||
const void *ad, size_t ad_len);
|
||||
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open(const EVP_AEAD_CTX *ctx, void *out, size_t *out_len, size_t max_out_len,
|
||||
const void *nonce, size_t nonce_len,
|
||||
const void *in, size_t in_len,
|
||||
const void *ad, size_t ad_len);
|
||||
|
||||
|
||||
void CCryptoBoringSSLShims_ED25519_keypair(void *out_public_key, void *out_private_key);
|
||||
|
||||
void CCryptoBoringSSLShims_ED25519_keypair_from_seed(void *out_public_key,
|
||||
void *out_private_key,
|
||||
const void *seed);
|
||||
|
||||
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_do_sign(const void *digest, size_t digest_len,
|
||||
const EC_KEY *eckey);
|
||||
|
||||
int CCryptoBoringSSLShims_ECDSA_do_verify(const void *digest, size_t digest_len,
|
||||
const ECDSA_SIG *sig, const EC_KEY *eckey);
|
||||
|
||||
void CCryptoBoringSSLShims_X25519_keypair(void *out_public_value, void *out_private_key);
|
||||
|
||||
void CCryptoBoringSSLShims_X25519_public_from_private(void *out_public_value,
|
||||
const void *private_key);
|
||||
|
||||
int CCryptoBoringSSLShims_X25519(void *out_shared_key, const void *private_key,
|
||||
const void *peer_public_value);
|
||||
|
||||
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(const void *in, size_t in_len);
|
||||
|
||||
int CCryptoBoringSSLShims_ED25519_verify(const void *message, size_t message_len,
|
||||
const void *signature, const void *public_key);
|
||||
|
||||
int CCryptoBoringSSLShims_ED25519_sign(void *out_sig, const void *message,
|
||||
size_t message_len, const void *private_key);
|
||||
|
||||
BIGNUM *CCryptoBoringSSLShims_BN_bin2bn(const void *in, size_t len, BIGNUM *ret);
|
||||
|
||||
size_t CCryptoBoringSSLShims_BN_bn2bin(const BIGNUM *in, void *out);
|
||||
|
||||
int CCryptoBoringSSLShims_BN_mod(BIGNUM *rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_verify(int hash_nid, const void *msg, size_t msg_len,
|
||||
const void *sig, size_t sig_len, RSA *rsa);
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_verify_pss_mgf1(RSA *rsa, const void *msg,
|
||||
size_t msg_len, const EVP_MD *md,
|
||||
const EVP_MD *mgf1_md, int salt_len,
|
||||
const void *sig, size_t sig_len);
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_sign(int hash_nid, const void *in,
|
||||
unsigned int in_len, void *out,
|
||||
unsigned int *out_len, RSA *rsa);
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_sign_pss_mgf1(RSA *rsa, size_t *out_len, void *out,
|
||||
size_t max_out, const void *in,
|
||||
size_t in_len, const EVP_MD *md,
|
||||
const EVP_MD *mgf1_md, int salt_len);
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_public_encrypt(int flen, const void *from, void *to,
|
||||
RSA *rsa, int padding);
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_private_decrypt(int flen, const void *from, void *to,
|
||||
RSA *rsa, int padding);
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, void *out,
|
||||
size_t *out_len, const void *in,
|
||||
size_t in_len);
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, void *out,
|
||||
size_t *out_len, const void *in,
|
||||
size_t in_len);
|
||||
|
||||
int CCryptoBoringSSLShims_EC_hash_to_curve_p256_xmd_sha256_sswu(const EC_GROUP *group, EC_POINT *out,
|
||||
const void *dst, size_t dst_len,
|
||||
const void *msg, size_t msg_len);
|
||||
|
||||
int CCryptoBoringSSLShims_EC_hash_to_curve_p384_xmd_sha384_sswu(const EC_GROUP *group, EC_POINT *out,
|
||||
const void *dst, size_t dst_len,
|
||||
const void *msg, size_t msg_len);
|
||||
|
||||
size_t CCryptoBoringSSLShims_EC_POINT_point2oct(const EC_GROUP *group,
|
||||
const EC_POINT *point,
|
||||
point_conversion_form_t form,
|
||||
void *buf, size_t max_out,
|
||||
BN_CTX *ctx);
|
||||
|
||||
#if defined(__cplusplus)
|
||||
}
|
||||
#endif // defined(__cplusplus)
|
||||
|
||||
#endif // C_CRYPTO_BORINGSSL_SHIMS_H
|
||||
@@ -1,4 +0,0 @@
|
||||
module CCryptoBoringSSLShims {
|
||||
header "CCryptoBoringSSLShims.h"
|
||||
export *
|
||||
}
|
||||
@@ -1,190 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#include <CCryptoBoringSSLShims.h>
|
||||
|
||||
// MARK:- Pointer type shims
|
||||
// This section of the code handles shims that change uint8_t* pointers to
|
||||
// void *s. This is done because Swift does not have the rule that C does, that
|
||||
// pointers to uint8_t can safely alias any other pointer. That means that Swift
|
||||
// Unsafe[Mutable]RawPointer cannot be passed to uint8_t * APIs, which is very
|
||||
// awkward, so we shim these to avoid the need to call bindMemory in Swift (which is
|
||||
// wrong).
|
||||
//
|
||||
// Our relevant citation is: https://github.com/apple/swift-nio-extras/pull/56#discussion_r329330295.
|
||||
// We want this to land: https://bugs.swift.org/browse/SR-11087. Once that lands we can remove these
|
||||
// shims.
|
||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_init(EVP_AEAD_CTX *ctx, const EVP_AEAD *aead,
|
||||
const void *key, size_t key_len, size_t tag_len,
|
||||
ENGINE *impl) {
|
||||
return CCryptoBoringSSL_EVP_AEAD_CTX_init(ctx, aead, key, key_len, tag_len, impl);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_seal_scatter(
|
||||
const EVP_AEAD_CTX *ctx,
|
||||
void *out,
|
||||
void *out_tag,
|
||||
size_t *out_tag_len,
|
||||
size_t max_out_tag_len,
|
||||
const void *nonce,
|
||||
size_t nonce_len,
|
||||
const void *in,
|
||||
size_t in_len,
|
||||
const void *extra_in,
|
||||
size_t extra_in_len,
|
||||
const void *ad,
|
||||
size_t ad_len) {
|
||||
return CCryptoBoringSSL_EVP_AEAD_CTX_seal_scatter(ctx, out, out_tag, out_tag_len, max_out_tag_len, nonce, nonce_len, in, in_len, extra_in, extra_in_len, ad, ad_len);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(const EVP_AEAD_CTX *ctx, void *out,
|
||||
const void *nonce, size_t nonce_len,
|
||||
const void *in, size_t in_len,
|
||||
const void *in_tag, size_t in_tag_len,
|
||||
const void *ad, size_t ad_len) {
|
||||
return CCryptoBoringSSL_EVP_AEAD_CTX_open_gather(ctx, out, nonce, nonce_len, in, in_len, in_tag, in_tag_len, ad, ad_len);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open(const EVP_AEAD_CTX *ctx, void *out, size_t *out_len, size_t max_out_len,
|
||||
const void *nonce, size_t nonce_len,
|
||||
const void *in, size_t in_len,
|
||||
const void *ad, size_t ad_len) {
|
||||
return CCryptoBoringSSL_EVP_AEAD_CTX_open(ctx, out, out_len, max_out_len, nonce, nonce_len, in, in_len, ad, ad_len);
|
||||
}
|
||||
|
||||
void CCryptoBoringSSLShims_ED25519_keypair(void *out_public_key, void *out_private_key) {
|
||||
CCryptoBoringSSL_ED25519_keypair(out_public_key, out_private_key);
|
||||
}
|
||||
|
||||
void CCryptoBoringSSLShims_ED25519_keypair_from_seed(void *out_public_key,
|
||||
void *out_private_key,
|
||||
const void *seed) {
|
||||
CCryptoBoringSSL_ED25519_keypair_from_seed(out_public_key, out_private_key, seed);
|
||||
}
|
||||
|
||||
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_do_sign(const void *digest, size_t digest_len,
|
||||
const EC_KEY *eckey) {
|
||||
return CCryptoBoringSSL_ECDSA_do_sign(digest, digest_len, eckey);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_ECDSA_do_verify(const void *digest, size_t digest_len,
|
||||
const ECDSA_SIG *sig, const EC_KEY *eckey) {
|
||||
return CCryptoBoringSSL_ECDSA_do_verify(digest, digest_len, sig, eckey);
|
||||
}
|
||||
|
||||
void CCryptoBoringSSLShims_X25519_keypair(void *out_public_value, void *out_private_key) {
|
||||
CCryptoBoringSSL_X25519_keypair(out_public_value, out_private_key);
|
||||
}
|
||||
|
||||
void CCryptoBoringSSLShims_X25519_public_from_private(void *out_public_value,
|
||||
const void *private_key) {
|
||||
CCryptoBoringSSL_X25519_public_from_private(out_public_value, private_key);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_X25519(void *out_shared_key, const void *private_key,
|
||||
const void *peer_public_value) {
|
||||
return CCryptoBoringSSL_X25519(out_shared_key, private_key, peer_public_value);
|
||||
}
|
||||
|
||||
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(const void *in, size_t in_len) {
|
||||
return CCryptoBoringSSL_ECDSA_SIG_from_bytes(in, in_len);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_ED25519_verify(const void *message, size_t message_len,
|
||||
const void *signature, const void *public_key) {
|
||||
return CCryptoBoringSSL_ED25519_verify(message, message_len, signature, public_key);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_ED25519_sign(void *out_sig, const void *message,
|
||||
size_t message_len, const void *private_key) {
|
||||
return CCryptoBoringSSL_ED25519_sign(out_sig, message, message_len, private_key);
|
||||
}
|
||||
|
||||
BIGNUM *CCryptoBoringSSLShims_BN_bin2bn(const void *in, size_t len, BIGNUM *ret) {
|
||||
return CCryptoBoringSSL_BN_bin2bn(in, len, ret);
|
||||
}
|
||||
|
||||
size_t CCryptoBoringSSLShims_BN_bn2bin(const BIGNUM *in, void *out) {
|
||||
return CCryptoBoringSSL_BN_bn2bin(in, out);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_BN_mod(BIGNUM *rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) {
|
||||
return BN_mod(rem, a, m, ctx);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_verify(int hash_nid, const void *msg, size_t msg_len,
|
||||
const void *sig, size_t sig_len, RSA *rsa) {
|
||||
return CCryptoBoringSSL_RSA_verify(hash_nid, msg, msg_len, sig, sig_len, rsa);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_verify_pss_mgf1(RSA *rsa, const void *msg,
|
||||
size_t msg_len, const EVP_MD *md,
|
||||
const EVP_MD *mgf1_md, int salt_len,
|
||||
const void *sig, size_t sig_len) {
|
||||
return CCryptoBoringSSL_RSA_verify_pss_mgf1(rsa, msg, msg_len, md, mgf1_md, salt_len, sig, sig_len);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_sign(int hash_nid, const void *in,
|
||||
unsigned int in_len, void *out,
|
||||
unsigned int *out_len, RSA *rsa) {
|
||||
return CCryptoBoringSSL_RSA_sign(hash_nid, in, in_len, out, out_len, rsa);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_sign_pss_mgf1(RSA *rsa, size_t *out_len, void *out,
|
||||
size_t max_out, const void *in,
|
||||
size_t in_len, const EVP_MD *md,
|
||||
const EVP_MD *mgf1_md, int salt_len) {
|
||||
return CCryptoBoringSSL_RSA_sign_pss_mgf1(rsa, out_len, out, max_out, in, in_len, md, mgf1_md, salt_len);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_public_encrypt(int flen, const void *from, void *to,
|
||||
RSA *rsa, int padding) {
|
||||
return CCryptoBoringSSL_RSA_public_encrypt(flen, from, to, rsa, padding);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_private_decrypt(int flen, const void *from, void *to,
|
||||
RSA *rsa, int padding) {
|
||||
return CCryptoBoringSSL_RSA_private_decrypt(flen, from, to, rsa, padding);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, void *out,
|
||||
size_t *out_len, const void *in,
|
||||
size_t in_len) {
|
||||
return CCryptoBoringSSL_EVP_PKEY_encrypt(ctx, out, out_len, in, in_len);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, void *out,
|
||||
size_t *out_len, const void *in,
|
||||
size_t in_len) {
|
||||
return CCryptoBoringSSL_EVP_PKEY_decrypt(ctx, out, out_len, in, in_len);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_EC_hash_to_curve_p256_xmd_sha256_sswu(const EC_GROUP *group, EC_POINT *out,
|
||||
const void *dst, size_t dst_len,
|
||||
const void *msg, size_t msg_len) {
|
||||
return CCryptoBoringSSL_EC_hash_to_curve_p256_xmd_sha256_sswu(group, out, dst, dst_len, msg, msg_len);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_EC_hash_to_curve_p384_xmd_sha384_sswu(const EC_GROUP *group, EC_POINT *out,
|
||||
const void *dst, size_t dst_len,
|
||||
const void *msg, size_t msg_len) {
|
||||
return CCryptoBoringSSL_EC_hash_to_curve_p384_xmd_sha384_sswu(group, out, dst, dst_len, msg, msg_len);
|
||||
}
|
||||
|
||||
size_t CCryptoBoringSSLShims_EC_POINT_point2oct(const EC_GROUP *group,
|
||||
const EC_POINT *point,
|
||||
point_conversion_form_t form,
|
||||
void *buf, size_t max_out,
|
||||
BN_CTX *ctx) {
|
||||
return CCryptoBoringSSL_EC_POINT_point2oct(group, point, form, buf, max_out, ctx);
|
||||
}
|
||||
@@ -13,7 +13,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
|
||||
@@ -12,18 +12,18 @@
|
||||
##
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
add_library(CCryptoBoringSSLShims STATIC
|
||||
add_library(CXKCPShims STATIC
|
||||
"shims.c"
|
||||
)
|
||||
|
||||
target_include_directories(CCryptoBoringSSLShims PUBLIC
|
||||
target_include_directories(CXKCPShims PUBLIC
|
||||
include
|
||||
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>)
|
||||
$<TARGET_PROPERTY:CXKCP,INCLUDE_DIRECTORIES>)
|
||||
|
||||
target_link_libraries(CCryptoBoringSSLShims PUBLIC
|
||||
CCryptoBoringSSL)
|
||||
target_link_libraries(CXKCPShims PUBLIC
|
||||
CXKCP)
|
||||
|
||||
set_target_properties(CCryptoBoringSSLShims PROPERTIES
|
||||
set_target_properties(CXKCPShims PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_CRYPTO_EXPORTS CCryptoBoringSSLShims)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_CRYPTO_EXPORTS CXKCPShims)
|
||||
File renamed without changes.
@@ -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);
|
||||
}
|
||||
@@ -11,29 +11,29 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@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
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@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 {
|
||||
@nonexhaustive
|
||||
public enum GCM: Cipher, Sendable {
|
||||
static let tagByteCount = 16
|
||||
static let defaultNonceByteCount = 12
|
||||
|
||||
|
||||
/// Fixed-length array of tagByteCount bytes.
|
||||
typealias TagStorage = [16 of UInt8]
|
||||
|
||||
/// Secures the given plaintext message with encryption and an
|
||||
/// authentication tag that covers both the encrypted data and
|
||||
/// additional data.
|
||||
@@ -41,12 +41,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,14 +56,38 @@ 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)
|
||||
}
|
||||
|
||||
/// Secures the given plaintext message with encryption and an optional authentication tag.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - message: The plaintext data to seal, which will be updated in place.
|
||||
/// - key: A cryptographic key used to seal the message.
|
||||
/// - nonce: The nonce the sealing process requires.
|
||||
/// - authenticatedData: Additional data to be authenticated, if provided.
|
||||
/// - tag: receives the 16-byte authentication tag
|
||||
#if compiler(<6.3)
|
||||
@_lifetime(message: copy message)
|
||||
#endif
|
||||
public static func seal(
|
||||
inPlace message: inout MutableRawSpan,
|
||||
using key: SymmetricKey,
|
||||
nonce: Nonce,
|
||||
authenticating authenticatedData: RawSpan? = nil,
|
||||
tag: inout OutputRawSpan
|
||||
) throws(CryptoKitMetaError) {
|
||||
return try AESGCMImpl.seal(
|
||||
key: key, message: &message, nonce: nonce.bytes,
|
||||
authenticatedData: authenticatedData, tag: &tag
|
||||
)
|
||||
}
|
||||
|
||||
/// Decrypts the message and verifies the authenticity of both the
|
||||
/// encrypted message and additional data.
|
||||
///
|
||||
@@ -76,7 +100,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,13 +113,42 @@ 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)
|
||||
}
|
||||
|
||||
/// Decrypts the message and verifies its authenticity.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - message: The message, which will be decrypted in place.
|
||||
/// - key: The cryptographic key that was used to seal the message.
|
||||
/// - nonce: The nonce used to encrypt the message.
|
||||
/// - tag : The 16-byte authentication tag.
|
||||
/// - authenticatedData: Additional data that was authenticated.
|
||||
///
|
||||
/// The call throws an error if decryption or authentication fail.
|
||||
#if compiler(<6.3)
|
||||
@_lifetime(message: copy message)
|
||||
#endif
|
||||
public static func open(
|
||||
inPlace message: inout MutableRawSpan,
|
||||
using key: SymmetricKey,
|
||||
nonce: Nonce,
|
||||
authenticating authenticatedData: RawSpan? = nil,
|
||||
tag: RawSpan
|
||||
) throws(CryptoKitMetaError) {
|
||||
try AESGCMImpl
|
||||
.open(
|
||||
key: key,
|
||||
message: &message,
|
||||
nonce: nonce.bytes,
|
||||
authenticatedData: authenticatedData,
|
||||
tag: tag
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension AES.GCM {
|
||||
/// A secure container for your data that you can access using a cipher.
|
||||
///
|
||||
@@ -111,8 +164,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 +219,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,15 +241,15 @@ 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
|
||||
let nonceByteCount = nonce.storage.count
|
||||
var combinedRepresentation = Data()
|
||||
combinedRepresentation.reserveCapacity(nonceByteCount + ciphertext.count + tag.count)
|
||||
combinedRepresentation.append(contentsOf: nonce.bytes)
|
||||
combinedRepresentation.append(contentsOf: nonce.storage)
|
||||
combinedRepresentation.append(contentsOf: ciphertext)
|
||||
combinedRepresentation.append(contentsOf: tag)
|
||||
|
||||
@@ -202,4 +258,4 @@ extension AES.GCM {
|
||||
|
||||
}
|
||||
}
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,12 +11,20 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
#endif
|
||||
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 {
|
||||
@@ -31,17 +39,16 @@ enum OpenSSLAESGCMImpl {
|
||||
|
||||
let aead = try Self._backingAEAD(key: key)
|
||||
|
||||
let ciphertext: Data
|
||||
let tag: Data
|
||||
let combined: Data
|
||||
if let ad = authenticatedData {
|
||||
(ciphertext, tag) = try aead.seal(
|
||||
combined = try aead.seal(
|
||||
message: message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
authenticatedData: ad
|
||||
)
|
||||
} else {
|
||||
(ciphertext, tag) = try aead.seal(
|
||||
combined = try aead.seal(
|
||||
message: message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
@@ -49,7 +56,39 @@ enum OpenSSLAESGCMImpl {
|
||||
)
|
||||
}
|
||||
|
||||
return try AES.GCM.SealedBox(nonce: nonce, ciphertext: ciphertext, tag: tag)
|
||||
return AES.GCM.SealedBox(combined: combined, nonceByteCount: nonce.count)
|
||||
}
|
||||
|
||||
#if compiler(<6.3)
|
||||
@_lifetime(message: copy message)
|
||||
#endif
|
||||
@inlinable
|
||||
static func seal(
|
||||
key: SymmetricKey,
|
||||
message: inout MutableRawSpan,
|
||||
nonce: RawSpan,
|
||||
authenticatedData: RawSpan?,
|
||||
tag: inout OutputRawSpan
|
||||
) throws {
|
||||
let aead = try Self._backingAEAD(key: key)
|
||||
|
||||
if let ad = authenticatedData {
|
||||
try aead.seal(
|
||||
message: &message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
authenticatedData: ad,
|
||||
tag: &tag
|
||||
)
|
||||
} else {
|
||||
try aead.seal(
|
||||
message: &message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
authenticatedData: RawSpan(),
|
||||
tag: &tag
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -79,6 +118,38 @@ enum OpenSSLAESGCMImpl {
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a given message in place.
|
||||
#if compiler(<6.3)
|
||||
@_lifetime(message: copy message)
|
||||
#endif
|
||||
@inlinable
|
||||
static func open(
|
||||
key: SymmetricKey,
|
||||
message: inout MutableRawSpan,
|
||||
nonce: RawSpan,
|
||||
authenticatedData: RawSpan?,
|
||||
tag: RawSpan
|
||||
) throws {
|
||||
let aead = try Self._backingAEAD(key: key)
|
||||
if let authenticatedData {
|
||||
return try aead.open(
|
||||
message: &message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
tag: tag,
|
||||
authenticatedData: authenticatedData
|
||||
)
|
||||
} else {
|
||||
return try aead.open(
|
||||
message: &message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
tag: tag,
|
||||
authenticatedData: RawSpan()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func _backingAEAD(key: SymmetricKey) throws -> BoringSSLAEAD {
|
||||
switch key.bitCount {
|
||||
@@ -93,4 +164,4 @@ enum OpenSSLAESGCMImpl {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,13 +11,20 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
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 {
|
||||
@@ -27,7 +34,7 @@ extension BoringSSLAEAD {
|
||||
key: SymmetricKey,
|
||||
nonce: Nonce,
|
||||
authenticatedData: AuthenticatedData
|
||||
) throws -> (ciphertext: Data, tag: Data) {
|
||||
) throws -> Data {
|
||||
do {
|
||||
let context = try AEADContext(cipher: self, key: key)
|
||||
return try context.seal(
|
||||
@@ -40,6 +47,30 @@ extension BoringSSLAEAD {
|
||||
}
|
||||
}
|
||||
|
||||
/// Seal a given message in place
|
||||
#if compiler(<6.3)
|
||||
@_lifetime(message: copy message)
|
||||
#endif
|
||||
func seal(
|
||||
message: inout MutableRawSpan,
|
||||
key: SymmetricKey,
|
||||
nonce: RawSpan,
|
||||
authenticatedData: RawSpan,
|
||||
tag: inout OutputRawSpan
|
||||
) throws {
|
||||
do {
|
||||
let context = try AEADContext(cipher: self, key: key)
|
||||
return try context.seal(
|
||||
message: &message,
|
||||
nonce: nonce,
|
||||
authenticatedData: authenticatedData,
|
||||
tag: &tag,
|
||||
)
|
||||
} catch CryptoBoringWrapperError.underlyingCoreCryptoError(let errorCode) {
|
||||
throw CryptoKitError.underlyingCoreCryptoError(error: errorCode)
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a given message.
|
||||
func open<Nonce: ContiguousBytes, AuthenticatedData: DataProtocol>(
|
||||
ciphertext: Data,
|
||||
@@ -60,6 +91,30 @@ extension BoringSSLAEAD {
|
||||
throw CryptoKitError.underlyingCoreCryptoError(error: errorCode)
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a given message in place.
|
||||
#if compiler(<6.3)
|
||||
@_lifetime(message: copy message)
|
||||
#endif
|
||||
public func open(
|
||||
message: inout MutableRawSpan,
|
||||
key: SymmetricKey,
|
||||
nonce: RawSpan,
|
||||
tag: RawSpan,
|
||||
authenticatedData: RawSpan
|
||||
) throws {
|
||||
do {
|
||||
let context = try AEADContext(cipher: self, key: key)
|
||||
return try context.open(
|
||||
message: &message,
|
||||
nonce: nonce,
|
||||
tag: tag,
|
||||
authenticatedData: authenticatedData
|
||||
)
|
||||
} catch CryptoBoringWrapperError.underlyingCoreCryptoError(let errorCode) {
|
||||
throw CryptoKitError.underlyingCoreCryptoError(error: errorCode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
@@ -75,17 +130,16 @@ enum OpenSSLChaChaPolyImpl {
|
||||
}
|
||||
let nonce = nonce ?? ChaChaPoly.Nonce()
|
||||
|
||||
let ciphertext: Data
|
||||
let tag: Data
|
||||
let combined: Data
|
||||
if let ad = authenticatedData {
|
||||
(ciphertext, tag) = try BoringSSLAEAD.chacha20.seal(
|
||||
combined = try BoringSSLAEAD.chacha20.seal(
|
||||
message: message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
authenticatedData: ad
|
||||
)
|
||||
} else {
|
||||
(ciphertext, tag) = try BoringSSLAEAD.chacha20.seal(
|
||||
combined = try BoringSSLAEAD.chacha20.seal(
|
||||
message: message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
@@ -93,7 +147,40 @@ enum OpenSSLChaChaPolyImpl {
|
||||
)
|
||||
}
|
||||
|
||||
return try ChaChaPoly.SealedBox(nonce: nonce, ciphertext: ciphertext, tag: tag)
|
||||
return ChaChaPoly.SealedBox(combined: combined, nonceByteCount: nonce.count)
|
||||
}
|
||||
|
||||
#if compiler(<6.3)
|
||||
@_lifetime(message: copy message)
|
||||
#endif
|
||||
static func encrypt(
|
||||
key: SymmetricKey,
|
||||
inPlace message: inout MutableRawSpan,
|
||||
nonce: RawSpan,
|
||||
authenticatedData: RawSpan?,
|
||||
tag: inout OutputRawSpan
|
||||
) throws {
|
||||
guard key.bitCount == ChaChaPoly.keyBitsCount else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
if let ad = authenticatedData {
|
||||
try BoringSSLAEAD.chacha20.seal(
|
||||
message: &message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
authenticatedData: ad,
|
||||
tag: &tag
|
||||
)
|
||||
} else {
|
||||
try BoringSSLAEAD.chacha20.seal(
|
||||
message: &message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
authenticatedData: RawSpan(),
|
||||
tag: &tag
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
static func decrypt<AD: DataProtocol>(
|
||||
@@ -123,5 +210,39 @@ enum OpenSSLChaChaPolyImpl {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(<6.3)
|
||||
@_lifetime(message: copy message)
|
||||
#endif
|
||||
static func decrypt(
|
||||
key: SymmetricKey,
|
||||
inPlace message: inout MutableRawSpan,
|
||||
nonce: RawSpan,
|
||||
tag: RawSpan,
|
||||
authenticatedData: RawSpan?
|
||||
) throws {
|
||||
guard key.bitCount == ChaChaPoly.keyBitsCount else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
if let authenticatedData {
|
||||
try BoringSSLAEAD.chacha20.open(
|
||||
message: &message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
tag: tag,
|
||||
authenticatedData: authenticatedData
|
||||
)
|
||||
} else {
|
||||
try BoringSSLAEAD.chacha20.open(
|
||||
message: &message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
tag: tag,
|
||||
authenticatedData: RawSpan()
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,23 +11,22 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@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
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
/// 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 {
|
||||
@nonexhaustive
|
||||
public enum ChaChaPoly: Cipher, Sendable {
|
||||
static let tagByteCount = 16
|
||||
static let keyBitsCount = 256
|
||||
static let nonceByteCount = 12
|
||||
@@ -39,7 +38,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 +53,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>
|
||||
@@ -62,6 +61,28 @@ public enum ChaChaPoly: Cipher {
|
||||
return try ChaChaPolyImpl.encrypt(key: key, message: message, nonce: nonce, authenticatedData: Data?.none)
|
||||
}
|
||||
|
||||
/// Secures the given plaintext message in place with encryption and an
|
||||
/// authentication tag.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - message: The plaintext data to seal.
|
||||
/// - key: A cryptographic key used to seal the message.
|
||||
/// - nonce: The nonce the sealing process requires.
|
||||
/// - authenticatedData: Additional data to be authenticated.
|
||||
/// - tag: Will be updated with the 16-byte authentication tag.
|
||||
#if compiler(<6.3)
|
||||
@_lifetime(message: copy message)
|
||||
#endif
|
||||
public static func seal(
|
||||
inPlace message: inout MutableRawSpan,
|
||||
using key: SymmetricKey,
|
||||
nonce: Nonce,
|
||||
authenticating authenticatedData: RawSpan? = nil,
|
||||
tag: inout OutputRawSpan
|
||||
) throws(CryptoKitMetaError) {
|
||||
try ChaChaPolyImpl.encrypt(key: key, inPlace: &message, nonce: nonce.bytes, authenticatedData: authenticatedData, tag: &tag)
|
||||
}
|
||||
|
||||
/// Decrypts the message and verifies the authenticity of both the encrypted
|
||||
/// message and additional data.
|
||||
///
|
||||
@@ -91,9 +112,32 @@ public enum ChaChaPoly: Cipher {
|
||||
(_ sealedBox: SealedBox, using key: SymmetricKey) throws -> Data {
|
||||
return try ChaChaPolyImpl.decrypt(key: key, ciphertext: sealedBox, authenticatedData: Data?.none)
|
||||
}
|
||||
|
||||
/// Decrypts the message and verifies the authenticity of both the encrypted
|
||||
/// message and additional data.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - message: The message, which will be decrypted in place.
|
||||
/// - key: The cryptographic key that was used to seal the message.
|
||||
/// - nonce: The nonce used to encrypt the message.
|
||||
/// - tag : The 16-byte authentication tag.
|
||||
/// - authenticatedData: Additional data that was authenticated.
|
||||
///
|
||||
/// The call throws an error if decryption or authentication fail.
|
||||
#if compiler(<6.3)
|
||||
@_lifetime(message: copy message)
|
||||
#endif
|
||||
public static func open(
|
||||
inPlace message: inout MutableRawSpan,
|
||||
using key: SymmetricKey,
|
||||
nonce: Nonce,
|
||||
authenticating authenticatedData: RawSpan? = nil,
|
||||
tag: RawSpan
|
||||
) throws(CryptoKitMetaError) {
|
||||
try ChaChaPolyImpl.decrypt(key: key, inPlace: &message, nonce: nonce.bytes, tag: tag, authenticatedData: authenticatedData)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ChaChaPoly {
|
||||
/// A secure container for your data that you access using a cipher.
|
||||
///
|
||||
@@ -110,8 +154,7 @@ extension ChaChaPoly {
|
||||
/// The receiver uses another instance of the same cipher, like the
|
||||
/// ``open(_:using:)`` method, to open the box.
|
||||
@frozen
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SealedBox: AEADSealedBox {
|
||||
public struct SealedBox: AEADSealedBox, Sendable {
|
||||
/// A combined element composed of the tag, the nonce, and the
|
||||
/// ciphertext.
|
||||
///
|
||||
@@ -170,4 +213,4 @@ extension ChaChaPoly {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,13 +11,19 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
protocol AEADSealedBox {
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
|
||||
protocol AEADSealedBox: Sendable {
|
||||
associatedtype Nonce: Sequence
|
||||
/// The authentication tag
|
||||
var tag: Data { get }
|
||||
@@ -36,7 +42,6 @@ protocol AEADSealedBox {
|
||||
}
|
||||
|
||||
/// A type representing authenticated encryption with associated data.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
protocol Cipher {
|
||||
associatedtype Key
|
||||
associatedtype SealedBox: AEADSealedBox
|
||||
@@ -52,7 +57,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 +70,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
|
||||
@@ -11,54 +11,89 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
// MARK: - Generated file, do NOT edit
|
||||
// any edits of this file WILL be overwritten and thus discarded
|
||||
// see section `gyb` in `README` for details.
|
||||
|
||||
|
||||
|
||||
|
||||
// MARK: - AES.GCM + Nonce
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension AES.GCM {
|
||||
/// A value used once during a cryptographic operation and then discarded.
|
||||
///
|
||||
/// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical
|
||||
/// that nonces are unique per call to encryption APIs in order to protect the
|
||||
/// integrity of the encryption.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct Nonce: ContiguousBytes, Sequence {
|
||||
let bytes: Data
|
||||
public struct Nonce: ContiguousBytes, Sequence, Sendable {
|
||||
typealias Storage = ContiguousArray<UInt8>
|
||||
|
||||
let storage: Storage
|
||||
|
||||
/// Creates a new random nonce.
|
||||
///
|
||||
/// The default nonce is a 12-byte random nonce.
|
||||
public init() {
|
||||
var data = Data(repeating: 0, count: AES.GCM.defaultNonceByteCount)
|
||||
data.withUnsafeMutableBytes {
|
||||
assert($0.count == AES.GCM.defaultNonceByteCount)
|
||||
$0.initializeWithRandomBytes(count: AES.GCM.defaultNonceByteCount)
|
||||
}
|
||||
self.bytes = data
|
||||
self.storage = Self.randomNonceStorage
|
||||
}
|
||||
|
||||
|
||||
/// Creates a nonce from the given data.
|
||||
///
|
||||
/// Unless your use case calls for a nonce with a specific value, use the
|
||||
/// ``init()`` method to instead create a random nonce.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - data: A 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 {
|
||||
if data.count < AES.GCM.defaultNonceByteCount {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
/// - data: A data representation of the nonce.
|
||||
/// The initializer throws an error if the data has a length smaller than 12 bytes.
|
||||
internal init(data: RawSpan) throws(CryptoKitMetaError) {
|
||||
if data.byteCount < AES.GCM.defaultNonceByteCount {
|
||||
throw error(CryptoKitError.incorrectParameterSize)
|
||||
}
|
||||
|
||||
self.bytes = Data(data)
|
||||
self.storage = Storage(copying: data)
|
||||
}
|
||||
|
||||
|
||||
/// Creates a nonce from the given data.
|
||||
///
|
||||
/// Unless your use case calls for a nonce with a specific value, use the
|
||||
/// ``init()`` method to instead create a random nonce.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bytes: The bytes that represent the nonce.
|
||||
/// The initializer throws an error if the data has a length smaller than 12 bytes.
|
||||
public init(copying bytes: RawSpan) throws(CryptoKitMetaError) {
|
||||
if bytes.byteCount < AES.GCM.defaultNonceByteCount {
|
||||
throw error(CryptoKitError.incorrectParameterSize)
|
||||
}
|
||||
|
||||
self.storage = Storage(copying: bytes)
|
||||
}
|
||||
|
||||
/// Creates a nonce from the given data.
|
||||
///
|
||||
/// Unless your use case calls for a nonce with a specific value, use the
|
||||
/// ``init()`` method to instead create a random nonce.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - data: A data representation of the nonce.
|
||||
/// The initializer throws an error if the data has a length smaller than 12 bytes.
|
||||
public init<D: DataProtocol>(data: D) throws(CryptoKitMetaError) {
|
||||
if data.count < AES.GCM.defaultNonceByteCount {
|
||||
throw error(CryptoKitError.incorrectParameterSize)
|
||||
}
|
||||
|
||||
self.storage = Storage(data)
|
||||
}
|
||||
|
||||
/// Calls the given closure with a pointer to the underlying bytes of the array’s
|
||||
/// contiguous storage.
|
||||
///
|
||||
@@ -70,59 +105,119 @@ 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
|
||||
|
||||
/// The bytes stored in the nonce.
|
||||
public var bytes: RawSpan {
|
||||
get {
|
||||
storage.span.bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of bytes stored in the nonce.
|
||||
public var count: Int { storage.count }
|
||||
|
||||
/// Returns an iterator over the elements of the nonce.
|
||||
public func makeIterator() -> Array<UInt8>.Iterator {
|
||||
self.withUnsafeBytes({ (buffPtr) in
|
||||
return Array(buffPtr).makeIterator()
|
||||
})
|
||||
}
|
||||
|
||||
/// Storage for a new, random nonce.
|
||||
static var randomNonceStorage: Storage {
|
||||
var data = Storage(repeating: 0, count: AES.GCM.defaultNonceByteCount)
|
||||
assert(data.count == AES.GCM.defaultNonceByteCount)
|
||||
|
||||
var mutableSpan = data.mutableSpan
|
||||
var mutableBytes = mutableSpan.mutableBytes
|
||||
initializeRandomNonce(into: &mutableBytes)
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
/// Initialize the given mutable span with random bytes.
|
||||
static func initializeRandomNonce(into data: inout MutableRawSpan) {
|
||||
data.initializeWithRandomBytes(count: data.byteCount)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ChaChaPoly + Nonce
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ChaChaPoly {
|
||||
/// A value used once during a cryptographic operation and then discarded.
|
||||
///
|
||||
/// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical
|
||||
/// that nonces are unique per call to encryption APIs in order to protect the
|
||||
/// integrity of the encryption.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct Nonce: ContiguousBytes, Sequence {
|
||||
let bytes: Data
|
||||
public struct Nonce: ContiguousBytes, Sequence, Sendable {
|
||||
typealias Storage = [12 of UInt8]
|
||||
|
||||
let storage: Storage
|
||||
|
||||
/// Creates a new random nonce.
|
||||
///
|
||||
/// The default nonce is a 12-byte random nonce.
|
||||
public init() {
|
||||
var data = Data(repeating: 0, count: ChaChaPoly.nonceByteCount)
|
||||
data.withUnsafeMutableBytes {
|
||||
assert($0.count == ChaChaPoly.nonceByteCount)
|
||||
$0.initializeWithRandomBytes(count: ChaChaPoly.nonceByteCount)
|
||||
}
|
||||
self.bytes = data
|
||||
self.storage = Self.randomNonceStorage
|
||||
}
|
||||
|
||||
|
||||
/// Creates a nonce from the given data.
|
||||
///
|
||||
/// Unless your use case calls for a nonce with a specific value, use the
|
||||
/// ``init()`` method to instead create a random nonce.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - data: A 12-byte data representation of the nonce. The initializer throws an
|
||||
/// error if the data has a length other than 12 bytes.
|
||||
public init<D: DataProtocol>(data: D) throws {
|
||||
if data.count != ChaChaPoly.nonceByteCount {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
/// - data: A 12-byte data representation of the nonce.
|
||||
/// The initializer throws an error if the data isn't 12 bytes long.
|
||||
internal init(data: RawSpan) throws(CryptoKitMetaError) {
|
||||
if data.byteCount != ChaChaPoly.nonceByteCount {
|
||||
throw error(CryptoKitError.incorrectParameterSize)
|
||||
}
|
||||
|
||||
self.bytes = Data(data)
|
||||
self.storage = Storage(copying: data)
|
||||
}
|
||||
|
||||
|
||||
/// Creates a nonce from the given data.
|
||||
///
|
||||
/// Unless your use case calls for a nonce with a specific value, use the
|
||||
/// ``init()`` method to instead create a random nonce.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bytes: The bytes that represent the nonce.
|
||||
/// The initializer throws an error if the data isn't 12 bytes long.
|
||||
public init(copying bytes: RawSpan) throws(CryptoKitMetaError) {
|
||||
if bytes.byteCount != ChaChaPoly.nonceByteCount {
|
||||
throw error(CryptoKitError.incorrectParameterSize)
|
||||
}
|
||||
|
||||
self.storage = Storage(copying: bytes)
|
||||
}
|
||||
|
||||
/// Creates a nonce from the given data.
|
||||
///
|
||||
/// Unless your use case calls for a nonce with a specific value, use the
|
||||
/// ``init()`` method to instead create a random nonce.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - data: A 12-byte data representation of the nonce.
|
||||
/// The initializer throws an error if the data isn't 12 bytes long.
|
||||
public init<D: DataProtocol>(data: D) throws(CryptoKitMetaError) {
|
||||
if data.count != ChaChaPoly.nonceByteCount {
|
||||
throw error(CryptoKitError.incorrectParameterSize)
|
||||
}
|
||||
|
||||
self.storage = Storage(copying: data)
|
||||
}
|
||||
|
||||
/// Calls the given closure with a pointer to the underlying bytes of the array’s
|
||||
/// contiguous storage.
|
||||
///
|
||||
@@ -134,16 +229,48 @@ 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
|
||||
|
||||
/// The bytes stored in the nonce.
|
||||
public var bytes: RawSpan {
|
||||
get {
|
||||
storage.span.bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of bytes stored in the nonce.
|
||||
public var count: Int { storage.count }
|
||||
|
||||
/// Returns an iterator over the elements of the nonce.
|
||||
public func makeIterator() -> Array<UInt8>.Iterator {
|
||||
self.withUnsafeBytes({ (buffPtr) in
|
||||
return Array(buffPtr).makeIterator()
|
||||
})
|
||||
}
|
||||
|
||||
/// Storage for a new, random nonce.
|
||||
static var randomNonceStorage: Storage {
|
||||
var data = Storage(repeating: 0)
|
||||
|
||||
var mutableSpan = data.mutableSpan
|
||||
var mutableBytes = mutableSpan.mutableBytes
|
||||
initializeRandomNonce(into: &mutableBytes)
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
/// Initialize the given mutable span with random bytes.
|
||||
static func initializeRandomNonce(into data: inout MutableRawSpan) {
|
||||
data.initializeWithRandomBytes(count: data.byteCount)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -1,93 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
// 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"}]
|
||||
}%
|
||||
% for cipher in ciphers:
|
||||
%{
|
||||
name = cipher["name"]
|
||||
nonceSize = cipher["recommendedNonceSize"]
|
||||
nonceValidation = cipher["nonceValidation"]
|
||||
}%
|
||||
|
||||
// MARK: - ${name} + Nonce
|
||||
extension ${name} {
|
||||
/// A value used once during a cryptographic operation and then discarded.
|
||||
///
|
||||
/// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical
|
||||
/// that nonces are unique per call to encryption APIs in order to protect the
|
||||
/// integrity of the encryption.
|
||||
public struct Nonce: ContiguousBytes, Sequence {
|
||||
let bytes: Data
|
||||
|
||||
/// Creates a new random nonce.
|
||||
///
|
||||
/// The default nonce is a 12-byte random nonce.
|
||||
public init() {
|
||||
var data = Data(repeating: 0, count: ${nonceSize})
|
||||
data.withUnsafeMutableBytes {
|
||||
assert($0.count == ${nonceSize})
|
||||
$0.initializeWithRandomBytes(count: ${nonceSize})
|
||||
}
|
||||
self.bytes = data
|
||||
}
|
||||
|
||||
/// Creates a nonce from the given data.
|
||||
///
|
||||
/// Unless your use case calls for a nonce with a specific value, use the
|
||||
/// ``init()`` method to instead create a random nonce.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - 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 {
|
||||
if data.count ${nonceValidation} {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
self.bytes = Data(data)
|
||||
}
|
||||
|
||||
/// Calls the given closure with a pointer to the underlying bytes of the array’s
|
||||
/// contiguous storage.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: A closure with an `UnsafeRawBufferPointer` parameter that points to the
|
||||
/// contiguous storage for the array. The system creates the storage if it doesn’t
|
||||
/// exist. If body has a return value, that value is also used as the return value
|
||||
/// for the ``withUnsafeBytes(_:)`` method. The argument is valid only for
|
||||
/// the duration of the closure’s execution.
|
||||
///
|
||||
/// - Returns: The return value, if any, of the body closure parameter.
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
|
||||
/// Returns an iterator over the elements of the nonce.
|
||||
public func makeIterator() -> Array<UInt8>.Iterator {
|
||||
self.withUnsafeBytes({ (buffPtr) in
|
||||
return Array(buffPtr).makeIterator()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
% end
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -11,10 +11,16 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
// This module implements "just enough" ASN.1. Specifically, we implement exactly enough ASN.1 DER parsing to handle
|
||||
// the following use-cases:
|
||||
@@ -103,18 +109,15 @@ import Foundation
|
||||
// generally: that is, we don't hard-code special knowledge of these formats as part of the parsing process. Instead we have written a
|
||||
// parser that can divide the world of ASN.1 into parseable chunks, and then we try to decode specific formats from those chunks. This
|
||||
// allows us to extend things in the future without too much pain.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal enum ASN1 { }
|
||||
|
||||
// MARK: - Parser Node
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
/// An `ASN1ParserNode` is a representation of a parsed ASN.1 TLV section. An `ASN1ParserNode` may be primitive, or may be composed of other `ASN1ParserNode`s.
|
||||
/// In our representation, we keep track of this by storing a node "depth", which allows rapid forward and backward scans to hop over sections
|
||||
/// we're uninterested in.
|
||||
///
|
||||
/// This type is not exposed to users of the API: it is only used internally for implementation of the user-level API.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
fileprivate struct ASN1ParserNode {
|
||||
/// The identifier.
|
||||
var identifier: ASN1Identifier
|
||||
@@ -127,23 +130,22 @@ extension ASN1 {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1ParserNode: Hashable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if !hasFeature(Embedded)
|
||||
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,43 +153,47 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Optional explicitly tagged
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
/// Parses an optional explicitly tagged element. Throws on a tag mismatch, returns nil if the element simply isn't there.
|
||||
///
|
||||
/// 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 +218,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)
|
||||
@@ -220,13 +226,12 @@ extension ASN1 {
|
||||
}
|
||||
|
||||
// MARK: - DEFAULT
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
/// Parses a value that is encoded with a DEFAULT. Such a value is optional, and if absent will
|
||||
/// be replaced with its default.
|
||||
///
|
||||
/// 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 +252,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
|
||||
@@ -269,10 +274,8 @@ extension ASN1 {
|
||||
}
|
||||
|
||||
// MARK: - Parsing
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
/// A parsed representation of ASN.1.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
fileprivate struct ASN1ParseResult {
|
||||
private static let maximumNodeDepth = 10
|
||||
|
||||
@@ -282,46 +285,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 {
|
||||
@@ -336,16 +339,14 @@ extension ASN1 {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1ParseResult: Hashable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
static func parse(_ data: [UInt8]) throws -> 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.
|
||||
@@ -368,13 +369,11 @@ extension ASN1 {
|
||||
}
|
||||
|
||||
// MARK: - ASN1NodeCollection
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
/// Represents a collection of ASN.1 nodes contained in a constructed ASN.1 node.
|
||||
///
|
||||
/// Constructed ASN.1 nodes are made up of multiple child nodes. This object represents the collection of those child nodes.
|
||||
/// It allows us to lazily construct the child nodes, potentially skipping over them when we don't care about them.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal struct ASN1NodeCollection {
|
||||
private var nodes: ArraySlice<ASN1ParserNode>
|
||||
|
||||
@@ -392,9 +391,7 @@ extension ASN1 {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1NodeCollection: Sequence {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct Iterator: IteratorProtocol {
|
||||
private var nodes: ArraySlice<ASN1.ASN1ParserNode>
|
||||
private var depth: Int
|
||||
@@ -428,7 +425,6 @@ extension ASN1.ASN1NodeCollection: Sequence {
|
||||
}
|
||||
|
||||
// MARK: - ASN1Node
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
/// An `ASN1Node` is a single entry in the ASN.1 representation of a data structure.
|
||||
///
|
||||
@@ -438,7 +434,6 @@ extension ASN1 {
|
||||
///
|
||||
/// In this way, ASN.1 objects tend to form a "tree", where each object is represented by a single top-level constructed
|
||||
/// node that contains other objects and primitives, eventually reaching the bottom which is made up of primitive objects.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal struct ASN1Node {
|
||||
internal var identifier: ASN1Identifier
|
||||
|
||||
@@ -447,10 +442,8 @@ extension ASN1 {
|
||||
}
|
||||
|
||||
// MARK: - ASN1Node.Content
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1Node {
|
||||
/// The content of a single ASN1Node.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
enum Content {
|
||||
case constructed(ASN1.ASN1NodeCollection)
|
||||
case primitive(ArraySlice<UInt8>)
|
||||
@@ -458,9 +451,7 @@ extension ASN1.ASN1Node {
|
||||
}
|
||||
|
||||
// MARK: - Serializing
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct Serializer {
|
||||
var serializedBytes: [UInt8]
|
||||
|
||||
@@ -471,48 +462,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 +515,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,
|
||||
@@ -568,78 +561,72 @@ 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!
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal protocol ASN1ImplicitlyTaggable: ASN1Parseable, ASN1Serializable {
|
||||
/// The tag that the first node will use "by default" if the grammar omits
|
||||
/// any more specific tag definition.
|
||||
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 +634,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 +653,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
|
||||
@@ -686,11 +673,10 @@ 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
|
||||
@@ -704,7 +690,6 @@ extension FixedWidthInteger {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Array where Element == UInt8 {
|
||||
fileprivate mutating func writeIdentifier(_ identifier: ASN1.ASN1Identifier) {
|
||||
self.append(identifier.baseTag)
|
||||
@@ -730,7 +715,6 @@ extension Array where Element == UInt8 {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Int {
|
||||
fileprivate var bytesNeededToEncode: Int {
|
||||
// ASN.1 lengths are in two forms. If we can store the length in 7 bits, we should:
|
||||
@@ -748,7 +732,6 @@ extension Int {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension FixedWidthInteger {
|
||||
// Bytes needed to store a given integer.
|
||||
internal var neededBytes: Int {
|
||||
@@ -757,4 +740,4 @@ extension FixedWidthInteger {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,12 +11,17 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
extension ASN1 {
|
||||
/// An ASN1 ANY represents...well, anything.
|
||||
///
|
||||
@@ -25,50 +30,47 @@ extension ASN1 {
|
||||
///
|
||||
/// The only things we allow users to do with ASN.1 ANYs is to try to decode them as something else,
|
||||
/// to create them from something else, or to serialize them.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct ASN1Any: ASN1Parseable, ASN1Serializable, Hashable {
|
||||
fileprivate var serializedBytes: ArraySlice<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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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)
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,15 +11,19 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
extension ASN1 {
|
||||
/// A bitstring is a representation of...well...some bits.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct ASN1BitString: ASN1ImplicitlyTaggable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.primitiveBitString
|
||||
@@ -27,9 +31,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 +43,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 +53,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)
|
||||
}
|
||||
@@ -58,14 +62,18 @@ extension ASN1 {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1BitString: Hashable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1BitString: ContiguousBytes {
|
||||
#if hasFeature(Embedded)
|
||||
func withUnsafeBytes<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
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,24 +11,29 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
extension Bool: ASN1ImplicitlyTaggable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.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 +45,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 {
|
||||
@@ -55,4 +60,4 @@ extension Bool: ASN1ImplicitlyTaggable {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,16 +11,20 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
extension ASN1 {
|
||||
/// An `ASN1Identifier` is a representation of the abstract notion of an ASN.1 identifier. Identifiers have a number of properties that relate to both the specific
|
||||
/// tag number as well as the properties of the identifier in the stream.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal struct ASN1Identifier {
|
||||
/// The base tag. In a general ASN.1 implementation we'd need an arbitrary precision integer here as the tag number can be arbitrarily large, but
|
||||
/// we don't need the full generality here.
|
||||
@@ -59,10 +63,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
|
||||
@@ -113,7 +117,6 @@ extension ASN1 {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1Identifier {
|
||||
internal static let objectIdentifier = try! ASN1.ASN1Identifier(rawIdentifier: 0x06)
|
||||
internal static let primitiveBitString = try! ASN1.ASN1Identifier(rawIdentifier: 0x03)
|
||||
@@ -138,14 +141,14 @@ extension ASN1.ASN1Identifier {
|
||||
internal static let generalizedTime = try! ASN1.ASN1Identifier(rawIdentifier: 0x18)
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1Identifier: Hashable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if !hasFeature(Embedded)
|
||||
extension ASN1.ASN1Identifier: CustomStringConvertible {
|
||||
var description: String {
|
||||
return "ASN1Identifier(\(self.baseTag))"
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,18 +11,23 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
/// A protocol that represents any internal object that can present itself as an INTEGER, or be parsed from
|
||||
/// an INTEGER.
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#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
|
||||
/// protocol exists today.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
protocol ASN1IntegerRepresentable: ASN1ImplicitlyTaggable {
|
||||
associatedtype IntegerBytes: RandomAccessCollection where IntegerBytes.Element == UInt8
|
||||
|
||||
@@ -30,20 +35,19 @@ 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, *)
|
||||
extension ASN1IntegerRepresentable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.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 +56,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 +68,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 +78,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)
|
||||
@@ -104,9 +108,8 @@ 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,12 +123,11 @@ 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))
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct IntegerBytesCollection<Integer: FixedWidthInteger> {
|
||||
private var integer: Integer
|
||||
|
||||
@@ -134,9 +136,7 @@ struct IntegerBytesCollection<Integer: FixedWidthInteger> {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension IntegerBytesCollection: RandomAccessCollection {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct Index {
|
||||
fileprivate var byteNumber: Int
|
||||
|
||||
@@ -170,10 +170,8 @@ extension IntegerBytesCollection: RandomAccessCollection {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension IntegerBytesCollection.Index: Equatable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension IntegerBytesCollection.Index: Comparable {
|
||||
// Comparable here is backwards to the original ordering.
|
||||
static func <(lhs: Self, rhs: Self) -> Bool {
|
||||
@@ -193,7 +191,6 @@ extension IntegerBytesCollection.Index: Comparable {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension IntegerBytesCollection.Index: Strideable {
|
||||
func advanced(by n: Int) -> IntegerBytesCollection<Integer>.Index {
|
||||
return IntegerBytesCollection.Index(byteNumber: self.byteNumber - n)
|
||||
@@ -225,7 +222,6 @@ extension Int: ASN1IntegerRepresentable { }
|
||||
|
||||
extension UInt: ASN1IntegerRepresentable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension RandomAccessCollection where Element == UInt8 {
|
||||
fileprivate func trimLeadingExcessBytes() -> SubSequence {
|
||||
var slice = self[...]
|
||||
@@ -273,11 +269,10 @@ extension RandomAccessCollection where Element == UInt8 {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension UInt8 {
|
||||
fileprivate var topBitSet: Bool {
|
||||
return (self & 0x80) != 0
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,15 +11,19 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
extension ASN1 {
|
||||
/// An ASN1 NULL represents nothing.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct ASN1Null: ASN1ImplicitlyTaggable, Hashable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.null
|
||||
@@ -27,20 +31,20 @@ 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 })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,15 +11,19 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
extension ASN1 {
|
||||
/// An octet string is a representation of a string of octets.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct ASN1OctetString: ASN1ImplicitlyTaggable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.primitiveOctetString
|
||||
@@ -27,9 +31,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,22 +47,26 @@ 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1OctetString: Hashable { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1OctetString: ContiguousBytes {
|
||||
#if hasFeature(Embedded)
|
||||
func withUnsafeBytes<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
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,24 +11,43 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 +55,42 @@ 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 +98,42 @@ 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 +141,42 @@ 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 +184,42 @@ 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 +227,64 @@ 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
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#if !hasFeature(Embedded)
|
||||
extension ASN1.ASN1TeletexString: ExpressibleByStringLiteral {
|
||||
public init(stringLiteral value: StringLiteralType) {
|
||||
self.bytes = ArraySlice(value.utf8)
|
||||
}
|
||||
}
|
||||
|
||||
extension ASN1.ASN1UTF8String: ExpressibleByStringLiteral {
|
||||
public init(stringLiteral value: StringLiteralType) {
|
||||
self.bytes = ArraySlice(value.utf8)
|
||||
}
|
||||
}
|
||||
|
||||
extension ASN1.ASN1PrintableString: ExpressibleByStringLiteral {
|
||||
public init(stringLiteral value: StringLiteralType) {
|
||||
self.bytes = ArraySlice(value.utf8)
|
||||
}
|
||||
}
|
||||
|
||||
extension ASN1.ASN1UniversalString: ExpressibleByStringLiteral {
|
||||
public init(stringLiteral value: StringLiteralType) {
|
||||
self.bytes = ArraySlice(value.utf8)
|
||||
}
|
||||
}
|
||||
|
||||
extension ASN1.ASN1BMPString: ExpressibleByStringLiteral {
|
||||
public init(stringLiteral value: StringLiteralType) {
|
||||
self.bytes = ArraySlice(value.utf8)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,10 +11,17 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
// For temporary purposes we pretend that ArraySlice is our "bigint" type. We don't really need anything else.
|
||||
extension ArraySlice: ASN1Serializable where Element == UInt8 { }
|
||||
|
||||
@@ -22,20 +29,19 @@ extension ArraySlice: ASN1Parseable where Element == UInt8 { }
|
||||
|
||||
extension ArraySlice: ASN1ImplicitlyTaggable where Element == UInt8 { }
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 {
|
||||
// We only use unsigned "bigint"s
|
||||
static var isSigned: Bool {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,14 +11,18 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
extension ASN1 {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct GeneralizedTime: ASN1ImplicitlyTaggable, Hashable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.generalizedTime
|
||||
@@ -102,7 +106,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 +118,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 +130,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,20 +164,19 @@ 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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 +184,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 +193,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,
|
||||
@@ -254,7 +257,6 @@ extension ASN1.GeneralizedTime {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ArraySlice where Element == UInt8 {
|
||||
fileprivate mutating func readFourDigitDecimalInteger() -> Int? {
|
||||
guard let first = self.readTwoDigitDecimalInteger(),
|
||||
@@ -284,8 +286,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 +306,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,14 +315,13 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Array where Element == UInt8 {
|
||||
fileprivate mutating func append(_ generalizedTime: ASN1.GeneralizedTime) {
|
||||
self.appendFourDigitDecimal(generalizedTime.year)
|
||||
@@ -332,26 +333,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,16 +387,15 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
@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.
|
||||
@@ -387,4 +409,4 @@ extension Int {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,19 +11,23 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
extension ASN1 {
|
||||
/// An Object Identifier is a representation of some kind of object: really any kind of object.
|
||||
///
|
||||
/// It represents a node in an OID hierarchy, and is usually represented as an ordered sequence of numbers.
|
||||
///
|
||||
/// We mostly don't care about the semantics of the thing, we just care about being able to store and compare them.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct ASN1ObjectIdentifier: ASN1ImplicitlyTaggable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.objectIdentifier
|
||||
@@ -31,9 +35,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 +71,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 +96,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!")
|
||||
@@ -133,19 +137,15 @@ extension ASN1 {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1ObjectIdentifier: Hashable {}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1ObjectIdentifier: ExpressibleByArrayLiteral {
|
||||
init(arrayLiteral elements: UInt...) {
|
||||
self.oidComponents = elements
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.ASN1ObjectIdentifier {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
enum NamedCurves {
|
||||
static let secp256r1: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10_045, 3, 1, 7]
|
||||
|
||||
@@ -154,19 +154,16 @@ extension ASN1.ASN1ObjectIdentifier {
|
||||
static let secp521r1: ASN1.ASN1ObjectIdentifier = [1, 3, 132, 0, 35]
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
enum HashFunctions {
|
||||
static let sha256: ASN1.ASN1ObjectIdentifier = [2, 16, 840, 1, 101, 3, 4, 2, 1]
|
||||
static let sha384: ASN1.ASN1ObjectIdentifier = [2, 16, 840, 1, 101, 3, 4, 2, 2]
|
||||
static let sha512: ASN1.ASN1ObjectIdentifier = [2, 16, 840, 1, 101, 3, 4, 2, 3]
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
enum AlgorithmIdentifier {
|
||||
static let idEcPublicKey: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10_045, 2, 1]
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
enum NameAttributes {
|
||||
static let name: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 41]
|
||||
static let surname: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 4]
|
||||
@@ -189,13 +186,12 @@ 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]
|
||||
@@ -206,12 +202,11 @@ 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
|
||||
@@ -225,4 +220,4 @@ extension UInt {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,12 +11,17 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
extension ASN1 {
|
||||
/// An ECDSA signature is laid out as follows:
|
||||
///
|
||||
@@ -26,7 +31,6 @@ extension ASN1 {
|
||||
/// }
|
||||
///
|
||||
/// This type is generic because our different backends want to use different bignum representations.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct ECDSASignature<IntegerType: ASN1IntegerRepresentable>: ASN1ImplicitlyTaggable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
@@ -40,8 +44,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 +53,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)
|
||||
}
|
||||
@@ -58,4 +62,4 @@ extension ASN1 {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,15 +11,19 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
extension ASN1 {
|
||||
/// A PEM document is some data, and a discriminator type that is used to advertise the content.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct PEMDocument {
|
||||
private static let lineLength = 64
|
||||
|
||||
@@ -88,7 +92,6 @@ extension ASN1 {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Substring {
|
||||
fileprivate var pemStartDiscriminator: String? {
|
||||
return self.pemDiscriminator(expectedPrefix: "-----BEGIN ", expectedSuffix: "-----")
|
||||
@@ -118,4 +121,4 @@ extension Substring {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,12 +11,16 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1 {
|
||||
// A PKCS#8 private key is one of two formats, depending on the version:
|
||||
//
|
||||
@@ -40,7 +44,6 @@ extension ASN1 {
|
||||
//
|
||||
// The private key octet string contains (surprise!) a SEC1-encoded private key! So we recursively invoke the
|
||||
// ASN.1 parser and go again.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct PKCS8PrivateKey: ASN1ImplicitlyTaggable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
return .sequence
|
||||
@@ -50,11 +53,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 +69,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 +89,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)
|
||||
|
||||
@@ -102,4 +105,4 @@ extension ASN1 {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,12 +11,17 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
extension ASN1 {
|
||||
// For private keys, SEC 1 uses:
|
||||
//
|
||||
@@ -26,7 +31,6 @@ extension ASN1 {
|
||||
// parameters [0] EXPLICIT ECDomainParameters OPTIONAL,
|
||||
// publicKey [1] EXPLICIT BIT STRING OPTIONAL
|
||||
// }
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct SEC1PrivateKey: ASN1ImplicitlyTaggable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
return .sequence
|
||||
@@ -38,18 +42,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 +61,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 +73,7 @@ extension ASN1 {
|
||||
case ASN1ObjectIdentifier.NamedCurves.secp521r1:
|
||||
return .ecdsaP521
|
||||
default:
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
throw error(CryptoKitASN1Error.invalidASN1Object)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,8 +84,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 +99,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)
|
||||
@@ -109,4 +113,4 @@ extension ASN1 {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,14 +11,18 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
extension ASN1 {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct SubjectPublicKeyInfo: ASN1ImplicitlyTaggable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
@@ -28,14 +32,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,15 +57,14 @@ 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct RFC5480AlgorithmIdentifier: ASN1ImplicitlyTaggable, Hashable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
@@ -76,7 +79,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 +94,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)
|
||||
@@ -112,7 +115,6 @@ extension ASN1 {
|
||||
}
|
||||
|
||||
// MARK: Algorithm Identifier Statics
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension ASN1.RFC5480AlgorithmIdentifier {
|
||||
static let ecdsaP256 = ASN1.RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey,
|
||||
parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp256r1))
|
||||
@@ -124,4 +126,4 @@ extension ASN1.RFC5480AlgorithmIdentifier {
|
||||
parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp521r1))
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -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,13 +91,22 @@ 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/ArraySpanHelpers.swift"
|
||||
"Util/Backports.swift"
|
||||
"Util/BoringSSL/CryptoKitErrors_boring.swift"
|
||||
"Util/BoringSSL/InlineArray+withBytes_boring.swift"
|
||||
"Util/BoringSSL/Optional+withUnsafeBytes_boring.swift"
|
||||
"Util/BoringSSL/RNG_boring.swift"
|
||||
"Util/BoringSSL/SafeCompare_boring.swift"
|
||||
"Util/BoringSSL/Zeroization_boring.swift"
|
||||
"Util/BoringSSL/_CryptoModuleAnchor.swift"
|
||||
"Util/Data+ArraySpan.swift"
|
||||
"Util/PrettyBytes.swift"
|
||||
"Util/SafeCompare.swift"
|
||||
"Util/SecureBytes.swift"
|
||||
@@ -98,21 +116,18 @@ add_library(Crypto
|
||||
target_compile_definitions(Crypto PRIVATE
|
||||
"$<$<COMPILE_LANGUAGE:Swift>:CRYPTO_IN_SWIFTPM>")
|
||||
|
||||
if(NOT CMAKE_SYSTEM_NAME STREQUAL "Darwin")
|
||||
target_compile_definitions(Crypto PRIVATE
|
||||
"$<$<COMPILE_LANGUAGE:Swift>:CRYPTO_IN_SWIFTPM_FORCE_BUILD_API>")
|
||||
endif()
|
||||
|
||||
target_include_directories(Crypto PRIVATE
|
||||
$<TARGET_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})
|
||||
|
||||
@@ -11,11 +11,12 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
/// General cryptography errors used by CryptoKit.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
@nonexhaustive
|
||||
public enum CryptoKitError: Error {
|
||||
/// The key size is incorrect.
|
||||
case incorrectKeySize
|
||||
@@ -34,11 +35,10 @@ public enum CryptoKitError: Error {
|
||||
case invalidParameter
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension CryptoKitError: Equatable, Hashable {}
|
||||
|
||||
/// Errors from decoding ASN.1 content.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
@nonexhaustive
|
||||
public enum CryptoKitASN1Error: Equatable, Error, Hashable {
|
||||
/// The ASN.1 tag for this field is invalid or unsupported.
|
||||
case invalidFieldIdentifier
|
||||
@@ -66,4 +66,49 @@ public enum CryptoKitASN1Error: Equatable, Error, Hashable {
|
||||
/// The string doesn’t parse as a PEM document.
|
||||
case invalidPEMDocument
|
||||
}
|
||||
|
||||
enum RSAPSSSPKIErrors: Error {
|
||||
case invalidPSSOID
|
||||
case missingParameters
|
||||
case incorrectHashFunction
|
||||
case incorrectMGF
|
||||
case missingMGFHashFunction
|
||||
case incorrectMGFHashFunction
|
||||
case invalidSaltLength
|
||||
}
|
||||
|
||||
#if hasFeature(Embedded)
|
||||
public struct RSAPSSSPKIError: Error {
|
||||
internal var error: RSAPSSSPKIErrors
|
||||
}
|
||||
#else
|
||||
struct RSAPSSSPKIError: Error {
|
||||
internal var error: RSAPSSSPKIErrors
|
||||
}
|
||||
#endif
|
||||
|
||||
#if hasFeature(Embedded)
|
||||
@nonexhaustive
|
||||
public enum CryptoKitMetaError: Error {
|
||||
case cryptoKitError(underlyingError: CryptoKitError)
|
||||
case asn1Error(underlyingError: CryptoKitASN1Error)
|
||||
case rsapssspkiError(underlyingError: RSAPSSSPKIError)
|
||||
}
|
||||
|
||||
internal func error(_ error: CryptoKitError) -> CryptoKitMetaError {
|
||||
.cryptoKitError(underlyingError: error)
|
||||
}
|
||||
internal func error(_ error: CryptoKitASN1Error) -> CryptoKitMetaError {
|
||||
.asn1Error(underlyingError: error)
|
||||
}
|
||||
internal func error(_ error: RSAPSSSPKIErrors) -> CryptoKitMetaError {
|
||||
.rsapssspkiError(underlyingError: RSAPSSSPKIError(error: error))
|
||||
}
|
||||
#else
|
||||
public typealias CryptoKitMetaError = any Error
|
||||
internal func error(_ error: CryptoKitError) -> CryptoKitError { error }
|
||||
internal func error(_ error: CryptoKitASN1Error) -> CryptoKitASN1Error { error }
|
||||
internal func error(_ error: RSAPSSSPKIErrors) -> RSAPSSSPKIErrors { error }
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -11,10 +11,14 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
protocol HashFunctionImplementationDetails: HashFunction where Digest: DigestPrivate {}
|
||||
@@ -47,7 +51,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 +75,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 +99,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 +123,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 +147,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() {
|
||||
@@ -168,10 +177,10 @@ private final class DigestContext<H: BoringSSLBackedHashFunction> {
|
||||
private var context: H.Context
|
||||
|
||||
init() {
|
||||
guard let contex = H.initialize() else {
|
||||
guard let context = H.initialize() else {
|
||||
preconditionFailure("Unable to initialize digest state")
|
||||
}
|
||||
self.context = contex
|
||||
self.context = context
|
||||
}
|
||||
|
||||
init(copying original: DigestContext) {
|
||||
@@ -197,7 +206,7 @@ private final class DigestContext<H: BoringSSLBackedHashFunction> {
|
||||
preconditionFailure("Unable to finalize digest state")
|
||||
}
|
||||
// We force unwrap here because if the digest size is wrong it's an internal error.
|
||||
return H.Digest(bufferPointer: UnsafeRawBufferPointer(digestPointer))!
|
||||
return H.Digest(copying: digestPointer.bytes)!
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,4 +214,4 @@ private final class DigestContext<H: BoringSSLBackedHashFunction> {
|
||||
withUnsafeMutablePointer(to: &self.context) { $0.zeroize() }
|
||||
}
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,40 +11,46 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
|
||||
#if hasFeature(Embedded)
|
||||
/// A type that represents the output of a hash.
|
||||
@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 {
|
||||
@preconcurrency
|
||||
public protocol Digest: Hashable, Sendable, ContiguousBytes, Sequence where Element == UInt8 {
|
||||
/// The number of bytes in the digest.
|
||||
static var byteCount: Int { get }
|
||||
}
|
||||
#else
|
||||
/// A type that represents the output of a hash.
|
||||
@preconcurrency
|
||||
public protocol Digest: Hashable, Sendable, ContiguousBytes, CustomStringConvertible, Sequence where Element == UInt8 {
|
||||
/// The number of bytes in the digest.
|
||||
static var byteCount: Int { get }
|
||||
}
|
||||
#endif // hasFeature(Embedded)
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
protocol DigestPrivate: Digest {
|
||||
init?(bufferPointer: UnsafeRawBufferPointer)
|
||||
init?(initializingWith body: (inout OutputRawSpan) -> ())
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension DigestPrivate {
|
||||
@inlinable
|
||||
init?(bytes: [UInt8]) {
|
||||
let some = bytes.withUnsafeBytes { bufferPointer in
|
||||
return Self(bufferPointer: bufferPointer)
|
||||
}
|
||||
|
||||
if some != nil {
|
||||
self = some!
|
||||
} else {
|
||||
return nil
|
||||
init?(copying bytes: RawSpan) {
|
||||
self.init() {
|
||||
$0.append(contentsOf: bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Digest {
|
||||
public func makeIterator() -> Array<UInt8>.Iterator {
|
||||
self.withUnsafeBytes({ (buffPtr) in
|
||||
@@ -54,7 +60,6 @@ extension Digest {
|
||||
}
|
||||
|
||||
// We want to implement constant-time comparison for digests.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Digest {
|
||||
/// Determines whether two digests are equal.
|
||||
///
|
||||
@@ -84,9 +89,14 @@ extension Digest {
|
||||
return safeCompare(lhs, rhs.regions.first!)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
extension Digest {
|
||||
public var description: String {
|
||||
return "\(Self.self): \(Array(self).hexString)"
|
||||
}
|
||||
}
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif
|
||||
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,27 +11,30 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
// MARK: - Generated file, do NOT edit
|
||||
// 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, *)
|
||||
public struct SHA256Digest: DigestPrivate {
|
||||
let bytes: (UInt64, UInt64, UInt64, UInt64)
|
||||
|
||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
||||
guard bufferPointer.count == 32 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
|
||||
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||
targetPtr.copyMemory(from: bufferPointer)
|
||||
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
|
||||
body(&output)
|
||||
return output.finalize(for: targetPtr)
|
||||
}
|
||||
guard initialized == 32 else {
|
||||
return nil
|
||||
}
|
||||
self.bytes = bytes
|
||||
}
|
||||
@@ -49,6 +52,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 +60,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 +76,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.
|
||||
///
|
||||
@@ -91,18 +106,18 @@ public struct SHA256Digest: DigestPrivate {
|
||||
|
||||
// MARK: - SHA384Digest + DigestPrivate
|
||||
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 384-bit digest.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA384Digest: DigestPrivate {
|
||||
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
|
||||
|
||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
||||
guard bufferPointer.count == 48 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
|
||||
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||
targetPtr.copyMemory(from: bufferPointer)
|
||||
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
|
||||
body(&output)
|
||||
return output.finalize(for: targetPtr)
|
||||
}
|
||||
guard initialized == 48 else {
|
||||
return nil
|
||||
}
|
||||
self.bytes = bytes
|
||||
}
|
||||
@@ -120,6 +135,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 +143,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 +161,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.
|
||||
///
|
||||
@@ -164,18 +191,18 @@ public struct SHA384Digest: DigestPrivate {
|
||||
|
||||
// MARK: - SHA512Digest + DigestPrivate
|
||||
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 512-bit digest.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA512Digest: DigestPrivate {
|
||||
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
|
||||
|
||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
||||
guard bufferPointer.count == 64 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
|
||||
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||
targetPtr.copyMemory(from: bufferPointer)
|
||||
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
|
||||
body(&output)
|
||||
return output.finalize(for: targetPtr)
|
||||
}
|
||||
guard initialized == 64 else {
|
||||
return nil
|
||||
}
|
||||
self.bytes = bytes
|
||||
}
|
||||
@@ -193,6 +220,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 +228,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 +248,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.
|
||||
///
|
||||
@@ -236,22 +275,21 @@ public struct SHA512Digest: DigestPrivate {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Insecure {
|
||||
// MARK: - SHA1Digest + DigestPrivate
|
||||
/// The output of a SHA1 hash.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA1Digest: DigestPrivate {
|
||||
let bytes: (UInt64, UInt64, UInt64)
|
||||
|
||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
||||
guard bufferPointer.count == 20 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
|
||||
var bytes = (UInt64(0), UInt64(0), UInt64(0))
|
||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||
targetPtr.copyMemory(from: bufferPointer)
|
||||
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
|
||||
body(&output)
|
||||
return output.finalize(for: targetPtr)
|
||||
}
|
||||
guard initialized == 20 else {
|
||||
return nil
|
||||
}
|
||||
self.bytes = bytes
|
||||
}
|
||||
@@ -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.
|
||||
///
|
||||
@@ -307,22 +357,21 @@ public struct SHA1Digest: DigestPrivate {
|
||||
}
|
||||
}
|
||||
}
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Insecure {
|
||||
// MARK: - MD5Digest + DigestPrivate
|
||||
/// The output of a MD5 hash.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct MD5Digest: DigestPrivate {
|
||||
let bytes: (UInt64, UInt64)
|
||||
|
||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
||||
guard bufferPointer.count == 16 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
|
||||
var bytes = (UInt64(0), UInt64(0))
|
||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||
targetPtr.copyMemory(from: bufferPointer)
|
||||
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
|
||||
body(&output)
|
||||
return output.finalize(for: targetPtr)
|
||||
}
|
||||
guard initialized == 16 else {
|
||||
return nil
|
||||
}
|
||||
self.bytes = bytes
|
||||
}
|
||||
@@ -340,6 +389,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 +397,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 +438,258 @@ public struct MD5Digest: DigestPrivate {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // Linux or !SwiftPM
|
||||
|
||||
|
||||
#if !CRYPTOKIT_IN_SEP
|
||||
|
||||
// MARK: - SHA3_256Digest + DigestPrivate
|
||||
/// The output of a Secure Hashing Algorithm 3 (SHA-2) hash with a 256-bit digest.
|
||||
public struct SHA3_256Digest: DigestPrivate {
|
||||
let bytes: (UInt64, UInt64, UInt64, UInt64)
|
||||
|
||||
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
|
||||
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
||||
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
|
||||
body(&output)
|
||||
return output.finalize(for: targetPtr)
|
||||
}
|
||||
guard initialized == 32 else {
|
||||
return nil
|
||||
}
|
||||
self.bytes = bytes
|
||||
}
|
||||
|
||||
/// 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.
|
||||
public struct SHA3_384Digest: DigestPrivate {
|
||||
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
|
||||
|
||||
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
|
||||
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
||||
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
|
||||
body(&output)
|
||||
return output.finalize(for: targetPtr)
|
||||
}
|
||||
guard initialized == 48 else {
|
||||
return nil
|
||||
}
|
||||
self.bytes = bytes
|
||||
}
|
||||
|
||||
/// 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.
|
||||
public struct SHA3_512Digest: DigestPrivate {
|
||||
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
|
||||
|
||||
init?(initializingWith body: (inout OutputRawSpan) -> ()) {
|
||||
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
||||
let initialized = withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||
var output = OutputRawSpan(buffer: targetPtr, initializedCount: 0)
|
||||
body(&output)
|
||||
return output.finalize(for: targetPtr)
|
||||
}
|
||||
guard initialized == 64 else {
|
||||
return nil
|
||||
}
|
||||
self.bytes = bytes
|
||||
}
|
||||
|
||||
/// 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 // canImport(CryptoKit)
|
||||
@@ -1,116 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
// MARK: - Generated file, do NOT edit
|
||||
// any edits of this file WILL be overwritten and thus discarded
|
||||
// see section `gyb` in `README` for details.
|
||||
%{
|
||||
digests_and_length = [{"name": "SHA256", "count": 32},{"name": "SHA384","count":48},{"name":"SHA512", "count": 64},{"name":"SHA1", "count":20, "prefix":"Insecure "},{"name":"MD5", "count":16, "prefix":"Insecure "}]
|
||||
}%
|
||||
% for HF in digests_and_length:
|
||||
%{
|
||||
name = HF["name"]
|
||||
byteCount = HF["count"]
|
||||
wordsCount = (byteCount*8)//64 + (0 if ((byteCount*8)%64) == 0 else 1)
|
||||
}%
|
||||
%{
|
||||
if "prefix" in HF.keys():
|
||||
protocol_prefix = ""
|
||||
protocol_prefix = protocol_prefix + "extension " + HF["prefix"] + "{"
|
||||
protocol_suffix = "}"
|
||||
parent = HF["prefix"].strip() + "/" + name
|
||||
else:
|
||||
protocol_prefix = ""
|
||||
protocol_suffix = ""
|
||||
parent = name
|
||||
|
||||
if name == "SHA1" or name == "MD5":
|
||||
abstract = "The output of a " + name + " hash."
|
||||
else:
|
||||
abstract = "The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a " + name[-3:] + "-bit digest."
|
||||
}%
|
||||
${protocol_prefix}
|
||||
// MARK: - ${name}Digest + DigestPrivate
|
||||
/// ${abstract}
|
||||
public struct ${name}Digest: DigestPrivate {
|
||||
let bytes: (${(wordsCount-1)*"UInt64, "+"UInt64"})
|
||||
|
||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
||||
guard bufferPointer.count == ${byteCount} else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var bytes = (${(wordsCount-1)*"UInt64(0), "+"UInt64(0)"})
|
||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||
targetPtr.copyMemory(from: bufferPointer)
|
||||
}
|
||||
self.bytes = bytes
|
||||
}
|
||||
|
||||
/// The number of bytes in the digest.
|
||||
public static var byteCount: Int {
|
||||
return ${byteCount}
|
||||
}
|
||||
|
||||
/// Invokes the given closure with a buffer pointer covering the raw bytes of
|
||||
/// the digest.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: A closure that takes a raw buffer pointer to the bytes of the digest
|
||||
/// and returns the digest.
|
||||
///
|
||||
/// - Returns: The digest, as returned from the body closure.
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
/// A human-readable description of the digest.
|
||||
public var description: String {
|
||||
return "\("${name}") digest: \(toArray().hexString)"
|
||||
}
|
||||
|
||||
/// Hashes the essential components of the digest by feeding them into the
|
||||
/// given hash function.
|
||||
///
|
||||
/// This method is part of the digest’s conformance to Swift standard library’s
|
||||
/// <doc://com.apple.documentation/documentation/swift/hashable> protocol, making
|
||||
/// it possible to compare digests. Don’t confuse that hashing with the
|
||||
/// cryptographically secure hashing that you use to create the digest in the
|
||||
/// first place by, for example, calling ``${parent}/hash(data:)``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - hasher: The hash function to use when combining the components of
|
||||
/// the digest.
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
self.withUnsafeBytes { hasher.combine(bytes: $0) }
|
||||
}
|
||||
}
|
||||
${protocol_suffix}
|
||||
% end
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -11,18 +11,18 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
typealias DigestImpl = CoreCryptoDigestImpl
|
||||
#else
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
typealias DigestImpl = OpenSSLDigestImpl
|
||||
#endif
|
||||
typealias DigestImplSHA3 = XKCPDigestImpl
|
||||
|
||||
import Foundation
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
|
||||
/// A type that performs cryptographically secure hashing.
|
||||
///
|
||||
@@ -42,16 +42,11 @@ 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.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol HashFunction {
|
||||
@preconcurrency
|
||||
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
|
||||
/// The type of the digest returned by the hash function.
|
||||
associatedtype Digest: CryptoKit.Digest
|
||||
#else
|
||||
associatedtype Digest: Crypto.Digest
|
||||
#endif
|
||||
|
||||
/// Creates a hash function.
|
||||
///
|
||||
@@ -97,7 +92,15 @@ public protocol HashFunction {
|
||||
func finalize() -> Digest
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension HashFunction {
|
||||
@inlinable
|
||||
public mutating func update(bytes: RawSpan) {
|
||||
bytes.withUnsafeBytes {
|
||||
self.update(bufferPointer: $0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension HashFunction {
|
||||
/// Computes a digest of the buffer.
|
||||
///
|
||||
@@ -110,8 +113,20 @@ extension HashFunction {
|
||||
hasher.update(bufferPointer: bufferPointer)
|
||||
return hasher.finalize()
|
||||
}
|
||||
|
||||
/// Computes a digest of a span of bytes.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bytes: The bytes to be hashed.
|
||||
/// - Returns: The computed digest.
|
||||
@inlinable
|
||||
public static func hash(bytes: RawSpan) -> Digest {
|
||||
var hasher = Self()
|
||||
hasher.update(bytes: bytes)
|
||||
return hasher.finalize()
|
||||
}
|
||||
|
||||
/// Computes the 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
|
||||
@@ -158,4 +173,4 @@ extension HashFunction {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,9 +11,24 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
/// 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.
|
||||
public typealias SHA2_256 = SHA256
|
||||
|
||||
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
||||
/// 256-bit digest.
|
||||
///
|
||||
@@ -26,20 +41,11 @@
|
||||
/// in memory, you can compute the digest iteratively by creating a new hash
|
||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||
/// data, and then calling the ``finalize()`` method to get the result.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA256: HashFunctionImplementationDetails {
|
||||
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 +65,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 +100,20 @@ 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.
|
||||
public typealias SHA2_384 = SHA384
|
||||
|
||||
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
||||
/// 384-bit digest.
|
||||
///
|
||||
@@ -109,20 +126,11 @@ public struct SHA256: HashFunctionImplementationDetails {
|
||||
/// in memory, you can compute the digest iteratively by creating a new hash
|
||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||
/// data, and then calling the ``finalize()`` method to get the result.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA384: HashFunctionImplementationDetails {
|
||||
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 +151,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 +186,20 @@ 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.
|
||||
public typealias SHA2_512 = SHA512
|
||||
|
||||
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
||||
/// 512-bit digest.
|
||||
///
|
||||
@@ -193,20 +212,11 @@ public struct SHA384: HashFunctionImplementationDetails {
|
||||
/// in memory, you can compute the digest iteratively by creating a new hash
|
||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||
/// data, and then calling the ``finalize()`` method to get the result.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA512: HashFunctionImplementationDetails {
|
||||
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
|
||||
|
||||
@@ -261,4 +271,4 @@ public struct SHA512: HashFunctionImplementationDetails {
|
||||
return impl.finalize()
|
||||
}
|
||||
}
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -0,0 +1,229 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#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.
|
||||
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.
|
||||
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.
|
||||
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 // canImport(CryptoKit)
|
||||
@@ -0,0 +1,165 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CXKCP
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CXKCPShims
|
||||
#else
|
||||
@_implementationOnly import CXKCP
|
||||
@_implementationOnly import CXKCPShims
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
protocol XKCPBackedHashFunction: HashFunctionImplementationDetails {
|
||||
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(copying: digestPointer.bytes)!
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
withUnsafeMutablePointer(to: &self.context) { $0.zeroize() }
|
||||
}
|
||||
}
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,17 +11,21 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#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 {
|
||||
@nonexhaustive
|
||||
public enum AEAD: CaseIterable, Hashable, Sendable {
|
||||
/// An Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 128 bits.
|
||||
case AES_GCM_128
|
||||
/// An Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 256 bits.
|
||||
@@ -33,6 +37,7 @@ extension HPKE {
|
||||
/// In export-only mode, HPKE negotiates key derivation, but you can't use it to encrypt or decrypt data.
|
||||
case exportOnly
|
||||
|
||||
/// Return the AEAD algorithm identifier as defined in section 7.3 of [RFC 9180](https://www.ietf.org/rfc/rfc9180.pdf).
|
||||
internal var value: UInt16 {
|
||||
switch self {
|
||||
case .AES_GCM_128: return 0x0001
|
||||
@@ -46,6 +51,7 @@ extension HPKE {
|
||||
return self == .exportOnly
|
||||
}
|
||||
|
||||
/// Return the AEAD key size in bytes
|
||||
internal var keyByteCount: Int {
|
||||
switch self {
|
||||
case .AES_GCM_128:
|
||||
@@ -59,6 +65,7 @@ extension HPKE {
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the AEAD nonce size in bytes
|
||||
internal var nonceByteCount: Int {
|
||||
switch self {
|
||||
case .AES_GCM_128, .AES_GCM_256, .chaChaPoly:
|
||||
@@ -68,6 +75,7 @@ extension HPKE {
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the AEAD tag size in bytes
|
||||
internal var tagByteCount: Int {
|
||||
switch self {
|
||||
case .AES_GCM_128, .AES_GCM_256, .chaChaPoly:
|
||||
@@ -113,4 +121,4 @@ extension HPKE {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,22 +11,25 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#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 +42,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.
|
||||
@@ -71,4 +77,4 @@ extension HPKE {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,24 +11,29 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
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 {
|
||||
@nonexhaustive
|
||||
public enum KDF: CaseIterable, Hashable, Sendable {
|
||||
/// An HMAC-based key derivation function that uses SHA-2 hashing with a 256-bit digest.
|
||||
case HKDF_SHA256
|
||||
/// 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
|
||||
|
||||
/// Return the KDF algorithm identifier as defined in section 7.2 of [RFC 9180](https://www.ietf.org/rfc/rfc9180.pdf).
|
||||
internal var value: UInt16 {
|
||||
switch self {
|
||||
case .HKDF_SHA256: return 0x0001
|
||||
@@ -63,7 +68,7 @@ extension HPKE {
|
||||
/// - ikm: The initial key material the derivation function uses to derive a key.
|
||||
///
|
||||
/// - Returns: A pseudorandom, cryptographically strong key in the form of a hashed authentication code.
|
||||
func extract<S: DataProtocol>(salt: S, ikm: SymmetricKey) -> SymmetricKey {
|
||||
internal 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 +90,7 @@ 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 {
|
||||
internal 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))
|
||||
@@ -98,4 +103,4 @@ extension HPKE {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,39 +11,38 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
|
||||
private let suiteIDLabel = Data("KEM".utf8)
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension HPKE {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct KexUtils {
|
||||
static func ExtractAndExpand(dh: ContiguousBytes, enc: Data,
|
||||
pkRm: Data, pkSm: Data? = nil, kem: HPKE.KEM, kdf: HPKE.KDF) -> SymmetricKey {
|
||||
var suiteID = suiteIDLabel
|
||||
suiteID.append(kem.identifier)
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
return CryptoKit.ExtractAndExpand(zz: dh, kemContext: kemContext(enc: enc, pkRm: pkRm, pkSm: pkSm),
|
||||
suiteID: suiteID, kem: kem, kdf: kdf)
|
||||
#else
|
||||
return Crypto.ExtractAndExpand(zz: dh, kemContext: kemContext(enc: enc, pkRm: pkRm, pkSm: pkSm),
|
||||
suiteID: suiteID, kem: kem, kdf: kdf)
|
||||
#endif
|
||||
}
|
||||
|
||||
static func kemContext(enc: Data, pkRm: Data, pkSm: Data? = nil) -> Data {
|
||||
var context = Data()
|
||||
context.append(enc)
|
||||
context.append(pkRm)
|
||||
if let pkSm = pkSm { context.append(pkSm) }
|
||||
if let pkSm { context.append(pkSm) }
|
||||
return context
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,37 +11,36 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
|
||||
private let protocolLabel = Data("HPKE-v1".utf8)
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
private let eaePRKLabel = Data("eae_prk".utf8)
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
private let sharedSecretLabel = Data("shared_secret".utf8)
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Data {
|
||||
internal init(unsafeFromContiguousBytes cb: ContiguousBytes) {
|
||||
self = cb.withUnsafeBytes { return Data($0) }
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal func ExtractAndExpand(zz: ContiguousBytes, kemContext: Data, suiteID: Data, kem: HPKE.KEM, kdf: HPKE.KDF) -> SymmetricKey {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
let eaePrk = LabeledExtract(salt: Data(), label: eaePRKLabel, ikm: zz, suiteID: suiteID, kdf: kdf)
|
||||
|
||||
return LabeledExpand(prk: eaePrk, label: sharedSecretLabel,
|
||||
info: kemContext, outputByteCount: kem.nSecret, suiteID: suiteID, kdf: kdf)
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal func LabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, suiteID: Data, kdf: HPKE.KDF) -> SymmetricKey {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
var labeled_ikm = protocolLabel
|
||||
labeled_ikm.append(suiteID)
|
||||
labeled_ikm.append(label)
|
||||
@@ -49,9 +48,7 @@ internal func LabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, su
|
||||
return kdf.extract(salt: salt ?? Data(), ikm: SymmetricKey(data: labeled_ikm))
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal func LabeledExpand<Info: DataProtocol>(prk: SymmetricKey, label: Data, info: Info, outputByteCount: UInt16, suiteID: Data, kdf: HPKE.KDF) -> SymmetricKey {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
var labeled_info = I2OSP(value: Int(outputByteCount), outputByteCount: 2)
|
||||
labeled_info.append(protocolLabel)
|
||||
labeled_info.append(suiteID)
|
||||
@@ -60,14 +57,12 @@ internal func LabeledExpand<Info: DataProtocol>(prk: SymmetricKey, label: Data,
|
||||
return kdf.expand(prk: prk, info: labeled_info, outputByteCount: Int(outputByteCount))
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal func NonSecretOutputLabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, suiteID: Data, kdf: HPKE.KDF) -> Data {
|
||||
return Data(unsafeFromContiguousBytes: LabeledExtract(salt: salt, label: label, ikm: ikm, suiteID: suiteID, kdf: kdf))
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal func NonSecretOutputLabeledExpand(prk: SymmetricKey, label: Data, info: Data, outputByteCount: UInt16, suiteID: Data, kdf: HPKE.KDF) -> Data {
|
||||
return Data(unsafeFromContiguousBytes: LabeledExpand(prk: prk, label: label, info: info, outputByteCount: outputByteCount, suiteID: suiteID, kdf: kdf))
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,21 +11,39 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#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
|
||||
|
||||
|
||||
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.")
|
||||
|
||||
@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))
|
||||
|
||||
precondition(outputByteCount >= requiredBytes)
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
var data = Data(repeating: 0, count: outputByteCount)
|
||||
|
||||
for i in (outputByteCount - requiredBytes)...(outputByteCount - 1) {
|
||||
@@ -35,4 +53,4 @@ internal func I2OSP(value: Int, outputByteCount: Int) -> Data {
|
||||
return data
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,14 +11,20 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
|
||||
/// A type that ``HPKE`` uses to encode the public key.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol HPKEPublicKeySerialization {
|
||||
@preconcurrency
|
||||
public protocol HPKEPublicKeySerialization: Sendable {
|
||||
/// Creates a public key from an encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -35,39 +41,50 @@ public protocol HPKEPublicKeySerialization {
|
||||
}
|
||||
|
||||
/// A type that represents the public key in a Diffie-Hellman key exchange.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol HPKEDiffieHellmanPublicKey: HPKEPublicKeySerialization where EphemeralPrivateKey.PublicKey == Self {
|
||||
@preconcurrency
|
||||
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
|
||||
public protocol HPKEKEMPublicKey: KEMPublicKey, HPKEPublicKeySerialization where EphemeralPrivateKey.PublicKey == Self {
|
||||
/// The type of the ephemeral private key.
|
||||
associatedtype EphemeralPrivateKey: HPKEKEMPrivateKeyGeneration
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol HPKEDiffieHellmanPrivateKey: DiffieHellmanKeyAgreement where PublicKey: HPKEDiffieHellmanPublicKey {}
|
||||
/// A type that represents the private key in a Diffie-Hellman key exchange.
|
||||
@preconcurrency
|
||||
public protocol HPKEDiffieHellmanPrivateKey: Sendable, DiffieHellmanKeyAgreement where PublicKey: HPKEDiffieHellmanPublicKey {}
|
||||
|
||||
/// A type that represents the private key in HPKE.
|
||||
@preconcurrency
|
||||
public protocol HPKEKEMPrivateKey: Sendable, KEMPrivateKey where PublicKey: HPKEKEMPublicKey {}
|
||||
|
||||
/// A type that represents the generation of private keys in a Diffie-Hellman key exchange.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public protocol HPKEDiffieHellmanPrivateKeyGeneration: HPKEDiffieHellmanPrivateKey {
|
||||
@preconcurrency
|
||||
public protocol HPKEDiffieHellmanPrivateKeyGeneration: HPKEDiffieHellmanPrivateKey, Sendable {
|
||||
/// Creates a private key generator.
|
||||
init()
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
/// A type that represents the generation of private keys in HPKE
|
||||
@preconcurrency
|
||||
public protocol HPKEKEMPrivateKeyGeneration: HPKEKEMPrivateKey, Sendable {
|
||||
/// Creates a private key generator.
|
||||
init() throws
|
||||
}
|
||||
|
||||
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 {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
@nonexhaustive
|
||||
public enum DHKEM: Sendable {
|
||||
struct PublicKey<DHPK: HPKEDiffieHellmanPublicKey>: KEMPublicKey where DHPK == DHPK.EphemeralPrivateKey.PublicKey {
|
||||
let kem: HPKE.KEM
|
||||
let key: DHPK
|
||||
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
typealias EncapsulationResult = CryptoKit.KEM.EncapsulationResult
|
||||
#else
|
||||
typealias EncapsulationResult = Crypto.KEM.EncapsulationResult
|
||||
#endif
|
||||
|
||||
init(_ publicKey: DHPK, kem: HPKE.KEM) throws {
|
||||
// TODO: Validate Ciphersuite Mismatches
|
||||
@@ -91,7 +108,6 @@ extension HPKE {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct PrivateKey<DHSK: HPKEDiffieHellmanPrivateKey>: KEMPrivateKey {
|
||||
let kem: HPKE.KEM
|
||||
let key: DHSK
|
||||
@@ -152,4 +168,4 @@ extension HPKE {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,16 +11,19 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
|
||||
extension Curve25519.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {}
|
||||
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Curve25519.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
||||
/// The type of the ephemeral private key associated with this public key.
|
||||
public typealias EphemeralPrivateKey = Curve25519.KeyAgreement.PrivateKey
|
||||
@@ -63,4 +66,4 @@ extension Curve25519.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
||||
public typealias HPKEEphemeralPrivateKey = Curve25519.KeyAgreement.PrivateKey
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,14 +11,17 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension P256.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
||||
/// Creates a NIST P-256 elliptic curve private key for use with Diffie-Hellman key exchange.
|
||||
public init() {
|
||||
@@ -26,8 +29,6 @@ extension P256.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension P256.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
||||
/// The type of the ephemeral private key associated with this public key.
|
||||
public typealias EphemeralPrivateKey = P256.KeyAgreement.PrivateKey
|
||||
@@ -67,8 +68,6 @@ extension P256.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
||||
public typealias HPKEEphemeralPrivateKey = P256.KeyAgreement.PrivateKey
|
||||
}
|
||||
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension P384.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
||||
/// Creates a NIST P-384 elliptic curve private key for use with Diffie-Hellman key exchange.
|
||||
public init() {
|
||||
@@ -76,8 +75,6 @@ extension P384.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension P384.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
||||
/// The type of the ephemeral private key associated with this public key.
|
||||
public typealias EphemeralPrivateKey = P384.KeyAgreement.PrivateKey
|
||||
@@ -117,8 +114,6 @@ extension P384.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension P521.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
||||
/// Creates a NIST P-521 elliptic curve private key for use with Diffie-Hellman key exchange.
|
||||
public init() {
|
||||
@@ -126,8 +121,6 @@ extension P521.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension P521.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
||||
/// The type of the ephemeral private key associated with this public key.
|
||||
public typealias EphemeralPrivateKey = P521.KeyAgreement.PrivateKey
|
||||
@@ -170,4 +163,4 @@ extension P521.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
||||
public typealias HPKEEphemeralPrivateKey = P521.KeyAgreement.PrivateKey
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,16 +11,31 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#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.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum KEM: CaseIterable, Hashable {
|
||||
///
|
||||
/// The module-lattice key encapsulation mechanism (ML-KEM) is designed to offer increased security in situations
|
||||
/// where an adversary uses a quantum computer.
|
||||
@nonexhaustive
|
||||
public enum KEM: CaseIterable, Hashable, Sendable {
|
||||
public static var allCases: [HPKE.KEM] {
|
||||
var cases = [KEM.P256_HKDF_SHA256, KEM.P384_HKDF_SHA384, KEM.P521_HKDF_SHA512, KEM.Curve25519_HKDF_SHA256]
|
||||
if #available(iOS 19.0, macOS 16.0, watchOS 12.0, tvOS 19.0, macCatalyst 19.0, *) {
|
||||
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 +48,28 @@ 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
|
||||
|
||||
/// 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).
|
||||
internal 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,13 +79,25 @@ 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
|
||||
internal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,15 +11,20 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
extension HPKE {
|
||||
/// Hybrid public key encryption (HPKE) errors that CryptoKit uses.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
@nonexhaustive
|
||||
public enum Errors: Error {
|
||||
/// The parameters for initializing an HPKE sender or receiver are inconsistent.
|
||||
case inconsistentParameters
|
||||
@@ -40,4 +45,4 @@ extension HPKE {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,10 +11,15 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
#if canImport(FoundationEssentials)
|
||||
public import FoundationEssentials
|
||||
#else
|
||||
public import Foundation
|
||||
#endif
|
||||
|
||||
/// A container for hybrid public key encryption (HPKE) operations.
|
||||
///
|
||||
@@ -45,11 +50,14 @@ import Foundation
|
||||
///
|
||||
/// ### Handling errors
|
||||
/// - ``Errors``
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum HPKE {}
|
||||
@nonexhaustive
|
||||
public enum HPKE: Sendable {}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension HPKE {
|
||||
/// Static constant used to store the fixed-string label for the HPKE export API
|
||||
/// See: https://datatracker.ietf.org/doc/html/rfc9180#name-secret-export
|
||||
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,
|
||||
@@ -58,12 +66,11 @@ extension HPKE {
|
||||
/// in turn to retrieve its ciphertext. The recipient of the messages needs to process them in the
|
||||
/// same order as the `Sender`, using the same encryption mode, cipher suite, and key schedule information
|
||||
/// (`info`), as well as the `Sender`'s ``encapsulatedKey``.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct Sender {
|
||||
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 +84,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 +107,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
|
||||
@@ -196,16 +220,15 @@ extension HPKE {
|
||||
/// same order as the `Sender`, using the same cipher suite, encryption mode, and key schedule information
|
||||
/// (`info` data).
|
||||
/// Use a separate `Recipient` instance for each stream of messages.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct Recipient {
|
||||
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 +237,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 +268,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)
|
||||
}
|
||||
|
||||
@@ -321,4 +358,4 @@ extension HPKE {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,15 +11,19 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
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 +35,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 +58,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,7 +68,12 @@ 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,15 +11,19 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
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 +107,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
|
||||
@@ -143,4 +158,4 @@ extension HPKE {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,14 +11,12 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension HPKE {
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
internal enum Mode: CaseIterable {
|
||||
case base
|
||||
case psk
|
||||
@@ -40,4 +38,4 @@ extension HPKE {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,7 +11,8 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
/// A container for older, cryptographically insecure algorithms.
|
||||
@@ -19,6 +20,6 @@
|
||||
/// - Important: These algorithms aren’t considered cryptographically secure,
|
||||
/// but the framework provides them for backward compatibility with older
|
||||
/// services that require them. For new services, avoid these algorithms.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum Insecure {}
|
||||
#endif // Linux or !SwiftPM
|
||||
@nonexhaustive
|
||||
public enum Insecure: Sendable {}
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -11,10 +11,10 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Insecure {
|
||||
/// An implementation of SHA1 hashing.
|
||||
///
|
||||
@@ -32,22 +32,13 @@ extension Insecure {
|
||||
/// secure, but is provided for backward compatibility with older services
|
||||
/// that require it. For new services, prefer one of the secure hashes, like
|
||||
/// ``SHA512``.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA1: HashFunctionImplementationDetails {
|
||||
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
|
||||
@@ -121,21 +112,12 @@ extension Insecure {
|
||||
/// secure, but is provided for backward compatibility with older services
|
||||
/// that require it. For new services, prefer one of the secure hashes, like
|
||||
/// ``SHA512``.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct MD5: HashFunctionImplementationDetails {
|
||||
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
|
||||
@@ -193,4 +175,4 @@ extension Insecure {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // Linux or !SwiftPM
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -0,0 +1,575 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
#endif
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
@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
|
||||
}
|
||||
|
||||
return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) {
|
||||
symmetricKeyDataPtr,
|
||||
count in
|
||||
let bytes: ContiguousBytes =
|
||||
encapsulated.regions.count == 1
|
||||
? encapsulated.regions.first!
|
||||
: Array(encapsulated)
|
||||
let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in
|
||||
CCryptoBoringSSL_MLKEM768_decap(
|
||||
symmetricKeyDataPtr.baseAddress,
|
||||
encapsulatedPtr.baseAddress,
|
||||
encapsulatedPtr.count,
|
||||
&self.key
|
||||
)
|
||||
}
|
||||
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
count = MLKEM.sharedSecretByteCount
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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
|
||||
}
|
||||
|
||||
return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) {
|
||||
symmetricKeyDataPtr,
|
||||
count in
|
||||
let bytes: ContiguousBytes =
|
||||
encapsulated.regions.count == 1
|
||||
? encapsulated.regions.first!
|
||||
: Array(encapsulated)
|
||||
let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in
|
||||
CCryptoBoringSSL_MLKEM1024_decap(
|
||||
symmetricKeyDataPtr.baseAddress,
|
||||
encapsulatedPtr.baseAddress,
|
||||
encapsulatedPtr.count,
|
||||
&self.key
|
||||
)
|
||||
}
|
||||
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
count = MLKEM.sharedSecretByteCount
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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 // canImport(CryptoKit)
|
||||
@@ -0,0 +1,313 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
#endif
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
%{
|
||||
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
|
||||
}
|
||||
|
||||
return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) {
|
||||
symmetricKeyDataPtr,
|
||||
count in
|
||||
let bytes: ContiguousBytes =
|
||||
encapsulated.regions.count == 1
|
||||
? encapsulated.regions.first!
|
||||
: Array(encapsulated)
|
||||
let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in
|
||||
CCryptoBoringSSL_MLKEM${parameter_set}_decap(
|
||||
symmetricKeyDataPtr.baseAddress,
|
||||
encapsulatedPtr.baseAddress,
|
||||
encapsulatedPtr.count,
|
||||
&self.key
|
||||
)
|
||||
}
|
||||
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
count = MLKEM.sharedSecretByteCount
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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 // canImport(CryptoKit)
|
||||
Loaded 100 of 367 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user