Compare commits

..
11 Commits
Author SHA1 Message Date
+6 e0883b430c Final catchup merge (#415)
This is the last catchup merge into the WWDC-25 branch required to get
the two branches to line up. From here, it's a straightforward merge to
`main` to get the WWDC-25 branch in.

---------

Co-authored-by: YourMJK <37852512+YourMJK@users.noreply.github.com>
Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
Co-authored-by: Raphael <josephnoir@users.noreply.github.com>
Co-authored-by: Si Beaumont <beaumont@apple.com>
Co-authored-by: Evan Wilde <ewilde@apple.com>
Co-authored-by: Tim Condon <0xTim@users.noreply.github.com>
Co-authored-by: Gus Cairo <gus.cairo@apple.com>
Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Fabrice de Gans <Steelskin@users.noreply.github.com>
Co-authored-by: Wojciech Nagrodzki <278594+wnagrodzki@users.noreply.github.com>
Co-authored-by: Jesse L. Zamora <xtremekforever@gmail.com>
Co-authored-by: aryan-25 <aryan_shah@apple.com>
Co-authored-by: Gwynne Raskind <gwynne@vapor.codes>
Co-authored-by: 3405691582 <dsk@google.com>
Co-authored-by: Paul Toffoloni <69189821+ptoffy@users.noreply.github.com>
2025-09-24 17:22:11 +01:00
Si Beaumont 459adb9e07 Fix compiler guard for SHA-3 tests (#401) 2025-09-22 13:40:32 +00:00
Tim Condon 4e662b89da Rename _CryptoExtras Take 2 (#407)
Following on from #281, opened as a new PR as the conflicts were too
many

### Checklist
- [x] I've run tests to see all new and existing tests pass
- [x] I've followed the code style of the rest of the project
- [x] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [x] I've updated the documentation if necessary

#### If you've made changes to `gyb` files
- [ ] I've run `.script/generate_boilerplate_files_with_gyb` and
included updated generated files in a commit of this pull request

### Motivation:

_[Explain here the context, and why you're making that change. What is
the problem you're trying to solve.]_

### Modifications:

_[Describe the modifications you've done.]_

### Result:

_[After your change, what will change.]_
2025-09-15 15:07:07 +01:00
Cory Benfield ea7f8fbce1 Update to RC SDK (#410)
This patch brings us up-to-date with the RC SDK. There are a couple of
tweaks to the MLDSA code and the XWing code, mostly a few minor
interface changes. I've adopted those in the backing code, and also
wired up the SHA3 integrity checks.
2025-09-10 10:26:24 +01:00
+3 890595d10e Catch-up merge main into wwdc25 branch (#403)
Co-authored-by: YourMJK <37852512+YourMJK@users.noreply.github.com>
Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
Co-authored-by: Raphael <josephnoir@users.noreply.github.com>
Co-authored-by: Si Beaumont <beaumont@apple.com>
Co-authored-by: Evan Wilde <ewilde@apple.com>
Co-authored-by: Tim Condon <0xTim@users.noreply.github.com>
Co-authored-by: Gus Cairo <gus.cairo@apple.com>
Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Fabrice de Gans <Steelskin@users.noreply.github.com>
Co-authored-by: Wojciech Nagrodzki <278594+wnagrodzki@users.noreply.github.com>
Co-authored-by: Jesse L. Zamora <xtremekforever@gmail.com>
Co-authored-by: aryan-25 <aryan_shah@apple.com>
2025-09-09 16:12:32 +01:00
Si Beaumont d9f3641899 [WWDC25] Add SHA-3 implementation backed by XKCP (#397)
## Motivation

CryptoKit is adding API for SHA-3, which BoringSSL does not support. To
maintain API parity, we need to provide a backing implementation. For
this, we can use XKCP[^1], which provides the reference implementation,
as well as several optimized solutions, suitable for vendoring into
other projects.

## Modifications

The following changes have been made in separate commits to help with
the review:

- Add vendor-xkcp.sh script
- Revendor xkcp#master (heads/master-0-g11297f5)
- Add CXCKP target with modulemap and umbrella header
- Add CXKCPTests test target with simple test vectors
- Add CXKCPShims with function wrappers for macros to call from Swift
- Remove #if false guard from HashFunctions_SHA3.swift
- Add SHA-3 implementation backed by libXKCP
- Add new DigestImplSHA3 platform-specific type alias
- Remove #if false from DigestsTests.swift to get SHA-3 tests

## Result

Swift Crypto provides functioning SHA-3 API.

## Notes

This PR is for the `wwdc-25` side branch.

[^1]: https://github.com/XKCP/XKCP
2025-08-11 19:28:46 +01:00
Cory Benfield 9b0697120a Adopt Swift 6 mode (#368)
Motivation

The Swift 6 language mode adopts data-race safety by default. While
Swift Crypto itself has no concurrent code, it is still useful to force
us to ensure that our code is properly Sendable-correct.

Modifications

- @unchecked Sendable on several CoW data types
- Some necessary Sendable constraints on ECToolbox protocols
- Add some missing protocol constraints on ARC types.

Result

Swift 6 clean.
2025-06-23 09:47:46 +01:00
Cory BenfieldandYourMJK 8be108101e Perform another catch-up merge for the WWDC 2025 branch (#367)
Co-authored-by: YourMJK <37852512+YourMJK@users.noreply.github.com>
2025-06-20 07:19:17 +01:00
Cory BenfieldandYourMJK 1eb3eec7d9 Catch the WWDC-25 branch up to the tip of main (#365)
To keep the WWDC-25 branch from rotting too badly, we'll be doing
regular catch-up merges. This is the first.

Co-authored-by: YourMJK <37852512+YourMJK@users.noreply.github.com>
2025-06-18 16:17:54 +01:00
Cory Benfield 83a1500dac Replace all Foundation imports with FoundationEssentials (#363)
### Motivation:

FoundationEssentials produces smaller binaries on most platforms.

### Modifications:

Where FoundationEssentials is available, import that.

### Result:

Improved binary size
2025-06-18 15:59:27 +01:00
Cory Benfield b5dde9c658 Bring swift-crypto up to date with CryptoKit 2025 Beta 1 (#359)
This PR sets swift-crypto up for alignment with the WWDC 2025 CryptoKit
APIs. This includes the parity APIs for MLKEM and MLDSA, as well as
XWing.

At this time the SHA3 APIs are disabled, as they require a novel
implementation strategy. This will come later in the summer. All API
features that require SHA3 are therefore also disabled at runtime.
2025-06-16 14:54:28 +01:00
41 changed files with 303 additions and 1741 deletions

No files matched your search

+4 -7
View File
@@ -1,8 +1,5 @@
name: Main
permissions:
contents: read
on:
push:
branches: [main]
@@ -15,19 +12,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"
@@ -35,9 +32,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
+5 -8
View File
@@ -1,8 +1,5 @@
name: PR
permissions:
contents: read
on:
pull_request:
types: [opened, reopened, synchronize]
@@ -10,7 +7,7 @@ on:
jobs:
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.7
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
with:
license_header_check_project_name: "SwiftCrypto"
docs_check_enabled: false
@@ -20,19 +17,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"
@@ -40,9 +37,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
+1 -4
View File
@@ -1,8 +1,5 @@
name: PR label
permissions:
contents: read
on:
pull_request:
types: [labeled, unlabeled, opened, reopened, synchronize]
@@ -14,7 +11,7 @@ jobs:
timeout-minutes: 1
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
persist-credentials: false
- name: Check for Semantic Version label
+1 -1
View File
@@ -1,4 +1,4 @@
// swift-tools-version:6.1
// swift-tools-version:5.10
import PackageDescription
let package = Package(
+1 -1
View File
@@ -1,4 +1,4 @@
// swift-tools-version:6.1
// swift-tools-version:6.0
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
+11 -21
View File
@@ -7,9 +7,9 @@ Swift Crypto is an open-source implementation of a substantial portion of the AP
Swift Crypto is available as a Swift Package Manager package. To use it, add the following dependency in your `Package.swift`:
```swift
// swift-crypto 1.x, 2.x, 3.x, and 4.x are almost API compatible, so most clients
// swift-crypto 1.x, 2.x and 3.x are almost API compatible, so most clients
// should allow any of them
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "5.0.0"),
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "4.0.0"),
```
and to your target, add `Crypto` to your dependencies. You can then `import Crypto` to get access to Swift Crypto's functionality.
@@ -31,11 +31,10 @@ When building Swift Crypto for use on an Apple platform where CryptoKit is alrea
When building Swift Crypto for use on Linux or Windows, Swift Crypto builds substantially more code. In particular, we build:
1. A vendored copy of BoringSSL's libcrypto.
2. 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.
2. The common API of Swift Crypto and CryptoKit.
3. The backing implementation of this common API, which calls into BoringSSL.
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The 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.
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The backing BoringSSL-based implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIS predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL implementation of the library in your application, no matter the platform.
## Evolution
@@ -49,11 +48,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`/`_xkcp` or are in a `BoringSSL`/`XKCP` 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` or are in a `BoringSSL` 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 `import CXKCP` or access a BoringSSL or XKCP 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 access a BoringSSL API, it needs to be marked this way.
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.
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.
## Contributing
@@ -109,7 +108,7 @@ If you believe you have identified a vulnerability in Swift Crypto, please [repo
### Swift versions
The most recent versions of Swift Crypto support Swift 6 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
The most recent versions of Swift Crypto support Swift 5.7 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
Swift Crypto | Minimum Swift Version
--------------------|----------------------
@@ -120,8 +119,7 @@ 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 ..< 4.0.0` | 5.10
`4.0.0 ...` | 6.0
`3.13.0 ...` | 5.10
### Compatibility
@@ -133,21 +131,13 @@ 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`.
To do so, please use the following dependency in your `Package.swift`:
```swift
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "5.0.0"),
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "3.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.
## Acknowledgements
This project contains source code from the BoringSSL and XKCP projects.
-1
View File
@@ -102,7 +102,6 @@ add_library(Crypto
"Util/BoringSSL/RNG_boring.swift"
"Util/BoringSSL/SafeCompare_boring.swift"
"Util/BoringSSL/Zeroization_boring.swift"
"Util/BoringSSL/_CryptoModuleAnchor.swift"
"Util/PrettyBytes.swift"
"Util/SafeCompare.swift"
"Util/SecureBytes.swift"
@@ -173,10 +173,10 @@ private final class DigestContext<H: BoringSSLBackedHashFunction> {
private var context: H.Context
init() {
guard let context = H.initialize() else {
guard let contex = H.initialize() else {
preconditionFailure("Unable to initialize digest state")
}
self.context = context
self.context = contex
}
init(copying original: DigestContext) {
@@ -236,13 +236,7 @@ extension OpenSSLXWingPrivateKeyImpl {
}
func decapsulate(_ encapsulated: Data) throws -> SymmetricKey {
guard encapsulated.count == Int(XWING_CIPHERTEXT_BYTES) else {
throw CryptoKitError.incorrectParameterSize
}
return try SymmetricKey(unsafeUninitializedCapacity: Int(XWING_SHARED_SECRET_BYTES)) {
sharedSecretBytes,
count in
try SymmetricKey(unsafeUninitializedCapacity: Int(XWING_SHARED_SECRET_BYTES)) { sharedSecretBytes, count in
try encapsulated.withUnsafeBytes { encapsulatedSecretBytes in
let rc = CCryptoBoringSSL_XWING_decap(
sharedSecretBytes.baseAddress,
@@ -1,25 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2024-2026 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
//
//===----------------------------------------------------------------------===//
// On Apple platforms the Crypto module re-exports CryptoKit and produces no
// symbols of its own. When Xcode 26+ builds SPM packages as dynamic
// frameworks (e.g. for test-target dependencies), an empty module generates a
// framework directory with no Mach-O binary, causing a linker error.
//
// This symbol ensures at least one exported entry is always present in the
// binary, regardless of how the package is linked.
// See: https://github.com/apple/swift-crypto/issues/435
@usableFromInline
internal func _cryptoModuleAnchor() {}
@@ -14,13 +14,8 @@
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
#if canImport(FoundationEssentials)
import protocol FoundationEssentials.ContiguousBytes
import struct FoundationEssentials.Data
#else
import protocol Foundation.ContiguousBytes
import struct Foundation.Data
#endif
/// A wrapper around BoringSSL's EC_POINT with some lifetime management and value semantics.
@usableFromInline
+94 -8
View File
@@ -25,6 +25,19 @@ extension AES {
/// suite.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
public enum _CBC {
private static var blockSize: Int { 16 }
private static func encryptBlockInPlace(
_ plaintext: inout Block,
priorCiphertextBlock: Block,
using key: SymmetricKey
) throws {
assert([128, 192, 256].contains(key.bitCount))
plaintext ^= priorCiphertextBlock
try AES.permute(&plaintext, key: key)
}
/// Encrypts data using AES-CBC.
///
/// - Parameters:
@@ -47,7 +60,44 @@ extension AES {
///
/// - Note: If `noPadding` is set to `true`, `plainText` has to be a multiple of the blockSize (16 bytes). Otherwise an error will be thrown.
public static func encrypt<Plaintext: DataProtocol>(_ plaintext: Plaintext, using key: SymmetricKey, iv: AES._CBC.IV, noPadding: Bool) throws -> Data {
try OpenSSLAESCBCImpl.encrypt(plaintext, using: key, iv: iv, noPadding: noPadding)
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
let requiresFullPaddingBlock = (plaintext.count % AES._CBC.blockSize) == 0
if noPadding && !requiresFullPaddingBlock {
throw CryptoKitError.incorrectParameterSize
}
var ciphertext = Data()
ciphertext.reserveCapacity(plaintext.count + Self.blockSize) // Room for padding.
var previousBlock = Block(iv)
var plaintext = plaintext[...]
while plaintext.count > 0 {
var block = Block(blockBytes: plaintext.prefix(Self.blockSize))
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
ciphertext.append(contentsOf: block)
previousBlock = block
plaintext = plaintext.dropFirst(Self.blockSize)
}
if requiresFullPaddingBlock && !noPadding {
var block = Block.paddingBlock
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
ciphertext.append(contentsOf: block)
}
return ciphertext
}
private static func decryptBlockInPlace(_ ciphertext: inout Block, priorCiphertextBlock: Block, using key: SymmetricKey) throws {
assert([128, 192, 256].contains(key.bitCount))
try AES.inversePermute(&ciphertext, key: key)
ciphertext ^= priorCiphertextBlock
}
/// Decrypts data using AES-CBC.
@@ -70,7 +120,29 @@ extension AES {
/// - noPadding: If this is set to `true`, padding won't be removed.
/// - Returns: The decrypted message.
public static func decrypt<Ciphertext: DataProtocol>(_ ciphertext: Ciphertext, using key: SymmetricKey, iv: AES._CBC.IV, noPadding: Bool) throws -> Data {
try OpenSSLAESCBCImpl.decrypt(ciphertext, using: key, iv: iv, noPadding: noPadding)
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
var plaintext = Data()
plaintext.reserveCapacity(ciphertext.count)
var previousBlock = Block(iv)
var ciphertext = ciphertext[...]
while ciphertext.count > 0 {
let ctBlock = Block(blockBytes: ciphertext.prefix(Self.blockSize))
var block = ctBlock
try Self.decryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
plaintext.append(contentsOf: block)
previousBlock = ctBlock
ciphertext = ciphertext.dropFirst(Self.blockSize)
}
if !noPadding {
try plaintext.trimPadding()
}
return plaintext
}
}
}
@@ -122,7 +194,7 @@ extension AES._CBC {
0, 0, 0, 0, 0, 0, 0, 0
)
Swift.withUnsafeMutableBytes(of: &self.ivBytes) { bytesPtr in
withUnsafeMutableBytes(of: &self.ivBytes) { bytesPtr in
bytesPtr.copyBytes(from: ivBytes)
}
}
@@ -133,10 +205,24 @@ extension AES._CBC {
Array(unsafeRawBufferPointer).makeIterator()
}
}
mutating func withUnsafeMutableBytes<ReturnType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
return try Swift.withUnsafeMutableBytes(of: &self.ivBytes, body)
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension Data {
fileprivate mutating func trimPadding() throws {
guard let paddingBytes = self.last else {
// Degenerate case, empty string. This is forbidden:
// we must always pad.
throw CryptoKitError.incorrectParameterSize
}
guard paddingBytes > 0 &&
self.count >= paddingBytes &&
self.suffix(Int(paddingBytes)).allSatisfy({ $0 == paddingBytes }) else {
throw CryptoKitError.incorrectParameterSize
}
self = self.dropLast(Int(paddingBytes))
}
}
@@ -118,6 +118,8 @@ extension AES {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
struct Block {
private static var blockSize: Int { 16 }
typealias BlockBytes = (
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8
@@ -133,9 +135,70 @@ extension AES {
)
}
init(_ blockBytes: BlockBytes) {
self.blockBytes = blockBytes
}
init(_ iv: AES._CBC.IV) {
self.blockBytes = iv.ivBytes
}
init<BlockBytes: Collection>(blockBytes: BlockBytes) where BlockBytes.Element == UInt8 {
// The block size is always 16. Pad out past there.
precondition(blockBytes.count <= Self.blockSize)
self.blockBytes = (
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
)
Swift.withUnsafeMutableBytes(of: &self.blockBytes) { bytesPtr in
bytesPtr.copyBytes(from: blockBytes)
// Early exit here.
if blockBytes.count == Self.blockSize {
return
}
var remainingBytes = bytesPtr.dropFirst(blockBytes.count)
let padByte = UInt8(remainingBytes.count)
for index in remainingBytes.indices {
remainingBytes[index] = padByte
}
}
}
static var paddingBlock: Block {
// The padding block is a full block of value blocksize.
let value = UInt8(truncatingIfNeeded: Self.blockSize)
return Block((
value, value, value, value, value, value, value, value,
value, value, value, value, value, value, value, value
))
}
func withUnsafeBytes<ReturnType>(_ body: (UnsafeRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
return try Swift.withUnsafeBytes(of: self.blockBytes, body)
}
mutating func withUnsafeMutableBytes<ReturnType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
return try Swift.withUnsafeMutableBytes(of: &self.blockBytes, body)
}
static func ^= (lhs: inout Block, rhs: Block) {
// Ideally we'd not use raw pointers for this.
lhs.withUnsafeMutableBytes { lhsPtr in
rhs.withUnsafeBytes { rhsPtr in
assert(lhsPtr.count == Self.blockSize)
assert(rhsPtr.count == Self.blockSize)
for index in 0..<Self.blockSize {
lhsPtr[index] ^= rhsPtr[index]
}
}
}
}
}
private static func isValidKey(_ key: SymmetricKey) -> Bool {
@@ -147,3 +210,52 @@ extension AES {
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension AES.Block: RandomAccessCollection, MutableCollection {
var startIndex: Int {
0
}
var endIndex: Int {
Self.blockSize
}
subscript(position: Int) -> UInt8 {
get {
precondition(position >= 0)
precondition(position < Self.blockSize)
return self.withUnsafeBytes { $0[position] }
}
set {
precondition(position >= 0)
precondition(position < Self.blockSize)
self.withUnsafeMutableBytes { $0[position] = newValue }
}
}
func withContiguousStorageIfAvailable<ReturnValue>(
_ body: (UnsafeBufferPointer<UInt8>) throws -> ReturnValue)
rethrows -> ReturnValue? {
return try withUnsafePointer(to: self.blockBytes) { tuplePtr in
// Homogeneous tuples are always bound to the element type as well as to their own type.
let retyped = UnsafeRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
let bufferised = UnsafeBufferPointer(start: retyped, count: Self.blockSize)
return try body(bufferised)
}
}
mutating func withContiguousMutableStorageIfAvailable<ReturnValue>(
_ body: (inout UnsafeMutableBufferPointer<UInt8>) throws -> ReturnValue)
rethrows -> ReturnValue? {
return try withUnsafeMutablePointer(to: &self.blockBytes) { tuplePtr in
// Homogeneous tuples are always bound to the element type as well as to their own type.
let retyped = UnsafeMutableRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
var bufferised = UnsafeMutableBufferPointer(start: retyped, count: Self.blockSize)
return try body(&bufferised)
}
}
}
@@ -1,189 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@_implementationOnly import CCryptoBoringSSL
import Crypto
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
@usableFromInline
enum OpenSSLAESCBCImpl {
private static let blockSize = 16
@usableFromInline
enum Direction {
case encrypt
case decrypt
@usableFromInline
var _boringSSLParameter: Int32 {
switch self {
case .encrypt: AES_ENCRYPT
case .decrypt: AES_DECRYPT
}
}
}
/// Encrypts plaintext using AES-CBC.
///
/// PKCS#7 padding is added unless `noPadding` is set, in which case the plaintext must
/// already be a whole number of blocks.
static func encrypt<Plaintext: DataProtocol>(
_ plaintext: Plaintext,
using key: SymmetricKey,
iv: AES._CBC.IV,
noPadding: Bool
) throws -> Data {
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
// With padding disabled the input must be a whole number of blocks.
if noPadding && (plaintext.count % Self.blockSize != 0) {
throw CryptoKitError.incorrectParameterSize
}
// AES_cbc_encrypt performs no padding, so PKCS#7 is applied here.
var padded = Data(plaintext)
if !noPadding {
// PKCS#7 always appends 1...blockSize bytes (a full block when already aligned).
let padLength = Self.blockSize - (plaintext.count % Self.blockSize)
let padding = repeatElement(UInt8(padLength), count: padLength)
padded.append(contentsOf: padding)
}
return padded.withUnsafeBytes { plaintextPtr in
Self._cipher(.encrypt, plaintextPtr, using: key, iv: iv)
}
}
/// Decrypts ciphertext using AES-CBC.
///
/// BoringSSL runs with padding disabled and, unless `noPadding` is set, PKCS#7 padding is
/// removed here in constant time. BoringSSL's own PKCS#7 removal is not constant-time (it is a
/// documented padding oracle absent authentication), so it must not be delegated.
static func decrypt<Ciphertext: DataProtocol>(
_ ciphertext: Ciphertext,
using key: SymmetricKey,
iv: AES._CBC.IV,
noPadding: Bool
) throws -> Data {
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
// CBC ciphertext is always a whole number of non-empty blocks.
guard ciphertext.count > 0, ciphertext.count % Self.blockSize == 0 else {
throw CryptoKitError.incorrectParameterSize
}
let contiguousCiphertext = Data(ciphertext)
let plaintext = contiguousCiphertext.withUnsafeBytes { ciphertextPtr in
Self._cipher(.decrypt, ciphertextPtr, using: key, iv: iv)
}
return noPadding ? plaintext : try plaintext.removingPKCS7PaddingConstantTime(blockSize: Self.blockSize)
}
/// Runs raw AES-CBC in the given direction over a single contiguous buffer.
///
/// `AES_cbc_encrypt` performs no padding, so `input` must be a whole number of blocks and the
/// output has the same length. PKCS#7 is applied and removed by the callers.
@usableFromInline
static func _cipher(
_ direction: Direction,
_ input: UnsafeRawBufferPointer,
using key: SymmetricKey,
iv: AES._CBC.IV
) -> Data {
precondition(input.count % Self.blockSize == 0)
var output = Data(count: input.count)
var iv = iv
key.withUnsafeBytes { keyPtr in
// AES_cbc_encrypt advances the IV in place, so operate on our own copy.
iv.withUnsafeMutableBytes { ivPtr in
var key = AES_KEY()
switch direction {
case .encrypt:
precondition(
CCryptoBoringSSL_AES_set_encrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key) == 0
)
case .decrypt:
precondition(
CCryptoBoringSSL_AES_set_decrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key) == 0
)
}
output.withUnsafeMutableBytes { outputPtr in
CCryptoBoringSSL_AES_cbc_encrypt(
input.baseAddress,
outputPtr.baseAddress,
input.count,
&key,
ivPtr.baseAddress,
direction._boringSSLParameter
)
}
}
}
return output
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension Data {
/// Removes PKCS#7 padding in constant time with respect to the padding bytes.
fileprivate func removingPKCS7PaddingConstantTime(blockSize: Int = 16) throws -> Data {
// The total length is not secret, so branching on it is safe.
guard self.count >= blockSize, self.count % blockSize == 0 else {
throw CryptoKitError.incorrectParameterSize
}
let padLength = self.last!
let lastBlock = self.suffix(blockSize)
// Validate padding in constant time.
var bad: UInt32 = 0
// A valid PKCS#7 pad length is 1...blockSize.
bad |= constantTimeLessThanOrEqual(padLength, 0)
bad |= constantTimeLessThanOrEqual(UInt8(blockSize + 1), padLength)
// We MUST operate on every byte in the block, and each byte in the padding region MUST equal `padLength`.
for index in lastBlock.indices {
let byte = UInt32(lastBlock[index])
let distanceFromEnd = self.endIndex - index
let inPadding = constantTimeLessThanOrEqual(UInt8(distanceFromEnd), padLength)
bad |= inPadding & (byte ^ UInt32(padLength))
}
// Throw if padding was invalid.
guard bad == 0 else {
throw CryptoKitError.incorrectParameterSize
}
// Drop the padding.
return self.dropLast(Int(padLength))
}
}
/// Returns `0xFFFFFFFF` if `lhs <= rhs`, otherwise `0`, without a data-dependent branch.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
private func constantTimeLessThanOrEqual(_ lhs: UInt8, _ rhs: UInt8) -> UInt32 {
// `lhs - rhs - 1` is negative iff `lhs <= rhs`; propagate its sign bit across the word.
let difference = Int32(lhs) - Int32(rhs) - 1
return UInt32(bitPattern: difference >> 31)
}
-8
View File
@@ -18,7 +18,6 @@ add_library(CryptoExtras
"AES/AES_CTR.swift"
"AES/AES_GCM_SIV.swift"
"AES/Block Function.swift"
"AES/BoringSSL/AES_CBC_boring.swift"
"AES/BoringSSL/AES_CFB_boring.swift"
"AES/BoringSSL/AES_CTR_boring.swift"
"AES/BoringSSL/AES_GCM_SIV_boring.swift"
@@ -34,11 +33,6 @@ add_library(CryptoExtras
"ARC/ARCServer.swift"
"ChaCha20CTR/BoringSSL/ChaCha20CTR_boring.swift"
"ChaCha20CTR/ChaCha20CTR.swift"
"Digests/BoringSSL/BoringSSLSHA512256Context.swift"
"Digests/BoringSSL/BoringSSLSHA512256HashFunction.swift"
"Digests/SHA512256.swift"
"Digests/SHA512256Digest.swift"
"EC/Curve25519+PEM.swift"
"EC/ObjectIdentifier.swift"
"EC/PKCS8DERRepresentation.swift"
"EC/PKCS8PrivateKey.swift"
@@ -58,12 +52,10 @@ add_library(CryptoExtras
"OPRFs/VOPRF+API.swift"
"OPRFs/VOPRFClient.swift"
"OPRFs/VOPRFServer.swift"
"RSA/BoringSSLPassphraseCallbackManager.swift"
"RSA/RSA+BlindSigning.swift"
"RSA/RSA.swift"
"RSA/RSA_boring.swift"
"Reexport.swift"
"Util/BoringSSL/Zeroization_boring.swift"
"Util/BoringSSLHelpers.swift"
"Util/CryptoKitErrors_boring.swift"
"Util/Data+Extensions.swift"
@@ -1,82 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@_implementationOnly import CCryptoBoringSSL
import Crypto
#if canImport(Darwin)
import Darwin
#endif
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
final class BoringSSLSHA512256Context {
private var context: SHA512_CTX
init() {
guard let context = BoringSSLSHA512256HashFunction.initialize() else {
preconditionFailure("Unable to initialize digest state")
}
self.context = context
}
deinit {
withUnsafeMutablePointer(to: &self.context) {
$0.zeroize()
}
}
init(copying original: BoringSSLSHA512256Context) {
self.context = original.context
}
func update(bufferPointer data: UnsafeRawBufferPointer) {
guard BoringSSLSHA512256HashFunction.update(&self.context, data: data) else {
preconditionFailure("Unable to update digest state")
}
}
func finalize() -> SHA512256Digest {
var copyContext = self.context
defer {
withUnsafeMutablePointer(to: &copyContext) {
$0.zeroize()
}
}
return withUnsafeTemporaryAllocation(byteCount: BoringSSLSHA512256HashFunction.digestSize, alignment: 1) {
digestPointer in
defer {
digestPointer.zeroize()
}
guard BoringSSLSHA512256HashFunction.finalize(&copyContext, 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 SHA512256Digest(bufferPointer: UnsafeRawBufferPointer(digestPointer))!
}
}
}
extension UnsafeMutablePointer {
fileprivate func zeroize() {
let size = MemoryLayout.size(ofValue: Pointee.self)
memset_s(self, size, 0, size)
}
}
extension UnsafeMutableRawBufferPointer {
fileprivate func zeroize() {
memset_s(self.baseAddress!, self.count, 0, self.count)
}
}
@@ -1,43 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@_implementationOnly import CCryptoBoringSSL
import Crypto
struct BoringSSLSHA512256HashFunction {
static var digestSize: Int {
Int(SHA256_DIGEST_LENGTH)
}
static func initialize() -> SHA512_CTX? {
var context = SHA512_CTX()
guard CCryptoBoringSSL_SHA512_256_Init(&context) == 1 else {
return nil
}
return context
}
static func update(_ context: inout SHA512_CTX, data: UnsafeRawBufferPointer) -> Bool {
let result = CCryptoBoringSSL_SHA512_256_Update(&context, data.baseAddress, data.count)
return result == 1
}
static func finalize(_ context: inout SHA512_CTX, digest: UnsafeMutableRawBufferPointer) -> Bool {
guard let baseAddress = digest.baseAddress, digest.count == Self.digestSize else {
return false
}
let result = CCryptoBoringSSL_SHA512_256_Final(baseAddress, &context)
return result == 1
}
}
@@ -1,88 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Crypto
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
/// 256-bit digest using the SHA-512/256 variant.
///
/// The ``SHA512256`` hash implements the ``HashFunction`` protocol for the
/// specific case of SHA-512/256 hashing with a 256-bit digest
/// (``SHA512256Digest``). SHA-512/256 is a truncated variant of SHA-512 that
/// provides the same security level as SHA-256 but can be faster on 64-bit
/// platforms.
///
/// You can compute the digest by calling the static ``hash(data:)`` method
/// once. Alternatively, if the data that you want to hash is too large to fit
/// in memory, you can compute the digest iteratively by creating a new hash
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
/// data, and then calling the ``finalize()`` method to get the result.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
public struct SHA512256: HashFunction, @unchecked Sendable {
/// The number of bytes that represents the hash function's internal state.
public static var blockByteCount: Int {
128
}
private var context = BoringSSLSHA512256Context()
/// Creates a SHA512-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() {}
/// 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 data: UnsafeRawBufferPointer) {
if !isKnownUniquelyReferenced(&self.context) {
self.context = BoringSSLSHA512256Context(copying: self.context)
}
self.context.update(bufferPointer: data)
}
/// 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() -> SHA512256Digest {
self.context.finalize()
}
}
@@ -1,99 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2026 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
//
//===----------------------------------------------------------------------===//
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 256-bit digest
/// using the SHA-512/256 variant.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
public struct SHA512256Digest: Digest {
let bytes: (UInt64, UInt64, UInt64, UInt64)
/// The number of bytes in the digest.
public static var byteCount: Int {
32
}
init?(bufferPointer: UnsafeRawBufferPointer) {
guard bufferPointer.count == 32 else {
return nil
}
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0))
withUnsafeMutableBytes(of: &bytes) { targetPtr in
targetPtr.copyBytes(from: bufferPointer)
}
self.bytes = bytes
}
/// 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 {
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 {
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(SHA512256Digest.byteCount)
}
#if !hasFeature(Embedded)
/// A human-readable description of the digest.
public var description: String {
"SHA512-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 ``SHA512256/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) }
}
}
@@ -1,185 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Crypto
import SwiftASN1
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *)
extension Curve25519.Signing.PrivateKey {
/// A Distinguished Encoding Rules (DER) encoded representation of the private key.
public var derRepresentation: Data {
let pkey = ASN1.PKCS8PrivateKey(algorithm: .ed25519, privateKey: Array(self.rawRepresentation))
var serializer = DER.Serializer()
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
/// A Privacy-Enhanced Mail (PEM) representation of the private key.
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
/// Creates a Curve25519 private key for signing from a Privacy-Enhanced Mail
/// (PEM) representation.
///
/// - Parameters:
/// - pemRepresentation: A PEM representation of the key.
public init(pemRepresentation: String) throws {
let document = try ASN1.PEMDocument(pemString: pemRepresentation)
self = try .init(derRepresentation: document.derBytes)
}
/// Creates a Curve25519 private key for signing from a Distinguished Encoding
/// Rules (DER) encoded representation.
///
/// - Parameters:
/// - derRepresentation: A DER-encoded representation of the key.
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
let key = try ASN1.PKCS8PrivateKey(derEncoded: bytes)
self = try .init(rawRepresentation: key.privateKey.bytes)
}
}
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *)
extension Curve25519.Signing.PublicKey {
/// A Distinguished Encoding Rules (DER) encoded representation of the public key.
public var derRepresentation: Data {
let spki = SubjectPublicKeyInfo(algorithmIdentifier: .ed25519, key: Array(self.rawRepresentation))
var serializer = DER.Serializer()
try! serializer.serialize(spki)
return Data(serializer.serializedBytes)
}
/// A Privacy-Enhanced Mail (PEM) representation of the public key.
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PUBLIC KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
/// Creates a Curve25519 public key for signing from a Privacy-Enhanced Mail
/// (PEM) representation.
///
/// - Parameters:
/// - pemRepresentation: A PEM representation of the key.
public init(pemRepresentation: String) throws {
let document = try ASN1.PEMDocument(pemString: pemRepresentation)
self = try .init(derRepresentation: document.derBytes)
}
/// Creates a Curve25519 public key for signing from a Distinguished Encoding
/// Rules (DER) encoded representation.
///
/// - Parameters:
/// - derRepresentation: A DER-encoded representation of the key.
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
let spki = try SubjectPublicKeyInfo(derEncoded: bytes)
guard spki.algorithmIdentifier == .ed25519 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: spki.key.bytes)
}
}
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *)
extension Curve25519.KeyAgreement.PrivateKey {
/// A Distinguished Encoding Rules (DER) encoded representation of the private key.
public var derRepresentation: Data {
let pkey = ASN1.PKCS8PrivateKey(algorithm: .x25519, privateKey: Array(self.rawRepresentation))
var serializer = DER.Serializer()
// Serializing this key can't throw
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
/// A Privacy-Enhanced Mail (PEM) representation of the private key.
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
/// Creates a Curve25519 private key for key agreement from a Privacy-Enhanced Mail
/// (PEM) representation.
///
/// - Parameters:
/// - pemRepresentation: A PEM representation of the key.
public init(pemRepresentation: String) throws {
let document = try ASN1.PEMDocument(pemString: pemRepresentation)
self = try .init(derRepresentation: document.derBytes)
}
/// Creates a Curve25519 private key for key agreement from a Distinguished Encoding
/// Rules (DER) encoded representation.
///
/// - Parameters:
/// - derRepresentation: A DER-encoded representation of the key.
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
let key = try ASN1.PKCS8PrivateKey(derEncoded: bytes)
self = try .init(rawRepresentation: key.privateKey.bytes)
}
}
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *)
extension Curve25519.KeyAgreement.PublicKey {
/// A Distinguished Encoding Rules (DER) encoded representation of the public key.
public var derRepresentation: Data {
let spki = SubjectPublicKeyInfo(algorithmIdentifier: .x25519, key: Array(self.rawRepresentation))
var serializer = DER.Serializer()
try! serializer.serialize(spki)
return Data(serializer.serializedBytes)
}
/// A Privacy-Enhanced Mail (PEM) representation of the public key.
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PUBLIC KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
/// Creates a Curve25519 public key for key agreement from a Privacy-Enhanced Mail
/// (PEM) representation.
///
/// - Parameters:
/// - pemRepresentation: A PEM representation of the key.
public init(pemRepresentation: String) throws {
let document = try ASN1.PEMDocument(pemString: pemRepresentation)
self = try .init(derRepresentation: document.derBytes)
}
/// Creates a Curve25519 public key for key agreement from a Distinguished Encoding
/// Rules (DER) encoded representation.
///
/// - Parameters:
/// - derRepresentation: A DER-encoded representation of the key.
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
let spki = try SubjectPublicKeyInfo(derEncoded: bytes)
guard spki.algorithmIdentifier == .x25519 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: spki.key.bytes)
}
}
@@ -13,19 +13,19 @@
//===----------------------------------------------------------------------===//
import Crypto
import SwiftASN1
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import SwiftASN1
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *)
extension Curve25519.Signing.PrivateKey {
/// A Distinguished Encoding Rules (DER) encoded representation of the private key in PKCS#8 format.
public var pkcs8DERRepresentation: Data {
self.derRepresentation
let pkey = ASN1.PKCS8PrivateKey(algorithm: .ed25519, privateKey: Array(self.rawRepresentation))
var serializer = DER.Serializer()
// Serializing this key can't throw
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
}
@@ -33,7 +33,12 @@ extension Curve25519.Signing.PrivateKey {
extension Curve25519.KeyAgreement.PrivateKey {
/// A Distinguished Encoding Rules (DER) encoded representation of the private key in PKCS#8 format.
public var pkcs8DERRepresentation: Data {
self.derRepresentation
let pkey = ASN1.PKCS8PrivateKey(algorithm: .x25519, privateKey: Array(self.rawRepresentation))
var serializer = DER.Serializer()
// Serializing this key can't throw
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
}
@@ -1,87 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2026 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
//
//===----------------------------------------------------------------------===//
/// An internal protocol that exists to let us avoid problems with generic types.
///
/// The issue we have here is that we want to allow users to use whatever collection type suits them best to set
/// the passphrase. For this reason, ``_RSA/Signing/PrivateKey/PassphraseSetter`` is a generic function, generic over the `Collection`
/// protocol. However, that causes us an issue, because we need to stuff that callback into a
/// ``BoringSSLPassphraseCallbackManager`` in order to create an `Unmanaged` and round-trip the pointer through C code.
///
/// That makes ``BoringSSLPassphraseCallbackManager`` a generic object, and now we're in *real* trouble, because
/// `Unmanaged` requires us to specify the *complete* type of the object we want to unwrap. In this case, we
/// don't know it, because it's generic!
///
/// Our way out is to note that while the class itself is generic, the only function we want to call in the
/// ``globalBoringSSLPassphraseCallback`` is not. Thus, rather than try to hold the actual specific ``BoringSSLPassphraseCallbackManager``,
/// we can hold it inside a protocol existential instead, so long as that protocol existential gives us the correct
/// function to call. Hence: ``CallbackManagerProtocol``, a private protocol with a single conforming type.
internal protocol CallbackManagerProtocol: AnyObject {
func invoke(buffer: UnsafeMutableBufferPointer<CChar>) -> CInt
}
/// This class exists primarily to work around the fact that Swift does not let us stuff
/// a closure into an `Unmanaged`. Instead, we use this object to keep hold of it.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
final class BoringSSLPassphraseCallbackManager<Bytes: Collection>: CallbackManagerProtocol
where Bytes.Element == UInt8 {
private let userCallback: _RSA.Signing.PrivateKey.PassphraseCallback<Bytes>
init(userCallback: @escaping _RSA.Signing.PrivateKey.PassphraseCallback<Bytes>) {
// We have to type-erase this.
self.userCallback = userCallback
}
func invoke(buffer: UnsafeMutableBufferPointer<CChar>) -> CInt {
var count: CInt = 0
do {
try self.userCallback { passphraseBytes in
// If we don't have enough space for the passphrase plus NUL, bail out.
guard passphraseBytes.count < buffer.count else { return }
_ = buffer.initialize(from: passphraseBytes.lazy.map { CChar($0) })
count = CInt(passphraseBytes.count)
// We need to add a NUL terminator, in case the user did not.
buffer[Int(passphraseBytes.count)] = 0
}
} catch {
// If we hit an error here, we just need to tolerate it. We'll return zero-length.
count = 0
}
return count
}
}
/// Our global static BoringSSL passphrase callback. This is used as a thunk to dispatch out to
/// the user-provided callback.
func globalBoringSSLPassphraseCallback(
buf: UnsafeMutablePointer<CChar>?,
size: CInt,
rwflag: CInt,
u: UnsafeMutableRawPointer?
) -> CInt {
guard let buffer = buf, let userData = u else {
preconditionFailure(
"Invalid pointers passed to passphrase callback, buf: \(String(describing: buf)) u: \(String(describing: u))"
)
}
let bufferPointer = UnsafeMutableBufferPointer(start: buffer, count: Int(size))
guard let cbManager = Unmanaged<AnyObject>.fromOpaque(userData).takeUnretainedValue() as? CallbackManagerProtocol
else {
preconditionFailure("Failed to pass object that can handle callback")
}
return cbManager.invoke(buffer: bufferPointer)
}
+5 -68
View File
@@ -183,45 +183,6 @@ extension _RSA.Signing {
}
}
/// A ``_RSA/Signing/PrivateKey/PassphraseCallback`` is a callback that will be invoked by Swift Crypto when it needs to
/// get access to a private key that is stored in encrypted form.
///
/// This callback will be invoked with one argument, a non-escaping closure that must be called with the
/// passphrase. Failing to call the closure will cause decryption to fail.
///
/// The reason this design has been used is to allow you to secure any memory storing the passphrase after
/// use. We guarantee that after the ``_RSA/Signing/PrivateKey/PassphraseSetter`` closure has been invoked the `Collection`
/// you have passed in will no longer be needed by BoringSSL, and so you can safely destroy any memory it
/// may be using if you need to.
public typealias PassphraseCallback<Bytes: Collection> = (PassphraseSetter<Bytes>) throws -> Void where Bytes.Element == UInt8
/// An ``_RSA/Signing/PrivateKey/PassphraseSetter`` is a closure that you must invoke to provide a passphrase to BoringSSL.
/// It will be provided to you when your ``_RSA/Signing/PrivateKey/PassphraseCallback`` is invoked.
public typealias PassphraseSetter<Bytes: Collection> = (Bytes) -> Void where Bytes.Element == UInt8
/// Construct an RSA private key from an encrypted PEM representation.
///
/// This initializer accepts a callback that will be invoked with a closure that must be called
/// with the passphrase. This design allows you to securely manage passphrase memory after use.
/// After the ``_RSA/Signing/PrivateKey/PassphraseSetter`` closure has been invoked, the passphrase bytes you passed in
/// will no longer be needed, and you can safely destroy any memory it may be using.
///
/// - Parameters:
/// - encryptedPEMRepresentation: The encrypted PEM representation of the private key.
/// - passphraseCallback: A callback that will be invoked with a ``_RSA/Signing/PrivateKey/PassphraseSetter`` closure.
/// You must call the provided closure with the passphrase bytes.
///
/// - Throws: An error if the key could not be initialized or the passphrase is incorrect.
public init<T: Collection>(
encryptedPEMRepresentation: String,
passphraseCallback: @escaping PassphraseCallback<T>
) throws where T.Element == UInt8 {
self.backing = try BackingPrivateKey(
encryptedPEMRepresentation: encryptedPEMRepresentation,
passphraseCallback: passphraseCallback
)
}
/// Construct an RSA private key from a DER representation.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
@@ -547,7 +508,7 @@ extension _RSA.Encryption {
/// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons.
public init(unsafePEMRepresentation pemRepresentation: String) throws {
self.backing = try BackingPublicKey(pemRepresentation: pemRepresentation)
guard self.keySizeInBits >= 1024, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
guard self.keySizeInBits >= 2048, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
}
/// Construct an RSA public key from a DER representation.
@@ -694,7 +655,6 @@ extension _RSA.Encryption {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
public struct Padding: Sendable {
internal enum Backing {
case _weakAndInsecure_pkcs1v1_5
case pkcs1_oaep(Digest)
}
@@ -703,18 +663,7 @@ extension _RSA.Encryption {
private init(_ backing: Backing) {
self.backing = backing
}
/// PKCS#1 v1.5 padding
///
/// As defined by [RFC 8017 § 7.2](https://datatracker.ietf.org/doc/html/rfc8017#section-7.2).
///
/// This padding exists only for legacy compatibility and is known to be
/// weak and insecure. This algorithm is vulnerable to chosen-ciphertext
/// attacks outlined in http://archiv.infsec.ethz.ch/education/fs08/secsem/bleichenbacher98.pdf.
///
/// When you have a choice, you should always favor OAEP over this.
public static let _WEAK_AND_INSECURE_PKCS_V1_5 = Self(._weakAndInsecure_pkcs1v1_5)
/// PKCS#1 OAEP padding
///
/// As defined by [RFC 8017 § 7.1](https://datatracker.ietf.org/doc/html/rfc8017#section-7.1).
@@ -726,14 +675,6 @@ extension _RSA.Encryption {
internal enum Digest {
case sha1
case sha256
/// Returns the number of bits in the resulting hash
var hashBitLength: Int {
switch self {
case .sha1: return 160
case .sha256: return 256
}
}
}
}
@@ -753,7 +694,7 @@ extension _RSA.Encryption.PublicKey {
/// Return the maximum amount of data in bytes this key can encrypt in a single operation when using
/// the specified padding mode.
///
/// ## Common values (for PKCS1 OAEP SHA1):
/// ## Common values:
///
/// Key size|Padding|Max length
/// -|-|-
@@ -762,12 +703,8 @@ extension _RSA.Encryption.PublicKey {
/// 4096|PKCS-OAEP|470 bytes
public func maximumEncryptSize(with padding: _RSA.Encryption.Padding) -> Int {
switch padding.backing {
case ._weakAndInsecure_pkcs1v1_5:
// https://www.rfc-editor.org/rfc/rfc8017#section-7.2
return (self.keySizeInBits / 8) - 11
case let .pkcs1_oaep(Digest):
// https://datatracker.ietf.org/doc/html/rfc8017#section-7.1.1
return (self.keySizeInBits / 8) - (2 * Digest.hashBitLength / 8) - 2
case .pkcs1_oaep:
return (self.keySizeInBits / 8) - 42
}
}
+30 -63
View File
@@ -94,17 +94,6 @@ internal struct BoringSSLRSAPrivateKey: Sendable {
self.backing = try Backing(pemRepresentation: pemRepresentation)
}
init<T: Collection>(
encryptedPEMRepresentation: String,
passphraseCallback: @escaping _RSA.Signing.PrivateKey.PassphraseCallback<T>
) throws where T.Element == UInt8 {
let manager = BoringSSLPassphraseCallbackManager(userCallback: passphraseCallback)
self.backing = try Backing(
encryptedPEMRepresentation: encryptedPEMRepresentation,
callbackManager: manager
)
}
init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
self.backing = try Backing(derRepresentation: derRepresentation)
}
@@ -222,17 +211,17 @@ extension BoringSSLRSAPublicKey {
self.pointer = pointer
}
fileprivate convenience init(copying other: Backing) {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
fileprivate init(copying other: Backing) {
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
let rsaPublicKey = CCryptoBoringSSL_RSAPublicKey_dup(
CCryptoBoringSSL_EVP_PKEY_get0_RSA(other.pointer)
)
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
}
fileprivate convenience init(pemRepresentation: String) throws {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
fileprivate init(pemRepresentation: String) throws {
var pemRepresentation = pemRepresentation
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
// There are two encodings for RSA public keys: PKCS#1 and the SPKI form.
// The SPKI form is what we support for EC keys, so we try that first, then we
@@ -248,19 +237,23 @@ extension BoringSSLRSAPublicKey {
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
let rsaPublicKey = try pemRepresentation.withUTF8 { utf8Ptr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPublicKey(bio, nil, nil, nil) else {
throw CryptoKitError.internalBoringSSLError()
do {
let rsaPublicKey = try pemRepresentation.withUTF8 { utf8Ptr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPublicKey(bio, nil, nil, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
}
return key
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
CCryptoBoringSSL_EVP_PKEY_free(self.pointer)
throw error
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
}
}
fileprivate convenience init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
if derRepresentation.regions.count == 1 {
try self.init(contiguousDerRepresentation: derRepresentation.regions.first!)
@@ -270,8 +263,8 @@ extension BoringSSLRSAPublicKey {
}
}
private convenience init<Bytes: ContiguousBytes>(contiguousDerRepresentation: Bytes) throws {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
private init<Bytes: ContiguousBytes>(contiguousDerRepresentation: Bytes) throws {
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
// There are two encodings for RSA public keys: PKCS#1 and the SPKI form.
// The SPKI form is what we support for EC keys, so we try that first, then we
// fall back to the PKCS#1 form if that parse fails.
@@ -286,20 +279,25 @@ extension BoringSSLRSAPublicKey {
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
let rsaPublicKey = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
guard let key = CCryptoBoringSSL_d2i_RSAPublicKey_bio(bio, nil) else {
throw CryptoKitError.internalBoringSSLError()
do {
let rsaPublicKey = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
guard let key = CCryptoBoringSSL_d2i_RSAPublicKey_bio(bio, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
}
return key
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
CCryptoBoringSSL_EVP_PKEY_free(self.pointer)
throw error
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
}
}
fileprivate convenience init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
fileprivate init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
let n = try ArbitraryPrecisionInteger(bytes: n)
let e = try ArbitraryPrecisionInteger(bytes: e)
@@ -420,8 +418,6 @@ extension BoringSSLRSAPublicKey {
CCryptoBoringSSL_EVP_PKEY_encrypt_init(ctx)
switch padding.backing {
case ._weakAndInsecure_pkcs1v1_5:
CCryptoBoringSSL_EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING)
case let .pkcs1_oaep(digest):
CCryptoBoringSSL_EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING)
switch digest {
@@ -606,33 +602,6 @@ extension BoringSSLRSAPrivateKey {
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPrivateKey)
}
fileprivate init(
encryptedPEMRepresentation: String,
callbackManager: CallbackManagerProtocol
) throws {
var encryptedPEMRepresentation = encryptedPEMRepresentation
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
let rsaPrivateKey = try encryptedPEMRepresentation.withUTF8 { utf8Ptr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
let key = withExtendedLifetime(callbackManager) { callbackManager -> OpaquePointer? in
CCryptoBoringSSL_PEM_read_bio_RSAPrivateKey(
bio,
nil,
{ globalBoringSSLPassphraseCallback(buf: $0, size: $1, rwflag: $2, u: $3) },
Unmanaged.passUnretained(callbackManager as AnyObject).toOpaque()
)
}
guard let key else {
throw CryptoKitError.internalBoringSSLError()
}
return key
}
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPrivateKey)
}
fileprivate convenience init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
if derRepresentation.regions.count == 1 {
try self.init(contiguousDerRepresentation: derRepresentation.regions.first!)
@@ -914,8 +883,6 @@ extension BoringSSLRSAPrivateKey {
CCryptoBoringSSL_EVP_PKEY_decrypt_init(ctx)
switch padding.backing {
case ._weakAndInsecure_pkcs1v1_5:
CCryptoBoringSSL_EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING)
case let .pkcs1_oaep(digest):
CCryptoBoringSSL_EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING)
switch digest {
@@ -1,29 +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
//
//===----------------------------------------------------------------------===//
#if !canImport(Darwin)
@_implementationOnly import CCryptoBoringSSL
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
typealias errno_t = CInt
// This is a Swift wrapper for the libc function that does not exist on Linux. We shim it via a call to OPENSSL_cleanse.
// We have the same syntax, but mostly ignore it.
@discardableResult
func memset_s(_ s: UnsafeMutableRawPointer!, _ smax: Int, _ byte: CInt, _ n: Int) -> errno_t {
assert(smax == n, "memset_s invariant not met")
assert(byte == 0, "memset_s used to not zero anything")
CCryptoBoringSSL_OPENSSL_cleanse(s, smax)
return 0
}
#endif
@@ -125,10 +125,3 @@ extension SubjectPublicKeyInfo {
return serializer.serializedBytes
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension RFC5480AlgorithmIdentifier {
static let ed25519 = RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEd25519, parameters: nil)
static let x25519 = RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idX25519, parameters: nil)
}
@@ -163,85 +163,6 @@ final class CBCTests: XCTestCase {
}
}
func testDecryptRejectsPaddingLengthGreaterThanBlockSize() throws {
// A plaintext whose final block claims a PKCS#7 pad length of 17 (0x11)
// is invalid for a 16-byte block: the maximum valid PKCS#7 pad is one
// full block (16). Correct unpadding must reject it. Regression guard:
// the previous `trimPadding` accepted any pad length up to 255 and
// scanned across blocks, so it wrongly stripped 17 bytes here.
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// 32-byte (block-multiple) plaintext ending in 17 bytes of 0x11.
var plaintext = Data(repeating: 0xAB, count: 15)
plaintext.append(Data(repeating: 0x11, count: 17))
precondition(plaintext.count == 32)
let ciphertext = try AES._CBC.encrypt(plaintext, using: key, iv: iv, noPadding: true)
XCTAssertThrowsError(
try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false)
) { error in
guard let error = error as? CryptoKitError, case .incorrectParameterSize = error else {
XCTFail("Unexpected error: \(error)")
return
}
}
}
func testUnpadAcceptsAllValidPaddingLengths() throws {
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// For every valid PKCS#7 pad length (1...16), round-trip a message that
// pads to exactly that length and assert exact recovery.
for padLength in 1...16 {
let messageLength = 32 - padLength // pads to 32 bytes (two blocks)
let message = Data((0..<messageLength).map { UInt8(truncatingIfNeeded: $0) })
let ciphertext = try AES._CBC.encrypt(message, using: key, iv: iv, noPadding: false)
let decrypted = try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false)
XCTAssertEqual(decrypted, message, "round-trip failed for pad length \(padLength)")
}
}
func testUnpadRejectsCorruptedPaddingByte() throws {
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// Build a validly-padded block-multiple plaintext, then corrupt each
// padding byte except the last (which encodes the claimed length). The
// constant-time scan must reject a mismatch at any position.
for padLength in 2...16 {
var padded = Data((0..<(32 - padLength)).map { UInt8(truncatingIfNeeded: $0) })
padded.append(Data(repeating: UInt8(padLength), count: padLength))
precondition(padded.count == 32)
for position in (32 - padLength)..<31 {
var corrupted = padded
corrupted[position] = UInt8(padLength) ^ 0xFF // guaranteed != padLength
let ciphertext = try AES._CBC.encrypt(corrupted, using: key, iv: iv, noPadding: true)
XCTAssertThrowsError(
try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false),
"corruption at pad length \(padLength), position \(position) was not rejected"
)
}
}
}
func testUnpadRejectsZeroPaddingLength() throws {
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// A final byte of 0x00 claims a pad length of zero, which is invalid PKCS#7.
var padded = Data((0..<31).map { UInt8(truncatingIfNeeded: $0) })
padded.append(0x00)
let ciphertext = try AES._CBC.encrypt(padded, using: key, iv: iv, noPadding: true)
XCTAssertThrowsError(try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false))
}
func testToDataConversion() throws {
let randomBytes = (0..<16).map { _ in UInt8.random(in: UInt8.min...UInt8.max) }
let dataIn = Data(randomBytes)
+1 -6
View File
@@ -13,13 +13,8 @@
//===----------------------------------------------------------------------===//
import Crypto
import CryptoExtras
import XCTest
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import XCTest
final class CMACTests: XCTestCase {
// Borrowed from CryptoKit
@@ -1,91 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import CryptoExtras
import XCTest
final class Curve25519DERTests: XCTestCase {
func testSigningPrivateKeyDERRoundTrip() throws {
let privateKey = Curve25519.Signing.PrivateKey()
let der = privateKey.derRepresentation
let imported = try Curve25519.Signing.PrivateKey(derRepresentation: der)
XCTAssertEqual(imported.rawRepresentation, privateKey.rawRepresentation)
}
func testSigningPublicKeyDERRoundTrip() throws {
let privateKey = Curve25519.Signing.PrivateKey()
let publicKey = privateKey.publicKey
let der = publicKey.derRepresentation
let imported = try Curve25519.Signing.PublicKey(derRepresentation: der)
XCTAssertEqual(imported.rawRepresentation, publicKey.rawRepresentation)
}
func testKeyAgreementPrivateKeyDERRoundTrip() throws {
let privateKey = Curve25519.KeyAgreement.PrivateKey()
let der = privateKey.derRepresentation
let imported = try Curve25519.KeyAgreement.PrivateKey(derRepresentation: der)
XCTAssertEqual(imported.rawRepresentation, privateKey.rawRepresentation)
}
func testKeyAgreementPublicKeyDERRoundTrip() throws {
let privateKey = Curve25519.KeyAgreement.PrivateKey()
let publicKey = privateKey.publicKey
let der = publicKey.derRepresentation
let imported = try Curve25519.KeyAgreement.PublicKey(derRepresentation: der)
XCTAssertEqual(imported.rawRepresentation, publicKey.rawRepresentation)
}
func testInvalidDERThrows() throws {
let invalidDER: [UInt8] = [0x01, 0x02, 0x03]
XCTAssertThrowsError(try Curve25519.Signing.PrivateKey(derRepresentation: invalidDER))
XCTAssertThrowsError(try Curve25519.Signing.PublicKey(derRepresentation: invalidDER))
XCTAssertThrowsError(try Curve25519.KeyAgreement.PrivateKey(derRepresentation: invalidDER))
XCTAssertThrowsError(try Curve25519.KeyAgreement.PublicKey(derRepresentation: invalidDER))
}
func testImportOpenSSLSigningPrivateKeyDER() throws {
// DER extracted from an OpenSSL-generated Ed25519 PKCS#8 PEM
let derBytes: [UInt8] = [
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70,
0x04, 0x22, 0x04, 0x20, 0x3f, 0x10, 0x52, 0x03, 0xb4, 0x06, 0x87, 0x0c,
0x51, 0x71, 0xfa, 0xdc, 0x8f, 0x96, 0xbd, 0x2a, 0x5f, 0x42, 0xac, 0x5c,
0xb9, 0x5b, 0x27, 0x4e, 0xf0, 0x06, 0xe5, 0x61, 0x6a, 0x12, 0x00, 0xa5,
]
let key = try Curve25519.Signing.PrivateKey(derRepresentation: derBytes)
XCTAssertEqual(key.rawRepresentation.count, 32)
}
func testImportOpenSSLKeyAgreementPrivateKeyDER() throws {
// DER extracted from an OpenSSL-generated X25519 PKCS#8 PEM
let derBytes: [UInt8] = [
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e,
0x04, 0x22, 0x04, 0x20, 0xb8, 0x38, 0x3f, 0x28, 0xea, 0x8f, 0x1d, 0x71,
0x49, 0xa2, 0xa3, 0x91, 0x37, 0x00, 0xa1, 0x0c, 0x7c, 0x9d, 0xa9, 0x59,
0x28, 0x2d, 0x14, 0x7e, 0x9b, 0x1e, 0x1b, 0x8c, 0x04, 0xa5, 0xd8, 0x47,
]
let key = try Curve25519.KeyAgreement.PrivateKey(derRepresentation: derBytes)
XCTAssertEqual(key.rawRepresentation.count, 32)
}
}
@@ -1,140 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import CryptoExtras
import XCTest
final class Curve25519PEMTests: XCTestCase {
func testSigningPrivateKeyPEMRoundTrip() throws {
let privateKey = Curve25519.Signing.PrivateKey()
let imported = try Curve25519.Signing.PrivateKey(pemRepresentation: privateKey.pemRepresentation)
XCTAssertEqual(imported.rawRepresentation, privateKey.rawRepresentation)
}
func testSigningPublicKeyPEMRoundTrip() throws {
let privateKey = Curve25519.Signing.PrivateKey()
let publicKey = privateKey.publicKey
let imported = try Curve25519.Signing.PublicKey(pemRepresentation: publicKey.pemRepresentation)
XCTAssertEqual(imported.rawRepresentation, publicKey.rawRepresentation)
}
func testKeyAgreementPrivateKeyPEMRoundTrip() throws {
let privateKey = Curve25519.KeyAgreement.PrivateKey()
let imported = try Curve25519.KeyAgreement.PrivateKey(pemRepresentation: privateKey.pemRepresentation)
XCTAssertEqual(imported.rawRepresentation, privateKey.rawRepresentation)
}
func testKeyAgreementPublicKeyPEMRoundTrip() throws {
let privateKey = Curve25519.KeyAgreement.PrivateKey()
let publicKey = privateKey.publicKey
let imported = try Curve25519.KeyAgreement.PublicKey(pemRepresentation: publicKey.pemRepresentation)
XCTAssertEqual(imported.rawRepresentation, publicKey.rawRepresentation)
}
func testImportOpenSSLSigningPrivateKeyPEM() throws {
// Generated via `openssl genpkey -algorithm Ed25519 -outform PEM`
let pem = """
-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VwBCIEIIHEchKSA2A/z1r4tVHJ9f+yS6YXhUbBdHJiryZnRqnD
-----END PRIVATE KEY-----
"""
let key = try Curve25519.Signing.PrivateKey(pemRepresentation: pem)
XCTAssertEqual(key.rawRepresentation.count, 32)
}
func testImportOpenSSLKeyAgreementPrivateKeyPEM() throws {
// Generated via `openssl genpkey -algorithm X25519 -outform PEM`
let pem = """
-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VuBCIEIMDJoDr+3A91QpL8BLIeCKSAKI5T7frtzEaE5HzugtR1
-----END PRIVATE KEY-----
"""
let key = try Curve25519.KeyAgreement.PrivateKey(pemRepresentation: pem)
XCTAssertEqual(key.rawRepresentation.count, 32)
}
func testInvalidPEMThrows() {
let invalidPEM = """
-----BEGIN PRIVATE KEY-----
abc
-----END PRIVATE KEY-----
"""
XCTAssertThrowsError(try Curve25519.Signing.PrivateKey(pemRepresentation: invalidPEM))
XCTAssertThrowsError(try Curve25519.KeyAgreement.PrivateKey(pemRepresentation: invalidPEM))
let invalidPublicPEM = """
-----BEGIN PUBLIC KEY-----
xyz
-----END PUBLIC KEY-----
"""
XCTAssertThrowsError(try Curve25519.Signing.PublicKey(pemRepresentation: invalidPublicPEM))
XCTAssertThrowsError(try Curve25519.KeyAgreement.PublicKey(pemRepresentation: invalidPEM))
}
func testWrongAlgorithmOIDThrows() throws {
XCTAssertThrowsError(try Curve25519.Signing.PrivateKey(pemRepresentation: rsaPEM))
XCTAssertThrowsError(try Curve25519.KeyAgreement.PublicKey(pemRepresentation: rsaPEM))
}
func testSigningPrivatePublicKeyConsistency() throws {
let privateKey = Curve25519.Signing.PrivateKey()
let publicKey = privateKey.publicKey
let importedPrivate = try Curve25519.Signing.PrivateKey(pemRepresentation: privateKey.pemRepresentation)
let importedPublic = try Curve25519.Signing.PublicKey(pemRepresentation: publicKey.pemRepresentation)
XCTAssertEqual(importedPrivate.publicKey.rawRepresentation, importedPublic.rawRepresentation)
}
func testKeyAgreementPrivatePublicKeyConsistency() throws {
let privateKey = Curve25519.KeyAgreement.PrivateKey()
let publicKey = privateKey.publicKey
let importedPrivate = try Curve25519.KeyAgreement.PrivateKey(pemRepresentation: privateKey.pemRepresentation)
let importedPublic = try Curve25519.KeyAgreement.PublicKey(pemRepresentation: publicKey.pemRepresentation)
XCTAssertEqual(importedPrivate.publicKey.rawRepresentation, importedPublic.rawRepresentation)
}
let rsaPEM = """
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDL8W1D9w5zHpmD
JqpTngIRJ+Sm21e42cRnTudhdejzKUiJQWkHSvQV5yC/+0iEXUsUJYEdSyrKhJFD
PT+IFGdjIiwb7IX+rUreWXlD/YYBL3/byMG4kYoO4oiPp2A+WvfeyLpuN549OXhk
7o5kXEZjKfjHTfmnAbCMoYW5BEpiHQC3HAeJZ5EiwAn8HZn5UY6lxJcf7H9hR83x
D0W7IZTNyxUu4aLNuihFIxJKgP/L/y95Y6ddZsyyHQopM43/7JOYBwufa07MWaxi
AdBdq1bR/ZeOt2aZaXhV+J6QUoUO8Z6fG6b2cQmvMgk4ybqoeciLII0DfFsyqavu
ip4hRr59AgMBAAECggEAUIw994XwMw922hG/W98gOd5jtHMVJnD73UGQqTGEm+VG
PM+Ux8iWtr/ec3Svo3elW4OkhwlVET9ikAf0u64zVzf769ty4K9YzpDQEEZlUrqL
6SZVPKxetppKDVKx9G7BT0BAQZ+947h7EIIXwxOeyTOeijkFzSwhqqlwwy4qoqzV
FTQS20QHE62hxzwuS5HBqw8ds183qAg9NbzR0Cp4za9qTiBB6C8KEcLqeatO+q+d
VCDsJcAMZOvW14N6BozKgbQ/WXZQ/3kNUPBndZLzzqaILFNmB1Zf2DVVJ9gU7+EK
xOac60StIfG81NllCTBrmRVq8yitNqwmutHMlxrIkQKBgQDvp39MkEHtNunFGkI5
R8IB5BZjtx5OdRBKkmPasmNU8U0XoQAJUKY/9piIpCtRi87tMXv8WWmlbULi66pu
4BnMIisw78xlIWRZTSizFrkFcEoVgEnbZBtSrOg/J5PAcjLEGCQoAdmMXAekR2/m
htv7FPijHPNUjyIFLaxwjl9izwKBgQDZ2mQeKNRHjIb5ZBzB0ZCvUy2y4+kaLrhZ
+CWMN1flL4dd1KuZKvCEfHY9kWOjqw6XneN4yT0aPmbBft4fihiiNW0Sm8i+fSpy
g0klw2HJl49wnwctBpRgTdMKGo9n14OGeu0xKOAy7I4j1tKrUXiRWnP9R583Ti7c
w7YHgdHM8wKBgEV147SaPzF08A6bzMPzY2zO4hpmsdcFoQIsKdryR04QXkrR9EO+
52C0pYM9Kf0Jq6Ed7ZS3iaJT58YDjjNyqqd648/cQP6yzfYAIiK+HERSRnay5zU6
b5zn1qyvWOi3cLVbVedumdJPvjtEJU/ImKvOaT5FntVMYwzjLw60hTsLAoGAZJnt
UeAY51GFovUQMpDL96q5l7qXknewuhtVe4KzHCrun+3tsDWcDBJNp/DTymjbvDg1
KzoC9XOLkB8+A+KJrZ5uWAGImi7Cw07NIJsxNR7AJonJjolTS4Wkxy2su49SNW/e
yKzPm7SRjwtNDb/5pWXX2kaQx8Fa8qeOD7lrYPECgYAwQ6o0vYmr+L1tOZZgMVv9
Jusa8beVUH5hyduJjmxbYOtFTkggAozdx7rs4BgyRsmDlV48cEmcVf/7IH4gMJLb
O+bbERwCYUChe+piANhnwfwDHzbRd8mmQus54P06X7bWu6Rmi7gbQGVN/Z6VhbIm
D2cOo0w4bk/3yb01xz1MEw==
-----END PRIVATE KEY-----
"""
}
@@ -11,14 +11,8 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Crypto
import XCTest
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import XCTest
#if !canImport(Darwin) || canImport(CryptoKit, _version: 241.100.42)
// Corresponds to the CryptoKit in XCode 16.3, which has Sendable annotations
@@ -1,130 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import CryptoExtras
import XCTest
final class EncryptedPEMTests: XCTestCase {
func testPBES2WithAES128EncryptedKeyInit() {
let pbes2WithAES128EncryptedPrivateKey = """
-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIHdTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQKnlnfHXtFrPkA7CL
baNwHwICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEAQIEELh7hPDbkABq2rBg
JHwZWXkEggcQipM8HDYRIsCGvTagGSuVmlvxnojkkTD3LlyjOFpPvo6KCYeyiPUv
MgiS+JrFjV3wNgz+s33yqFcXz57u7w2F/YnKg5G04C4LyAfDx0COSraag7iDivy3
sX8wigmGuiR5ZpxY64E4yPaawKyFPqdepubJmfyXaOfAY5tZ6OdurEJvr0ddLIni
xYHufjW7fr8WIX34oamvoWkfaGNKXqvrpiZQ7ibR5Yw8Of+scHSogXdaYXYvZa21
9R6XE5LLCy2R8IvrUorcJYPcJgHUisK0ph4GTloL5qoWywHiTAtdylfanIn3TWa1
Dbj2Q97kepDAQBflbw+ChYaY3zOAue5EIlpMEToCP3BYU8IqEbPtE+J7Vpimrqrl
mLq9LFiipRXHabcQxRryK+nO3b9NI5IBmXKpBukiOUa9VjNZqMYkqneE90kJeAyE
cI2mrZ3JeMoLeG7CTbJ7yC16snA/ZBx9491JIVztJcuCw8DClBaEoP+wRhykmW35
/5IFOxDPp9d5a/spbXIHwQf22JIx6EoudABzigHt6RFRQiRdxi9H1DUciuCarz5Y
Oeg/+4R/iOlHCxMyu+zZn2L7o2UfOZspLJz3/6GQseMiZxqPxqgHOlD2mKBrtxPn
DjMVbUz3NhBH+tK6DXl8TbFhMPjlCDLkuZIjf8CIkDsEgVgMXmORb3e96vYFVfcC
659G1uAUyto1MyiGZ5QYLumFLC3sjqhGT8NWLI76HwWB+hxMSWLldjFFOyUx9SeB
WKvJ9++83LoYlm6jZ6hvi+PQ3JkwV1oIRlFxVCKj5+XwR0sOL5Im5zDNoXjQjIB2
7jILO6DQcFRhyxWjqNZ07nE3PpJ9N1kcRCgAwu837uQRq+8M+Nqc0W2IwxAyRelB
+TDO+v9dV0AL/HLoWzlyKYlOXxFovBYfjJEoxBnUP0/APuMnE2nnTN/qQSLZ/c3M
IWyfsoLsZEjWt9JEoERXVgCFelFEvIiqp/GBRNeaAArlr4Xe1JKB4aqIL9zN8oMr
pLyXyKivkVQ8uZ2pMFLtvjtZvy/j+yF1MHJBU5tKxwNs7Sv7/DED8k3gdk1WpbhZ
E2tRk+Hud0WpY39UIsxBE229WQgmUr6bEJbEeAPkkKR7s4/1Gs/U3cfmjjSWkg8P
8ETag2xJlnh4gY1tXOTPyLeRPLysOyXAkp83/DG88OhjmG5sH2jMtrLjL76Pwpl1
zVKqC8CCWs3iC2OeQmcvktwfJ5IzqfPHZkJnS/Y0lnGH/WnK2ijJ1mUs3ppiwFS6
fs8RSF9P2F1hpL2R73cCJAnwB6koq2qAwDIT8wq1cYOyGemuaq/0BJaBLNkM1+Hm
o82OuVURRkD4ZL8JhsKx2yaz9sONs+F7V50IZr8gZqP4dwunZ0KvK7u18aCz/vhx
tebPowd8JLRnZJAZN9JmthZepvVWUsIawR8E8RqJnowCIMaB1ujAsU6K7jvNhLAx
dEewmb5M1Q/QSX4y+3WaAphD6Z8jcKn14GMbRXa/cq/4ZEYKMsxzlhE3AftUVh6e
907C7DBN74wXzd/WO30yaeOIJuiCGa7VGhIFkfwebnZsFv/YTMB5pkDXbjCSQY5+
wRzxpl6H8gtnZVQjT2qNvLtQco9QyDCcwuCAAoohdWQbyOuwO07/g1ZWAekzFNNk
OR0d4N6XDJDIJXpdah8PbJb3N0QJ+ug871V+HntJxEuh9Wv5JbK268WCG/scQN5a
ER5FgaBeuSKhVPbA0bFqwVSgcpJL65eLVrytNXvhu1LyWssZf8qqEWw2n+mbBHro
a4yYSFseG50xEBlgjSX0+fghAbrguB6aEgcHo36a+N5pA7PuFULpG/tEX7xYoB3z
gwS7f1JAzXZOvi/fraUOrOpVDjIadX6imXYETVYA7fxMLNSQeLU1gabepAzgrRG8
PuI5KxfkQWoEt36EqroetOq/fZ62KiZEKZ4cOMFM8BvpszhAWYpVDw9nWVnCcV1C
eJ7DDwjsTM+qEG92ZA/XGGiLiwjrknXDQsthJdzFrNuNoMi2pZjFvJK/hnHEp/oK
ffwNo7nN4lCK0bF7pdpQLhEBjDDh5WYkTPo8wWl9xACUfeh28Pc2vhzHJS9+tYZL
Zzx815NI2jUvein/kJ5GqEeY/FG1W/yGvnzi3aqt/T7s55pVk9IGApAYG06OGNlI
4C7dJowCXT86oA6svOFmrJUobm7wMCdyutG646pX3VEmo24aPNwW1ieQ5a0w/Vf1
rgT1F55lnTKCivV/AA3wYKiaKRylu6MTnoJ+lIq4T7oMs8IZj6oHo3jAU/kMYdnb
MKxahISGpACyQYRsH4PEkGB2ZDzzaKW+yLPIrH4YgloGzZd1Q3kIKmfZKoYmystn
Ark25aRyIIVDu0KcIx4kAp11hmkf72NPQ3f9zaFZV+gys0VA3r1bRhs=
-----END ENCRYPTED PRIVATE KEY-----
"""
XCTAssertNoThrow(
try _RSA.Signing.PrivateKey(
encryptedPEMRepresentation: pbes2WithAES128EncryptedPrivateKey
) { passphraseSetter in
passphraseSetter("foobar".utf8)
}
)
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey(
encryptedPEMRepresentation: pbes2WithAES128EncryptedPrivateKey
) { passphraseSetter in
passphraseSetter("wrong".utf8)
}
)
}
func testPBES2WithTripleDESKeyEncryptedKeyInit() {
let pbes2WithTripleDESEncryptedPrivateKey = """
-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIFJDBWBgkqhkiG9w0BBQ0wSTAxBgkqhkiG9w0BBQwwJAQQ8HZLW3BDKXdsGjxA
5BM8GgICCAAwDAYIKoZIhvcNAgkFADAUBggqhkiG9w0DBwQIUo0QnIb9O+wEggTI
GqGG0X9OWxs8opGqJ6ynfJzCUy1TJh9CGJgBBVOMS8zqz7qAkBCKhT+VPCtn7W0g
GTf+OhOkj7YnmN/GSwbih/O33NFXoVQrP+kJOTRYFne2zVQ5KvG48oN3P7T4tHMP
zRqq7+qpz6Y0906z/6RmVZWEPryAb0xYEd2DhdX4wBMyHfTf28u10ivEsfTWa5/5
/n4ENmwAce2MLUbvNGgtXvgbiDn5ITj17Reyal3hTzRoL3J6kLj6xFpBkaAAvvQP
O8FGaVuvi4seeWPVAwwuksRiCwA+wPi3eyREPwG8Q4tS2IKwJqUrbPjrIhxl7HwK
bb2iaQ+es+FZIHXHWvfWiEUyDs2OMcErlUqx8Qaf9K/3o8KFdyqZ7qOKNjK+Z0BC
AHelXjvO62N/sNoK8318LYOkCZ1Wd820JdSTac3AVy9BGQRu7GfhcpjjNbOxsjhz
HSnrZR8PIRNujTyLC8b2fzsTpDNLUE6KYiNzZWfUDOVMmm9xi64kwCMvsKsLd47n
4VdaPHaqqSA3XkXIDyqAZUKo6r2CUkJH6CYKuVLl6GsA6lLFxVCHtdbQu6MopymO
0+XkLTJrZItEB4ZIbtG88/ubnYOPqOn7Jvi7W8TEDBXw9inGO4osj7wSnWNEsTRx
8P/uF9ygpKTANuR84welaJk6c3pxf96esfmxkp7XxGdRx9o0OWbSqB1C4LUjWmKs
LpPF8TvnzFlZyfyW5VyzOs8/4zNO7B0S6X5Ywwytobo0G0/6/eilFIPGZfLTz7gw
2LPMYKgi+OjE27KGUS3fSDlVkcQqrfrADchtEM6bSYHU1B0K8QE2bkRVM97DRVTv
lngqxvr9yeE+ILCGOf/kTfqGqvoampUUUUMi8is80oSlSVApYiZ3uWJWOMsHlH7X
H1sONAARzhbm+BQ7QRFTH41mMmHIzNSuXVYItRxbC4VkbRqMzLCfZtsCCZ7Mupo7
a9FdDMDsLeA28EDTESzWEPREk4i0wvJ1QRLdQFJ9GL+RP/YsV1GEwRqHu9lsZCAL
Oz83V41/NfSuTrykZFKaLA2D4DjVGbyinxxcThUL/3u3k98EjBKdfMj6wMF8hKCx
eYvowNOJUdMG3+i7Bo5rKhKZ5mIeRP3MGvelvSQ8gXm03pM255iDV441Ir4F/mpJ
TaMXySqhZef4Ls6tkxsq7E2mXhsPkJVy/hSmnbqZi3FltMGvkbiM3aqNJQcG67mO
NX66Zlbb8JHi6OG8o7H3u6i3BTeyvQkPO0n+sUWrYo1vqemykDUHAdqLdSIdC4pb
kCvRncCw729CD1B3IVkvSZ6NTqNxGCqmc1g/6bkqCaNOXXOqiT4Fzxxv+FCt2sGf
m2G8BvdBVILRRVSGgmG7ahvIY5O+911duS6vkzoxF39VJjrYXcqzKRh71zfAM3J0
h9GLgrI+lZ7HYCi4eDsSMOdARfL6C7beA6Jaa4snHfGNNrwCECuV0zKrB61n33nN
wE1Nc+gPZ4rbYeYUa8EvdchNB5JdMTyKqOAHrHrM4EberwnZAZMk4Aal/PLAup5L
mrdalZF0qlLUetwUPmAGMuW34igiV084ecKxsuZWXvKtLTHhiTN4NYBgV2rvJ2LE
PRiLIoKv+M+qjywhjPeQbD70byOdIx5J
-----END ENCRYPTED PRIVATE KEY-----
"""
XCTAssertNoThrow(
try _RSA.Signing.PrivateKey(
encryptedPEMRepresentation: pbes2WithTripleDESEncryptedPrivateKey
) { passphraseSetter in
passphraseSetter("foobar".utf8)
}
)
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey(
encryptedPEMRepresentation: pbes2WithTripleDESEncryptedPrivateKey
) { passphraseSetter in
passphraseSetter("wrong".utf8)
}
)
}
}
@@ -13,16 +13,11 @@
//===----------------------------------------------------------------------===//
import Crypto
import Foundation
import XCTest
@testable import CryptoExtras
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
final class PKCS8DERRepresentationTests: XCTestCase {
func test_RSA() {
let rsaPrivateKeyPEM = """
@@ -1,97 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Crypto
import CryptoExtras
import XCTest
final class SHA512256DigestTests: XCTestCase {
func testHashFunction() throws {
let data =
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"
.data(using: .ascii)!
var hasher = SHA512256()
hasher.update(data: data)
let digest = hasher.finalize()
let expected = try Array(hexString: "3928e184fb8690f840da3988121d31be65cb9d3ef83ee6146feac861e19b563a")
XCTAssertEqual(Array(digest), expected)
XCTAssertEqual(Array(SHA512256.hash(data: data)), expected)
let (contiguousResult, discontiguousResult) = expected.asDataProtocols()
XCTAssert(digest == contiguousResult)
XCTAssert(digest == discontiguousResult)
XCTAssertFalse(digest == DispatchData.empty)
}
func testNullHash() throws {
let digest = SHA512256.hash(data: Data())
let expected = try Array(hexString: "c672b8d1ef56ed28ab87c3622c5114069bdd3ad7b8f9737498d0c01ecef0967a")
XCTAssertEqual(Array(digest), expected)
}
func testABC() throws {
let digest = SHA512256.hash(data: "abc".data(using: .ascii)!)
let expected = try Array(hexString: "53048e2681941ef99b2e29b76b4c7dabe4c2d0c634fc6d46e0e2f13107e7af23")
XCTAssertEqual(Array(digest), expected)
}
func testTwoBlockMessage() throws {
let data = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopmopq".data(using: .ascii)!
let digest = SHA512256.hash(data: data)
let expected = try Array(hexString: "35de8c8794b9ed4b463c257fe50e62b516e07976a2931f4f78f1cd69a456dccd")
XCTAssertEqual(Array(digest), expected)
}
func testSingleByte() throws {
let digest = SHA512256.hash(data: Data([0x61]))
let expected = try Array(hexString: "455e518824bc0601f9fb858ff5c37d417d67c2f8e0df2babe4808858aea830f8")
XCTAssertEqual(Array(digest), expected)
}
func testRepeatedBytes() throws {
let data = Data(repeating: 0x61, count: 1_000_000)
let digest = SHA512256.hash(data: data)
let expected = try Array(hexString: "9a59a052930187a97038cae692f30708aa6491923ef5194394dc68d56c74fb21")
XCTAssertEqual(Array(digest), expected)
}
func testCopyOnWrite() {
var hasher = SHA512256()
hasher.update(data: [1, 2, 3, 4])
var copy = hasher
hasher.update(data: [5, 6, 7, 8])
let digest = hasher.finalize()
copy.update(data: [5, 6, 7, 8])
let copyDigest = copy.finalize()
XCTAssertEqual(digest, copyDigest)
}
func testBlockSize() {
XCTAssertEqual(SHA512256.blockByteCount, 128)
}
func testDigestByteCount() {
XCTAssertEqual(SHA512256Digest.byteCount, 32)
}
}
@@ -140,95 +140,6 @@ final class TestRSAEncryption: XCTestCase {
XCTAssertEqual(primitives.publicExponent, e)
}
}
func testMaximumEncryptSize() throws {
let pemRepresentation1024 = """
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTLbu1QZhtXWKCHOjavP5NUCwJ
5DwjoMKGlEM/PQOMiY+wup8R1kCOHV6g+FvJ86laHJc0gqwFf1U51YxtQFy7cGV4
W2zJeTkqadO2fvTCjbZU+Oa78iVtTynq5h4yRWrTmveyzInhdVpi075Ql2hpGuET
H1qYVxqaDIJEHyETDQIDAQAB
-----END PUBLIC KEY-----
"""
let pubKey1024 = try _RSA.Encryption.PublicKey(unsafePEMRepresentation: pemRepresentation1024)
XCTAssertEqual(86, pubKey1024.maximumEncryptSize(with: .PKCS1_OAEP))
XCTAssertEqual(62, pubKey1024.maximumEncryptSize(with: .PKCS1_OAEP_SHA256))
let pemRepresentation2048 = """
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx8IRKcs5FrHlWye2lfwc
Hr0Pi8g5iZhGMOOwmyIVsNULAvUIGZlIw38NNqebH3eF6ZxPiSRpwPwIs6QRcH5/
IwbHkUc0KdBbUwXDrLs0w00I7Flu5RP7IEfkOZdDGEWFY1pA3H1HaogxKFc5k3mM
s7pW6oty1eP4O7aVa/Pp363Vba7EZ2nru9lz4Ta+JU8UIHbpoddMGikGEKHrQ/Ge
n9RMNzSIy/e7TgTwC39GKn8fwN6VfcdNjvIhJrFNha/ORNArpzup7FUUauGLKt3a
jgsIjrAPBp63+Sy7+aFVoGTvI7DCkZ/Wv3JCFRuTAdYOa0A1xiqhTb1pcypvrd2T
ZQIDAQAB
-----END PUBLIC KEY-----
"""
let pubKey2048 = try _RSA.Encryption.PublicKey(pemRepresentation: pemRepresentation2048)
XCTAssertEqual(214, pubKey2048.maximumEncryptSize(with: .PKCS1_OAEP))
XCTAssertEqual(190, pubKey2048.maximumEncryptSize(with: .PKCS1_OAEP_SHA256))
}
func testPKCS1() throws {
let pubKeyPEM = """
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAv6ElnElHGQO1BC5wsU/S01tHK8GbCnDLkxkS1259kOU250pEjOJa
ceOGFnhYzE36KXmKTrGw3o1m5vgbQz88j7/tNjymAX990I3YdWTnGQYcypp8c4TD
wHIj5Q3OHYXAC0KUHRBSKBeS+QJybrMI6SAQbFpHh9C3Q9W3WTtSAVqs8VveS4Jc
j4a3K21MNeHgNfyxwn3KTrrNs/c0yOvWlwyfxYTdWLFVVp2hn6YVQUfo7twM4BCE
Xz/6gR03NpqjVqKeyBmmMtDIy82+BzG4vd3jm02zwNvahsBy9b2NCOjq3y2ud72b
Q4bYU9/r/ccApts5BIW8ASwmYSGSmE6MzwIDAQAB
-----END RSA PUBLIC KEY-----
"""
let privKeyPEM = """
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC/oSWcSUcZA7UE
LnCxT9LTW0crwZsKcMuTGRLXbn2Q5TbnSkSM4lpx44YWeFjMTfopeYpOsbDejWbm
+BtDPzyPv+02PKYBf33Qjdh1ZOcZBhzKmnxzhMPAciPlDc4dhcALQpQdEFIoF5L5
AnJuswjpIBBsWkeH0LdD1bdZO1IBWqzxW95LglyPhrcrbUw14eA1/LHCfcpOus2z
9zTI69aXDJ/FhN1YsVVWnaGfphVBR+ju3AzgEIRfP/qBHTc2mqNWop7IGaYy0MjL
zb4HMbi93eObTbPA29qGwHL1vY0I6OrfLa53vZtDhthT3+v9xwCm2zkEhbwBLCZh
IZKYTozPAgMBAAECggEAGncL9bCdFBRR/JjZUXOfvzbc9msPmXqIcvFEi+Ijj05I
rdqw6vAb45yzmQjX4qdmRDIX6tRZg/LtYjqjsT7bg1LTVOk9V/mei537ZgMgc3FH
qqd5Ro7wZfSdhnXIoIUnR6bTQ8xMPGM9FgzDdwxcz61w9zXkqRonJUQvxTAPHEaH
SiNhRP8LUjzB0Y2ZYVXMWbs0nPPrSE+xuzjcGRX3lvz7nNOM1N4EyWto1RVJIlry
4EV8RFczo3BjPXZFbtval76AGPmurDVqBdHpDN6IBZdhz4ZX/0fq8NR2p8/6S5VZ
4Ylcth1S3HErcnG2UqT8rl/P3m9idTv4EZOg6HziyQKBgQDsmxaQCFTJnDwxSQR+
4j9WsgDpSxvCdnUtMX9w77aw3EIdcHkhnX99jTvNkt3uwGAsVsx4x7ilj1eaZOfl
soMIX1WBBx11yN4GOw173VmzC0LtaBGTh/2ollxuNoEqYxkuKLNxWxTGW0uc5TVA
0hK2c6cF4eZ5sH07aIU6HIIknQKBgQDPVkeyxhF6lvgobLxFQOChOyLVcb1EymnU
W1zF27HciA+0FuaiWTj69bKoR8d+ZIFtIzVvjo7MfoFRJvEZmDGy5+I8HhpSW6JQ
NLdaRI5RGYxbEGmmC48icknXioZJ8JOXhbVuMyT4uLaN5D1M47ZYaq75dPM83fqZ
BDc+izDdWwKBgQCJw5d0j9VGeni1va0nb/avNP/A1qG4LZ72jH6GtJysB+NbHtT4
1KqZ4PU0MlKUpGCbEIMHxEpn47l/RUec/765zkCL2ye1IBreh93HBFApJuJ2NwUc
4K66TapN5eB5XLAZp0ssMns7L4csOG00a9zHbTmP/ENlEXUpdSc1ecnxJQKBgFsJ
n2G35mTVdREK7X/bBMbGmHzv/BMAbYd4tjuKQ4Z5l6uTgqE2W/aVe2S4X7f3mXy6
QPRCvCC+Szm+x45dbTUI7CVJcnVHFvXwr7FK+NJTTXWOt1TZLngJhrLFeEFvCN83
Lnq8qjcro7yZwvDH64DXFw0hdMv9C9O0Li2gIEyRAoGBAK+C7Stfm3vViV2YfByt
MI73t2rN+t3ffnKsXZtGzWW1kxv4cueiAdeM7QwE2AaN7yKzsSMfsSXe+/r69wUR
UPB8NcGLKWE/gJuIcitQx1HCbQZ3AplRK6xhjDVXG1A5SszQVx09hhq76JVBm0sJ
DDYta1f+sEfAS750XLJ7A1h0
-----END PRIVATE KEY-----
"""
let pubKey = try _RSA.Encryption.PublicKey(pemRepresentation: pubKeyPEM)
let privKey = try _RSA.Encryption.PrivateKey(pemRepresentation: privKeyPEM)
let msgs = [
// empty
"",
// short
"467A8AFB-9165-484A-8377-B66BCACD774A",
// example text
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla rutrum odio ut sem luctus, non finibus diam congue. Suspendisse nisl enim, placerat consectetur dolor non, mattis sollicitudin augue.",
// max length
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla rutrum odio ut sem luctus, non finibus diam congue. Suspendisse nisl enim, placerat consectetur dolor non, mattis sollicitudin augue. Pellentesque a est eget enim efficitur volutpat ",
]
for msg in msgs {
let msgEnc = try pubKey.encrypt(msg.data(using: .utf8)!, padding: ._WEAK_AND_INSECURE_PKCS_V1_5)
let msgDec = String(data: try privKey.decrypt(msgEnc, padding: ._WEAK_AND_INSECURE_PKCS_V1_5), encoding: .utf8)!
XCTAssertEqual(msg, msgDec)
}
}
}
struct RSAEncryptionOAEPTestGroup: Codable {
@@ -910,23 +910,6 @@ final class TestRSASigning: XCTestCase {
return pemLines.joined(separator: "\n")
}
func test_invalidDERPublicKeyThrowsWithoutDoubleFree() throws {
// SEQUENCE { INTEGER 0, INTEGER 0 }
let badBase64 = "MAYCAQACAQ=="
let badDER = Array(Data(base64Encoded: badBase64)!)
XCTAssertThrowsError(try BoringSSLRSAPublicKey(derRepresentation: badDER))
}
func test_invalidPEMPublicKeyThrowsWithoutDoubleFree() throws {
// SEQUENCE { INTEGER 0, INTEGER 0 }
let badPEM = """
-----BEGIN PUBLIC KEY-----
MAYCAQACAQ==
-----END PUBLIC KEY-----
"""
XCTAssertThrowsError(try BoringSSLRSAPublicKey(pemRepresentation: badPEM))
}
}
@@ -29,6 +29,7 @@ struct RFCVectorDecoder {
for _ in 0..<3 {
fileURL!.deleteLastPathComponent()
}
#if compiler(>=6.0)
if #available(macOS 13, iOS 16, watchOS 9, tvOS 16, visionOS 1, macCatalyst 16, *) {
fileURL!.append(path: "CryptoExtrasVectors", directoryHint: .isDirectory)
fileURL!.append(path: "\(fileName).txt", directoryHint: .notDirectory)
@@ -36,6 +37,10 @@ struct RFCVectorDecoder {
fileURL! = fileURL!.appendingPathComponent("CryptoExtrasVectors", isDirectory: true)
fileURL! = fileURL!.appendingPathComponent("\(fileName).txt", isDirectory: false)
}
#else
fileURL! = fileURL!.appendingPathComponent("CryptoExtrasVectors", isDirectory: true)
fileURL! = fileURL!.appendingPathComponent("\(fileName).txt", isDirectory: false)
#endif
let rfcVectorData = try Data(contentsOf: fileURL!)
self.rfcVectorData = String(decoding: rfcVectorData, as: Unicode.UTF8.self)
@@ -25,6 +25,7 @@ extension XCTestCase {
for _ in 0..<3 {
fileURL.deleteLastPathComponent()
}
#if compiler(>=6.0)
if #available(macOS 13, iOS 16, watchOS 9, tvOS 16, visionOS 1, macCatalyst 16, *) {
fileURL.append(path: "CryptoExtrasVectors", directoryHint: .isDirectory)
fileURL.append(path: "\(jsonName).json", directoryHint: .notDirectory)
@@ -32,6 +33,10 @@ extension XCTestCase {
fileURL = fileURL.appendingPathComponent("CryptoExtrasVectors", isDirectory: true)
fileURL = fileURL.appendingPathComponent("\(jsonName).json", isDirectory: false)
}
#else
fileURL = fileURL.appendingPathComponent("CryptoExtrasVectors", isDirectory: true)
fileURL = fileURL.appendingPathComponent("\(jsonName).json", isDirectory: false)
#endif
let data = try Data(contentsOf: fileURL)
-33
View File
@@ -84,39 +84,6 @@ final class XWingTests: XCTestCase {
let importedKey = try XWingMLKEM768X25519.PrivateKey.init(integrityCheckedRepresentation: exportedFormat)
XCTAssertEqual(importedKey.seedRepresentation, privateKey.seedRepresentation)
}
func testDecapsulateInputValidation() throws {
let ciphersuite = HPKE.Ciphersuite.XWingMLKEM768X25519_SHA256_AES_GCM_256
let skR = try XWingMLKEM768X25519.PrivateKey.generate()
// Dummy key with the correct size fails with an error from the underlying implementation.
let corretlySizedKey = Data(repeating: 0x00, count: 1120)
XCTAssertThrowsError(
try HPKE.Recipient(
privateKey: skR,
ciphersuite: ciphersuite,
info: Data(),
encapsulatedKey: corretlySizedKey
),
error: CryptoKitError.underlyingCoreCryptoError(error: 0)
)
// Keys with the wrong size fail input validation.
let keySizesToTest = [0, 1, 1119, 1221, 2000]
for keySize in keySizesToTest {
let wronglySizedKey = Data(repeating: 0x00, count: keySize)
XCTAssertThrowsError(
try HPKE.Recipient(
privateKey: skR,
ciphersuite: ciphersuite,
info: Data(),
encapsulatedKey: wronglySizedKey
),
error: CryptoKitError.incorrectParameterSize,
"Unexpectedly returned from malformed decapsulation path for keySize \(keySize)"
)
}
}
}
// Struct to parse KAT file
+5
View File
@@ -33,6 +33,7 @@ struct RFCVectorDecoder {
for _ in 0..<3 {
fileURL!.deleteLastPathComponent()
}
#if compiler(>=6.0)
if #available(macOS 13, iOS 16, watchOS 9, tvOS 16, visionOS 1, macCatalyst 16, *) {
fileURL!.append(path: "Test Vectors", directoryHint: .isDirectory)
fileURL!.append(path: "\(fileName).txt", directoryHint: .notDirectory)
@@ -40,6 +41,10 @@ struct RFCVectorDecoder {
fileURL! = fileURL!.appendingPathComponent("Test Vectors", isDirectory: true)
fileURL! = fileURL!.appendingPathComponent("\(fileName).txt", isDirectory: false)
}
#else
fileURL! = fileURL!.appendingPathComponent("Test Vectors", isDirectory: true)
fileURL! = fileURL!.appendingPathComponent("\(fileName).txt", isDirectory: false)
#endif
#endif
let rfcVectorData = try Data(contentsOf: fileURL!)
+5
View File
@@ -29,6 +29,7 @@ extension XCTestCase {
for _ in 0..<3 {
fileURL.deleteLastPathComponent()
}
#if compiler(>=6.0)
if #available(macOS 13, iOS 16, watchOS 9, tvOS 16, visionOS 1, macCatalyst 16, *) {
fileURL.append(path: "Test Vectors", directoryHint: .isDirectory)
fileURL.append(path: "\(jsonName).json", directoryHint: .notDirectory)
@@ -36,6 +37,10 @@ extension XCTestCase {
fileURL = fileURL.appendingPathComponent("Test Vectors", isDirectory: true)
fileURL = fileURL.appendingPathComponent("\(jsonName).json", isDirectory: false)
}
#else
fileURL = fileURL.appendingPathComponent("Test Vectors", isDirectory: true)
fileURL = fileURL.appendingPathComponent("\(jsonName).json", isDirectory: false)
#endif
#endif
let data = try orFail(file: file, line: line) { try Data(contentsOf: unwrap(fileURL, file: file, line: line)) }