Compare commits

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

---------

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

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

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

### Motivation:

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

### Modifications:

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

### Result:

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

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

## Modifications

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

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

## Result

Swift Crypto provides functioning SHA-3 API.

## Notes

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

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

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

Modifications

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

Result

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

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

FoundationEssentials produces smaller binaries on most platforms.

### Modifications:

Where FoundationEssentials is available, import that.

### Result:

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

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

No files matched your search

-3
View File
@@ -1,8 +1,5 @@
name: Main
permissions:
contents: read
on:
push:
branches: [main]
-3
View File
@@ -1,8 +1,5 @@
name: PR
permissions:
contents: read
on:
pull_request:
types: [opened, reopened, synchronize]
-3
View File
@@ -1,8 +1,5 @@
name: PR label
permissions:
contents: read
on:
pull_request:
types: [labeled, unlabeled, opened, reopened, synchronize]
+5 -10
View File
@@ -7,9 +7,9 @@ Swift Crypto is an open-source implementation of a substantial portion of the AP
Swift Crypto is available as a Swift Package Manager package. To use it, add the following dependency in your `Package.swift`:
```swift
// swift-crypto 1.x, 2.x, 3.x, and 4.x are almost API compatible, so most clients
// swift-crypto 1.x, 2.x and 3.x are almost API compatible, so most clients
// should allow any of them
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "5.0.0"),
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "4.0.0"),
```
and to your target, add `Crypto` to your dependencies. You can then `import Crypto` to get access to Swift Crypto's functionality.
@@ -108,7 +108,7 @@ If you believe you have identified a vulnerability in Swift Crypto, please [repo
### Swift versions
The most recent versions of Swift Crypto support Swift 6 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
The most recent versions of Swift Crypto support Swift 5.7 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
Swift Crypto | Minimum Swift Version
--------------------|----------------------
@@ -119,8 +119,7 @@ Swift Crypto | Minimum Swift Version
`3.1.0 ..< 3.3.0` | 5.7
`3.3.0 ..< 3.8.0` | 5.8
`3.9.0 ..< 3.13.0` | 5.9
`3.13.0 ..< 4.0.0` | 5.10
`4.0.0 ...` | 6.0
`3.13.0 ...` | 5.10
### Compatibility
@@ -132,14 +131,10 @@ SemVer and Swift Crypto's Public API guarantees should result in a working progr
Swift Crypto 2.0.0 was released in September 2021. The only breaking change between Swift Crypto 2.0.0 and 1.0.0 was the addition of new cases in the `CryptoError` enumeration. For most users, then, it's safe to depend on either the 1.0.0 _or_ 2.0.0 series of releases.
Swift Crypto 3.0.0 was released in September 2023. Again the only breaking change was the addition of new cases in the `CryptoError` enumeration, so most users can safely depend on the 1.0.0, 2.0.0, or 3.0.0 series of releases.
Swift Crypto 4.0.0 was released in September 2025. Again the only breaking change was the addition of new cases in the `CryptoError` enumeration, so most users can safely depend on the 1.0.0, 2.0.0, 3.0.0, or 4.0.0 series of releases. Note that in this release `_CryptoExtras` was renamed to `CryptoExtras`. The old products and targets have been kept around for compatibility reasons, but users depending only on new code should use `CryptoExtras` not `_CryptoExtras`.
To do so, please use the following dependency in your `Package.swift`:
```swift
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "5.0.0"),
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "3.0.0"),
```
### Developing Swift Crypto on macOS
-1
View File
@@ -33,7 +33,6 @@ add_library(CryptoExtras
"ARC/ARCServer.swift"
"ChaCha20CTR/BoringSSL/ChaCha20CTR_boring.swift"
"ChaCha20CTR/ChaCha20CTR.swift"
"EC/Curve25519+PEM.swift"
"EC/ObjectIdentifier.swift"
"EC/PKCS8DERRepresentation.swift"
"EC/PKCS8PrivateKey.swift"
@@ -1,180 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Crypto
import Foundation
import SwiftASN1
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *)
extension Curve25519.Signing.PrivateKey {
/// A Distinguished Encoding Rules (DER) encoded representation of the private key.
public var derRepresentation: Data {
let pkey = ASN1.PKCS8PrivateKey(algorithm: .ed25519, privateKey: Array(self.rawRepresentation))
var serializer = DER.Serializer()
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
/// A Privacy-Enhanced Mail (PEM) representation of the private key.
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
/// Creates a Curve25519 private key for signing from a Privacy-Enhanced Mail
/// (PEM) representation.
///
/// - Parameters:
/// - pemRepresentation: A PEM representation of the key.
public init(pemRepresentation: String) throws {
let document = try ASN1.PEMDocument(pemString: pemRepresentation)
self = try .init(derRepresentation: document.derBytes)
}
/// Creates a Curve25519 private key for signing from a Distinguished Encoding
/// Rules (DER) encoded representation.
///
/// - Parameters:
/// - derRepresentation: A DER-encoded representation of the key.
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
let key = try ASN1.PKCS8PrivateKey(derEncoded: bytes)
self = try .init(rawRepresentation: key.privateKey.bytes)
}
}
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *)
extension Curve25519.Signing.PublicKey {
/// A Distinguished Encoding Rules (DER) encoded representation of the public key.
public var derRepresentation: Data {
let spki = SubjectPublicKeyInfo(algorithmIdentifier: .ed25519, key: Array(self.rawRepresentation))
var serializer = DER.Serializer()
try! serializer.serialize(spki)
return Data(serializer.serializedBytes)
}
/// A Privacy-Enhanced Mail (PEM) representation of the public key.
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PUBLIC KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
/// Creates a Curve25519 public key for signing from a Privacy-Enhanced Mail
/// (PEM) representation.
///
/// - Parameters:
/// - pemRepresentation: A PEM representation of the key.
public init(pemRepresentation: String) throws {
let document = try ASN1.PEMDocument(pemString: pemRepresentation)
self = try .init(derRepresentation: document.derBytes)
}
/// Creates a Curve25519 public key for signing from a Distinguished Encoding
/// Rules (DER) encoded representation.
///
/// - Parameters:
/// - derRepresentation: A DER-encoded representation of the key.
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
let spki = try SubjectPublicKeyInfo(derEncoded: bytes)
guard spki.algorithmIdentifier == .ed25519 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: spki.key.bytes)
}
}
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *)
extension Curve25519.KeyAgreement.PrivateKey {
/// A Distinguished Encoding Rules (DER) encoded representation of the private key.
public var derRepresentation: Data {
let pkey = ASN1.PKCS8PrivateKey(algorithm: .x25519, privateKey: Array(self.rawRepresentation))
var serializer = DER.Serializer()
// Serializing this key can't throw
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
/// A Privacy-Enhanced Mail (PEM) representation of the private key.
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
/// Creates a Curve25519 private key for key agreement from a Privacy-Enhanced Mail
/// (PEM) representation.
///
/// - Parameters:
/// - pemRepresentation: A PEM representation of the key.
public init(pemRepresentation: String) throws {
let document = try ASN1.PEMDocument(pemString: pemRepresentation)
self = try .init(derRepresentation: document.derBytes)
}
/// Creates a Curve25519 private key for key agreement from a Distinguished Encoding
/// Rules (DER) encoded representation.
///
/// - Parameters:
/// - derRepresentation: A DER-encoded representation of the key.
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
let key = try ASN1.PKCS8PrivateKey(derEncoded: bytes)
self = try .init(rawRepresentation: key.privateKey.bytes)
}
}
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *)
extension Curve25519.KeyAgreement.PublicKey {
/// A Distinguished Encoding Rules (DER) encoded representation of the public key.
public var derRepresentation: Data {
let spki = SubjectPublicKeyInfo(algorithmIdentifier: .x25519, key: Array(self.rawRepresentation))
var serializer = DER.Serializer()
try! serializer.serialize(spki)
return Data(serializer.serializedBytes)
}
/// A Privacy-Enhanced Mail (PEM) representation of the public key.
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PUBLIC KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
/// Creates a Curve25519 public key for key agreement from a Privacy-Enhanced Mail
/// (PEM) representation.
///
/// - Parameters:
/// - pemRepresentation: A PEM representation of the key.
public init(pemRepresentation: String) throws {
let document = try ASN1.PEMDocument(pemString: pemRepresentation)
self = try .init(derRepresentation: document.derBytes)
}
/// Creates a Curve25519 public key for key agreement from a Distinguished Encoding
/// Rules (DER) encoded representation.
///
/// - Parameters:
/// - derRepresentation: A DER-encoded representation of the key.
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
let spki = try SubjectPublicKeyInfo(derEncoded: bytes)
guard spki.algorithmIdentifier == .x25519 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(rawRepresentation: spki.key.bytes)
}
}
@@ -20,7 +20,12 @@ import SwiftASN1
extension Curve25519.Signing.PrivateKey {
/// A Distinguished Encoding Rules (DER) encoded representation of the private key in PKCS#8 format.
public var pkcs8DERRepresentation: Data {
self.derRepresentation
let pkey = ASN1.PKCS8PrivateKey(algorithm: .ed25519, privateKey: Array(self.rawRepresentation))
var serializer = DER.Serializer()
// Serializing this key can't throw
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
}
@@ -28,7 +33,12 @@ extension Curve25519.Signing.PrivateKey {
extension Curve25519.KeyAgreement.PrivateKey {
/// A Distinguished Encoding Rules (DER) encoded representation of the private key in PKCS#8 format.
public var pkcs8DERRepresentation: Data {
self.derRepresentation
let pkey = ASN1.PKCS8PrivateKey(algorithm: .x25519, privateKey: Array(self.rawRepresentation))
var serializer = DER.Serializer()
// Serializing this key can't throw
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
}
+5 -29
View File
@@ -508,7 +508,7 @@ extension _RSA.Encryption {
/// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons.
public init(unsafePEMRepresentation pemRepresentation: String) throws {
self.backing = try BackingPublicKey(pemRepresentation: pemRepresentation)
guard self.keySizeInBits >= 1024, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
guard self.keySizeInBits >= 2048, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
}
/// Construct an RSA public key from a DER representation.
@@ -655,7 +655,6 @@ extension _RSA.Encryption {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
public struct Padding: Sendable {
internal enum Backing {
case _weakAndInsecure_pkcs1v1_5
case pkcs1_oaep(Digest)
}
@@ -664,18 +663,7 @@ extension _RSA.Encryption {
private init(_ backing: Backing) {
self.backing = backing
}
/// PKCS#1 v1.5 padding
///
/// As defined by [RFC 8017 § 7.2](https://datatracker.ietf.org/doc/html/rfc8017#section-7.2).
///
/// This padding exists only for legacy compatibility and is known to be
/// weak and insecure. This algorithm is vulnerable to chosen-ciphertext
/// attacks outlined in http://archiv.infsec.ethz.ch/education/fs08/secsem/bleichenbacher98.pdf.
///
/// When you have a choice, you should always favor OAEP over this.
public static let _WEAK_AND_INSECURE_PKCS_V1_5 = Self(._weakAndInsecure_pkcs1v1_5)
/// PKCS#1 OAEP padding
///
/// As defined by [RFC 8017 § 7.1](https://datatracker.ietf.org/doc/html/rfc8017#section-7.1).
@@ -687,14 +675,6 @@ extension _RSA.Encryption {
internal enum Digest {
case sha1
case sha256
/// Returns the number of bits in the resulting hash
var hashBitLength: Int {
switch self {
case .sha1: return 160
case .sha256: return 256
}
}
}
}
@@ -714,7 +694,7 @@ extension _RSA.Encryption.PublicKey {
/// Return the maximum amount of data in bytes this key can encrypt in a single operation when using
/// the specified padding mode.
///
/// ## Common values (for PKCS1 OAEP SHA1):
/// ## Common values:
///
/// Key size|Padding|Max length
/// -|-|-
@@ -723,12 +703,8 @@ extension _RSA.Encryption.PublicKey {
/// 4096|PKCS-OAEP|470 bytes
public func maximumEncryptSize(with padding: _RSA.Encryption.Padding) -> Int {
switch padding.backing {
case ._weakAndInsecure_pkcs1v1_5:
// https://www.rfc-editor.org/rfc/rfc8017#section-7.2
return (self.keySizeInBits / 8) - 11
case let .pkcs1_oaep(Digest):
// https://datatracker.ietf.org/doc/html/rfc8017#section-7.1.1
return (self.keySizeInBits / 8) - (2 * Digest.hashBitLength / 8) - 2
case .pkcs1_oaep:
return (self.keySizeInBits / 8) - 42
}
}
@@ -418,8 +418,6 @@ extension BoringSSLRSAPublicKey {
CCryptoBoringSSL_EVP_PKEY_encrypt_init(ctx)
switch padding.backing {
case ._weakAndInsecure_pkcs1v1_5:
CCryptoBoringSSL_EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING)
case let .pkcs1_oaep(digest):
CCryptoBoringSSL_EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING)
switch digest {
@@ -885,8 +883,6 @@ extension BoringSSLRSAPrivateKey {
CCryptoBoringSSL_EVP_PKEY_decrypt_init(ctx)
switch padding.backing {
case ._weakAndInsecure_pkcs1v1_5:
CCryptoBoringSSL_EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING)
case let .pkcs1_oaep(digest):
CCryptoBoringSSL_EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING)
switch digest {
@@ -125,10 +125,3 @@ extension SubjectPublicKeyInfo {
return serializer.serializedBytes
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension RFC5480AlgorithmIdentifier {
static let ed25519 = RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEd25519, parameters: nil)
static let x25519 = RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idX25519, parameters: nil)
}
@@ -1,91 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import CryptoExtras
import XCTest
final class Curve25519DERTests: XCTestCase {
func testSigningPrivateKeyDERRoundTrip() throws {
let privateKey = Curve25519.Signing.PrivateKey()
let der = privateKey.derRepresentation
let imported = try Curve25519.Signing.PrivateKey(derRepresentation: der)
XCTAssertEqual(imported.rawRepresentation, privateKey.rawRepresentation)
}
func testSigningPublicKeyDERRoundTrip() throws {
let privateKey = Curve25519.Signing.PrivateKey()
let publicKey = privateKey.publicKey
let der = publicKey.derRepresentation
let imported = try Curve25519.Signing.PublicKey(derRepresentation: der)
XCTAssertEqual(imported.rawRepresentation, publicKey.rawRepresentation)
}
func testKeyAgreementPrivateKeyDERRoundTrip() throws {
let privateKey = Curve25519.KeyAgreement.PrivateKey()
let der = privateKey.derRepresentation
let imported = try Curve25519.KeyAgreement.PrivateKey(derRepresentation: der)
XCTAssertEqual(imported.rawRepresentation, privateKey.rawRepresentation)
}
func testKeyAgreementPublicKeyDERRoundTrip() throws {
let privateKey = Curve25519.KeyAgreement.PrivateKey()
let publicKey = privateKey.publicKey
let der = publicKey.derRepresentation
let imported = try Curve25519.KeyAgreement.PublicKey(derRepresentation: der)
XCTAssertEqual(imported.rawRepresentation, publicKey.rawRepresentation)
}
func testInvalidDERThrows() throws {
let invalidDER: [UInt8] = [0x01, 0x02, 0x03]
XCTAssertThrowsError(try Curve25519.Signing.PrivateKey(derRepresentation: invalidDER))
XCTAssertThrowsError(try Curve25519.Signing.PublicKey(derRepresentation: invalidDER))
XCTAssertThrowsError(try Curve25519.KeyAgreement.PrivateKey(derRepresentation: invalidDER))
XCTAssertThrowsError(try Curve25519.KeyAgreement.PublicKey(derRepresentation: invalidDER))
}
func testImportOpenSSLSigningPrivateKeyDER() throws {
// DER extracted from an OpenSSL-generated Ed25519 PKCS#8 PEM
let derBytes: [UInt8] = [
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70,
0x04, 0x22, 0x04, 0x20, 0x3f, 0x10, 0x52, 0x03, 0xb4, 0x06, 0x87, 0x0c,
0x51, 0x71, 0xfa, 0xdc, 0x8f, 0x96, 0xbd, 0x2a, 0x5f, 0x42, 0xac, 0x5c,
0xb9, 0x5b, 0x27, 0x4e, 0xf0, 0x06, 0xe5, 0x61, 0x6a, 0x12, 0x00, 0xa5,
]
let key = try Curve25519.Signing.PrivateKey(derRepresentation: derBytes)
XCTAssertEqual(key.rawRepresentation.count, 32)
}
func testImportOpenSSLKeyAgreementPrivateKeyDER() throws {
// DER extracted from an OpenSSL-generated X25519 PKCS#8 PEM
let derBytes: [UInt8] = [
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e,
0x04, 0x22, 0x04, 0x20, 0xb8, 0x38, 0x3f, 0x28, 0xea, 0x8f, 0x1d, 0x71,
0x49, 0xa2, 0xa3, 0x91, 0x37, 0x00, 0xa1, 0x0c, 0x7c, 0x9d, 0xa9, 0x59,
0x28, 0x2d, 0x14, 0x7e, 0x9b, 0x1e, 0x1b, 0x8c, 0x04, 0xa5, 0xd8, 0x47,
]
let key = try Curve25519.KeyAgreement.PrivateKey(derRepresentation: derBytes)
XCTAssertEqual(key.rawRepresentation.count, 32)
}
}
@@ -1,140 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import CryptoExtras
import XCTest
final class Curve25519PEMTests: XCTestCase {
func testSigningPrivateKeyPEMRoundTrip() throws {
let privateKey = Curve25519.Signing.PrivateKey()
let imported = try Curve25519.Signing.PrivateKey(pemRepresentation: privateKey.pemRepresentation)
XCTAssertEqual(imported.rawRepresentation, privateKey.rawRepresentation)
}
func testSigningPublicKeyPEMRoundTrip() throws {
let privateKey = Curve25519.Signing.PrivateKey()
let publicKey = privateKey.publicKey
let imported = try Curve25519.Signing.PublicKey(pemRepresentation: publicKey.pemRepresentation)
XCTAssertEqual(imported.rawRepresentation, publicKey.rawRepresentation)
}
func testKeyAgreementPrivateKeyPEMRoundTrip() throws {
let privateKey = Curve25519.KeyAgreement.PrivateKey()
let imported = try Curve25519.KeyAgreement.PrivateKey(pemRepresentation: privateKey.pemRepresentation)
XCTAssertEqual(imported.rawRepresentation, privateKey.rawRepresentation)
}
func testKeyAgreementPublicKeyPEMRoundTrip() throws {
let privateKey = Curve25519.KeyAgreement.PrivateKey()
let publicKey = privateKey.publicKey
let imported = try Curve25519.KeyAgreement.PublicKey(pemRepresentation: publicKey.pemRepresentation)
XCTAssertEqual(imported.rawRepresentation, publicKey.rawRepresentation)
}
func testImportOpenSSLSigningPrivateKeyPEM() throws {
// Generated via `openssl genpkey -algorithm Ed25519 -outform PEM`
let pem = """
-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VwBCIEIIHEchKSA2A/z1r4tVHJ9f+yS6YXhUbBdHJiryZnRqnD
-----END PRIVATE KEY-----
"""
let key = try Curve25519.Signing.PrivateKey(pemRepresentation: pem)
XCTAssertEqual(key.rawRepresentation.count, 32)
}
func testImportOpenSSLKeyAgreementPrivateKeyPEM() throws {
// Generated via `openssl genpkey -algorithm X25519 -outform PEM`
let pem = """
-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VuBCIEIMDJoDr+3A91QpL8BLIeCKSAKI5T7frtzEaE5HzugtR1
-----END PRIVATE KEY-----
"""
let key = try Curve25519.KeyAgreement.PrivateKey(pemRepresentation: pem)
XCTAssertEqual(key.rawRepresentation.count, 32)
}
func testInvalidPEMThrows() {
let invalidPEM = """
-----BEGIN PRIVATE KEY-----
abc
-----END PRIVATE KEY-----
"""
XCTAssertThrowsError(try Curve25519.Signing.PrivateKey(pemRepresentation: invalidPEM))
XCTAssertThrowsError(try Curve25519.KeyAgreement.PrivateKey(pemRepresentation: invalidPEM))
let invalidPublicPEM = """
-----BEGIN PUBLIC KEY-----
xyz
-----END PUBLIC KEY-----
"""
XCTAssertThrowsError(try Curve25519.Signing.PublicKey(pemRepresentation: invalidPublicPEM))
XCTAssertThrowsError(try Curve25519.KeyAgreement.PublicKey(pemRepresentation: invalidPEM))
}
func testWrongAlgorithmOIDThrows() throws {
XCTAssertThrowsError(try Curve25519.Signing.PrivateKey(pemRepresentation: rsaPEM))
XCTAssertThrowsError(try Curve25519.KeyAgreement.PublicKey(pemRepresentation: rsaPEM))
}
func testSigningPrivatePublicKeyConsistency() throws {
let privateKey = Curve25519.Signing.PrivateKey()
let publicKey = privateKey.publicKey
let importedPrivate = try Curve25519.Signing.PrivateKey(pemRepresentation: privateKey.pemRepresentation)
let importedPublic = try Curve25519.Signing.PublicKey(pemRepresentation: publicKey.pemRepresentation)
XCTAssertEqual(importedPrivate.publicKey.rawRepresentation, importedPublic.rawRepresentation)
}
func testKeyAgreementPrivatePublicKeyConsistency() throws {
let privateKey = Curve25519.KeyAgreement.PrivateKey()
let publicKey = privateKey.publicKey
let importedPrivate = try Curve25519.KeyAgreement.PrivateKey(pemRepresentation: privateKey.pemRepresentation)
let importedPublic = try Curve25519.KeyAgreement.PublicKey(pemRepresentation: publicKey.pemRepresentation)
XCTAssertEqual(importedPrivate.publicKey.rawRepresentation, importedPublic.rawRepresentation)
}
let rsaPEM = """
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDL8W1D9w5zHpmD
JqpTngIRJ+Sm21e42cRnTudhdejzKUiJQWkHSvQV5yC/+0iEXUsUJYEdSyrKhJFD
PT+IFGdjIiwb7IX+rUreWXlD/YYBL3/byMG4kYoO4oiPp2A+WvfeyLpuN549OXhk
7o5kXEZjKfjHTfmnAbCMoYW5BEpiHQC3HAeJZ5EiwAn8HZn5UY6lxJcf7H9hR83x
D0W7IZTNyxUu4aLNuihFIxJKgP/L/y95Y6ddZsyyHQopM43/7JOYBwufa07MWaxi
AdBdq1bR/ZeOt2aZaXhV+J6QUoUO8Z6fG6b2cQmvMgk4ybqoeciLII0DfFsyqavu
ip4hRr59AgMBAAECggEAUIw994XwMw922hG/W98gOd5jtHMVJnD73UGQqTGEm+VG
PM+Ux8iWtr/ec3Svo3elW4OkhwlVET9ikAf0u64zVzf769ty4K9YzpDQEEZlUrq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mi7gbQGVN/Z6VhbIm
D2cOo0w4bk/3yb01xz1MEw==
-----END PRIVATE KEY-----
"""
}
@@ -11,7 +11,6 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Crypto
import Foundation
import XCTest
@@ -140,95 +140,6 @@ final class TestRSAEncryption: XCTestCase {
XCTAssertEqual(primitives.publicExponent, e)
}
}
func testMaximumEncryptSize() throws {
let pemRepresentation1024 = """
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTLbu1QZhtXWKCHOjavP5NUCwJ
5DwjoMKGlEM/PQOMiY+wup8R1kCOHV6g+FvJ86laHJc0gqwFf1U51YxtQFy7cGV4
W2zJeTkqadO2fvTCjbZU+Oa78iVtTynq5h4yRWrTmveyzInhdVpi075Ql2hpGuET
H1qYVxqaDIJEHyETDQIDAQAB
-----END PUBLIC KEY-----
"""
let pubKey1024 = try _RSA.Encryption.PublicKey(unsafePEMRepresentation: pemRepresentation1024)
XCTAssertEqual(86, pubKey1024.maximumEncryptSize(with: .PKCS1_OAEP))
XCTAssertEqual(62, pubKey1024.maximumEncryptSize(with: .PKCS1_OAEP_SHA256))
let pemRepresentation2048 = """
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx8IRKcs5FrHlWye2lfwc
Hr0Pi8g5iZhGMOOwmyIVsNULAvUIGZlIw38NNqebH3eF6ZxPiSRpwPwIs6QRcH5/
IwbHkUc0KdBbUwXDrLs0w00I7Flu5RP7IEfkOZdDGEWFY1pA3H1HaogxKFc5k3mM
s7pW6oty1eP4O7aVa/Pp363Vba7EZ2nru9lz4Ta+JU8UIHbpoddMGikGEKHrQ/Ge
n9RMNzSIy/e7TgTwC39GKn8fwN6VfcdNjvIhJrFNha/ORNArpzup7FUUauGLKt3a
jgsIjrAPBp63+Sy7+aFVoGTvI7DCkZ/Wv3JCFRuTAdYOa0A1xiqhTb1pcypvrd2T
ZQIDAQAB
-----END PUBLIC KEY-----
"""
let pubKey2048 = try _RSA.Encryption.PublicKey(pemRepresentation: pemRepresentation2048)
XCTAssertEqual(214, pubKey2048.maximumEncryptSize(with: .PKCS1_OAEP))
XCTAssertEqual(190, pubKey2048.maximumEncryptSize(with: .PKCS1_OAEP_SHA256))
}
func testPKCS1() throws {
let pubKeyPEM = """
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAv6ElnElHGQO1BC5wsU/S01tHK8GbCnDLkxkS1259kOU250pEjOJa
ceOGFnhYzE36KXmKTrGw3o1m5vgbQz88j7/tNjymAX990I3YdWTnGQYcypp8c4TD
wHIj5Q3OHYXAC0KUHRBSKBeS+QJybrMI6SAQbFpHh9C3Q9W3WTtSAVqs8VveS4Jc
j4a3K21MNeHgNfyxwn3KTrrNs/c0yOvWlwyfxYTdWLFVVp2hn6YVQUfo7twM4BCE
Xz/6gR03NpqjVqKeyBmmMtDIy82+BzG4vd3jm02zwNvahsBy9b2NCOjq3y2ud72b
Q4bYU9/r/ccApts5BIW8ASwmYSGSmE6MzwIDAQAB
-----END RSA PUBLIC KEY-----
"""
let privKeyPEM = """
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC/oSWcSUcZA7UE
LnCxT9LTW0crwZsKcMuTGRLXbn2Q5TbnSkSM4lpx44YWeFjMTfopeYpOsbDejWbm
+BtDPzyPv+02PKYBf33Qjdh1ZOcZBhzKmnxzhMPAciPlDc4dhcALQpQdEFIoF5L5
AnJuswjpIBBsWkeH0LdD1bdZO1IBWqzxW95LglyPhrcrbUw14eA1/LHCfcpOus2z
9zTI69aXDJ/FhN1YsVVWnaGfphVBR+ju3AzgEIRfP/qBHTc2mqNWop7IGaYy0MjL
zb4HMbi93eObTbPA29qGwHL1vY0I6OrfLa53vZtDhthT3+v9xwCm2zkEhbwBLCZh
IZKYTozPAgMBAAECggEAGncL9bCdFBRR/JjZU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73t2rN+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 {