Compare commits

...
9 Commits
Author SHA1 Message Date
Si BeaumontandCory Benfield b0b1963823 Add AES.GCM.open and seal APIs over output span (#507)
### Motivation:

We don't have any API for `AES.GCM.seal` or `open` a read-only buffer
into a caller-provided destination.

### Modifications:

- Add `seal` and `open` helpers to `BoringSSLAEAD.AEADContext` that take
`RawSpan` as input and append to an `OutputRawSpan`.
- Refactor the in-place versions to throw from inside the BoringSSL
call, to match the new functions.
- Add `AES.GCM._seal(_:using:nonce:authenticating:tag:output:)` and
`AES.GCM._open(_:using:nonce:authenticating:tag:output:)` to
CryptoExtras.
- Add tests.

### Result:

New API in CryptoExtras:
- `AES.GCM._seal(_:using:nonce:authenticating:tag:output:)`
- `AES.GCM._open(_:using:nonce:authenticating:tag:output:)`

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-11-23 18:05:24 +00:00
Si Beaumont 40ca846975 Reject Curve25519 private keys labelled with the wrong algorithm (#506)
### Motivation:

Curve25519 `PrivateKey(derRepresentation:)` and
`PrivateKey(pemRepresentation:)` in CryptoExtras never compare the
PKCS#8 `privateKeyAlgorithm` to the key type. An X25519 PKCS#8 loads as
an Ed25519 signing key, and an Ed25519 PKCS#8 loads as an X25519 key
agreement key. The public key initializers already check the OID.

### Modifications:

- Throw `invalidASN1Object` when the PKCS#8 OID doesn't match the key
type, for `Signing` and `KeyAgreement`, DER and PEM
- Add a test that loads each key type's key under the other's OID

### Result:

Keys labelled with the wrong algorithm now throw.
2026-11-23 16:24:10 +00:00
Si Beaumont e652730d73 Fix the default Scrypt memory limit (#508)
### Motivation:

If the caller passes no `maxMemory`, `KDF.Scrypt.deriveKey` sets the
limit to `128 * blockSize * rounds * parallelism` plus a page. BoringSSL
needs `128 * blockSize * (rounds + parallelism + 1)` bytes, so some
valid parameters fail with `MEMORY_LIMIT_EXCEEDED`. For example,
`rounds: 2, blockSize: 1024, parallelism: 1` gets a limit of 256 KiB
plus a page and needs 512 KiB.

### Modifications:

- Compute the default limit as `128 * blockSize * (rounds + parallelism
+ 1)` plus a page. Overflow still throws
`CryptoKitError.incorrectParameterSize`.
- Add a test for `rounds: 2, blockSize: 1024, parallelism: 1` with no
`maxMemory`, and an overflow case for `parallelism: .max`.

### Result:

The default limit covers the memory BoringSSL needs, so valid parameters
no longer fail.

Fixes #489.
2026-11-23 15:31:15 +00:00
Si Beaumont 3280a5f728 Merge commit from fork 2026-11-19 14:46:02 +00:00
Si Beaumont 1fa43495bc Merge commit from fork
* Enforce the maxMemory limit passed to KDF.Scrypt

* Reject out-of-range scrypt parameters instead of trapping

* Reject a maxMemory that no derivation could satisfy
2026-11-19 14:45:16 +00:00
Si Beaumont 9f96b82711 Run CMake CI job in a matrix by supported Swift version (#500)
### Motivation:

We recently broke downstream builds for some narrow compilation modes
(broken in 5.1.0, fixed in 5.1.1). We would have caught this in our
CMake pipelines, but these only ran on 6.2. Had they run on 6.3 or 6.4,
they would have gated the break. There's no good reason not to run this
CMake CI build in a matrix with all current supported Swift versions.

### Modifications:

Run CMake CI job in a matrix by supported Swift version

### Result:

Two more CI jobs.
2026-11-06 16:56:34 +00:00
Si Beaumont 281a92df6c Build the CMake targets in the Swift 6 language mode (#501)
### Motivation:

`Package.swift` uses tools version 6.2 and declares no
`swiftLanguageModes`, so SwiftPM builds Swift Crypto in the Swift 6
language mode. The CMake build passes no `-swift-version`, so the
compiler falls back to the Swift 5 language mode. The two build systems
compile the same sources in different language modes.

### Modifications:

- Set `CMAKE_Swift_LANGUAGE_VERSION` to 6 after the swift-asn1
`FetchContent` block, so swift-asn1 keeps its own language mode when
CMake fetches it.
- Raise the minimum CMake version to 3.16, the release that added
`Swift_LANGUAGE_VERSION`.
- Remove the branch that set Windows output directories for CMake
versions before 3.16.

### Result:

CMake builds Swift Crypto in the Swift 6 language mode, as SwiftPM does.
2026-11-04 11:55:03 +00:00
Si Beaumont 32adcc5038 Update conditional compilation blocks to use compiler version instead of language mode (#499) 2026-11-03 18:08:15 +00:00
Si Beaumont 1586608eee Clarify the privacy manifest comment in the package manifest (#498)
### Motivation:

The comment we have in our package manifest was a bit ambiguous about
Foundation linking and caused some confusion (reported in #496). As
discussed on that issue, I don't think there's anything we want to do
differently here, but we can try and improve the comment so other
adopters don't waste time on a misunderstanding.

### Modifications:

Clarify the privacy manifest comment in the package manifest.

### Result:

Fixes #496.
2026-11-03 17:17:39 +00:00
23 changed files with 685 additions and 80 deletions

No files matched your search

+5 -1
View File
@@ -48,6 +48,10 @@ jobs:
cmake-checks: cmake-checks:
name: CMake checks name: CMake checks
strategy:
fail-fast: false
matrix:
swift_version: ["6.2", "6.3", "6.4"]
uses: apple/swift-nio/.github/workflows/cmake_tests.yml@main uses: apple/swift-nio/.github/workflows/cmake_tests.yml@main
with: with:
update_cmake_lists_config: >- update_cmake_lists_config: >-
@@ -62,7 +66,7 @@ jobs:
{ "name": "CCryptoBoringSSL", "type": "assembly", "exceptions": [ "*/AES/*.swift" ] } { "name": "CCryptoBoringSSL", "type": "assembly", "exceptions": [ "*/AES/*.swift" ] }
] ]
} }
image: swift:6.2 image: "swift:${{ matrix.swift_version }}"
macos-tests: macos-tests:
name: macOS tests name: macOS tests
+6 -8
View File
@@ -12,7 +12,7 @@
## ##
##===----------------------------------------------------------------------===## ##===----------------------------------------------------------------------===##
cmake_minimum_required(VERSION 3.15.1) cmake_minimum_required(VERSION 3.16)
if(POLICY CMP0157) if(POLICY CMP0157)
cmake_policy(SET CMP0157 NEW) cmake_policy(SET CMP0157 NEW)
@@ -25,13 +25,8 @@ list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules)
include(SwiftSupport) include(SwiftSupport)
if(CMAKE_VERSION VERSION_LESS 3.16 AND CMAKE_SYSTEM_NAME STREQUAL Windows) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
else()
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
endif()
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift) set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift)
@@ -79,5 +74,8 @@ if(NOT SwiftASN1_FOUND)
FetchContent_MakeAvailable(ASN1) FetchContent_MakeAvailable(ASN1)
endif() endif()
# Set after vending swift-asn1 so its targets keep their own language mode.
set(CMAKE_Swift_LANGUAGE_VERSION 6)
add_subdirectory(Sources) add_subdirectory(Sources)
add_subdirectory(cmake/modules) add_subdirectory(cmake/modules)
+2 -3
View File
@@ -49,9 +49,8 @@ var swiftSettings: [SwiftSetting] = [
swiftSettings.append(.enableExperimentalFeature("CheckImplementationOnly")) swiftSettings.append(.enableExperimentalFeature("CheckImplementationOnly"))
#endif #endif
// This doesn't work when cross-compiling: the privacy manifest will be included in the Bundle and // A resource makes SwiftPM generate a `Bundle.module` accessor that imports Foundation, not just FoundationEssentials.
// Foundation will be linked. This is, however, strictly better than unconditionally adding the // `canImport(Darwin)` checks the host, not the target, so cross-compiling from Darwin still adds the resource.
// resource.
#if canImport(Darwin) #if canImport(Darwin)
let privacyManifestExclude: [String] = [] let privacyManifestExclude: [String] = []
let privacyManifestResource: [PackageDescription.Resource] = [.copy("PrivacyInfo.xcprivacy")] let privacyManifestResource: [PackageDescription.Resource] = [.copy("PrivacyInfo.xcprivacy")]
+2 -2
View File
@@ -72,7 +72,7 @@ extension AES {
/// - nonce: The nonce the sealing process requires. /// - nonce: The nonce the sealing process requires.
/// - authenticatedData: Additional data to be authenticated, if provided. /// - authenticatedData: Additional data to be authenticated, if provided.
/// - tag: receives the 16-byte authentication tag /// - tag: receives the 16-byte authentication tag
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(message: copy message) @_lifetime(message: copy message)
#endif #endif
public static func seal( public static func seal(
@@ -127,7 +127,7 @@ extension AES {
/// - authenticatedData: Additional data that was authenticated. /// - authenticatedData: Additional data that was authenticated.
/// ///
/// The call throws an error if decryption or authentication fail. /// The call throws an error if decryption or authentication fail.
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(message: copy message) @_lifetime(message: copy message)
#endif #endif
public static func open( public static func open(
@@ -59,7 +59,7 @@ enum OpenSSLAESGCMImpl {
return AES.GCM.SealedBox(combined: combined, nonceByteCount: nonce.count) return AES.GCM.SealedBox(combined: combined, nonceByteCount: nonce.count)
} }
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(message: copy message) @_lifetime(message: copy message)
#endif #endif
@inlinable @inlinable
@@ -119,7 +119,7 @@ enum OpenSSLAESGCMImpl {
} }
/// Open a given message in place. /// Open a given message in place.
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(message: copy message) @_lifetime(message: copy message)
#endif #endif
@inlinable @inlinable
@@ -48,7 +48,7 @@ extension BoringSSLAEAD {
} }
/// Seal a given message in place /// Seal a given message in place
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(message: copy message) @_lifetime(message: copy message)
#endif #endif
func seal( func seal(
@@ -93,7 +93,7 @@ extension BoringSSLAEAD {
} }
/// Open a given message in place. /// Open a given message in place.
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(message: copy message) @_lifetime(message: copy message)
#endif #endif
public func open( public func open(
@@ -150,7 +150,7 @@ enum OpenSSLChaChaPolyImpl {
return ChaChaPoly.SealedBox(combined: combined, nonceByteCount: nonce.count) return ChaChaPoly.SealedBox(combined: combined, nonceByteCount: nonce.count)
} }
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(message: copy message) @_lifetime(message: copy message)
#endif #endif
static func encrypt( static func encrypt(
@@ -211,7 +211,7 @@ enum OpenSSLChaChaPolyImpl {
} }
} }
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(message: copy message) @_lifetime(message: copy message)
#endif #endif
static func decrypt( static func decrypt(
@@ -70,7 +70,7 @@ public enum ChaChaPoly: Cipher, Sendable {
/// - nonce: The nonce the sealing process requires. /// - nonce: The nonce the sealing process requires.
/// - authenticatedData: Additional data to be authenticated. /// - authenticatedData: Additional data to be authenticated.
/// - tag: Will be updated with the 16-byte authentication tag. /// - tag: Will be updated with the 16-byte authentication tag.
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(message: copy message) @_lifetime(message: copy message)
#endif #endif
public static func seal( public static func seal(
@@ -124,7 +124,7 @@ public enum ChaChaPoly: Cipher, Sendable {
/// - authenticatedData: Additional data that was authenticated. /// - authenticatedData: Additional data that was authenticated.
/// ///
/// The call throws an error if decryption or authentication fail. /// The call throws an error if decryption or authentication fail.
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(message: copy message) @_lifetime(message: copy message)
#endif #endif
public static func open( public static func open(
+2 -2
View File
@@ -48,7 +48,7 @@ public struct HKDF<H: HashFunction>: Sendable {
/// - info: The shared information to use for key derivation. /// - info: The shared information to use for key derivation.
/// - outputKey: An output span that will be populated with the derived /// - outputKey: An output span that will be populated with the derived
/// symmetric key. /// symmetric key.
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(outputKey: copy outputKey) @_lifetime(outputKey: copy outputKey)
#endif #endif
public static func deriveKey(inputKeyMaterial: SymmetricKey, public static func deriveKey(inputKeyMaterial: SymmetricKey,
@@ -258,7 +258,7 @@ public struct HKDF<H: HashFunction>: Sendable {
/// - outputByteCount: The length in bytes of the resulting symmetric key. /// - outputByteCount: The length in bytes of the resulting symmetric key.
/// ///
/// - Returns: The derived symmetric key. /// - Returns: The derived symmetric key.
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(output: copy output) @_lifetime(output: copy output)
#endif #endif
public static func expand(pseudoRandomKey prk: RawSpan, info: RawSpan?, into output: inout OutputRawSpan) { public static func expand(pseudoRandomKey prk: RawSpan, info: RawSpan?, into output: inout OutputRawSpan) {
@@ -121,10 +121,10 @@ extension Curve25519.KeyAgreement {
) throws ) throws
-> SharedSecret -> SharedSecret
{ {
let sharedSecret = SecureBytes( let sharedSecret = try SecureBytes(
unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes
) { secretPointer, secretSize in ) { secretPointer, secretSize in
self.key.withUnsafeBytes { privateKeyPointer in try self.key.withUnsafeBytes { privateKeyPointer in
// We precondition on all of these sizes because bounds checking is cool. // We precondition on all of these sizes because bounds checking is cool.
// These are fatal instead of guards because we allocated the secret (so it must be right), // These are fatal instead of guards because we allocated the secret (so it must be right),
// we either allocated the private key or validated it on construction (so it must be right), // we either allocated the private key or validated it on construction (so it must be right),
@@ -133,16 +133,17 @@ extension Curve25519.KeyAgreement {
precondition(privateKeyPointer.count == Curve25519.KeyAgreement.keySizeBytes) precondition(privateKeyPointer.count == Curve25519.KeyAgreement.keySizeBytes)
precondition(publicKeyShare.keyBytes.count == Curve25519.KeyAgreement.keySizeBytes) precondition(publicKeyShare.keyBytes.count == Curve25519.KeyAgreement.keySizeBytes)
// We don't check the return code here. This return code only validates that the generated secret is not the weak all-zero // BoringSSL returns 0 when the peer's public key has low order, which makes the shared secret
// secret (it is not possible for BoringSSL's X25519 implementation to fail, which is nice). There is currently what I would // the weak all-zero value. CryptoKit rejects that key agreement, so we do too.
// politely describe as a "lack of consensus" as to whether crypto libraries should reject this secret. CryptoKit on Apple guard
// platforms currently does not, so for the sake of conformance with our peer implementation I will also refuse to check it. CCryptoBoringSSL_X25519(
// We may elect to revisit this decision if the security best-practice thinking changes. secretPointer.baseAddress,
CCryptoBoringSSL_X25519( privateKeyPointer.baseAddress,
secretPointer.baseAddress, publicKeyShare.keyBytes
privateKeyPointer.baseAddress, ) == 1
publicKeyShare.keyBytes else {
) throw CryptoKitError.internalBoringSSLError()
}
} }
secretSize = Curve25519.KeyAgreement.keySizeBytes // We always use all of it. secretSize = Curve25519.KeyAgreement.keySizeBytes // We always use all of it.
+2 -2
View File
@@ -57,7 +57,7 @@ extension ContiguousArray where Element == UInt8 {
extension OutputRawSpan { extension OutputRawSpan {
/// Append the contents of the given raw span to this output span. /// Append the contents of the given raw span to this output span.
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(self: copy self) @_lifetime(self: copy self)
#endif #endif
mutating func append(contentsOf bytes: RawSpan) { mutating func append(contentsOf bytes: RawSpan) {
@@ -69,7 +69,7 @@ extension OutputRawSpan {
extension OutputSpan<UInt8> { extension OutputSpan<UInt8> {
/// Append the contents of the given raw span to this output span. /// Append the contents of the given raw span to this output span.
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(self: copy self) @_lifetime(self: copy self)
#endif #endif
mutating func append(contentsOf bytes: RawSpan) { mutating func append(contentsOf bytes: RawSpan) {
@@ -45,7 +45,7 @@ extension UnsafeMutableRawBufferPointer {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension MutableRawSpan { extension MutableRawSpan {
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(self: copy self) @_lifetime(self: copy self)
#endif #endif
mutating func initializeWithRandomBytes(count: Int) { mutating func initializeWithRandomBytes(count: Int) {
@@ -55,7 +55,7 @@ extension MutableRawSpan {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension OutputRawSpan { extension OutputRawSpan {
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(self: copy self) @_lifetime(self: copy self)
#endif #endif
mutating func appendingRandomBytes(count: Int) { mutating func appendingRandomBytes(count: Int) {
@@ -152,8 +152,8 @@ extension BoringSSLAEAD.AEADContext {
} }
/// Lowest level seal operation that calls into BoringSSL directly and /// Lowest level seal operation that calls into BoringSSL directly and
/// operates on already-allocated memory. /// operates in-place on already-allocated memory.
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(tag: copy tag) @_lifetime(tag: copy tag)
#endif #endif
public func seal( public func seal(
@@ -162,43 +162,99 @@ extension BoringSSLAEAD.AEADContext {
authenticatedData: RawSpan, authenticatedData: RawSpan,
tag: inout OutputRawSpan tag: inout OutputRawSpan
) throws { ) throws {
let tagByteCount = CCryptoBoringSSL_EVP_AEAD_max_overhead(self.context.aead) // BoringSSL writes up to (EVP_AEAD_max_overhead + extra_in_len) bytes. We use zero extra_in_len.
precondition(tag.freeCapacity >= tagByteCount) let maxTagByteCount = CCryptoBoringSSL_EVP_AEAD_max_overhead(self.context.aead)
var actualTagSize = tagByteCount precondition(tag.freeCapacity >= maxTagByteCount)
let rc = withUnsafeMutablePointer(to: &self.context) { contextPointer in try withUnsafeMutablePointer(to: &self.context) { contextPointer in
message.withUnsafeMutableBytes { messageBuffer in try message.withUnsafeMutableBytes { messageBuffer in
tag.withUnsafeMutableBytes { tagBuffer, tagInitializedCount in try tag.withUnsafeMutableBytes { tagBuffer, tagInitializedCount in
defer { // BoringSSL returns the size of the tag it wrote.
tagInitializedCount += actualTagSize var actualTagByteCount = maxTagByteCount
} defer { tagInitializedCount += actualTagByteCount }
// BoringSSL guarantees to fill out with in_len bytes, even on error.
return authenticatedData.withUnsafeBytes { authenticatedDataBuffer in try authenticatedData.withUnsafeBytes { authenticatedDataBuffer in
nonce.withUnsafeBytes { nonceBuffer in try nonce.withUnsafeBytes { nonceBuffer in
CCryptoBoringSSL_EVP_AEAD_CTX_seal_scatter( guard
contextPointer, CCryptoBoringSSL_EVP_AEAD_CTX_seal_scatter(
messageBuffer.baseAddress, contextPointer,
tagBuffer.baseAddress! + tagInitializedCount, messageBuffer.baseAddress,
&actualTagSize, tagBuffer.baseAddress! + tagInitializedCount,
tagBuffer.count - tagInitializedCount, &actualTagByteCount,
nonceBuffer.baseAddress, tagBuffer.count - tagInitializedCount,
nonceBuffer.count, nonceBuffer.baseAddress,
messageBuffer.baseAddress, nonceBuffer.count,
messageBuffer.count, messageBuffer.baseAddress,
nil, messageBuffer.count,
0, nil,
authenticatedDataBuffer.baseAddress, 0,
authenticatedDataBuffer.count authenticatedDataBuffer.baseAddress,
) authenticatedDataBuffer.count
) == 1
else {
throw CryptoBoringWrapperError.internalBoringSSLError()
}
} }
} }
} }
} }
} }
}
guard rc == 1 else { /// Lowest level seal operation that calls into BoringSSL directly and
throw CryptoBoringWrapperError.internalBoringSSLError() /// operates on already-allocated memory to input and output buffers.
#if compiler(<6.3)
@_lifetime(tag: copy tag)
@_lifetime(output: copy output)
#endif
public func seal(
message: RawSpan,
output: inout OutputRawSpan,
nonce: RawSpan,
authenticatedData: RawSpan,
tag: inout OutputRawSpan,
) throws {
// BoringSSL writes up to (EVP_AEAD_max_overhead + extra_in_len) bytes. We use zero extra_in_len.
let maxTagByteCount = CCryptoBoringSSL_EVP_AEAD_max_overhead(self.context.aead)
precondition(tag.freeCapacity >= maxTagByteCount)
precondition(output.freeCapacity >= message.byteCount)
try withUnsafeMutablePointer(to: &self.context) { contextPointer in
try message.withUnsafeBytes { messageBuffer in
try tag.withUnsafeMutableBytes { tagBuffer, tagInitializedCount in
// BoringSSL returns the size of the tag it wrote.
var actualTagByteCount = maxTagByteCount
try output.withUnsafeMutableBytes { outputBuffer, outputInitializedCount in
try authenticatedData.withUnsafeBytes { authenticatedDataBuffer in
try nonce.withUnsafeBytes { nonceBuffer in
guard
CCryptoBoringSSL_EVP_AEAD_CTX_seal_scatter(
contextPointer,
outputBuffer.baseAddress?.advanced(by: outputInitializedCount),
tagBuffer.baseAddress! + tagInitializedCount,
&actualTagByteCount,
tagBuffer.count - tagInitializedCount,
nonceBuffer.baseAddress,
nonceBuffer.count,
messageBuffer.baseAddress,
messageBuffer.count,
nil,
0,
authenticatedDataBuffer.baseAddress,
authenticatedDataBuffer.count
) == 1
else {
throw CryptoBoringWrapperError.internalBoringSSLError()
}
}
}
// BoringSSL writes zeros on error; count only on success so a throw leaves output unchanged.
outputInitializedCount += messageBuffer.count
}
tagInitializedCount += actualTagByteCount
}
}
} }
} }
@@ -303,7 +359,7 @@ extension BoringSSLAEAD.AEADContext {
} }
/// Lowest level call into BoringSSL that decrypts in place. /// Lowest level call into BoringSSL that decrypts in place.
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(message: copy message) @_lifetime(message: copy message)
#endif #endif
public func open( public func open(
@@ -340,6 +396,52 @@ extension BoringSSLAEAD.AEADContext {
} }
} }
/// Lowest level open operation that calls into BoringSSL directly and
/// operates on already-allocated memory to input and output buffers.
#if compiler(<6.3)
@_lifetime(output: copy output)
#endif
public func open(
message: RawSpan,
output: inout OutputRawSpan,
nonce: RawSpan,
tag: RawSpan,
authenticatedData: RawSpan
) throws {
precondition(output.freeCapacity >= message.byteCount)
try withUnsafePointer(to: &self.context) { contextPointer in
try message.withUnsafeBytes { messageBuffer in
try output.withUnsafeMutableBytes { outputBuffer, outputInitializedCount in
try nonce.withUnsafeBytes { nonceBuffer in
try tag.withUnsafeBytes { tagBuffer in
try authenticatedData.withUnsafeBytes { authenticatedDataBuffer in
guard
CCryptoBoringSSL_EVP_AEAD_CTX_open_gather(
contextPointer,
outputBuffer.baseAddress?.advanced(by: outputInitializedCount),
nonceBuffer.baseAddress,
nonceBuffer.count,
messageBuffer.baseAddress,
messageBuffer.count,
tagBuffer.baseAddress,
tagBuffer.count,
authenticatedDataBuffer.baseAddress,
authenticatedDataBuffer.count
) == 1
else {
throw CryptoBoringWrapperError.internalBoringSSLError()
}
}
}
}
// BoringSSL writes zeros on error; count only on success so a throw leaves output unchanged.
outputInitializedCount += messageBuffer.count
}
}
}
}
/// The unsafe base call: not inlinable so that it can touch private variables. /// The unsafe base call: not inlinable so that it can touch private variables.
@usableFromInline @usableFromInline
func _openContiguous( func _openContiguous(
@@ -47,7 +47,7 @@ extension UnsafeMutableRawBufferPointer {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension OutputRawSpan { extension OutputRawSpan {
#if swift(<6.3) #if compiler(<6.3)
@_lifetime(self: copy self) @_lifetime(self: copy self)
#endif #endif
package mutating func appendingRandomBytes(count: Int) { package mutating func appendingRandomBytes(count: Int) {
@@ -0,0 +1,85 @@
//===----------------------------------------------------------------------===//
//
// 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
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension AES.GCM {
/// Secures the given plaintext message with encryption and an authentication tag.
///
/// - Parameters:
/// - message: The plaintext data to seal.
/// - key: A cryptographic key used to seal the message.
/// - nonce: The nonce the sealing process requires.
/// - authenticatedData: Additional data to be authenticated, if provided.
/// - tag: Receives the 16-byte authentication tag. Needs at least 16 bytes of free capacity.
/// - output: Receives the encrypted message. Needs at least `message.byteCount` bytes of free capacity.
///
/// The call traps if `tag` or `output` lacks the free capacity. If the call throws, `tag` and
/// `output` are unchanged.
#if compiler(<6.3)
@_lifetime(tag: copy tag)
@_lifetime(output: copy output)
#endif
public static func _seal(
_ message: RawSpan,
using key: SymmetricKey,
nonce: Nonce,
authenticating authenticatedData: RawSpan? = nil,
tag: inout OutputRawSpan,
output: inout OutputRawSpan
) throws(CryptoKitMetaError) {
try OpenSSLAESGCMImpl.seal(
key: key,
message: message,
output: &output,
nonce: nonce,
authenticatedData: authenticatedData,
tag: &tag
)
}
/// Decrypts the message and verifies its authenticity.
///
/// - Parameters:
/// - message: The ciphertext to decrypt.
/// - key: The cryptographic key that was used to seal the message.
/// - nonce: The nonce used to encrypt the message.
/// - authenticatedData: Additional data that was authenticated, if provided.
/// - tag: The 16-byte authentication tag.
/// - output: Receives the decrypted message. Needs at least `message.byteCount` bytes of free capacity.
///
/// The call traps if `output` lacks the free capacity. The call throws an error if decryption or
/// authentication fail, and leaves `output` unchanged.
#if compiler(<6.3)
@_lifetime(output: copy output)
#endif
public static func _open(
_ message: RawSpan,
using key: SymmetricKey,
nonce: Nonce,
authenticating authenticatedData: RawSpan? = nil,
tag: RawSpan,
output: inout OutputRawSpan
) throws(CryptoKitMetaError) {
try OpenSSLAESGCMImpl.open(
key: key,
message: message,
output: &output,
nonce: nonce,
authenticatedData: authenticatedData,
tag: tag
)
}
}
@@ -0,0 +1,139 @@
//===----------------------------------------------------------------------===//
//
// 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 CryptoBoringWrapper
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension BoringSSLAEAD {
/// Seal a given message with caller owned buffers.
#if compiler(<6.3)
@_lifetime(tag: copy tag)
@_lifetime(output: copy output)
#endif
func seal(
message: RawSpan,
key: SymmetricKey,
output: inout OutputRawSpan,
nonce: RawSpan,
authenticatedData: RawSpan,
tag: inout OutputRawSpan
) throws {
do {
let context = try AEADContext(cipher: self, key: key)
return try context.seal(
message: message,
output: &output,
nonce: nonce,
authenticatedData: authenticatedData,
tag: &tag
)
} catch CryptoBoringWrapperError.underlyingCoreCryptoError(let errorCode) {
throw CryptoKitError.underlyingCoreCryptoError(error: errorCode)
}
}
/// Open a given message with caller owned buffers.
#if compiler(<6.3)
@_lifetime(output: copy output)
#endif
func open(
message: RawSpan,
key: SymmetricKey,
output: inout OutputRawSpan,
nonce: RawSpan,
tag: RawSpan,
authenticatedData: RawSpan
) throws {
do {
let context = try AEADContext(cipher: self, key: key)
return try context.open(
message: message,
output: &output,
nonce: nonce,
tag: tag,
authenticatedData: authenticatedData
)
} catch CryptoBoringWrapperError.underlyingCoreCryptoError(let errorCode) {
throw CryptoKitError.underlyingCoreCryptoError(error: errorCode)
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
enum OpenSSLAESGCMImpl {
#if compiler(<6.3)
@_lifetime(tag: copy tag)
@_lifetime(output: copy output)
#endif
static func seal(
key: SymmetricKey,
message: RawSpan,
output: inout OutputRawSpan,
nonce: AES.GCM.Nonce,
authenticatedData: RawSpan?,
tag: inout OutputRawSpan
) throws {
let aead = try Self._backingAEAD(key: key)
let authenticatedData = if let authenticatedData { authenticatedData } else { RawSpan() }
try nonce.withUnsafeBytes { nonceBuffer in
try aead.seal(
message: message,
key: key,
output: &output,
nonce: nonceBuffer.bytes,
authenticatedData: authenticatedData,
tag: &tag
)
}
}
#if compiler(<6.3)
@_lifetime(output: copy output)
#endif
static func open(
key: SymmetricKey,
message: RawSpan,
output: inout OutputRawSpan,
nonce: AES.GCM.Nonce,
authenticatedData: RawSpan?,
tag: RawSpan
) throws {
let aead = try Self._backingAEAD(key: key)
let authenticatedData = if let authenticatedData { authenticatedData } else { RawSpan() }
try nonce.withUnsafeBytes { nonceBuffer in
try aead.open(
message: message,
key: key,
output: &output,
nonce: nonceBuffer.bytes,
tag: tag,
authenticatedData: authenticatedData
)
}
}
static func _backingAEAD(key: SymmetricKey) throws -> BoringSSLAEAD {
switch key.bitCount {
case 128:
return .aes128gcm
case 192:
return .aes192gcm
case 256:
return .aes256gcm
default:
throw CryptoKitError.incorrectKeySize
}
}
}
+2
View File
@@ -16,12 +16,14 @@ add_library(CryptoExtras
"AES/AES_CBC.swift" "AES/AES_CBC.swift"
"AES/AES_CFB.swift" "AES/AES_CFB.swift"
"AES/AES_CTR.swift" "AES/AES_CTR.swift"
"AES/AES_GCM+Extensions.swift"
"AES/AES_GCM_SIV.swift" "AES/AES_GCM_SIV.swift"
"AES/Block Function.swift" "AES/Block Function.swift"
"AES/BoringSSL/AES_CBC_boring.swift" "AES/BoringSSL/AES_CBC_boring.swift"
"AES/BoringSSL/AES_CFB_boring.swift" "AES/BoringSSL/AES_CFB_boring.swift"
"AES/BoringSSL/AES_CTR_boring.swift" "AES/BoringSSL/AES_CTR_boring.swift"
"AES/BoringSSL/AES_GCM_SIV_boring.swift" "AES/BoringSSL/AES_GCM_SIV_boring.swift"
"AES/BoringSSL/AES_GCM_boring.swift"
"AES/CMAC.swift" "AES/CMAC.swift"
"ARC/ARC+API.swift" "ARC/ARC+API.swift"
"ARC/ARC.swift" "ARC/ARC.swift"
@@ -56,6 +56,9 @@ extension Curve25519.Signing.PrivateKey {
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 { public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation) let bytes = Array(derRepresentation)
let key = try ASN1.PKCS8PrivateKey(derEncoded: bytes) let key = try ASN1.PKCS8PrivateKey(derEncoded: bytes)
guard key.algorithm == .ed25519 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: key.privateKey.bytes) self = try .init(rawRepresentation: key.privateKey.bytes)
} }
} }
@@ -138,6 +141,9 @@ extension Curve25519.KeyAgreement.PrivateKey {
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 { public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation) let bytes = Array(derRepresentation)
let key = try ASN1.PKCS8PrivateKey(derEncoded: bytes) let key = try ASN1.PKCS8PrivateKey(derEncoded: bytes)
guard key.algorithm == .x25519 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: key.privateKey.bytes) self = try .init(rawRepresentation: key.privateKey.bytes)
} }
} }
@@ -85,9 +85,24 @@ internal struct BoringSSLScrypt {
var derivedKeyData = Data(count: outputByteCount) var derivedKeyData = Data(count: outputByteCount)
defer { derivedKeyData.withUnsafeMutableBytes { $0.zeroize() } } defer { derivedKeyData.withUnsafeMutableBytes { $0.zeroize() } }
// This computes the maximum amount of memory that will be used by the scrypt algorithm with an additional memory page to spare. This value will be used by the BoringSSL as the memory limit for the algorithm. let memoryLimit: Int
// An additional memory page is added to the computed value (using POSIX specification) to ensure that the memory limit is not too tight. if let maxMemory {
let maxMemory = maxMemory ?? (128 * rounds * blockSize * parallelism + getPageSize()) memoryLimit = maxMemory
} else {
// BoringSSL needs 128 * blockSize * (rounds + parallelism + 1) bytes; one page is added as slack.
let (blockBytes, blockBytesOverflowed) = 128.multipliedReportingOverflow(by: blockSize)
let (scratchBlockCount, scratchBlockCountOverflowed) = rounds.addingReportingOverflow(parallelism)
let (blockCount, blockCountOverflowed) = scratchBlockCount.addingReportingOverflow(1)
let (stateBytes, stateBytesOverflowed) = blockBytes.multipliedReportingOverflow(by: blockCount)
let (computedLimit, computedLimitOverflowed) = stateBytes.addingReportingOverflow(getPageSize())
guard
!blockBytesOverflowed, !scratchBlockCountOverflowed, !blockCountOverflowed, !stateBytesOverflowed,
!computedLimitOverflowed
else {
throw CryptoKitError.incorrectParameterSize
}
memoryLimit = computedLimit
}
let result = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes -> Int32 in let result = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes -> Int32 in
let saltBytes: ContiguousBytes = salt.regions.count == 1 ? salt.regions.first! : Array(salt) let saltBytes: ContiguousBytes = salt.regions.count == 1 ? salt.regions.first! : Array(salt)
@@ -103,7 +118,7 @@ internal struct BoringSSLScrypt {
UInt64(rounds), UInt64(rounds),
UInt64(blockSize), UInt64(blockSize),
UInt64(parallelism), UInt64(parallelism),
maxMemory, memoryLimit,
derivedKeyBytes.baseAddress!, derivedKeyBytes.baseAddress!,
derivedKeyBytes.count derivedKeyBytes.count
) )
@@ -35,10 +35,16 @@ extension KDF {
/// - rounds: The number of rounds which should be used to perform key derivation. Must be a power of 2 less than `2^(128 * blockSize / 8)`. /// - rounds: The number of rounds which should be used to perform key derivation. Must be a power of 2 less than `2^(128 * blockSize / 8)`.
/// - blockSize: The block size to use for key derivation. /// - blockSize: The block size to use for key derivation.
/// - parallelism: The parallelism factor to use for key derivation. Must be a positive integer less than or equal to `((2^32 - 1) * 32) / (128 * blockSize)`. /// - parallelism: The parallelism factor to use for key derivation. Must be a positive integer less than or equal to `((2^32 - 1) * 32) / (128 * blockSize)`.
/// - maxMemory: The maximum amount of memory allowed to use for key derivation. If not provided, the default value is computed for the provided parameters. /// - maxMemory: The maximum amount of memory allowed to use for key derivation. Must be positive. If not provided, the default value is computed for the provided parameters.
/// - Returns: The derived symmetric key. /// - Returns: The derived symmetric key.
public static func deriveKey<Passphrase: DataProtocol, Salt: DataProtocol>(from password: Passphrase, salt: Salt, outputByteCount: Int, rounds: Int, blockSize: Int, parallelism: Int, maxMemory: Int? = nil) throws -> SymmetricKey { public static func deriveKey<Passphrase: DataProtocol, Salt: DataProtocol>(from password: Passphrase, salt: Salt, outputByteCount: Int, rounds: Int, blockSize: Int, parallelism: Int, maxMemory: Int? = nil) throws -> SymmetricKey {
return try BackingScrypt.deriveKey(from: password, salt: salt, outputByteCount: outputByteCount, rounds: rounds, blockSize: blockSize, parallelism: parallelism) guard rounds > 0, blockSize > 0, parallelism > 0, outputByteCount >= 0 else {
throw CryptoKitError.incorrectParameterSize
}
if let maxMemory, maxMemory <= 0 {
throw CryptoKitError.incorrectParameterSize
}
return try BackingScrypt.deriveKey(from: password, salt: salt, outputByteCount: outputByteCount, rounds: rounds, blockSize: blockSize, parallelism: parallelism, maxMemory: maxMemory)
} }
} }
} }
@@ -0,0 +1,107 @@
//===----------------------------------------------------------------------===//
//
// 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 AESGCMExtensionsTests: XCTestCase {
func testSealOverOutputSpanAppendsCiphertext() throws {
guard #available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0, *) else {
throw XCTSkip("Array.span requires macOS 26.0+, iOS 26.0+, watchOS 26.0+, tvOS 26.0+, visionOS 26.0+")
}
let key = SymmetricKey(size: .bits256)
let nonce = AES.GCM.Nonce()
let plaintext = Array("Some Super Secret Message".utf8)
let authenticatedData = Array("Some Authenticated Data".utf8)
var ciphertext = [UInt8](repeating: 0xFF, count: 1 + plaintext.count)
var tag = [UInt8](repeating: 0, count: 16)
try ciphertext.withUnsafeMutableBytes { ciphertextBuffer in
try tag.withUnsafeMutableBytes { tagBuffer in
var ciphertextOutput = OutputRawSpan(buffer: ciphertextBuffer, initializedCount: 1)
var tagOutput = OutputRawSpan(buffer: tagBuffer, initializedCount: 0)
try AES.GCM._seal(
plaintext.span.bytes,
using: key,
nonce: nonce,
authenticating: authenticatedData.span.bytes,
tag: &tagOutput,
output: &ciphertextOutput
)
XCTAssertEqual(ciphertextOutput.byteCount, ciphertextBuffer.count)
XCTAssertEqual(tagOutput.byteCount, tagBuffer.count)
}
}
let sealedBox = try AES.GCM.seal(plaintext, using: key, nonce: nonce, authenticating: authenticatedData)
XCTAssertEqual(ciphertext, [0xFF] + Array(sealedBox.ciphertext))
XCTAssertEqual(tag, Array(sealedBox.tag))
}
func testOpenOverOutputSpanAppendsPlaintext() throws {
guard #available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0, *) else {
throw XCTSkip("Array.span requires macOS 26.0+, iOS 26.0+, watchOS 26.0+, tvOS 26.0+, visionOS 26.0+")
}
let key = SymmetricKey(size: .bits256)
let nonce = AES.GCM.Nonce()
let plaintext = Array("Some Super Secret Message".utf8)
let authenticatedData = Array("Some Authenticated Data".utf8)
let sealedBox = try AES.GCM.seal(plaintext, using: key, nonce: nonce, authenticating: authenticatedData)
let ciphertext = Array(sealedBox.ciphertext)
let tag = Array(sealedBox.tag)
var decrypted = [UInt8](repeating: 0xFF, count: 1 + ciphertext.count)
try decrypted.withUnsafeMutableBytes { decryptedBuffer in
var output = OutputRawSpan(buffer: decryptedBuffer, initializedCount: 1)
try AES.GCM._open(
ciphertext.span.bytes,
using: key,
nonce: nonce,
authenticating: authenticatedData.span.bytes,
tag: tag.span.bytes,
output: &output
)
XCTAssertEqual(output.byteCount, decryptedBuffer.count)
}
XCTAssertEqual(decrypted, [0xFF] + plaintext)
}
func testOpenOverOutputSpanWithModifiedTagThrows() throws {
guard #available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0, *) else {
throw XCTSkip("Array.span requires macOS 26.0+, iOS 26.0+, watchOS 26.0+, tvOS 26.0+, visionOS 26.0+")
}
let key = SymmetricKey(size: .bits256)
let nonce = AES.GCM.Nonce()
let sealedBox = try AES.GCM.seal(Array("Some Super Secret Message".utf8), using: key, nonce: nonce)
let ciphertext = Array(sealedBox.ciphertext)
var tag = Array(sealedBox.tag)
tag[0] ^= 1
var decrypted = [UInt8](repeating: 0, count: ciphertext.count)
try decrypted.withUnsafeMutableBytes { decryptedBuffer in
var output = OutputRawSpan(buffer: decryptedBuffer, initializedCount: 0)
XCTAssertThrowsError(
try AES.GCM._open(
ciphertext.span.bytes,
using: key,
nonce: nonce,
tag: tag.span.bytes,
output: &output
)
)
XCTAssertEqual(output.byteCount, 0)
}
}
}
@@ -89,4 +89,14 @@ final class Curve25519DERTests: XCTestCase {
let key = try Curve25519.KeyAgreement.PrivateKey(derRepresentation: derBytes) let key = try Curve25519.KeyAgreement.PrivateKey(derRepresentation: derBytes)
XCTAssertEqual(key.rawRepresentation.count, 32) XCTAssertEqual(key.rawRepresentation.count, 32)
} }
func testPrivateKeyWithMismatchedAlgorithmThrows() throws {
let signingKey = Curve25519.Signing.PrivateKey()
let keyAgreementKey = Curve25519.KeyAgreement.PrivateKey()
XCTAssertThrowsError(try Curve25519.Signing.PrivateKey(derRepresentation: keyAgreementKey.derRepresentation))
XCTAssertThrowsError(try Curve25519.Signing.PrivateKey(pemRepresentation: keyAgreementKey.pemRepresentation))
XCTAssertThrowsError(try Curve25519.KeyAgreement.PrivateKey(derRepresentation: signingKey.derRepresentation))
XCTAssertThrowsError(try Curve25519.KeyAgreement.PrivateKey(pemRepresentation: signingKey.pemRepresentation))
}
} }
+81
View File
@@ -84,4 +84,85 @@ class ScryptTests: XCTestCase {
try orFail { try self.testRFCVector(vector) } try orFail { try self.testRFCVector(vector) }
} }
} }
func testDeriveKeyWithMaxMemoryBelowRequirementThrows() throws {
let password = Array("password".utf8)
let salt = Array("salt".utf8)
// These parameters need 128 * blockSize * (rounds + parallelism + 1) bytes, just over 1 MiB.
// BoringSSL reads a limit of zero as "use the default limit", and a negative limit as a huge size_t.
for maxMemory in [1024, 0, -1] {
XCTAssertThrowsError(
try KDF.Scrypt.deriveKey(
from: password,
salt: salt,
outputByteCount: 32,
rounds: 1024,
blockSize: 8,
parallelism: 1,
maxMemory: maxMemory
)
)
}
let bounded = try KDF.Scrypt.deriveKey(
from: password,
salt: salt,
outputByteCount: 32,
rounds: 1024,
blockSize: 8,
parallelism: 1,
maxMemory: 2 << 20
)
let unbounded = try KDF.Scrypt.deriveKey(
from: password,
salt: salt,
outputByteCount: 32,
rounds: 1024,
blockSize: 8,
parallelism: 1
)
XCTAssertEqual(bounded, unbounded)
}
func testDeriveKeyWithDefaultMaxMemoryAndBlockSizeAboveRoundsSucceeds() throws {
// Needs 128 * 1024 * (2 + 1 + 1) bytes, more than 128 * blockSize * rounds * parallelism.
XCTAssertNoThrow(
try KDF.Scrypt.deriveKey(
from: [UInt8](),
salt: [UInt8](),
outputByteCount: 32,
rounds: 2,
blockSize: 1024,
parallelism: 1
)
)
}
func testDeriveKeyWithOutOfRangeParametersThrows() throws {
let password = Array("password".utf8)
let salt = Array("salt".utf8)
for (rounds, blockSize, parallelism, outputByteCount) in [
// Negative values reach UInt64 conversions and Data(count:), both of which trap.
(-1, 8, 1, 32),
(1024, -1, 1, 32),
(1024, 8, -1, 32),
(1024, 8, 1, -1),
// 128 * blockSize * (rounds + parallelism + 1) overflows Int.
(1 << 32, 1 << 30, 1, 32),
(1024, 8, .max, 32),
] {
XCTAssertThrowsError(
try KDF.Scrypt.deriveKey(
from: password,
salt: salt,
outputByteCount: outputByteCount,
rounds: rounds,
blockSize: blockSize,
parallelism: parallelism
)
)
}
}
} }
@@ -0,0 +1,50 @@
//===----------------------------------------------------------------------===//
//
// 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 XCTest
#if canImport(CryptoKit)
// Skip tests that require @testable imports of CryptoKit.
#else
@testable import Crypto
extension X25519Tests {
func testKeyAgreementWithLowOrderPublicKeyThrows() throws {
// The vectors whose shared secret is all-zero: the seven low-order u-coordinates, which are
// 0, 1, both points of order 8, p-1, p and p+1, plus a non-canonical spelling of each.
try wycheproofTest(
bundleType: self,
jsonName: "x25519_test",
testFunction: { (group: ECDHTestGroup) in
let zeroSharedSecretTests = group.tests.filter { $0.flags.contains("ZeroSharedSecret") }
XCTAssert(!zeroSharedSecretTests.isEmpty)
for testVector in zeroSharedSecretTests {
// The public key itself is accepted, as it is by CryptoKit; only the agreement fails.
let publicKey = try Curve25519.KeyAgreement.PublicKey(
rawRepresentation: Array(hexString: testVector.publicKey)
)
let privateKey = try Curve25519.KeyAgreement.PrivateKey(
rawRepresentation: Array(hexString: testVector.privateKey)
)
XCTAssertThrowsError(
try privateKey.sharedSecretFromKeyAgreement(with: publicKey),
"tcId \(testVector.tcId)"
)
}
}
)
}
}
#endif // canImport(CryptoKit)