Compare commits

..
11 Commits
Author SHA1 Message Date
Si BeaumontandCory Benfield da9d28d69e Enforce a 2048-bit minimum on RSA raw number initializers (#467)
### Motivation:

The RSA initializers that take raw numbers, e.g. `init(n:e:)` and
friends, do not enforce a minimum key size.

Our other public API has two lower bounds: the "safe" APIs, e.g.
`init(pemRepresentation:)`, which has a 2048-bit lower bound, and the
"unsafe" variants, e.g. `init(unsfafePEMRepresentation:)`, which has a
1024-bit minimum.

Given the raw number initializers do not state they are unsafe, they
should probably have a 2048-bit minimum too.

### Modifications:

- Add a 2048-bit minimum key length check to the raw number
initializers.
- Update the documentation to match the wording on the PEM and DER
initializers.
- Extend the tests.

### Result:

The RSA initializers that take raw numbers, e.g. `init(n:e:)` and
friends, now enforce a 2048-bit minimum key length.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-09-01 18:48:04 +01:00
Si Beaumont f79a3ffbc0 Compute RSA key size from the modulus bit length (#466)
### Motivation:

The BoringSSL RSA backing computes `keySizeInBits` using `RSA_size(key)
* 8`, which is incorrect. `RSA_size` returns the number of bytes
required to represent the modulus, so is rounding up to the nearest
byte.

Because of this, the minimum key strength checks are slightly off. For
example, 1017-bit keys are accepted by initializers that document a 1024
minimum, and similar for the initializers guarding for a 2048-bit
minimum.

### Modifications:

- Compute `keySizeInBits` using `RSA_bits` instead of `RSA_size`, which
returns the modulus bit length.
- Add a `modulusByteCount` property, which does still use `RSA_size`,
and use it for the block-size checks.
- Document the byte-alignment requirement of
`_RSA.Encryption.init(pemRepresentation:)` and friends.
- Update and add more tests.

### Result:

- RSA `keySizeInBits` correctly reports the modulus bit length.
- The documented minimum key length requirements are now correctly
enforced, closing a 7-bit gap.
2026-09-01 18:12:06 +01:00
Si Beaumont fa2832e44b Reapply swift-format to fixup PR CI (#465)
### Motivation:

Not entirely sure how (maybe a merge in from a GHSA fork), but right now
we have failing CI on PRs for a formatting
drift.

### Modifications:

Rerun swift-format.

### Result:

Get pull request CI passing cleanly.
2026-09-01 11:06:49 +00:00
Dmitry 315a799ccc Match the documented parameter names to the signatures (#463) 2026-08-31 21:00:33 +00:00
Si Beaumont 3ed653865a Update contributing guidelines (#464) 2026-08-28 15:36:47 +01:00
Si Beaumont 47d3869a72 Merge commit from fork
* Fix double-free when RSA key init from bytes fails

Motivation:

When initializing an RSA public key from DER or PEM bytes throws an error,
we double-free of the `EVP_PKEY*`: first in the catch block, then in the
backing `deinit`. The first of these should be removed.

Modifications:

Remove the duplicative call to `EVP_PKEY_free`.

Result:

Fixed double-free of `EVP_PKEY*` when failing to initialize RSA public
key from bytes.

Testing:

Tests have been added that reliably fail under ASan:

```console
% swift --version
Swift version 6.3.2 (swift-6.3.2-RELEASE)
Target: aarch64-unknown-linux-gnu

% env ASAN_OPTIONS=detect_leaks=0 swift test -c release --sanitize=address \
  --filter test_invalidPEMPublicKeyThrowsWithoutDoubleFree \
  --filter test_invalidDERPublicKeyThrowsWithoutDoubleFree

Test Suite 'Selected tests' started at 2026-07-06 09:36:58.468
Test Suite 'TestRSASigning' started at 2026-07-06 09:36:58.469
Test Case 'TestRSASigning.test_invalidDERPublicKeyThrowsWithoutDoubleFree' started at 2026-07-06 09:36:58.469
Test Case 'TestRSASigning.test_invalidDERPublicKeyThrowsWithoutDoubleFree' passed (0.001 seconds)
Test Case 'TestRSASigning.test_invalidPEMPublicKeyThrowsWithoutDoubleFree' started at 2026-07-06 09:36:58.470
Test Case 'TestRSASigning.test_invalidPEMPublicKeyThrowsWithoutDoubleFree' passed (0.001 seconds)
Test Suite 'TestRSASigning' passed at 2026-07-06 09:36:58.471
         Executed 2 tests, with 0 failures (0 unexpected) in 0.002 (0.002) seconds
Test Suite 'Selected tests' passed at 2026-07-06 09:36:58.471
         Executed 2 tests, with 0 failures (0 unexpected) in 0.002 (0.002) seconds
◇ Test run started.
↳ Testing Library Version: 6.3.2 (70eff261d7f462c)
↳ Target Platform: aarch64-unknown-linux-gnu
✔ Test run with 0 tests in 0 suites passed after 0.001 seconds.
```

* Have only one designated init for BoringSSLRSAPublicKey.Backing
2026-07-16 13:29:36 +01:00
Si Beaumont c3d9fc8938 Back AES-CBC with BoringSSL and constant-time PKCS#7 unpadding (#448)
### Motivation:

Our AES-CBC padding check is a padding-oracle timing side channel.
Validation short-circuits on the first mismatching byte, so the time
taken leaks padding validity; an attacker with a decryption oracle could
recover plaintext without the key. The AES core is already
BoringSSL-backed, so the remaining fix is to move the CBC mode onto
BoringSSL and update padding removal to be constant-time.

Aside: padding removal cannot be delegated to BoringSSL, whose generic
unpad is itself a documented padding oracle absent authentication.

### Modifications:

- Replace the Swift CBC block loop in `AES._CBC` with BoringSSL's
`AES_cbc_encrypt`.
- Add padding on encrypt in Swift, since `AES_cbc_encrypt` does not pad.
- Replace `trimPadding` with `removingPKCS7PaddingConstantTime`
- Add regression tests rejecting over-long pad lengths.
- Add unpad tests for every valid length.
- Add unpad tests for every corruption position.

### Result:

AES-CBC is BoringSSL-backed and padding validation runs in constant
time, removing a timing side channel.
2026-07-16 12:28:36 +00:00
Si Beaumont 1ca42a1885 Update cross-platform dependencies in README (#446)
### Motivation:

Swift Crypto 4.0 included SHA3 APIs, which required a backing
implementation on non-Apple platforms. We brought in libXCKP for this
purpose, similar to how we use BoringSSL for the implementation of the
rest of CryptoKit API on non-Apple platforms. The README includes
details of how the code is organised but was not updated to reflect this
change.

### Modifications:

- Update the backend implementation section to include XCKP alongside
BoringSSL
- Add an acknowledgments section to the README

### Result:

The README now includes details of both our backing dependencies, not
just BoringSSL.

Fixes #439.
2026-07-01 10:08:47 +00:00
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
30 changed files with 1301 additions and 287 deletions

No files matched your search

+29 -9
View File
@@ -5,6 +5,18 @@ your contribution to Apple and the community, and agree by submitting the patch
that your contributions are licensed under the Apache 2.0 license (see
`LICENSE.txt`).
## AI tools
Human discourse is an essential part of open source development. To encourage
productive collaboration between contributors and maintainers, please refrain
from using AI tools for the following:
- Issues: titles, bodies, and comments.
- Pull requests: titles, descriptions, and comments.
Contributors who feel more comfortable writing in another language may use
automated translation tools, but must include their original content in their
preferred language.
## How to submit a bug report
@@ -44,19 +56,27 @@ $ uname -a
Linux beefy.machine 4.4.0-101-generic #124-Ubuntu SMP Fri Nov 10 18:29:59 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
```
## Writing a Patch
## Contributing a pull request
A good swift-crypto patch is:
> [!IMPORTANT]
> To ensure productive use of contributor and maintainer time and resources,
> contributors must first agree their proposed change with a maintainer in an
> issue. Pull requests opened without prior discussion may be closed without
> review.
1. Concise, and contains as few changes as needed to achieve the end result.
2. Tested, ensuring that any tests provided failed before the patch and pass after it.
3. Documented, adding API documentation as needed to cover new functions and properties.
4. Accompanied by a great commit message, using our commit message template.
If there is no issue already tracking the problem or feature request, please
file a new one using your own voice (see "AI tools" usage above).
Once an issue is assigned to you, follow these steps:
## How to contribute your work
Please open a pull request at https://github.com/apple/swift-crypto. Make sure the CI passes, and then wait for code review.
- Prepare your change, keeping in mind that a good patch is:
- Concise, and contains as few changes as needed to achieve the end result.
- Tested, ensuring that any tests provided failed before the patch and pass
after it.
- Documented, adding API documentation as needed to cover new functions and
properties.
- Accompanied by a great commit message.
- Open a pull request and wait for code review by the maintainers.
### How to update CMakeLists files
+11 -6
View File
@@ -31,10 +31,11 @@ When building Swift Crypto for use on an Apple platform where CryptoKit is alrea
When building Swift Crypto for use on Linux or Windows, Swift Crypto builds substantially more code. In particular, we build:
1. A vendored copy of BoringSSL's libcrypto.
2. The common API of Swift Crypto and CryptoKit.
3. The backing implementation of this common API, which calls into BoringSSL.
2. A vendored copy of XKCP's libXKCP.
3. The common API of Swift Crypto and CryptoKit.
4. The backing implementation of this common API, which calls into BoringSSL or XKCP.
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The backing BoringSSL-based implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIS predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL implementation of the library in your application, no matter the platform.
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The BoringSSL/XKCP backing implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIs predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL/XKCP implementation of the library in your application, no matter the platform.
## Evolution
@@ -48,11 +49,11 @@ Note that Swift Crypto does not intend to support all possible cryptographic pri
### Code Organisation
Files in this repository are divided into two groups, based on whether they have a name that ends in `_boring` or are in a `BoringSSL` directory, or if they are not.
Files in this repository are divided into two groups, based on whether they have a name that ends in `_boring`/`_xkcp` or are in a `BoringSSL`/`XKCP` directory, or if they are not.
Files that meet the above criteria are specific to the Swift Crypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or access a BoringSSL API, it needs to be marked this way.
Files that meet the above criteria are specific to the Swift Crypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or `import CXKCP` or access a BoringSSL or XKCP API, it needs to be marked this way.
Files that do not have the `_boring` suffix are part of the public API of CryptoKit. Changing these requires passing a higher bar, as any change in these files must be accompanied by a change in CryptoKit itself.
Files that do not have the `_boring` or `_xkcp` suffix are part of the public API of CryptoKit. Changing these requires passing a higher bar, as any change in these files must be accompanied by a change in CryptoKit itself.
## Contributing
@@ -146,3 +147,7 @@ To do so, please use the following dependency in your `Package.swift`:
Swift Crypto normally defers to the OS implementation of CryptoKit on macOS. Naturally, this makes developing Swift Crypto on macOS tricky. To get Swift Crypto to build the open source implementation on macOS, in `Package.swift`, change `let development = false` to `let development = true`, as this will force Swift Crypto to build its public API.
## Acknowledgements
This project contains source code from the BoringSSL and XKCP projects.
+1
View File
@@ -102,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) {
@@ -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
+5 -91
View File
@@ -25,19 +25,6 @@ extension AES {
/// suite.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
public enum _CBC {
private static var blockSize: Int { 16 }
private static func encryptBlockInPlace(
_ plaintext: inout Block,
priorCiphertextBlock: Block,
using key: SymmetricKey
) throws {
assert([128, 192, 256].contains(key.bitCount))
plaintext ^= priorCiphertextBlock
try AES.permute(&plaintext, key: key)
}
/// Encrypts data using AES-CBC.
///
/// - Parameters:
@@ -60,44 +47,7 @@ extension AES {
///
/// - Note: If `noPadding` is set to `true`, `plainText` has to be a multiple of the blockSize (16 bytes). Otherwise an error will be thrown.
public static func encrypt<Plaintext: DataProtocol>(_ plaintext: Plaintext, using key: SymmetricKey, iv: AES._CBC.IV, noPadding: Bool) throws -> Data {
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
let requiresFullPaddingBlock = (plaintext.count % AES._CBC.blockSize) == 0
if noPadding && !requiresFullPaddingBlock {
throw CryptoKitError.incorrectParameterSize
}
var ciphertext = Data()
ciphertext.reserveCapacity(plaintext.count + Self.blockSize) // Room for padding.
var previousBlock = Block(iv)
var plaintext = plaintext[...]
while plaintext.count > 0 {
var block = Block(blockBytes: plaintext.prefix(Self.blockSize))
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
ciphertext.append(contentsOf: block)
previousBlock = block
plaintext = plaintext.dropFirst(Self.blockSize)
}
if requiresFullPaddingBlock && !noPadding {
var block = Block.paddingBlock
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
ciphertext.append(contentsOf: block)
}
return ciphertext
}
private static func decryptBlockInPlace(_ ciphertext: inout Block, priorCiphertextBlock: Block, using key: SymmetricKey) throws {
assert([128, 192, 256].contains(key.bitCount))
try AES.inversePermute(&ciphertext, key: key)
ciphertext ^= priorCiphertextBlock
try OpenSSLAESCBCImpl.encrypt(plaintext, using: key, iv: iv, noPadding: noPadding)
}
/// Decrypts data using AES-CBC.
@@ -120,29 +70,7 @@ extension AES {
/// - noPadding: If this is set to `true`, padding won't be removed.
/// - Returns: The decrypted message.
public static func decrypt<Ciphertext: DataProtocol>(_ ciphertext: Ciphertext, using key: SymmetricKey, iv: AES._CBC.IV, noPadding: Bool) throws -> Data {
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
var plaintext = Data()
plaintext.reserveCapacity(ciphertext.count)
var previousBlock = Block(iv)
var ciphertext = ciphertext[...]
while ciphertext.count > 0 {
let ctBlock = Block(blockBytes: ciphertext.prefix(Self.blockSize))
var block = ctBlock
try Self.decryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
plaintext.append(contentsOf: block)
previousBlock = ctBlock
ciphertext = ciphertext.dropFirst(Self.blockSize)
}
if !noPadding {
try plaintext.trimPadding()
}
return plaintext
try OpenSSLAESCBCImpl.decrypt(ciphertext, using: key, iv: iv, noPadding: noPadding)
}
}
}
@@ -194,7 +122,7 @@ extension AES._CBC {
0, 0, 0, 0, 0, 0, 0, 0
)
withUnsafeMutableBytes(of: &self.ivBytes) { bytesPtr in
Swift.withUnsafeMutableBytes(of: &self.ivBytes) { bytesPtr in
bytesPtr.copyBytes(from: ivBytes)
}
}
@@ -205,24 +133,10 @@ extension AES._CBC {
Array(unsafeRawBufferPointer).makeIterator()
}
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension Data {
fileprivate mutating func trimPadding() throws {
guard let paddingBytes = self.last else {
// Degenerate case, empty string. This is forbidden:
// we must always pad.
throw CryptoKitError.incorrectParameterSize
mutating func withUnsafeMutableBytes<ReturnType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
return try Swift.withUnsafeMutableBytes(of: &self.ivBytes, body)
}
guard paddingBytes > 0 &&
self.count >= paddingBytes &&
self.suffix(Int(paddingBytes)).allSatisfy({ $0 == paddingBytes }) else {
throw CryptoKitError.incorrectParameterSize
}
self = self.dropLast(Int(paddingBytes))
}
}
@@ -63,7 +63,6 @@ extension AES.GCM {
/// - Parameters:
/// - sealedBox: The sealed box to authenticate and decrypt
/// - key: An encryption key of 128 or 256 bits
/// - nonce: An Nonce for AES-GCM-SIV encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with AES.GCM.Nonce().
/// - authenticatedData: Data that was authenticated as part of the seal
/// - Returns: The ciphertext if opening was successful
/// - Throws: CipherError errors. If the authentication of the sealed box failed, incorrectTag is thrown.
@@ -77,7 +76,6 @@ extension AES.GCM {
/// - Parameters:
/// - sealedBox: The sealed box to authenticate and decrypt
/// - key: An encryption key of 128 or 256 bits
/// - nonce: An Nonce for AES-GCM-SIV encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with AES.GCM.Nonce().
/// - Returns: The ciphertext if opening was successful
/// - Throws: CipherError errors. If the authentication of the sealed box failed, incorrectTag is thrown.
public static func open(_ sealedBox: SealedBox, using key: SymmetricKey) throws -> Data {
@@ -118,8 +118,6 @@ extension AES {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
struct Block {
private static var blockSize: Int { 16 }
typealias BlockBytes = (
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8
@@ -135,70 +133,9 @@ extension AES {
)
}
init(_ blockBytes: BlockBytes) {
self.blockBytes = blockBytes
}
init(_ iv: AES._CBC.IV) {
self.blockBytes = iv.ivBytes
}
init<BlockBytes: Collection>(blockBytes: BlockBytes) where BlockBytes.Element == UInt8 {
// The block size is always 16. Pad out past there.
precondition(blockBytes.count <= Self.blockSize)
self.blockBytes = (
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
)
Swift.withUnsafeMutableBytes(of: &self.blockBytes) { bytesPtr in
bytesPtr.copyBytes(from: blockBytes)
// Early exit here.
if blockBytes.count == Self.blockSize {
return
}
var remainingBytes = bytesPtr.dropFirst(blockBytes.count)
let padByte = UInt8(remainingBytes.count)
for index in remainingBytes.indices {
remainingBytes[index] = padByte
}
}
}
static var paddingBlock: Block {
// The padding block is a full block of value blocksize.
let value = UInt8(truncatingIfNeeded: Self.blockSize)
return Block((
value, value, value, value, value, value, value, value,
value, value, value, value, value, value, value, value
))
}
func withUnsafeBytes<ReturnType>(_ body: (UnsafeRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
return try Swift.withUnsafeBytes(of: self.blockBytes, body)
}
mutating func withUnsafeMutableBytes<ReturnType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
return try Swift.withUnsafeMutableBytes(of: &self.blockBytes, body)
}
static func ^= (lhs: inout Block, rhs: Block) {
// Ideally we'd not use raw pointers for this.
lhs.withUnsafeMutableBytes { lhsPtr in
rhs.withUnsafeBytes { rhsPtr in
assert(lhsPtr.count == Self.blockSize)
assert(rhsPtr.count == Self.blockSize)
for index in 0..<Self.blockSize {
lhsPtr[index] ^= rhsPtr[index]
}
}
}
}
}
private static func isValidKey(_ key: SymmetricKey) -> Bool {
@@ -210,52 +147,3 @@ extension AES {
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension AES.Block: RandomAccessCollection, MutableCollection {
var startIndex: Int {
0
}
var endIndex: Int {
Self.blockSize
}
subscript(position: Int) -> UInt8 {
get {
precondition(position >= 0)
precondition(position < Self.blockSize)
return self.withUnsafeBytes { $0[position] }
}
set {
precondition(position >= 0)
precondition(position < Self.blockSize)
self.withUnsafeMutableBytes { $0[position] = newValue }
}
}
func withContiguousStorageIfAvailable<ReturnValue>(
_ body: (UnsafeBufferPointer<UInt8>) throws -> ReturnValue)
rethrows -> ReturnValue? {
return try withUnsafePointer(to: self.blockBytes) { tuplePtr in
// Homogeneous tuples are always bound to the element type as well as to their own type.
let retyped = UnsafeRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
let bufferised = UnsafeBufferPointer(start: retyped, count: Self.blockSize)
return try body(bufferised)
}
}
mutating func withContiguousMutableStorageIfAvailable<ReturnValue>(
_ body: (inout UnsafeMutableBufferPointer<UInt8>) throws -> ReturnValue)
rethrows -> ReturnValue? {
return try withUnsafeMutablePointer(to: &self.blockBytes) { tuplePtr in
// Homogeneous tuples are always bound to the element type as well as to their own type.
let retyped = UnsafeMutableRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
var bufferised = UnsafeMutableBufferPointer(start: retyped, count: Self.blockSize)
return try body(&bufferised)
}
}
}
@@ -0,0 +1,189 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@_implementationOnly import CCryptoBoringSSL
import Crypto
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
@usableFromInline
enum OpenSSLAESCBCImpl {
private static let blockSize = 16
@usableFromInline
enum Direction {
case encrypt
case decrypt
@usableFromInline
var _boringSSLParameter: Int32 {
switch self {
case .encrypt: AES_ENCRYPT
case .decrypt: AES_DECRYPT
}
}
}
/// Encrypts plaintext using AES-CBC.
///
/// PKCS#7 padding is added unless `noPadding` is set, in which case the plaintext must
/// already be a whole number of blocks.
static func encrypt<Plaintext: DataProtocol>(
_ plaintext: Plaintext,
using key: SymmetricKey,
iv: AES._CBC.IV,
noPadding: Bool
) throws -> Data {
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
// With padding disabled the input must be a whole number of blocks.
if noPadding && (plaintext.count % Self.blockSize != 0) {
throw CryptoKitError.incorrectParameterSize
}
// AES_cbc_encrypt performs no padding, so PKCS#7 is applied here.
var padded = Data(plaintext)
if !noPadding {
// PKCS#7 always appends 1...blockSize bytes (a full block when already aligned).
let padLength = Self.blockSize - (plaintext.count % Self.blockSize)
let padding = repeatElement(UInt8(padLength), count: padLength)
padded.append(contentsOf: padding)
}
return padded.withUnsafeBytes { plaintextPtr in
Self._cipher(.encrypt, plaintextPtr, using: key, iv: iv)
}
}
/// Decrypts ciphertext using AES-CBC.
///
/// BoringSSL runs with padding disabled and, unless `noPadding` is set, PKCS#7 padding is
/// removed here in constant time. BoringSSL's own PKCS#7 removal is not constant-time (it is a
/// documented padding oracle absent authentication), so it must not be delegated.
static func decrypt<Ciphertext: DataProtocol>(
_ ciphertext: Ciphertext,
using key: SymmetricKey,
iv: AES._CBC.IV,
noPadding: Bool
) throws -> Data {
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
// CBC ciphertext is always a whole number of non-empty blocks.
guard ciphertext.count > 0, ciphertext.count % Self.blockSize == 0 else {
throw CryptoKitError.incorrectParameterSize
}
let contiguousCiphertext = Data(ciphertext)
let plaintext = contiguousCiphertext.withUnsafeBytes { ciphertextPtr in
Self._cipher(.decrypt, ciphertextPtr, using: key, iv: iv)
}
return noPadding ? plaintext : try plaintext.removingPKCS7PaddingConstantTime(blockSize: Self.blockSize)
}
/// Runs raw AES-CBC in the given direction over a single contiguous buffer.
///
/// `AES_cbc_encrypt` performs no padding, so `input` must be a whole number of blocks and the
/// output has the same length. PKCS#7 is applied and removed by the callers.
@usableFromInline
static func _cipher(
_ direction: Direction,
_ input: UnsafeRawBufferPointer,
using key: SymmetricKey,
iv: AES._CBC.IV
) -> Data {
precondition(input.count % Self.blockSize == 0)
var output = Data(count: input.count)
var iv = iv
key.withUnsafeBytes { keyPtr in
// AES_cbc_encrypt advances the IV in place, so operate on our own copy.
iv.withUnsafeMutableBytes { ivPtr in
var key = AES_KEY()
switch direction {
case .encrypt:
precondition(
CCryptoBoringSSL_AES_set_encrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key) == 0
)
case .decrypt:
precondition(
CCryptoBoringSSL_AES_set_decrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key) == 0
)
}
output.withUnsafeMutableBytes { outputPtr in
CCryptoBoringSSL_AES_cbc_encrypt(
input.baseAddress,
outputPtr.baseAddress,
input.count,
&key,
ivPtr.baseAddress,
direction._boringSSLParameter
)
}
}
}
return output
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension Data {
/// Removes PKCS#7 padding in constant time with respect to the padding bytes.
fileprivate func removingPKCS7PaddingConstantTime(blockSize: Int = 16) throws -> Data {
// The total length is not secret, so branching on it is safe.
guard self.count >= blockSize, self.count % blockSize == 0 else {
throw CryptoKitError.incorrectParameterSize
}
let padLength = self.last!
let lastBlock = self.suffix(blockSize)
// Validate padding in constant time.
var bad: UInt32 = 0
// A valid PKCS#7 pad length is 1...blockSize.
bad |= constantTimeLessThanOrEqual(padLength, 0)
bad |= constantTimeLessThanOrEqual(UInt8(blockSize + 1), padLength)
// We MUST operate on every byte in the block, and each byte in the padding region MUST equal `padLength`.
for index in lastBlock.indices {
let byte = UInt32(lastBlock[index])
let distanceFromEnd = self.endIndex - index
let inPadding = constantTimeLessThanOrEqual(UInt8(distanceFromEnd), padLength)
bad |= inPadding & (byte ^ UInt32(padLength))
}
// Throw if padding was invalid.
guard bad == 0 else {
throw CryptoKitError.incorrectParameterSize
}
// Drop the padding.
return self.dropLast(Int(padLength))
}
}
/// Returns `0xFFFFFFFF` if `lhs <= rhs`, otherwise `0`, without a data-dependent branch.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
private func constantTimeLessThanOrEqual(_ lhs: UInt8, _ rhs: UInt8) -> UInt32 {
// `lhs - rhs - 1` is negative iff `lhs <= rhs`; propagate its sign bit across the word.
let difference = Int32(lhs) - Int32(rhs) - 1
return UInt32(bitPattern: difference >> 31)
}
+6
View File
@@ -18,6 +18,7 @@ add_library(CryptoExtras
"AES/AES_CTR.swift"
"AES/AES_GCM_SIV.swift"
"AES/Block Function.swift"
"AES/BoringSSL/AES_CBC_boring.swift"
"AES/BoringSSL/AES_CFB_boring.swift"
"AES/BoringSSL/AES_CTR_boring.swift"
"AES/BoringSSL/AES_GCM_SIV_boring.swift"
@@ -33,6 +34,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"
@@ -58,6 +63,7 @@ add_library(CryptoExtras
"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.
@@ -161,7 +161,7 @@ struct OpenSSLGroupScalar<C: OpenSSLSupportedNISTCurve>: GroupScalar, CustomStri
/// Deserializes a scalar from data.
/// - Parameters:
/// - data: The serialized scalar
/// - bytes: The serialized scalar
/// - reductionIsModOrder: Resulting number is taken "mod q" (characteristic) by default. Override by setting true if "mod p" (order) is desired.
/// - Returns: The deserialized scalar
init(bytes: Data, reductionIsModOrder: Bool = false) throws {
@@ -105,9 +105,15 @@ extension _RSA.BlindSigning {
}
/// Construct a RSA public key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes, parameters: Parameters) throws {
self.backing = try BackingPublicKey(n: n, e: e)
self.parameters = parameters
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
public var pkcs1DERRepresentation: Data {
@@ -206,9 +212,15 @@ extension _RSA.BlindSigning {
}
/// Construct an RSA private key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes, parameters: Parameters) throws {
self.backing = try BackingPrivateKey(n: n, e: e, d: d, p: p, q: q)
self.parameters = parameters
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
/// Randomly generate a new RSA private key of a given size.
+39 -6
View File
@@ -117,8 +117,14 @@ extension _RSA.Signing {
}
/// Construct an RSA public key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.backing = try BackingPublicKey(n: n, e: e)
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
public var pkcs1DERRepresentation: Data {
@@ -248,8 +254,14 @@ extension _RSA.Signing {
}
/// Construct an RSA private key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes) throws {
self.backing = try BackingPrivateKey(n: n, e: e, d: d, p: p, q: q)
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
/// Randomly generate a new RSA private key of a given size.
@@ -535,6 +547,7 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
public init(pemRepresentation: String) throws {
self.backing = try BackingPublicKey(pemRepresentation: pemRepresentation)
guard self.keySizeInBits >= 2048, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
@@ -544,6 +557,7 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 1024 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
/// - 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)
@@ -554,6 +568,7 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
public init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
self.backing = try BackingPublicKey(derRepresentation: derRepresentation)
guard self.keySizeInBits >= 2048, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
@@ -563,6 +578,7 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 1024 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
/// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons.
public init<Bytes: DataProtocol>(unsafeDERRepresentation derRepresentation: Bytes) throws {
self.backing = try BackingPublicKey(derRepresentation: derRepresentation)
@@ -570,8 +586,14 @@ extension _RSA.Encryption {
}
/// Construct an RSA public key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.backing = try BackingPublicKey(n: n, e: e)
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
public var pkcs1DERRepresentation: Data { self.backing.pkcs1DERRepresentation }
@@ -579,6 +601,7 @@ extension _RSA.Encryption {
public var derRepresentation: Data { self.backing.derRepresentation }
public var pemRepresentation: String { self.backing.pemRepresentation }
public var keySizeInBits: Int { self.backing.keySizeInBits }
internal var modulusByteCount: Int { self.backing.modulusByteCount }
fileprivate init(_ backing: BackingPublicKey) { self.backing = backing }
public func getKeyPrimitives() throws -> Primitives {
@@ -596,6 +619,7 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
public init(pemRepresentation: String) throws {
self.backing = try BackingPrivateKey(pemRepresentation: pemRepresentation)
guard self.keySizeInBits >= 2048, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
@@ -605,6 +629,7 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 1024 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
/// - 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 BackingPrivateKey(pemRepresentation: pemRepresentation)
@@ -615,6 +640,7 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
public init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
self.backing = try BackingPrivateKey(derRepresentation: derRepresentation)
guard self.keySizeInBits >= 2048, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
@@ -624,6 +650,7 @@ extension _RSA.Encryption {
///
/// This constructor supports key sizes of 1024 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// The key's modulus bit length must also be a multiple of 8.
/// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons.
public init<Bytes: DataProtocol>(unsafeDERRepresentation derRepresentation: Bytes) throws {
self.backing = try BackingPrivateKey(derRepresentation: derRepresentation)
@@ -632,8 +659,14 @@ extension _RSA.Encryption {
/// Construct an RSA private key with the specified parameters.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes) throws {
self.backing = try BackingPrivateKey(n: n, e: e, d: d, p: p, q: q)
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
/// Randomly generate a new RSA private key of a given size.
@@ -741,8 +774,8 @@ extension _RSA.Encryption {
extension _RSA.Encryption.PrivateKey {
/// Decrypt a message encrypted with this key's public key and using the specified padding mode.
///
/// > Important: The size of the data to decrypt must be equal to the block size of the key (e.g.
/// `keySizeInBits / 8`). Attempting to decrypt data of the wrong size will fail.
/// > Important: The size of the data to decrypt must be equal to the block size of the key.
/// Attempting to decrypt data of the wrong size will fail.
public func decrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
return try self.backing.decrypt(data, padding: padding)
}
@@ -764,17 +797,17 @@ extension _RSA.Encryption.PublicKey {
switch padding.backing {
case ._weakAndInsecure_pkcs1v1_5:
// https://www.rfc-editor.org/rfc/rfc8017#section-7.2
return (self.keySizeInBits / 8) - 11
return self.modulusByteCount - 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
return self.modulusByteCount - (2 * Digest.hashBitLength / 8) - 2
}
}
/// Encrypt a message with this key, using the specified padding mode.
///
/// > Important: The size of the data to encrypt _must_ not exceed the modulus of the key (e.g.
/// `keySizeInBits / 8`), minus any additional space required by the padding mode. Attempting to
/// > Important: The size of the data to encrypt _must_ not exceed the block size of the key,
/// minus any additional space required by the padding mode. Attempting to
/// encrypt data larger than this will fail. Use ``maximumEncryptSize(with:)`` to determine
/// exactly how many bytes can be encrypted by the key.
public func encrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
+31 -34
View File
@@ -77,6 +77,10 @@ internal struct BoringSSLRSAPublicKey: Sendable {
self.backing.keySizeInBits
}
var modulusByteCount: Int {
self.backing.modulusByteCount
}
fileprivate init(_ backing: Backing) {
self.backing = backing
}
@@ -222,17 +226,17 @@ extension BoringSSLRSAPublicKey {
self.pointer = pointer
}
fileprivate init(copying other: Backing) {
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
fileprivate convenience init(copying other: Backing) {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
let rsaPublicKey = CCryptoBoringSSL_RSAPublicKey_dup(
CCryptoBoringSSL_EVP_PKEY_get0_RSA(other.pointer)
)
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
}
fileprivate init(pemRepresentation: String) throws {
fileprivate convenience init(pemRepresentation: String) throws {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
var pemRepresentation = pemRepresentation
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
// There are two encodings for RSA public keys: PKCS#1 and the SPKI form.
// The SPKI form is what we support for EC keys, so we try that first, then we
@@ -248,20 +252,15 @@ extension BoringSSLRSAPublicKey {
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
do {
let rsaPublicKey = try pemRepresentation.withUTF8 { utf8Ptr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPublicKey(bio, nil, nil, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
let rsaPublicKey = try pemRepresentation.withUTF8 { utf8Ptr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPublicKey(bio, nil, nil, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
CCryptoBoringSSL_EVP_PKEY_free(self.pointer)
throw error
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
}
}
@@ -274,8 +273,8 @@ extension BoringSSLRSAPublicKey {
}
}
private init<Bytes: ContiguousBytes>(contiguousDerRepresentation: Bytes) throws {
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
private convenience init<Bytes: ContiguousBytes>(contiguousDerRepresentation: Bytes) throws {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
// There are two encodings for RSA public keys: PKCS#1 and the SPKI form.
// The SPKI form is what we support for EC keys, so we try that first, then we
// fall back to the PKCS#1 form if that parse fails.
@@ -290,25 +289,20 @@ extension BoringSSLRSAPublicKey {
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
do {
let rsaPublicKey = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
guard let key = CCryptoBoringSSL_d2i_RSAPublicKey_bio(bio, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
let rsaPublicKey = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
guard let key = CCryptoBoringSSL_d2i_RSAPublicKey_bio(bio, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
CCryptoBoringSSL_EVP_PKEY_free(self.pointer)
throw error
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
}
}
fileprivate init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
fileprivate convenience init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
let n = try ArbitraryPrecisionInteger(bytes: n)
let e = try ArbitraryPrecisionInteger(bytes: e)
@@ -355,7 +349,12 @@ extension BoringSSLRSAPublicKey {
fileprivate var keySizeInBits: Int {
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
return Int(CCryptoBoringSSL_RSA_size(rsaPublicKey)) * 8
return Int(CCryptoBoringSSL_RSA_bits(rsaPublicKey))
}
fileprivate var modulusByteCount: Int {
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
return Int(CCryptoBoringSSL_RSA_size(rsaPublicKey))
}
fileprivate func isValidSignature<D: Digest>(
@@ -467,7 +466,6 @@ extension BoringSSLRSAPublicKey {
parameters: _RSA.BlindSigning.Parameters<H>
) throws -> _RSA.BlindSigning.BlindingResult {
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
let modulusByteCount = Int(CCryptoBoringSSL_RSA_size(rsaPublicKey))
let e = try ArbitraryPrecisionInteger(copying: CCryptoBoringSSL_RSA_get0_e(rsaPublicKey))
let n = try ArbitraryPrecisionInteger(copying: CCryptoBoringSSL_RSA_get0_n(rsaPublicKey))
let finiteField = try FiniteFieldArithmeticContext(fieldSize: n)
@@ -525,7 +523,6 @@ extension BoringSSLRSAPublicKey {
parameters: _RSA.BlindSigning.Parameters<H>
) throws -> _RSA.Signing.RSASignature {
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
let modulusByteCount = Int(CCryptoBoringSSL_RSA_size(rsaPublicKey))
let n = try ArbitraryPrecisionInteger(copying: CCryptoBoringSSL_RSA_get0_n(rsaPublicKey))
let finiteField = try FiniteFieldArithmeticContext(fieldSize: n)
@@ -825,7 +822,7 @@ extension BoringSSLRSAPrivateKey {
fileprivate var keySizeInBits: Int {
let rsaPrivateKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
return Int(CCryptoBoringSSL_RSA_size(rsaPrivateKey)) * 8
return Int(CCryptoBoringSSL_RSA_bits(rsaPrivateKey))
}
fileprivate var publicKey: BoringSSLRSAPublicKey {
@@ -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
@@ -163,6 +163,85 @@ final class CBCTests: XCTestCase {
}
}
func testDecryptRejectsPaddingLengthGreaterThanBlockSize() throws {
// A plaintext whose final block claims a PKCS#7 pad length of 17 (0x11)
// is invalid for a 16-byte block: the maximum valid PKCS#7 pad is one
// full block (16). Correct unpadding must reject it. Regression guard:
// the previous `trimPadding` accepted any pad length up to 255 and
// scanned across blocks, so it wrongly stripped 17 bytes here.
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// 32-byte (block-multiple) plaintext ending in 17 bytes of 0x11.
var plaintext = Data(repeating: 0xAB, count: 15)
plaintext.append(Data(repeating: 0x11, count: 17))
precondition(plaintext.count == 32)
let ciphertext = try AES._CBC.encrypt(plaintext, using: key, iv: iv, noPadding: true)
XCTAssertThrowsError(
try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false)
) { error in
guard let error = error as? CryptoKitError, case .incorrectParameterSize = error else {
XCTFail("Unexpected error: \(error)")
return
}
}
}
func testUnpadAcceptsAllValidPaddingLengths() throws {
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// For every valid PKCS#7 pad length (1...16), round-trip a message that
// pads to exactly that length and assert exact recovery.
for padLength in 1...16 {
let messageLength = 32 - padLength // pads to 32 bytes (two blocks)
let message = Data((0..<messageLength).map { UInt8(truncatingIfNeeded: $0) })
let ciphertext = try AES._CBC.encrypt(message, using: key, iv: iv, noPadding: false)
let decrypted = try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false)
XCTAssertEqual(decrypted, message, "round-trip failed for pad length \(padLength)")
}
}
func testUnpadRejectsCorruptedPaddingByte() throws {
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// Build a validly-padded block-multiple plaintext, then corrupt each
// padding byte except the last (which encodes the claimed length). The
// constant-time scan must reject a mismatch at any position.
for padLength in 2...16 {
var padded = Data((0..<(32 - padLength)).map { UInt8(truncatingIfNeeded: $0) })
padded.append(Data(repeating: UInt8(padLength), count: padLength))
precondition(padded.count == 32)
for position in (32 - padLength)..<31 {
var corrupted = padded
corrupted[position] = UInt8(padLength) ^ 0xFF // guaranteed != padLength
let ciphertext = try AES._CBC.encrypt(corrupted, using: key, iv: iv, noPadding: true)
XCTAssertThrowsError(
try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false),
"corruption at pad length \(padLength), position \(position) was not rejected"
)
}
}
}
func testUnpadRejectsZeroPaddingLength() throws {
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// A final byte of 0x00 claims a pad length of zero, which is invalid PKCS#7.
var padded = Data((0..<31).map { UInt8(truncatingIfNeeded: $0) })
padded.append(0x00)
let ciphertext = try AES._CBC.encrypt(padded, using: key, iv: iv, noPadding: true)
XCTAssertThrowsError(try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false))
}
func testToDataConversion() throws {
let randomBytes = (0..<16).map { _ in UInt8.random(in: UInt8.min...UInt8.max) }
let dataIn = Data(randomBytes)
+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
@@ -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)
}
}
@@ -201,6 +201,17 @@ final class TestRSABlindSigning: XCTestCase {
e: bytesValues.randomElement()!,
parameters: .RSABSSA_SHA384_PSS_Randomized
)
// Modulus of a 512-bit key: `openssl rsa -in key.pem -noout -modulus`.
let _512BitModulus =
"e24c4c2c70e673315c2420b0e211542bbccf5b79f2ce6bdaa4aac29650bd064b"
+ "955ae1613a449c7143e906d7f251e49356771d9d6f8f15bcf4044f87de1c1bed"
XCTAssertThrowsError(
try _RSA.BlindSigning.PublicKey(
n: Data(hexString: _512BitModulus),
e: Data(hexString: "010001"),
parameters: .RSABSSA_SHA384_PSS_Randomized
)
)
}
func testConstructAndUseKeyFromRSANumbersWhileRecoveringPrimes() throws {
@@ -111,6 +111,13 @@ final class TestRSAEncryption: XCTestCase {
n: bytesValues.randomElement()!,
e: bytesValues.randomElement()!
)
// Modulus of a 512-bit key: `openssl rsa -in key.pem -noout -modulus`.
let _512BitModulus =
"e24c4c2c70e673315c2420b0e211542bbccf5b79f2ce6bdaa4aac29650bd064b"
+ "955ae1613a449c7143e906d7f251e49356771d9d6f8f15bcf4044f87de1c1bed"
XCTAssertThrowsError(
try _RSA.Encryption.PublicKey(n: Data(hexString: _512BitModulus), e: Data(hexString: "010001"))
)
}
func testConstructAndUseKeyFromRSANumbersWhileRecoveringPrimes() throws {
@@ -170,6 +177,77 @@ final class TestRSAEncryption: XCTestCase {
XCTAssertEqual(190, pubKey2048.maximumEncryptSize(with: .PKCS1_OAEP_SHA256))
}
// The encryption key initializers require the modulus bit length to be a multiple of 8.
func testRejectKeysWithNonByteAlignedModulus() throws {
// Equivalent key: `openssl genrsa -traditional 2050`, converted to the encodings below.
let _2050BitRSAPrivateKeyPEM = """
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQECxVSlteS7/eN5dXzn+RdyApV8JJILQaXaZOgxl/FELWhXq4lY
Uk6+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h6rtuvPdNmCM270c
C2LXpYvZY1TPt73/Aiglw5kp5SNpEUZK8quCV3IEuE6sWQjn+418AAjp0+2Jzsec
ZbyRo0VU6G0u4AfFKLeKB9ECgYAURk8NIBHoWXggJDGbPhtSfHwLQdYgaREH88lM
es0apJ5Fo8bbFCrf9+GmTDZ/35zZ3yUCM7CkrgvpRxu41CfUXFkqXjwxBQ1/neWN
p6imZ+dej1RVmxl7LDCG4FTglpWbeKOonpYVceIzWZxxw3KY9ospk1n6n3HjHSrK
UYyK8QKBgQDWsxq+0VhPgMRDUKg2p1gdnluX9I5lmZVwy1No6QfChJUo/RCRYcIe
jLXlpoAW9UUR5JCx3/hKyKvbl34J/LV3Tc/63vHxOGnh8eAySyCcpFJFmyciIZdY
iRLB6wzq+zLIZkK7+5TdHCZ9jIi5oKyk2YDT6LSTUnuG9DlGpcSmqA==
-----END RSA PRIVATE KEY-----
"""
let _2050BitRSAPublicKeyPEM = """
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQECxVSlteS7/eN5dXzn+Rdy
ApV8JJILQaXaZOgxl/FELWhXq4lYUk6+0keFtdLvSsdsBAZlq7VT8vHyfxqhcpb0
RkjThWfVhR2BjzO8TNLA+mlKGKZJfoTE3r7o99Ev4X+H4QxCyAC8oyAKy1lyDA4w
T7OFBBXtXJmeQ/PbYCuMMyqrCWUgVL48rK150QxHQ0U9XsGCnF70X/PMPebKY60O
S36pTYhmi77h0maiY4yW2kHNfgeGMbc3XQ19Sr42f5zKe0AIQfzK91v6M5PaEIpJ
Afm+JPDNWf2+RKEVa93gNiuTZ2+pgUjf7ut8mY5MEn7fZhCeZeNBjNTuKXj3JqdP
3wIDAQAB
-----END PUBLIC KEY-----
"""
XCTAssertThrowsError(try _RSA.Encryption.PrivateKey(pemRepresentation: _2050BitRSAPrivateKeyPEM))
XCTAssertThrowsError(try _RSA.Encryption.PrivateKey(unsafePEMRepresentation: _2050BitRSAPrivateKeyPEM))
XCTAssertThrowsError(try _RSA.Encryption.PublicKey(pemRepresentation: _2050BitRSAPublicKeyPEM))
XCTAssertThrowsError(try _RSA.Encryption.PublicKey(unsafePEMRepresentation: _2050BitRSAPublicKeyPEM))
}
// The raw number encryption key initializers do not require the key modulus bit length to be a multiple of 8.
func testMaximumEncryptSizeWithNonByteAlignedModulus() throws {
// Modulus of a 2050-bit key: `openssl rsa -in key.pem -noout -modulus`.
let _2050BitModulus = Data(
base64Encoded:
"AsVUpbXku/3jeXV85/kXcgKVfCSSC0Gl2mToMZfxRC1oV6uJWFJOvtJHhbX" +
"S70rHbAQGZau1U/Lx8n8aoXKW9EZI04Vn1YUdgY8zvEzSwPppShimSX6ExN" +
"6+6PfRL+F/h+EMQsgAvKMgCstZcgwOME+zhQQV7VyZnkPz22ArjDMqqwllI" +
"FS+PKytedEMR0NFPV7Bgpxe9F/zzD3mymOtDkt+qU2IZou+4dJmomOMltpB" +
"zX4HhjG3N10NfUq+Nn+cyntACEH8yvdb+jOT2hCKSQH5viTwzVn9vkShFWv" +
"d4DYrk2dvqYFI3+7rfJmOTBJ+32YQnmXjQYzU7il49yanT98="
)!
let publicExponent = Data(base64Encoded: "AQAB")!
let publicKey = try _RSA.Encryption.PublicKey(n: _2050BitModulus, e: publicExponent)
XCTAssertEqual(2050, publicKey.keySizeInBits)
XCTAssertEqual(215, publicKey.maximumEncryptSize(with: .PKCS1_OAEP))
XCTAssertEqual(191, publicKey.maximumEncryptSize(with: .PKCS1_OAEP_SHA256))
}
func testPKCS1() throws {
let pubKeyPEM = """
-----BEGIN RSA PUBLIC KEY-----
+309 -19
View File
@@ -361,8 +361,10 @@ final class TestRSASigning: XCTestCase {
try XCTAssertThrowsError((_RSA.Signing.PrivateKey(keySize: .init(bitCount: 1024)), 1024))
}
func testRejectSmallKeys() throws {
let smallRSAPrivateKeyPEM = """
// The default initializers require a modulus of at least 2048 bits.
func testRejectKeysBelow2048BitMinimum() throws {
// Equivalent key: `openssl genrsa -traditional 512`, converted to the encodings below.
let _512BitRSAPrivateKeyPEM = """
-----BEGIN RSA PRIVATE KEY-----
MIIBPAIBAAJBAOJMTCxw5nMxXCQgsOIRVCu8z1t58s5r2qSqwpZQvQZLlVrhYTpE
nHFD6QbX8lHkk1Z3HZ1vjxW89ARPh94cG+0CAwEAAQJBAMdmOVyTYswvuyPuVk3s
@@ -374,14 +376,14 @@ final class TestRSASigning: XCTestCase {
-----END RSA PRIVATE KEY-----
"""
let smallRSAPublicKeyPEM = """
let _512BitRSAPublicKeyPEM = """
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOJMTCxw5nMxXCQgsOIRVCu8z1t58s5r
2qSqwpZQvQZLlVrhYTpEnHFD6QbX8lHkk1Z3HZ1vjxW89ARPh94cG+0CAwEAAQ==
-----END PUBLIC KEY-----
"""
let smallRSAPrivateKeyPKCS8PEM = """
let _512BitRSAPrivateKeyPKCS8PEM = """
-----BEGIN PRIVATE KEY-----
MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA4kxMLHDmczFcJCCw
4hFUK7zPW3nyzmvapKrCllC9BkuVWuFhOkSccUPpBtfyUeSTVncdnW+PFbz0BE+H
@@ -394,7 +396,7 @@ final class TestRSASigning: XCTestCase {
-----END PRIVATE KEY-----
"""
let smallRSAPrivateKeyDER = Data(base64Encoded:
let _512BitRSAPrivateKeyDER = Data(base64Encoded:
"MIIBPAIBAAJBAOJMTCxw5nMxXCQgsOIRVCu8z1t58s5r2qSqwpZQvQZLlVr" +
"hYTpEnHFD6QbX8lHkk1Z3HZ1vjxW89ARPh94cG+0CAwEAAQJBAMdmOVyTYs" +
"wvuyPuVk3svQEJDqFpFATFTlP4TxuKKvTmbdQuVCorMmLLKThDI3pDNWKuA" +
@@ -405,7 +407,7 @@ final class TestRSASigning: XCTestCase {
"7MWbrFpUouirbQ="
)!
let smallRSAPrivateKeyPKCS8DER = Data(base64Encoded:
let _512BitRSAPrivateKeyPKCS8DER = Data(base64Encoded:
"MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA4kxMLHDmczF" +
"cJCCw4hFUK7zPW3nyzmvapKrCllC9BkuVWuFhOkSccUPpBtfyUeSTVncdnW" +
"+PFbz0BE+H3hwb7QIDAQABAkEAx2Y5XJNizC+7I+5WTey9AQkOoWkUBMVOU" +
@@ -416,18 +418,282 @@ final class TestRSASigning: XCTestCase {
"w8CIQCNHhOCOnp3lmwZQr0gcaw1Y/XJKtqDsxZusWlSi6KttA=="
)!
let smallRSAPublicKeyDER = Data(base64Encoded:
let _512BitRSAPublicKeyDER = Data(base64Encoded:
"MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOJMTCxw5nMxXCQgsOIRVCu8z1t" +
"58s5r2qSqwpZQvQZLlVrhYTpEnHFD6QbX8lHkk1Z3HZ1vjxW89ARPh94cG+" +
"0CAwEAAQ=="
)!
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: smallRSAPrivateKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: smallRSAPrivateKeyPKCS8PEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: smallRSAPrivateKeyDER))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: smallRSAPrivateKeyPKCS8DER))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(pemRepresentation: smallRSAPublicKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(derRepresentation: smallRSAPublicKeyDER))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: _512BitRSAPrivateKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: _512BitRSAPrivateKeyPKCS8PEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: _512BitRSAPrivateKeyDER))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: _512BitRSAPrivateKeyPKCS8DER))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(pemRepresentation: _512BitRSAPublicKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(derRepresentation: _512BitRSAPublicKeyDER))
// Generated via `openssl genrsa -traditional 2047`, then converted to the encodings below.
let _2047BitRSAPrivateKeyPEM = """
-----BEGIN RSA PRIVATE KEY-----
MIIEoAIBAAKCAQBXog86uwpuCobeXXokHAePMu15O2Cwfvwx7/EzZl6jY70ConNX
mzR5U39kQQpFa0dxRQdgUA8YpU5/8aILp3Yv0S2BssiuqdL5IkzdBzLNRhSQabuM
+vyCQjImHF/bA28+5DKJ9uzIhywA9JS2o/4TtE6mLqWbFAY+dM716llarKJgzLh/
Vg0mH6H5vDoo4D6z+M2jQRiUbV+yIiiaY8/SMyLltsZeEl/hx/NyACPSUAClVlsj
vRRZzQl8oDybMVvUAbrIwR+ZVQltdqVgx5zVf8G3BHi7lUdyqxIt0QWQRBTTd1tY
sSOKmVhYB+DvPv2IJKGXqKo+XKQBLmm9UIuxAgMBAAECggEAN/6hZJGnNHEdhHCO
XwxZ+DI+czxxp9U8KFx87q72wcg1Ob27nbraaLvlppW4jmriF4pYED6XptPZuP8Y
4AF9D0jFnx4yBQkWeYJlQsYau/ePpEcrRAYL2t+ZU6jFxxgGuVTuxiE1Y1ybzXB6
pclbzBNmPeGIh/LfmoDgzVmVBs6FhBrl8z+eWciISgskTaESkboiV+HAzDBJ23gP
LD0fjk69Dw75MS7QHBYm5jDIpXFvh+nPJOfwIAuaEQ9ZaF3Uh8zjBOyhtOSO9cdV
wXME4sIvA7IqlGoacxUtjyoWarPqk/V4UWl7/Q8gZlRagqjaJ+DqpqrD6UFCxwvw
KCyJ0QKBgQDTV7joBHuuw/RuDe8VwxUuRJTIcdrn6g2Kn3CxV9YLJhxr1doEmw3Y
DASY7zddkgJjssbkub5FhySAlqOIz5ok62erHMsyC90VXqWDC1uFHW6EQh/N/S/A
vgEuyIJ/dtxXYLFyozm0Az98A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EFAAOCAQ4AMIIBCQKCAQBXog86uwpuCobeXXo" +
"kHAePMu15O2Cwfvwx7/EzZl6jY70ConNXmzR5U39kQQpFa0dxRQdgUA8YpU" +
"5/8aILp3Yv0S2BssiuqdL5IkzdBzLNRhSQabuM+vyCQjImHF/bA28+5DKJ9" +
"uzIhywA9JS2o/4TtE6mLqWbFAY+dM716llarKJgzLh/Vg0mH6H5vDoo4D6z" +
"+M2jQRiUbV+yIiiaY8/SMyLltsZeEl/hx/NyACPSUAClVlsjvRRZzQl8oDy" +
"bMVvUAbrIwR+ZVQltdqVgx5zVf8G3BHi7lUdyqxIt0QWQRBTTd1tYsSOKmV" +
"hYB+DvPv2IJKGXqKo+XKQBLmm9UIuxAgMBAAE="
)!
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: _2047BitRSAPrivateKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(pemRepresentation: _2047BitRSAPrivateKeyPKCS8PEM))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: _2047BitRSAPrivateKeyDER))
XCTAssertThrowsError(try _RSA.Signing.PrivateKey(derRepresentation: _2047BitRSAPrivateKeyPKCS8DER))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(pemRepresentation: _2047BitRSAPublicKeyPEM))
XCTAssertThrowsError(try _RSA.Signing.PublicKey(derRepresentation: _2047BitRSAPublicKeyDER))
}
// The unsafe initializers require a modulus of at least 1024 bits. 1017 bits occupies 128 bytes,
// the same as 1024.
func testRejectKeysBelow1024BitMinimum() throws {
// Generated via `openssl genrsa -traditional 1017`, then converted to the encodings below.
let _1017BitRSAPrivateKeyPEM = """
-----BEGIN RSA PRIVATE KEY-----
MIICWAIBAAKBgAFVByFodT87fB0oWSEkwybEeqayqUavihFHLu3Ss/XuUxVosi5z
lnzxbta17k8WXJYXa7OZC4jicxQer5xrZr9Op1k99zlJUbMtznl+BiSRKoAOjmsQ
mLPU5er1hF1MnHUJsS1SgoTbR0CLPFNh4ai7WtOY6bWv/k9B03xNPeRVAgMBAAEC
gYAAhvHcYWZL0DELpKSoPdDPLV5PSlE7fEjJD37dcsvtXBIaXaRsRybcZ/jxE2qq
dvHKHphqp/vtfZYF9yKMZd9xcsxceGTRWR9kxQdKe6r9y1gzF1piRAyU4UcyjzFc
h4w4psX3AqqN4qpQJgYUZamSRnnoJ3Vq7u/oR3W0P+PL3QJAGTnDt6UAHahmdryj
KMFyQan+GU/eo6KDD84blk1L8axsEHtKUvtVBOWPRaR2WJI+q26adZbVvp707brW
8sa+9wJADYTjZOw5A2C+mXlbBwV78cLrXwsZ/+5zrlGH5dMuDYbuJH3InXK/SguL
f/OqQmrtUwSmL5QfQ//QPbUpsioIEwJABg1h8/HWsUbyLpLb4q9nJnIO0SvkkwYu
w+ADpnAtRHLGCr5J+tbqcx5Q3biz3FRaTO9gh84EwpOI2HD3mZAtyQJABk3sRQor
5DlfaO7A1ltmW23MmXvx2fn3FFmNCE4c8c30jCvkPBhgwET1/utAgMygc9B9Nz7Z
/bn0AHLVSPJ05QJAFJqFaLd6j9v/WK7noJk0f7lWTZnfeRkZPxJh4AobfnGKV1yO
+mB6mLJo/StOBrM82IdCBXTHRYYS2zUCCoJG1Q==
-----END RSA PRIVATE KEY-----
"""
let _1017BitRSAPublicKeyPEM = """
-----BEGIN PUBLIC KEY-----
MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgAFVByFodT87fB0oWSEkwybEeqay
qUavihFHLu3Ss/XuUxVosi5zlnzxbta17k8WXJYXa7OZC4jicxQer5xrZr9Op1k9
9zlJUbMtznl+BiSRKoAOjmsQmLPU5er1hF1MnHUJsS1SgoTbR0CLPFNh4ai7WtOY
6bWv/k9B03xNPeRVAgMBAAE=
-----END PUBLIC KEY-----
"""
let _1017BitRSAPrivateKeyPKCS8PEM = """
-----BEGIN PRIVATE KEY-----
MIICcgIBADANBgkqhkiG9w0BAQEFAASCAlwwggJYAgEAAoGAAVUHIWh1Pzt8HShZ
ISTDJ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dq" +
"GZ2vKMowXJBqf4ZT96jooMPzhuWTUvxrGwQe0pS+1UE5Y9FpHZYkj6rbpp1" +
"ltW+nvTtutbyxr73AkANhONk7DkDYL6ZeVsHBXvxwutfCxn/7nOuUYfl0y4" +
"Nhu4kfcidcr9KC4t/86pCau1TBKYvlB9D/9A9tSmyKggTAkAGDWHz8daxRv" +
"Iuktvir2cmcg7RK+STBi7D4AOmcC1EcsYKvkn61upzHlDduLPcVFpM72CHz" +
"gTCk4jYcPeZkC3JAkAGTexFCivkOV9o7sDWW2ZbbcyZe/HZ+fcUWY0IThzx" +
"zfSMK+Q8GGDARPX+60CAzKBz0H03Ptn9ufQActVI8nTlAkAUmoVot3qP2/9" +
"YruegmTR/uVZNmd95GRk/EmHgCht+cYpXXI76YHqYsmj9K04GszzYh0IFdM" +
"dFhhLbNQIKgkbV"
)!
let _1017BitRSAPublicKeyDER = Data(base64Encoded:
"MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgAFVByFodT87fB0oWSEkwyb" +
"EeqayqUavihFHLu3Ss/XuUxVosi5zlnzxbta17k8WXJYXa7OZC4jicxQer5" +
"xrZr9Op1k99zlJUbMtznl+BiSRKoAOjmsQmLPU5er1hF1MnHUJsS1SgoTbR" +
"0CLPFNh4ai7WtOY6bWv/k9B03xNPeRVAgMBAAE="
)!
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey(unsafePEMRepresentation: _1017BitRSAPrivateKeyPEM)
)
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey(unsafePEMRepresentation: _1017BitRSAPrivateKeyPKCS8PEM)
)
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey(unsafeDERRepresentation: _1017BitRSAPrivateKeyDER)
)
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey(unsafeDERRepresentation: _1017BitRSAPrivateKeyPKCS8DER)
)
XCTAssertThrowsError(
try _RSA.Signing.PublicKey(unsafePEMRepresentation: _1017BitRSAPublicKeyPEM)
)
XCTAssertThrowsError(
try _RSA.Signing.PublicKey(unsafeDERRepresentation: _1017BitRSAPublicKeyDER)
)
}
func testHandlingNonStandardKeys() throws {
@@ -575,12 +841,12 @@ final class TestRSASigning: XCTestCase {
"En7fZhCeZeNBjNTuKXj3JqdP3wIDAQAB"
)!
XCTAssertEqual(try _RSA.Signing.PrivateKey(pemRepresentation: awkwardRSAPrivateKeyPEM).keySizeInBits, 2056)
XCTAssertEqual(try _RSA.Signing.PrivateKey(pemRepresentation: awkwardRSAPrivateKeyPKCS8PEM).keySizeInBits, 2056)
XCTAssertEqual(try _RSA.Signing.PrivateKey(derRepresentation: awkwardRSAPrivateKeyDER).keySizeInBits, 2056)
XCTAssertEqual(try _RSA.Signing.PrivateKey(derRepresentation: awkwardRSAPrivateKeyPKCS8DER).keySizeInBits, 2056)
XCTAssertEqual(try _RSA.Signing.PublicKey(pemRepresentation: awkwardRSAPublicKeyPEM).keySizeInBits, 2056)
XCTAssertEqual(try _RSA.Signing.PublicKey(derRepresentation: awkwardRSAPublicKeyDER).keySizeInBits, 2056)
XCTAssertEqual(try _RSA.Signing.PrivateKey(pemRepresentation: awkwardRSAPrivateKeyPEM).keySizeInBits, 2050)
XCTAssertEqual(try _RSA.Signing.PrivateKey(pemRepresentation: awkwardRSAPrivateKeyPKCS8PEM).keySizeInBits, 2050)
XCTAssertEqual(try _RSA.Signing.PrivateKey(derRepresentation: awkwardRSAPrivateKeyDER).keySizeInBits, 2050)
XCTAssertEqual(try _RSA.Signing.PrivateKey(derRepresentation: awkwardRSAPrivateKeyPKCS8DER).keySizeInBits, 2050)
XCTAssertEqual(try _RSA.Signing.PublicKey(pemRepresentation: awkwardRSAPublicKeyPEM).keySizeInBits, 2050)
XCTAssertEqual(try _RSA.Signing.PublicKey(derRepresentation: awkwardRSAPublicKeyDER).keySizeInBits, 2050)
}
func testMangledPKCS8DERKey() throws {
@@ -770,6 +1036,13 @@ final class TestRSASigning: XCTestCase {
n: bytesValues.randomElement()!,
e: bytesValues.randomElement()!
)
// Modulus of the 512-bit key above: `openssl rsa -in key.pem -noout -modulus`.
let _512BitModulus =
"e24c4c2c70e673315c2420b0e211542bbccf5b79f2ce6bdaa4aac29650bd064b"
+ "955ae1613a449c7143e906d7f251e49356771d9d6f8f15bcf4044f87de1c1bed"
XCTAssertThrowsError(
try _RSA.Signing.PublicKey(n: Data(hexString: _512BitModulus), e: Data(hexString: "010001"))
)
}
func testConstructAndUseKeyFromRSANumbersWhileRecoveringPrimes() throws {
@@ -910,6 +1183,23 @@ final class TestRSASigning: XCTestCase {
return pemLines.joined(separator: "\n")
}
func test_invalidDERPublicKeyThrowsWithoutDoubleFree() throws {
// SEQUENCE { INTEGER 0, INTEGER 0 }
let badBase64 = "MAYCAQACAQ=="
let badDER = Array(Data(base64Encoded: badBase64)!)
XCTAssertThrowsError(try BoringSSLRSAPublicKey(derRepresentation: badDER))
}
func test_invalidPEMPublicKeyThrowsWithoutDoubleFree() throws {
// SEQUENCE { INTEGER 0, INTEGER 0 }
let badPEM = """
-----BEGIN PUBLIC KEY-----
MAYCAQACAQ==
-----END PUBLIC KEY-----
"""
XCTAssertThrowsError(try BoringSSLRSAPublicKey(pemRepresentation: badPEM))
}
}