Compare commits

...
10 Commits
Author SHA1 Message Date
1b6b2e274e Add module anchor to fix empty dynamic framework on Xcode 26 (#436)
## Summary

Fixes #435.

On Apple platforms every source file in the `Crypto` target compiles to
just `@_exported import CryptoKit` (because `CRYPTO_IN_SWIFTPM` is
defined but `CRYPTO_IN_SWIFTPM_FORCE_BUILD_API` is not), producing
**zero exported symbols**.

Xcode 26 changed how SPM packages are built for test-target
dependencies: each package product is built as a separate dynamic
framework. A module with no symbols generates a `.framework` directory
but no Mach-O binary, causing a linker error:

```
clang: error: no such file or directory:
  '.../PackageFrameworks/Crypto_17A3B1FFC41E47_PackageProduct.framework/Crypto_17A3B1FFC41E47_PackageProduct'
```

## Fix

Added a minimal `_CryptoModuleAnchor` public enum (outside the
conditional compilation guard) so the module always produces at least
one exported symbol, regardless of how it is linked. The type is
prefixed with `_` to signal it is not intended for public use.

## Test plan

- [ ] Build a project with a test target that has `swift-crypto` (or a
transitive dependency like `swift-certificates`) as a
`packageProductDependency` on Xcode 26 targeting iOS Simulator — should
now succeed
- [ ] Verify existing tests still pass (`swift test`)

---------

Co-authored-by: Niccolò Calamai <niccolo.calamai@esselunga.it>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-04-20 09:37:39 +01:00
2d37b1192f Adopt FoundationEssentials instead of Foundation where available (#317)
Use `FoundationEssentials` if available.

<!-- Thanks for contributing to Swift Crypto! Before you submit your
issue, please make sure you followed our checklist and check the
appropriate boxes by putting an x in the [ ]: [x] -->

### Checklist
- [x] I've run tests to see all new and existing tests pass (macOS and
linux)
- [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
```
bash .script/generate_boilerplate_files_with_gyb
bash: .script/generate_boilerplate_files_with_gyb: No such file or directory
```

### Motivation:

Would be great that packages that depend on `swift-crypto` can be built
without linking full `Foundation`.

### Modifications:

This patch simply replaces `import Foundation` with a conditional
`import FoundationEssentials`.

In some files this also required to explicitly import the C standard
lib.

Maybe we could follow the same approach as in
https://github.com/swiftlang/swift-tools-support-core/blob/main/Sources/TSCLibc/libc.swift
and add an internal module that abstracts this import dance in a single
place.

### Result:

After this change the package should only depend on
`FoundationEssentials`.

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-04-17 15:06:53 +00:00
Andreas BauerandCory Benfield c5b1d7f0cb Add support for SHA-512/256 (#432)
Add SHA-512/256 digest implementation via BoringSSL

### 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
- [N/A] I've run `.script/generate_boilerplate_files_with_gyb` and
included updated generated files in a commit of this pull request

### Motivation:

Neither CryptoKit nor swift-crypto currently explore the SHA-512/256
hashing function. SHA-512/256 provides the same 256-bit security level
as SHA-256 but can be significantly faster on 64-bit platforms because
it uses the SHA-512 internal structure, which operates on 64-bit words.

### Modifications:

We modified CryptoExtras to include support using the BoringSSL
implementation.

### Result:

Swift ecosystem supports SHA-512/256.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-04-17 14:02:55 +00:00
Rick Newton-Rogers 476538ccb8 Drop Swift 6.0 (#434)
Motivation:

Swift 6.0 is no longer supported, we should bump the tools version and
remove it from our CI.

Modifications:

* Bump the Swift tools version to Swift 6.1
* Remove Swift 6.0 jobs where appropriate in main.yml, pull_request.yml

Result:

Code reflects our support window.
2026-04-08 15:04:09 +01:00
Rick Newton-Rogers 5ef6059b2b Enable Swift 6.3 jobs in CI (#433)
Motivation:

Swift 6.3 has been released, we should add it to our CI coverage.

Modifications:

Add additional Swift 6.3 jobs where appropriate in main.yml,
pull_request.yml

Result:

Improved test coverage.
2026-04-01 14:20:59 +01:00
Raphael bb4ba815da Merge commit from fork
* Reproduce memory-safty issue in HPKE decapsulation

* Validate ciphertext len before calling decapsulate
2026-04-01 10:08:47 +01:00
Rick Newton-Rogers fa308c07a6 update actions/checkout from v4 to v6 (#431)
Motivation

* Following [GitHub's
announcement](https://github.blog/changelog/2025-09-19-deprecation-of-node-20-on-github-actions-runners/),
Node 20 is being deprecated and runners will begin using Node 24 by
default starting March 4th, 2026. Node 20 will reach end-of-life in
April 2026.

Modifications

* Upgrade GitHub Actions to their latest versions to ensure
compatibility with Node 24.
* Replace `actions/checkout@v4` with `actions/checkout@v6` in all
workflow files.

Result

* Workflow files reference `actions/checkout@v6`.
2026-03-02 13:29:52 +00:00
Francesco Paolo Severino a5a71cfcbc Add support for encrypted PEM keys via BoringSSL (#428)
Add support for creating RSA private keys from encrypted PEM files.

### 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 `./scripts/generate_boilerplate_files_with_gyb.sh` and
included updated generated files in a commit of this pull request

### Motivation:

Resolves #264

### Modifications:

Adds an initializer to `_RSA.Signing.PrivateKey` that takes the
encrypted PEM representation and the encryption password and calls the
high-level BoringSSL function to parse the encrypted key format.

Tests were copied from #318 by @ptoffy.

### Result:

RSA private keys can be created from encrypted PEM files.
2026-02-23 13:29:41 +00:00
Rick Newton-Rogers 31611736b0 switch from main to 0.0.7 for swiftlang workflows (#430)
Motivation

* `@main` references to `swiftlang/github-workflows` are deprecated.

Modifications

* Replace `@main` with `@0.0.7` in all workflow files.

Result

* Workflow files reference a pinned version of
`swiftlang/github-workflows`.
2026-02-20 13:34:31 +00:00
Mike SchragandMike Schrag 6f70fa9eab Add RSA PKCSv1.5 padding support for legacy compat (#425)
Add RSA PKCSv1.5 padding support for legacy compat

### 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
- [n/a] I've run `./scripts/generate_boilerplate_files_with_gyb.sh` and
included updated generated files in a commit of this pull request

### Motivation:
I have a scenario that requires me to be able to encrypt and decrypt
values that use RSA PKCSv1.5 padding. This is known to be a weak
algorithm, so we explicitly want to discourage its use, but there are
scenarios where you need the algorithm for legacy compatibility, so we
want to provide the capability, even if we strongly discourage its use.

### Modifications:
Added a new enum + constant + passthrough to allow users to specify RSA
PKCSv1.5. From the internal review, we thought it would be best to
explicitly name the constants in a way that discouraged use without very
intentional needs, hence the "weak" and "insecure" references in all of
the naming.

### Result:
You can now specify PKCSv1.5 padding for use in encryption and
decryption. This is only adding constants, and the enums are not public,
so there should not be any impact on compatibility (source or binary).

Co-authored-by: Mike Schrag <schrag@apple.com>
2025-11-19 20:31:42 +00:00
32 changed files with 933 additions and 41 deletions

No files matched your search

+4 -4
View File
@@ -15,19 +15,19 @@ jobs:
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
with:
linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_0_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_1_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_2_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_3_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_0_enabled: true
windows_6_1_enabled: true
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
windows_6_0_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_1_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_2_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_3_arguments_override: "--explicit-target-dependency-import-check error"
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
@@ -35,9 +35,9 @@ jobs:
name: Release builds
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
with:
windows_6_0_enabled: true
windows_6_1_enabled: true
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
+5 -5
View File
@@ -10,7 +10,7 @@ on:
jobs:
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.7
with:
license_header_check_project_name: "SwiftCrypto"
docs_check_enabled: false
@@ -20,19 +20,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 +40,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 -1
View File
@@ -14,7 +14,7 @@ jobs:
timeout-minutes: 1
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
persist-credentials: false
- name: Check for Semantic Version label
+1 -1
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.10
// swift-tools-version:6.1
import PackageDescription
let package = Package(
+1 -1
View File
@@ -1,4 +1,4 @@
// swift-tools-version:6.0
// swift-tools-version:6.1
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
+1
View File
@@ -102,6 +102,7 @@ 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 contex = H.initialize() else {
guard let context = H.initialize() else {
preconditionFailure("Unable to initialize digest state")
}
self.context = contex
self.context = context
}
init(copying original: DigestContext) {
@@ -236,7 +236,13 @@ extension OpenSSLXWingPrivateKeyImpl {
}
func decapsulate(_ encapsulated: Data) throws -> SymmetricKey {
try SymmetricKey(unsafeUninitializedCapacity: Int(XWING_SHARED_SECRET_BYTES)) { sharedSecretBytes, count in
guard encapsulated.count == Int(XWING_CIPHERTEXT_BYTES) else {
throw CryptoKitError.incorrectParameterSize
}
return try SymmetricKey(unsafeUninitializedCapacity: Int(XWING_SHARED_SECRET_BYTES)) {
sharedSecretBytes,
count in
try encapsulated.withUnsafeBytes { encapsulatedSecretBytes in
let rc = CCryptoBoringSSL_XWING_decap(
sharedSecretBytes.baseAddress,
@@ -0,0 +1,25 @@
//===----------------------------------------------------------------------===//
//
// 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,8 +14,13 @@
@_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
+6
View File
@@ -33,6 +33,10 @@ 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"
@@ -53,10 +57,12 @@ 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"
@@ -0,0 +1,82 @@
//===----------------------------------------------------------------------===//
//
// 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)
}
}
@@ -0,0 +1,43 @@
//===----------------------------------------------------------------------===//
//
// 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
}
}
@@ -0,0 +1,88 @@
//===----------------------------------------------------------------------===//
//
// 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()
}
}
@@ -0,0 +1,99 @@
//===----------------------------------------------------------------------===//
//
// 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) }
}
}
+6 -1
View File
@@ -13,9 +13,14 @@
//===----------------------------------------------------------------------===//
import Crypto
import Foundation
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.
@@ -13,9 +13,14 @@
//===----------------------------------------------------------------------===//
import Crypto
import Foundation
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 in PKCS#8 format.
@@ -0,0 +1,87 @@
//===----------------------------------------------------------------------===//
//
// 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)
}
+55 -1
View File
@@ -183,6 +183,45 @@ 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
@@ -655,6 +694,7 @@ 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)
}
@@ -663,7 +703,18 @@ 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).
@@ -711,6 +762,9 @@ 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
+42
View File
@@ -94,6 +94,17 @@ 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)
}
@@ -418,6 +429,8 @@ 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 {
@@ -602,6 +615,33 @@ 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!)
@@ -883,6 +923,8 @@ 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 {
@@ -0,0 +1,29 @@
//===----------------------------------------------------------------------===//
//
// 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
+6 -1
View File
@@ -13,9 +13,14 @@
//===----------------------------------------------------------------------===//
import Crypto
import CryptoExtras
import Foundation
import XCTest
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
final class CMACTests: XCTestCase {
// Borrowed from CryptoKit
func testVector1() throws {
@@ -12,9 +12,14 @@
//
//===----------------------------------------------------------------------===//
import Crypto
import Foundation
import XCTest
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#if !canImport(Darwin) || canImport(CryptoKit, _version: 241.100.42)
// Corresponds to the CryptoKit in XCode 16.3, which has Sendable annotations
import Crypto
@@ -0,0 +1,130 @@
//===----------------------------------------------------------------------===//
//
// 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
DjMVbU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0QJ+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-----
MIIFJDBWBgkqhkiG9w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qMzLCfZtsCCZ7Mupo7
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,11 +13,16 @@
//===----------------------------------------------------------------------===//
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 = """
@@ -0,0 +1,97 @@
//===----------------------------------------------------------------------===//
//
// 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)
}
}
@@ -169,6 +169,66 @@ final class TestRSAEncryption: XCTestCase {
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-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hbVuMyT4uLaN5D1M47ZYaq75dPM83fqZ
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 {
@@ -29,7 +29,6 @@ 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)
@@ -37,10 +36,6 @@ 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,7 +25,6 @@ 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)
@@ -33,10 +32,6 @@ 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,6 +84,39 @@ 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,7 +33,6 @@ 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)
@@ -41,10 +40,6 @@ 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,7 +29,6 @@ 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)
@@ -37,10 +36,6 @@ 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)) }