mirror of
https://github.com/apple/swift-crypto
synced 2026-11-23 04:34:21 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
15b0fb5b45 | ||
|
|
ce8db4769d | ||
|
|
8ee9962f37 | ||
|
|
0a26a9e309 |
No files matched your search
@@ -21,16 +21,16 @@ jobs:
|
||||
with:
|
||||
linux_6_2_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||
linux_6_3_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||
linux_nightly_next_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_nightly_next_arguments_override: "--build-system native -Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||
linux_nightly_main_arguments_override: "--build-system native --explicit-target-dependency-import-check error"
|
||||
windows_6_2_enabled: true
|
||||
windows_6_3_enabled: true
|
||||
windows_nightly_next_enabled: true
|
||||
windows_nightly_main_enabled: true
|
||||
windows_6_2_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||
windows_6_3_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||
windows_nightly_next_arguments_override: "-Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_nightly_next_arguments_override: "--build-system native -Xswiftc -warnings-as-errors -Xswiftc -Wwarning -Xswiftc ImplementationOnlyDeprecated --explicit-target-dependency-import-check error"
|
||||
windows_nightly_main_arguments_override: "--build-system native --explicit-target-dependency-import-check error"
|
||||
|
||||
release-builds:
|
||||
name: Release builds
|
||||
@@ -53,6 +53,7 @@ jobs:
|
||||
{
|
||||
"targets": [
|
||||
{ "name": "CCryptoBoringSSL", "type": "source", "exceptions": [] },
|
||||
{ "name": "CCryptoBoringSSLShims", "type": "source", "exceptions": [] },
|
||||
{ "name": "CryptoBoringWrapper", "type": "source", "exceptions": [] },
|
||||
{ "name": "CXKCP", "type": "source", "exceptions": [] },
|
||||
{ "name": "CXKCPShims", "type": "source", "exceptions": [] },
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# Code of Conduct
|
||||
|
||||
The code of conduct for this project can be found at https://swift.org/code-of-conduct.
|
||||
+10
-30
@@ -5,18 +5,6 @@ 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
|
||||
|
||||
@@ -56,27 +44,19 @@ $ 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
|
||||
```
|
||||
|
||||
## Contributing a pull request
|
||||
## Writing a Patch
|
||||
|
||||
> [!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.
|
||||
A good swift-crypto patch is:
|
||||
|
||||
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).
|
||||
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.
|
||||
|
||||
Once an issue is assigned to you, follow these steps:
|
||||
|
||||
- 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 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.
|
||||
|
||||
### How to update CMakeLists files
|
||||
|
||||
@@ -89,7 +69,7 @@ act --container-architecture linux/amd64 pull_request -j cmake-lists -W ./.githu
|
||||
|
||||
You can find the underlying script at https://github.com/apple/swift-nio/blob/main/scripts/update-cmake-lists.sh . Using the script directly is less straightforwards because it requires you to pass the JSON config from the `pull_request.yml` file into the script, such as:
|
||||
```
|
||||
curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/update-cmake-lists.sh | CONFIG_JSON='{"targets":[{"name":"CCryptoBoringSSL","type":"source","exceptions":[]},{"name":"CryptoBoringWrapper","type":"source","exceptions":[]},{"name":"Crypto","type":"source","exceptions":[]},{"name":"CryptoExtras","type":"source","exceptions":[]},{"name":"CCryptoBoringSSL","type":"assembly","exceptions":["*/AES/*.swift"]}]}' bash
|
||||
curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/update-cmake-lists.sh | CONFIG_JSON='{"targets":[{"name":"CCryptoBoringSSL","type":"source","exceptions":[]},{"name":"CCryptoBoringSSLShims","type":"source","exceptions":[]},{"name":"CryptoBoringWrapper","type":"source","exceptions":[]},{"name":"Crypto","type":"source","exceptions":[]},{"name":"CryptoExtras","type":"source","exceptions":[]},{"name":"CCryptoBoringSSL","type":"assembly","exceptions":["*/AES/*.swift"]}]}' bash
|
||||
```
|
||||
|
||||
## API Evolution
|
||||
|
||||
@@ -126,6 +126,14 @@ let package = Package(
|
||||
.disableWarning("macro-redefined"),
|
||||
]
|
||||
),
|
||||
.target(
|
||||
name: "CCryptoBoringSSLShims",
|
||||
dependencies: ["CCryptoBoringSSL"],
|
||||
exclude: privacyManifestExclude + [
|
||||
"CMakeLists.txt"
|
||||
],
|
||||
resources: privacyManifestResource
|
||||
),
|
||||
.target(
|
||||
name: "CXKCPShims",
|
||||
dependencies: ["CXKCP"],
|
||||
@@ -138,6 +146,7 @@ let package = Package(
|
||||
name: "Crypto",
|
||||
dependencies: [
|
||||
.target(name: "CCryptoBoringSSL", condition: .when(platforms: nonDarwinPlatforms)),
|
||||
.target(name: "CCryptoBoringSSLShims", condition: .when(platforms: nonDarwinPlatforms)),
|
||||
.target(name: "CryptoBoringWrapper", condition: .when(platforms: nonDarwinPlatforms)),
|
||||
.target(name: "CXKCP", condition: .when(platforms: nonDarwinPlatforms)),
|
||||
.target(name: "CXKCPShims", condition: .when(platforms: nonDarwinPlatforms)),
|
||||
@@ -155,6 +164,7 @@ let package = Package(
|
||||
name: "CryptoExtras",
|
||||
dependencies: [
|
||||
"CCryptoBoringSSL",
|
||||
"CCryptoBoringSSLShims",
|
||||
"CryptoBoringWrapper",
|
||||
"Crypto",
|
||||
.product(name: "SwiftASN1", package: "swift-asn1"),
|
||||
@@ -176,6 +186,7 @@ let package = Package(
|
||||
name: "CryptoBoringWrapper",
|
||||
dependencies: [
|
||||
"CCryptoBoringSSL",
|
||||
"CCryptoBoringSSLShims",
|
||||
],
|
||||
exclude: privacyManifestExclude + [
|
||||
"CMakeLists.txt"
|
||||
|
||||
@@ -31,11 +31,10 @@ When building Swift Crypto for use on an Apple platform where CryptoKit is alrea
|
||||
When building Swift Crypto for use on other platforms, Swift Crypto builds substantially more code. In particular, we build:
|
||||
|
||||
1. A vendored copy of BoringSSL's libcrypto.
|
||||
2. A vendored copy of XKCP's libXKCP.
|
||||
3. The common API of Swift Crypto and CryptoKit.
|
||||
4. The backing implementation of this common API, which calls into BoringSSL or XKCP.
|
||||
2. The common API of Swift Crypto and CryptoKit.
|
||||
3. The backing implementation of this common API, which calls into BoringSSL.
|
||||
|
||||
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The BoringSSL/XKCP backing implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIs predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL/XKCP implementation of the library in your application, no matter the platform.
|
||||
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The backing BoringSSL-based implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIS predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL implementation of the library in your application, no matter the platform.
|
||||
|
||||
## Evolution
|
||||
|
||||
@@ -49,11 +48,11 @@ Note that Swift Crypto does not intend to support all possible cryptographic pri
|
||||
|
||||
### Code Organisation
|
||||
|
||||
Files in this repository are divided into two groups, based on whether they have a name that ends in `_boring`/`_xkcp` or are in a `BoringSSL`/`XKCP` directory, or if they are not.
|
||||
Files in this repository are divided into two groups, based on whether they have a name that ends in `_boring` or are in a `BoringSSL` directory, or if they are not.
|
||||
|
||||
Files that meet the above criteria are specific to the Swift Crypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or `import CXKCP` or access a BoringSSL or XKCP API, it needs to be marked this way.
|
||||
Files that meet the above criteria are specific to the Swift Crypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or access a BoringSSL API, it needs to be marked this way.
|
||||
|
||||
Files that do not have the `_boring` or `_xkcp` suffix are part of the public API of CryptoKit. Changing these requires passing a higher bar, as any change in these files must be accompanied by a change in CryptoKit itself.
|
||||
Files that do not have the `_boring` suffix are part of the public API of CryptoKit. Changing these requires passing a higher bar, as any change in these files must be accompanied by a change in CryptoKit itself.
|
||||
|
||||
## Contributing
|
||||
|
||||
@@ -151,7 +150,3 @@ 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`, use a Linux container. A Dev Container config is provided in the repo to make this easier.
|
||||
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
This project contains source code from the BoringSSL and XKCP projects.
|
||||
@@ -0,0 +1,29 @@
|
||||
##===----------------------------------------------------------------------===##
|
||||
##
|
||||
## This source file is part of the SwiftCrypto open source project
|
||||
##
|
||||
## Copyright (c) 2021 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
|
||||
##
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
add_library(CCryptoBoringSSLShims STATIC
|
||||
"shims.c"
|
||||
)
|
||||
|
||||
target_include_directories(CCryptoBoringSSLShims PUBLIC
|
||||
include
|
||||
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>)
|
||||
|
||||
target_link_libraries(CCryptoBoringSSLShims PUBLIC
|
||||
CCryptoBoringSSL)
|
||||
|
||||
set_target_properties(CCryptoBoringSSLShims PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_CRYPTO_EXPORTS CCryptoBoringSSLShims)
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSPrivacyTracking</key>
|
||||
<false/>
|
||||
<key>NSPrivacyAccessedAPITypes</key>
|
||||
<array/>
|
||||
<key>NSPrivacyCollectedDataTypes</key>
|
||||
<array/>
|
||||
<key>NSPrivacyTrackingDomains</key>
|
||||
<array/>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#ifndef C_CRYPTO_BORINGSSL_SHIMS_H
|
||||
#define C_CRYPTO_BORINGSSL_SHIMS_H
|
||||
|
||||
// This is for instances when `swift package generate-xcodeproj` is used as CCryptoBoringSSL
|
||||
// is treated as a framework and requires the framework's name as a prefix.
|
||||
#if __has_include(<CCryptoBoringSSL/CCryptoBoringSSL.h>)
|
||||
#include <CCryptoBoringSSL/CCryptoBoringSSL.h>
|
||||
#else
|
||||
#include <CCryptoBoringSSL.h>
|
||||
#endif
|
||||
|
||||
#if defined(__cplusplus)
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
// MARK:- Pointer type shims
|
||||
// This section of the code handles shims that change uint8_t* pointers to
|
||||
// void *s. This is done because Swift does not have the rule that C does, that
|
||||
// pointers to uint8_t can safely alias any other pointer. That means that Swift
|
||||
// Unsafe[Mutable]RawPointer cannot be passed to uint8_t * APIs, which is very
|
||||
// awkward, so we shim these to avoid the need to call bindMemory in Swift (which is
|
||||
// wrong).
|
||||
//
|
||||
// Our relevant citation is: https://github.com/apple/swift-nio-extras/pull/56#discussion_r329330295.
|
||||
// We want this to land: https://bugs.swift.org/browse/SR-11087. Once that lands we can remove these
|
||||
// shims.
|
||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_init(EVP_AEAD_CTX *ctx, const EVP_AEAD *aead,
|
||||
const void *key, size_t key_len, size_t tag_len,
|
||||
ENGINE *impl);
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_seal_scatter(
|
||||
const EVP_AEAD_CTX *ctx,
|
||||
void *out,
|
||||
void *out_tag,
|
||||
size_t *out_tag_len,
|
||||
size_t max_out_tag_len,
|
||||
const void *nonce,
|
||||
size_t nonce_len,
|
||||
const void *in,
|
||||
size_t in_len,
|
||||
const void *extra_in,
|
||||
size_t extra_in_len,
|
||||
const void *ad,
|
||||
size_t ad_len);
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(const EVP_AEAD_CTX *ctx, void *out,
|
||||
const void *nonce, size_t nonce_len,
|
||||
const void *in, size_t in_len,
|
||||
const void *in_tag, size_t in_tag_len,
|
||||
const void *ad, size_t ad_len);
|
||||
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open(const EVP_AEAD_CTX *ctx, void *out, size_t *out_len, size_t max_out_len,
|
||||
const void *nonce, size_t nonce_len,
|
||||
const void *in, size_t in_len,
|
||||
const void *ad, size_t ad_len);
|
||||
|
||||
|
||||
void CCryptoBoringSSLShims_ED25519_keypair(void *out_public_key, void *out_private_key);
|
||||
|
||||
void CCryptoBoringSSLShims_ED25519_keypair_from_seed(void *out_public_key,
|
||||
void *out_private_key,
|
||||
const void *seed);
|
||||
|
||||
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_do_sign(const void *digest, size_t digest_len,
|
||||
const EC_KEY *eckey);
|
||||
|
||||
int CCryptoBoringSSLShims_ECDSA_do_verify(const void *digest, size_t digest_len,
|
||||
const ECDSA_SIG *sig, const EC_KEY *eckey);
|
||||
|
||||
void CCryptoBoringSSLShims_X25519_keypair(void *out_public_value, void *out_private_key);
|
||||
|
||||
void CCryptoBoringSSLShims_X25519_public_from_private(void *out_public_value,
|
||||
const void *private_key);
|
||||
|
||||
int CCryptoBoringSSLShims_X25519(void *out_shared_key, const void *private_key,
|
||||
const void *peer_public_value);
|
||||
|
||||
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(const void *in, size_t in_len);
|
||||
|
||||
int CCryptoBoringSSLShims_ED25519_verify(const void *message, size_t message_len,
|
||||
const void *signature, const void *public_key);
|
||||
|
||||
int CCryptoBoringSSLShims_ED25519_sign(void *out_sig, const void *message,
|
||||
size_t message_len, const void *private_key);
|
||||
|
||||
BIGNUM *CCryptoBoringSSLShims_BN_bin2bn(const void *in, size_t len, BIGNUM *ret);
|
||||
|
||||
size_t CCryptoBoringSSLShims_BN_bn2bin(const BIGNUM *in, void *out);
|
||||
|
||||
int CCryptoBoringSSLShims_BN_mod(BIGNUM *rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_verify(int hash_nid, const void *msg, size_t msg_len,
|
||||
const void *sig, size_t sig_len, RSA *rsa);
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_verify_pss_mgf1(RSA *rsa, const void *msg,
|
||||
size_t msg_len, const EVP_MD *md,
|
||||
const EVP_MD *mgf1_md, int salt_len,
|
||||
const void *sig, size_t sig_len);
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_sign(int hash_nid, const void *in,
|
||||
unsigned int in_len, void *out,
|
||||
unsigned int *out_len, RSA *rsa);
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_sign_pss_mgf1(RSA *rsa, size_t *out_len, void *out,
|
||||
size_t max_out, const void *in,
|
||||
size_t in_len, const EVP_MD *md,
|
||||
const EVP_MD *mgf1_md, int salt_len);
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_public_encrypt(int flen, const void *from, void *to,
|
||||
RSA *rsa, int padding);
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_private_decrypt(int flen, const void *from, void *to,
|
||||
RSA *rsa, int padding);
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, void *out,
|
||||
size_t *out_len, const void *in,
|
||||
size_t in_len);
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, void *out,
|
||||
size_t *out_len, const void *in,
|
||||
size_t in_len);
|
||||
|
||||
int CCryptoBoringSSLShims_EC_hash_to_curve_p256_xmd_sha256_sswu(const EC_GROUP *group, EC_POINT *out,
|
||||
const void *dst, size_t dst_len,
|
||||
const void *msg, size_t msg_len);
|
||||
|
||||
int CCryptoBoringSSLShims_EC_hash_to_curve_p384_xmd_sha384_sswu(const EC_GROUP *group, EC_POINT *out,
|
||||
const void *dst, size_t dst_len,
|
||||
const void *msg, size_t msg_len);
|
||||
|
||||
size_t CCryptoBoringSSLShims_EC_POINT_point2oct(const EC_GROUP *group,
|
||||
const EC_POINT *point,
|
||||
point_conversion_form_t form,
|
||||
void *buf, size_t max_out,
|
||||
BN_CTX *ctx);
|
||||
|
||||
#if defined(__cplusplus)
|
||||
}
|
||||
#endif // defined(__cplusplus)
|
||||
|
||||
#endif // C_CRYPTO_BORINGSSL_SHIMS_H
|
||||
@@ -0,0 +1,4 @@
|
||||
module CCryptoBoringSSLShims {
|
||||
header "CCryptoBoringSSLShims.h"
|
||||
export *
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#include <CCryptoBoringSSLShims.h>
|
||||
|
||||
// MARK:- Pointer type shims
|
||||
// This section of the code handles shims that change uint8_t* pointers to
|
||||
// void *s. This is done because Swift does not have the rule that C does, that
|
||||
// pointers to uint8_t can safely alias any other pointer. That means that Swift
|
||||
// Unsafe[Mutable]RawPointer cannot be passed to uint8_t * APIs, which is very
|
||||
// awkward, so we shim these to avoid the need to call bindMemory in Swift (which is
|
||||
// wrong).
|
||||
//
|
||||
// Our relevant citation is: https://github.com/apple/swift-nio-extras/pull/56#discussion_r329330295.
|
||||
// We want this to land: https://bugs.swift.org/browse/SR-11087. Once that lands we can remove these
|
||||
// shims.
|
||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_init(EVP_AEAD_CTX *ctx, const EVP_AEAD *aead,
|
||||
const void *key, size_t key_len, size_t tag_len,
|
||||
ENGINE *impl) {
|
||||
return CCryptoBoringSSL_EVP_AEAD_CTX_init(ctx, aead, key, key_len, tag_len, impl);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_seal_scatter(
|
||||
const EVP_AEAD_CTX *ctx,
|
||||
void *out,
|
||||
void *out_tag,
|
||||
size_t *out_tag_len,
|
||||
size_t max_out_tag_len,
|
||||
const void *nonce,
|
||||
size_t nonce_len,
|
||||
const void *in,
|
||||
size_t in_len,
|
||||
const void *extra_in,
|
||||
size_t extra_in_len,
|
||||
const void *ad,
|
||||
size_t ad_len) {
|
||||
return CCryptoBoringSSL_EVP_AEAD_CTX_seal_scatter(ctx, out, out_tag, out_tag_len, max_out_tag_len, nonce, nonce_len, in, in_len, extra_in, extra_in_len, ad, ad_len);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(const EVP_AEAD_CTX *ctx, void *out,
|
||||
const void *nonce, size_t nonce_len,
|
||||
const void *in, size_t in_len,
|
||||
const void *in_tag, size_t in_tag_len,
|
||||
const void *ad, size_t ad_len) {
|
||||
return CCryptoBoringSSL_EVP_AEAD_CTX_open_gather(ctx, out, nonce, nonce_len, in, in_len, in_tag, in_tag_len, ad, ad_len);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_AEAD_CTX_open(const EVP_AEAD_CTX *ctx, void *out, size_t *out_len, size_t max_out_len,
|
||||
const void *nonce, size_t nonce_len,
|
||||
const void *in, size_t in_len,
|
||||
const void *ad, size_t ad_len) {
|
||||
return CCryptoBoringSSL_EVP_AEAD_CTX_open(ctx, out, out_len, max_out_len, nonce, nonce_len, in, in_len, ad, ad_len);
|
||||
}
|
||||
|
||||
void CCryptoBoringSSLShims_ED25519_keypair(void *out_public_key, void *out_private_key) {
|
||||
CCryptoBoringSSL_ED25519_keypair(out_public_key, out_private_key);
|
||||
}
|
||||
|
||||
void CCryptoBoringSSLShims_ED25519_keypair_from_seed(void *out_public_key,
|
||||
void *out_private_key,
|
||||
const void *seed) {
|
||||
CCryptoBoringSSL_ED25519_keypair_from_seed(out_public_key, out_private_key, seed);
|
||||
}
|
||||
|
||||
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_do_sign(const void *digest, size_t digest_len,
|
||||
const EC_KEY *eckey) {
|
||||
return CCryptoBoringSSL_ECDSA_do_sign(digest, digest_len, eckey);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_ECDSA_do_verify(const void *digest, size_t digest_len,
|
||||
const ECDSA_SIG *sig, const EC_KEY *eckey) {
|
||||
return CCryptoBoringSSL_ECDSA_do_verify(digest, digest_len, sig, eckey);
|
||||
}
|
||||
|
||||
void CCryptoBoringSSLShims_X25519_keypair(void *out_public_value, void *out_private_key) {
|
||||
CCryptoBoringSSL_X25519_keypair(out_public_value, out_private_key);
|
||||
}
|
||||
|
||||
void CCryptoBoringSSLShims_X25519_public_from_private(void *out_public_value,
|
||||
const void *private_key) {
|
||||
CCryptoBoringSSL_X25519_public_from_private(out_public_value, private_key);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_X25519(void *out_shared_key, const void *private_key,
|
||||
const void *peer_public_value) {
|
||||
return CCryptoBoringSSL_X25519(out_shared_key, private_key, peer_public_value);
|
||||
}
|
||||
|
||||
ECDSA_SIG *CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(const void *in, size_t in_len) {
|
||||
return CCryptoBoringSSL_ECDSA_SIG_from_bytes(in, in_len);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_ED25519_verify(const void *message, size_t message_len,
|
||||
const void *signature, const void *public_key) {
|
||||
return CCryptoBoringSSL_ED25519_verify(message, message_len, signature, public_key);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_ED25519_sign(void *out_sig, const void *message,
|
||||
size_t message_len, const void *private_key) {
|
||||
return CCryptoBoringSSL_ED25519_sign(out_sig, message, message_len, private_key);
|
||||
}
|
||||
|
||||
BIGNUM *CCryptoBoringSSLShims_BN_bin2bn(const void *in, size_t len, BIGNUM *ret) {
|
||||
return CCryptoBoringSSL_BN_bin2bn(in, len, ret);
|
||||
}
|
||||
|
||||
size_t CCryptoBoringSSLShims_BN_bn2bin(const BIGNUM *in, void *out) {
|
||||
return CCryptoBoringSSL_BN_bn2bin(in, out);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_BN_mod(BIGNUM *rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) {
|
||||
return BN_mod(rem, a, m, ctx);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_verify(int hash_nid, const void *msg, size_t msg_len,
|
||||
const void *sig, size_t sig_len, RSA *rsa) {
|
||||
return CCryptoBoringSSL_RSA_verify(hash_nid, msg, msg_len, sig, sig_len, rsa);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_verify_pss_mgf1(RSA *rsa, const void *msg,
|
||||
size_t msg_len, const EVP_MD *md,
|
||||
const EVP_MD *mgf1_md, int salt_len,
|
||||
const void *sig, size_t sig_len) {
|
||||
return CCryptoBoringSSL_RSA_verify_pss_mgf1(rsa, msg, msg_len, md, mgf1_md, salt_len, sig, sig_len);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_sign(int hash_nid, const void *in,
|
||||
unsigned int in_len, void *out,
|
||||
unsigned int *out_len, RSA *rsa) {
|
||||
return CCryptoBoringSSL_RSA_sign(hash_nid, in, in_len, out, out_len, rsa);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_sign_pss_mgf1(RSA *rsa, size_t *out_len, void *out,
|
||||
size_t max_out, const void *in,
|
||||
size_t in_len, const EVP_MD *md,
|
||||
const EVP_MD *mgf1_md, int salt_len) {
|
||||
return CCryptoBoringSSL_RSA_sign_pss_mgf1(rsa, out_len, out, max_out, in, in_len, md, mgf1_md, salt_len);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_public_encrypt(int flen, const void *from, void *to,
|
||||
RSA *rsa, int padding) {
|
||||
return CCryptoBoringSSL_RSA_public_encrypt(flen, from, to, rsa, padding);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_RSA_private_decrypt(int flen, const void *from, void *to,
|
||||
RSA *rsa, int padding) {
|
||||
return CCryptoBoringSSL_RSA_private_decrypt(flen, from, to, rsa, padding);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, void *out,
|
||||
size_t *out_len, const void *in,
|
||||
size_t in_len) {
|
||||
return CCryptoBoringSSL_EVP_PKEY_encrypt(ctx, out, out_len, in, in_len);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, void *out,
|
||||
size_t *out_len, const void *in,
|
||||
size_t in_len) {
|
||||
return CCryptoBoringSSL_EVP_PKEY_decrypt(ctx, out, out_len, in, in_len);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_EC_hash_to_curve_p256_xmd_sha256_sswu(const EC_GROUP *group, EC_POINT *out,
|
||||
const void *dst, size_t dst_len,
|
||||
const void *msg, size_t msg_len) {
|
||||
return CCryptoBoringSSL_EC_hash_to_curve_p256_xmd_sha256_sswu(group, out, dst, dst_len, msg, msg_len);
|
||||
}
|
||||
|
||||
int CCryptoBoringSSLShims_EC_hash_to_curve_p384_xmd_sha384_sswu(const EC_GROUP *group, EC_POINT *out,
|
||||
const void *dst, size_t dst_len,
|
||||
const void *msg, size_t msg_len) {
|
||||
return CCryptoBoringSSL_EC_hash_to_curve_p384_xmd_sha384_sswu(group, out, dst, dst_len, msg, msg_len);
|
||||
}
|
||||
|
||||
size_t CCryptoBoringSSLShims_EC_POINT_point2oct(const EC_GROUP *group,
|
||||
const EC_POINT *point,
|
||||
point_conversion_form_t form,
|
||||
void *buf, size_t max_out,
|
||||
BN_CTX *ctx) {
|
||||
return CCryptoBoringSSL_EC_POINT_point2oct(group, point, form, buf, max_out, ctx);
|
||||
}
|
||||
@@ -13,6 +13,7 @@
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
add_subdirectory(CCryptoBoringSSL)
|
||||
add_subdirectory(CCryptoBoringSSLShims)
|
||||
add_subdirectory(CXKCP)
|
||||
add_subdirectory(CXKCPShims)
|
||||
add_subdirectory(CryptoBoringWrapper)
|
||||
|
||||
@@ -16,8 +16,10 @@
|
||||
#else
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
import CryptoBoringWrapper
|
||||
#if canImport(FoundationEssentials)
|
||||
|
||||
@@ -117,6 +117,7 @@ target_compile_definitions(Crypto PRIVATE
|
||||
|
||||
target_include_directories(Crypto PRIVATE
|
||||
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
|
||||
$<TARGET_PROPERTY:CCryptoBoringSSLShims,INCLUDE_DIRECTORIES>
|
||||
$<TARGET_PROPERTY:CryptoBoringWrapper,INCLUDE_DIRECTORIES>
|
||||
$<TARGET_PROPERTY:CXKCP,INCLUDE_DIRECTORIES>
|
||||
$<TARGET_PROPERTY:CXKCPShims,INCLUDE_DIRECTORIES>)
|
||||
@@ -124,6 +125,7 @@ target_link_libraries(Crypto PUBLIC
|
||||
$<$<NOT:$<PLATFORM_ID:Darwin>>:dispatch>
|
||||
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
|
||||
CCryptoBoringSSL
|
||||
CCryptoBoringSSLShims
|
||||
CryptoBoringWrapper
|
||||
CXKCP
|
||||
CXKCPShims)
|
||||
|
||||
@@ -33,8 +33,12 @@ enum BoringSSLAESWRAPImpl {
|
||||
|
||||
let rc = try key.withUnsafeAESKEY(mode: .encrypting) { aesKey in
|
||||
output.withUnsafeMutableBytes { outputPtr -> CInt in
|
||||
keyToWrap.withUnsafeBytes { keyToWrapPtr -> CInt in
|
||||
CCryptoBoringSSL_AES_wrap_key(
|
||||
// Memory bind is safe: we cannot alias the pointer here.
|
||||
let outputPtr = outputPtr.bindMemory(to: UInt8.self)
|
||||
return keyToWrap.withUnsafeBytes { keyToWrapPtr -> CInt in
|
||||
// Memory bind is safe: we cannot alias the pointer here.
|
||||
let keyToWrapPtr = keyToWrapPtr.bindMemory(to: UInt8.self)
|
||||
return CCryptoBoringSSL_AES_wrap_key(
|
||||
aesKey,
|
||||
nil,
|
||||
outputPtr.baseAddress,
|
||||
@@ -74,6 +78,8 @@ enum BoringSSLAESWRAPImpl {
|
||||
) throws -> SymmetricKey {
|
||||
let unwrapped = try contiguousWrappedKey.withUnsafeBytes { inPtr in
|
||||
try [UInt8](unsafeUninitializedCapacity: inPtr.count) { outputPtr, count in
|
||||
// Bind is safe: we cannot violate the aliasing rules here as we never call to arbitrary code.
|
||||
let inPtr = inPtr.bindMemory(to: UInt8.self)
|
||||
let rc = try key.withUnsafeAESKEY(mode: .decrypting) { aesKey in
|
||||
CCryptoBoringSSL_AES_unwrap_key(
|
||||
aesKey,
|
||||
@@ -111,6 +117,8 @@ extension SymmetricKey {
|
||||
_ body: (UnsafePointer<AES_KEY>) throws -> ResultType
|
||||
) throws -> ResultType {
|
||||
try self.withUnsafeBytes { bytesPointer in
|
||||
// Bind is safe: cannot alias the pointer here.
|
||||
let bytesPointer = bytesPointer.bindMemory(to: UInt8.self)
|
||||
|
||||
var aesKey = AES_KEY()
|
||||
let bitsInKey = UInt32(bytesPointer.count * 8)
|
||||
|
||||
@@ -16,8 +16,10 @@
|
||||
#else
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
@@ -44,7 +46,7 @@ extension Curve25519.Signing {
|
||||
privateKeyBytes in
|
||||
privateKeyBytes = 64
|
||||
publicKey.withUnsafeMutableBytes { publicKeyPtr in
|
||||
CCryptoBoringSSL_ED25519_keypair(
|
||||
CCryptoBoringSSLShims_ED25519_keypair(
|
||||
publicKeyPtr.baseAddress,
|
||||
privateKeyPtr.baseAddress
|
||||
)
|
||||
@@ -78,7 +80,7 @@ extension Curve25519.Signing {
|
||||
privateKeyBytes in
|
||||
privateKeyBytes = 64
|
||||
publicKey.withUnsafeMutableBytes { publicKeyPtr in
|
||||
CCryptoBoringSSL_ED25519_keypair_from_seed(
|
||||
CCryptoBoringSSLShims_ED25519_keypair_from_seed(
|
||||
publicKeyPtr.baseAddress,
|
||||
privateKeyPtr.baseAddress,
|
||||
seedPtr.baseAddress
|
||||
|
||||
@@ -16,8 +16,10 @@
|
||||
#else
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
import CryptoBoringWrapper
|
||||
#if canImport(FoundationEssentials)
|
||||
@@ -146,7 +148,7 @@ struct OpenSSLNISTCurvePublicKeyImpl<Curve: OpenSSLSupportedNISTCurve>: Sendable
|
||||
/// allows some helper operations.
|
||||
@usableFromInline
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
final class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
|
||||
class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
|
||||
@usableFromInline
|
||||
let key: OpaquePointer
|
||||
|
||||
@@ -333,7 +335,7 @@ final class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unc
|
||||
func sign<D: Digest>(digest: D) throws -> ECDSASignature {
|
||||
let optionalRawSignature: UnsafeMutablePointer<ECDSA_SIG>? = digest.withUnsafeBytes {
|
||||
digestPtr in
|
||||
CCryptoBoringSSL_ECDSA_do_sign(digestPtr.baseAddress, digestPtr.count, self.key)
|
||||
CCryptoBoringSSLShims_ECDSA_do_sign(digestPtr.baseAddress, digestPtr.count, self.key)
|
||||
}
|
||||
guard let rawSignature = optionalRawSignature else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
@@ -351,7 +353,7 @@ final class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unc
|
||||
/// allows some helper operations.
|
||||
@usableFromInline
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
final class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
|
||||
class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unchecked Sendable {
|
||||
@usableFromInline
|
||||
let key: OpaquePointer
|
||||
|
||||
@@ -573,7 +575,7 @@ final class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve>: @unch
|
||||
func isValidSignature<D: Digest>(_ signature: ECDSASignature, for digest: D) -> Bool {
|
||||
let rc: CInt = signature.withUnsafeSignaturePointer { signaturePointer in
|
||||
digest.withUnsafeBytes { digestPointer in
|
||||
CCryptoBoringSSL_ECDSA_do_verify(
|
||||
CCryptoBoringSSLShims_ECDSA_do_verify(
|
||||
digestPointer.baseAddress,
|
||||
digestPointer.count,
|
||||
signaturePointer,
|
||||
@@ -684,7 +686,7 @@ func readRawPublicNumbers(
|
||||
/// In a number of places we need to know if an EC key is compact representable. This function implements that check.
|
||||
///
|
||||
/// The check is defined in https://tools.ietf.org/id/draft-jivsov-ecc-compact-05.html#rfc.section.4.2.1. Specifically, a
|
||||
/// point is compact representable if its y coordinate is the smaller of min(y, p-y) where p is the prime of the base field.
|
||||
/// point is compact representable if its y coordinate is the smaller of min(y, p-y) where p is the order of the prime field.
|
||||
@usableFromInline
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
func _isCompactRepresentable(
|
||||
@@ -699,7 +701,7 @@ func _isCompactRepresentable(
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
let context = try! FiniteFieldArithmeticContext(fieldSize: p)
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
let newY = try! context.subtract(y, from: p)
|
||||
let newY = try! context.subtract(y, from: group.order)
|
||||
|
||||
// The point is compact representable if y is less than or equal to newY.
|
||||
return y <= newY
|
||||
|
||||
@@ -16,8 +16,10 @@
|
||||
#else
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
@@ -75,7 +77,7 @@ extension Curve25519.KeyAgreement {
|
||||
publicKey.withUnsafeMutableBytes { publicKeyBytes in
|
||||
precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
|
||||
precondition(privateKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
|
||||
CCryptoBoringSSL_X25519_keypair(
|
||||
CCryptoBoringSSLShims_X25519_keypair(
|
||||
publicKeyBytes.baseAddress,
|
||||
privateKeyBytes.baseAddress
|
||||
)
|
||||
@@ -103,7 +105,7 @@ extension Curve25519.KeyAgreement {
|
||||
publicKeyBytes,
|
||||
publicKeySize in
|
||||
precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
|
||||
CCryptoBoringSSL_X25519_public_from_private(
|
||||
CCryptoBoringSSLShims_X25519_public_from_private(
|
||||
publicKeyBytes.baseAddress,
|
||||
privatePointer.baseAddress
|
||||
)
|
||||
@@ -138,7 +140,7 @@ extension Curve25519.KeyAgreement {
|
||||
// politely describe as a "lack of consensus" as to whether crypto libraries should reject this secret. CryptoKit on Apple
|
||||
// platforms currently does not, so for the sake of conformance with our peer implementation I will also refuse to check it.
|
||||
// We may elect to revisit this decision if the security best-practice thinking changes.
|
||||
CCryptoBoringSSL_X25519(
|
||||
CCryptoBoringSSLShims_X25519(
|
||||
secretPointer.baseAddress,
|
||||
privateKeyPointer.baseAddress,
|
||||
publicKeyShare.keyBytes
|
||||
|
||||
@@ -71,7 +71,7 @@ extension MessageAuthenticationCode {
|
||||
|
||||
public func makeIterator() -> Array<UInt8>.Iterator {
|
||||
self.withUnsafeBytes({ (buffPtr) in
|
||||
return Array(buffPtr).makeIterator()
|
||||
return Array(buffPtr.bindMemory(to: UInt8.self)).makeIterator()
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -16,8 +16,10 @@
|
||||
#else
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
import CryptoBoringWrapper
|
||||
#if canImport(FoundationEssentials)
|
||||
@@ -28,13 +30,13 @@ import Foundation
|
||||
|
||||
/// A wrapper around BoringSSL's ECDSA_SIG with some lifetime management.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
final class ECDSASignature {
|
||||
class ECDSASignature {
|
||||
private var _baseSig: UnsafeMutablePointer<ECDSA_SIG>
|
||||
|
||||
init<ContiguousBuffer: ContiguousBytes>(contiguousDERBytes derBytes: ContiguousBuffer) throws {
|
||||
self._baseSig = try derBytes.withUnsafeBytes { bytesPtr in
|
||||
guard
|
||||
let sig = CCryptoBoringSSL_ECDSA_SIG_from_bytes(bytesPtr.baseAddress, bytesPtr.count)
|
||||
let sig = CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(bytesPtr.baseAddress, bytesPtr.count)
|
||||
else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
@@ -99,6 +101,21 @@ final class ECDSASignature {
|
||||
)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var derBytes: Data {
|
||||
var dataPtr: UnsafeMutablePointer<UInt8>?
|
||||
var length = 0
|
||||
guard CCryptoBoringSSL_ECDSA_SIG_to_bytes(&dataPtr, &length, self._baseSig) == 1 else {
|
||||
fatalError("Unable to marshal signature to DER")
|
||||
}
|
||||
defer {
|
||||
// We must free this pointer.
|
||||
CCryptoBoringSSL_OPENSSL_free(dataPtr)
|
||||
}
|
||||
|
||||
return Data(UnsafeBufferPointer(start: dataPtr, count: length))
|
||||
}
|
||||
|
||||
func withUnsafeSignaturePointer<T>(
|
||||
_ body: (UnsafeMutablePointer<ECDSA_SIG>) throws -> T
|
||||
)
|
||||
|
||||
@@ -67,6 +67,17 @@ extension Data {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension P256.Signing.ECDSASignature {
|
||||
init<D: DataProtocol>(openSSLDERSignature derRepresentation: D) throws {
|
||||
self.rawRepresentation = try Data(derSignature: derRepresentation, over: P256.self)
|
||||
}
|
||||
|
||||
var openSSLDERRepresentation: Data {
|
||||
try! ECDSASignature(rawRepresentation: self.rawRepresentation).derBytes
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension P256.Signing.PrivateKey {
|
||||
func openSSLSignature<D: Digest>(for digest: D) throws -> P256.Signing.ECDSASignature {
|
||||
@@ -93,6 +104,17 @@ extension P256.Signing.PublicKey {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension P384.Signing.ECDSASignature {
|
||||
init<D: DataProtocol>(openSSLDERSignature derRepresentation: D) throws {
|
||||
self.rawRepresentation = try Data(derSignature: derRepresentation, over: P384.self)
|
||||
}
|
||||
|
||||
var openSSLDERRepresentation: Data {
|
||||
try! ECDSASignature(rawRepresentation: self.rawRepresentation).derBytes
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension P384.Signing.PrivateKey {
|
||||
func openSSLSignature<D: Digest>(for digest: D) throws -> P384.Signing.ECDSASignature {
|
||||
@@ -119,6 +141,17 @@ extension P384.Signing.PublicKey {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension P521.Signing.ECDSASignature {
|
||||
init<D: DataProtocol>(openSSLDERSignature derRepresentation: D) throws {
|
||||
self.rawRepresentation = try Data(derSignature: derRepresentation, over: P521.self)
|
||||
}
|
||||
|
||||
var openSSLDERRepresentation: Data {
|
||||
try! ECDSASignature(rawRepresentation: self.rawRepresentation).derBytes
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension P521.Signing.PrivateKey {
|
||||
func openSSLSignature<D: Digest>(for digest: D) throws -> P521.Signing.ECDSASignature {
|
||||
|
||||
@@ -16,8 +16,10 @@
|
||||
#else
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
@@ -92,7 +94,7 @@ extension Curve25519.Signing.PublicKey {
|
||||
precondition(signaturePointer.count == Curve25519.Signing.PublicKey.signatureByteCount)
|
||||
precondition(self.keyBytes.count == 32)
|
||||
let rc: CInt = self.keyBytes.withUnsafeBytes { keyBytesPtr in
|
||||
CCryptoBoringSSL_ED25519_verify(
|
||||
CCryptoBoringSSLShims_ED25519_verify(
|
||||
dataPointer.baseAddress,
|
||||
dataPointer.count,
|
||||
signaturePointer.baseAddress,
|
||||
@@ -131,7 +133,7 @@ extension Curve25519.Signing.PrivateKey {
|
||||
precondition(signaturePointer.count == Curve25519.Signing.PublicKey.signatureByteCount)
|
||||
precondition(keyPointer.count == ED25519_PRIVATE_KEY_LEN)
|
||||
|
||||
return CCryptoBoringSSL_ED25519_sign(
|
||||
return CCryptoBoringSSLShims_ED25519_sign(
|
||||
signaturePointer.baseAddress,
|
||||
dataPointer.baseAddress,
|
||||
dataPointer.count,
|
||||
|
||||
@@ -12,13 +12,24 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
#endif
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
// MARK: - Generated file, do NOT edit
|
||||
// any edits of this file WILL be overwritten and thus discarded
|
||||
// see section `gyb` in `README` for details.
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
#else
|
||||
|
||||
@@ -12,13 +12,24 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
#endif
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
// MARK: - Generated file, do NOT edit
|
||||
// any edits of this file WILL be overwritten and thus discarded
|
||||
// see section `gyb` in `README` for details.
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
#else
|
||||
|
||||
@@ -14,8 +14,10 @@
|
||||
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
@@ -41,7 +43,7 @@ extension BoringSSLAEAD {
|
||||
// Arguably this class is excessive, but it's probably better for this API to be as safe as possible
|
||||
// rather than rely on defer statements for our cleanup.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public final class AEADContext {
|
||||
public class AEADContext {
|
||||
private var context: EVP_AEAD_CTX
|
||||
|
||||
public init<Key: ContiguousBytes>(cipher: BoringSSLAEAD, key: Key) throws {
|
||||
@@ -50,7 +52,7 @@ extension BoringSSLAEAD {
|
||||
let rc: CInt = key.withUnsafeBytes { keyPointer in
|
||||
withUnsafeMutablePointer(to: &self.context) { contextPointer in
|
||||
// Create the AEAD context with a default tag length using the given key.
|
||||
CCryptoBoringSSL_EVP_AEAD_CTX_init(
|
||||
CCryptoBoringSSLShims_EVP_AEAD_CTX_init(
|
||||
contextPointer,
|
||||
cipher.boringSSLCipher,
|
||||
keyPointer.baseAddress,
|
||||
@@ -175,7 +177,7 @@ extension BoringSSLAEAD.AEADContext {
|
||||
|
||||
return authenticatedData.withUnsafeBytes { authenticatedDataBuffer in
|
||||
nonce.withUnsafeBytes { nonceBuffer in
|
||||
CCryptoBoringSSL_EVP_AEAD_CTX_seal_scatter(
|
||||
CCryptoBoringSSLShims_EVP_AEAD_CTX_seal_scatter(
|
||||
contextPointer,
|
||||
messageBuffer.baseAddress,
|
||||
tagBuffer.baseAddress! + tagInitializedCount,
|
||||
@@ -317,7 +319,7 @@ extension BoringSSLAEAD.AEADContext {
|
||||
nonce.withUnsafeBytes { nonceBuffer in
|
||||
tag.withUnsafeBytes { tagBuffer in
|
||||
authenticatedData.withUnsafeBytes { adBuffer in
|
||||
CCryptoBoringSSL_EVP_AEAD_CTX_open_gather(
|
||||
CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(
|
||||
contextPointer,
|
||||
messageBuffer.baseAddress,
|
||||
nonceBuffer.baseAddress,
|
||||
@@ -428,7 +430,7 @@ extension BoringSSLAEAD.AEADContext {
|
||||
|
||||
var writtenBytes = 0
|
||||
let rc = withUnsafePointer(to: &self.context) { contextPointer in
|
||||
CCryptoBoringSSL_EVP_AEAD_CTX_open(
|
||||
CCryptoBoringSSLShims_EVP_AEAD_CTX_open(
|
||||
contextPointer,
|
||||
outputBuffer.baseAddress,
|
||||
&writtenBytes,
|
||||
|
||||
@@ -24,11 +24,13 @@ add_library(CryptoBoringWrapper STATIC
|
||||
)
|
||||
|
||||
target_include_directories(CryptoBoringWrapper PUBLIC
|
||||
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>)
|
||||
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
|
||||
$<TARGET_PROPERTY:CCryptoBoringSSLShims,INCLUDE_DIRECTORIES>)
|
||||
|
||||
target_link_libraries(CryptoBoringWrapper PUBLIC
|
||||
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
|
||||
CCryptoBoringSSL)
|
||||
CCryptoBoringSSL
|
||||
CCryptoBoringSSLShims)
|
||||
|
||||
target_compile_options(CryptoBoringWrapper PRIVATE ${SWIFT_CRYPTO_COMPILE_OPTIONS})
|
||||
|
||||
|
||||
@@ -13,8 +13,10 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
@@ -492,35 +494,29 @@ extension EllipticCurvePoint {
|
||||
to group: BoringSSLEllipticCurveGroup,
|
||||
domainSeparationTag: DSTBytes
|
||||
) throws {
|
||||
let hashToCurveFunction =
|
||||
switch group.curveName {
|
||||
case .p256: CCryptoBoringSSLShims_EC_hash_to_curve_p256_xmd_sha256_sswu
|
||||
case .p384: CCryptoBoringSSLShims_EC_hash_to_curve_p384_xmd_sha384_sswu
|
||||
// BoringSSL has no P521 hash_to_curve API.
|
||||
case .p521: throw CryptoBoringWrapperError.invalidParameter
|
||||
case .none: throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
try self.init(_pointAtInfinityOn: group)
|
||||
try msg.withUnsafeBytes { msgPtr in
|
||||
try group.withUnsafeGroupPointer { groupPtr in
|
||||
try domainSeparationTag.withUnsafeBytes { dstPtr in
|
||||
let rc: CInt
|
||||
switch group.curveName {
|
||||
case .p256:
|
||||
rc = CCryptoBoringSSL_EC_hash_to_curve_p256_xmd_sha256_sswu(
|
||||
guard
|
||||
hashToCurveFunction(
|
||||
groupPtr,
|
||||
self._basePoint,
|
||||
dstPtr.baseAddress,
|
||||
dstPtr.count,
|
||||
msgPtr.baseAddress,
|
||||
msgPtr.count
|
||||
)
|
||||
case .p384:
|
||||
rc = CCryptoBoringSSL_EC_hash_to_curve_p384_xmd_sha384_sswu(
|
||||
groupPtr,
|
||||
self._basePoint,
|
||||
dstPtr.baseAddress,
|
||||
dstPtr.count,
|
||||
msgPtr.baseAddress,
|
||||
msgPtr.count
|
||||
)
|
||||
// BoringSSL has no P521 hash_to_curve API.
|
||||
case .p521: throw CryptoBoringWrapperError.invalidParameter
|
||||
case .none: throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
guard rc == 1 else { throw CryptoBoringWrapperError.internalBoringSSLError() }
|
||||
) == 1
|
||||
else { throw CryptoBoringWrapperError.internalBoringSSLError() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -607,7 +603,7 @@ extension EllipticCurvePoint {
|
||||
|
||||
let numBytesWritten = group.withUnsafeGroupPointer { groupPtr in
|
||||
buf.withUnsafeMutableBytes { bufPtr in
|
||||
CCryptoBoringSSL_EC_POINT_point2oct(
|
||||
CCryptoBoringSSLShims_EC_POINT_point2oct(
|
||||
groupPtr,
|
||||
self._basePoint,
|
||||
compressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED,
|
||||
|
||||
@@ -14,8 +14,10 @@
|
||||
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
@@ -121,7 +123,7 @@ extension ArbitraryPrecisionInteger.BackingStorage {
|
||||
self.init()
|
||||
|
||||
let rc: UnsafeMutablePointer<BIGNUM>? = bytes.withUnsafeBytes { bytesPointer in
|
||||
CCryptoBoringSSL_BN_bin2bn(
|
||||
CCryptoBoringSSLShims_BN_bin2bn(
|
||||
bytesPointer.baseAddress,
|
||||
bytesPointer.count,
|
||||
&self._backing
|
||||
@@ -457,8 +459,7 @@ extension ArbitraryPrecisionInteger {
|
||||
if nonNegative {
|
||||
CCryptoBoringSSL_BN_nnmod(resultPtr, selfPtr, modPtr, bnCtx)
|
||||
} else {
|
||||
// BN_mod is a C macro for BN_div with a nil quotient; call that directly.
|
||||
CCryptoBoringSSL_BN_div(nil, resultPtr, selfPtr, modPtr, bnCtx)
|
||||
CCryptoBoringSSLShims_BN_mod(resultPtr, selfPtr, modPtr, bnCtx)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -717,7 +718,7 @@ extension Data {
|
||||
assert(bytesPtr.count == byteCount)
|
||||
|
||||
return integer.withUnsafeBignumPointer { bnPtr in
|
||||
CCryptoBoringSSL_BN_bn2bin(bnPtr, bytesPtr.baseAddress!)
|
||||
CCryptoBoringSSLShims_BN_bn2bin(bnPtr, bytesPtr.baseAddress!)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ import Foundation
|
||||
/// ourselves.
|
||||
@usableFromInline
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
package final class FiniteFieldArithmeticContext: @unchecked Sendable {
|
||||
package class FiniteFieldArithmeticContext: @unchecked Sendable {
|
||||
private let fieldSize: ArbitraryPrecisionInteger
|
||||
package let bnCtx: OpaquePointer
|
||||
|
||||
|
||||
@@ -25,6 +25,19 @@ extension AES {
|
||||
/// suite.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum _CBC {
|
||||
private static var blockSize: Int { 16 }
|
||||
|
||||
private static func encryptBlockInPlace(
|
||||
_ plaintext: inout Block,
|
||||
priorCiphertextBlock: Block,
|
||||
using key: SymmetricKey
|
||||
) throws {
|
||||
assert([128, 192, 256].contains(key.bitCount))
|
||||
|
||||
plaintext ^= priorCiphertextBlock
|
||||
try AES.permute(&plaintext, key: key)
|
||||
}
|
||||
|
||||
/// Encrypts data using AES-CBC.
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -47,7 +60,44 @@ extension AES {
|
||||
///
|
||||
/// - Note: If `noPadding` is set to `true`, `plainText` has to be a multiple of the blockSize (16 bytes). Otherwise an error will be thrown.
|
||||
public static func encrypt<Plaintext: DataProtocol>(_ plaintext: Plaintext, using key: SymmetricKey, iv: AES._CBC.IV, noPadding: Bool) throws -> Data {
|
||||
try OpenSSLAESCBCImpl.encrypt(plaintext, using: key, iv: iv, noPadding: noPadding)
|
||||
guard [128, 192, 256].contains(key.bitCount) else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
let requiresFullPaddingBlock = (plaintext.count % AES._CBC.blockSize) == 0
|
||||
|
||||
if noPadding && !requiresFullPaddingBlock {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
var ciphertext = Data()
|
||||
ciphertext.reserveCapacity(plaintext.count + Self.blockSize) // Room for padding.
|
||||
|
||||
var previousBlock = Block(iv)
|
||||
var plaintext = plaintext[...]
|
||||
|
||||
while plaintext.count > 0 {
|
||||
var block = Block(blockBytes: plaintext.prefix(Self.blockSize))
|
||||
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
|
||||
ciphertext.append(contentsOf: block)
|
||||
previousBlock = block
|
||||
plaintext = plaintext.dropFirst(Self.blockSize)
|
||||
}
|
||||
|
||||
if requiresFullPaddingBlock && !noPadding {
|
||||
var block = Block.paddingBlock
|
||||
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
|
||||
ciphertext.append(contentsOf: block)
|
||||
}
|
||||
|
||||
return ciphertext
|
||||
}
|
||||
|
||||
private static func decryptBlockInPlace(_ ciphertext: inout Block, priorCiphertextBlock: Block, using key: SymmetricKey) throws {
|
||||
assert([128, 192, 256].contains(key.bitCount))
|
||||
|
||||
try AES.inversePermute(&ciphertext, key: key)
|
||||
ciphertext ^= priorCiphertextBlock
|
||||
}
|
||||
|
||||
/// Decrypts data using AES-CBC.
|
||||
@@ -70,7 +120,29 @@ extension AES {
|
||||
/// - noPadding: If this is set to `true`, padding won't be removed.
|
||||
/// - Returns: The decrypted message.
|
||||
public static func decrypt<Ciphertext: DataProtocol>(_ ciphertext: Ciphertext, using key: SymmetricKey, iv: AES._CBC.IV, noPadding: Bool) throws -> Data {
|
||||
try OpenSSLAESCBCImpl.decrypt(ciphertext, using: key, iv: iv, noPadding: noPadding)
|
||||
guard [128, 192, 256].contains(key.bitCount) else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
var plaintext = Data()
|
||||
plaintext.reserveCapacity(ciphertext.count)
|
||||
|
||||
var previousBlock = Block(iv)
|
||||
var ciphertext = ciphertext[...]
|
||||
|
||||
while ciphertext.count > 0 {
|
||||
let ctBlock = Block(blockBytes: ciphertext.prefix(Self.blockSize))
|
||||
var block = ctBlock
|
||||
try Self.decryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
|
||||
plaintext.append(contentsOf: block)
|
||||
previousBlock = ctBlock
|
||||
ciphertext = ciphertext.dropFirst(Self.blockSize)
|
||||
}
|
||||
|
||||
if !noPadding {
|
||||
try plaintext.trimPadding()
|
||||
}
|
||||
return plaintext
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -122,7 +194,7 @@ extension AES._CBC {
|
||||
0, 0, 0, 0, 0, 0, 0, 0
|
||||
)
|
||||
|
||||
Swift.withUnsafeMutableBytes(of: &self.ivBytes) { bytesPtr in
|
||||
withUnsafeMutableBytes(of: &self.ivBytes) { bytesPtr in
|
||||
bytesPtr.copyBytes(from: ivBytes)
|
||||
}
|
||||
}
|
||||
@@ -133,10 +205,24 @@ extension AES._CBC {
|
||||
Array(unsafeRawBufferPointer).makeIterator()
|
||||
}
|
||||
}
|
||||
|
||||
mutating func withUnsafeMutableBytes<ReturnType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
|
||||
return try Swift.withUnsafeMutableBytes(of: &self.ivBytes, body)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Data {
|
||||
fileprivate mutating func trimPadding() throws {
|
||||
guard let paddingBytes = self.last else {
|
||||
// Degenerate case, empty string. This is forbidden:
|
||||
// we must always pad.
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
guard paddingBytes > 0 &&
|
||||
self.count >= paddingBytes &&
|
||||
self.suffix(Int(paddingBytes)).allSatisfy({ $0 == paddingBytes }) else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
self = self.dropLast(Int(paddingBytes))
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,10 @@
|
||||
import Crypto
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
import CryptoBoringWrapper
|
||||
#if canImport(FoundationEssentials)
|
||||
@@ -66,6 +68,7 @@ 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.
|
||||
@@ -79,6 +82,7 @@ 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 {
|
||||
|
||||
@@ -15,8 +15,10 @@
|
||||
import Crypto
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
import CryptoBoringWrapper
|
||||
#if canImport(FoundationEssentials)
|
||||
@@ -97,24 +99,32 @@ extension AES {
|
||||
precondition(payload.count == Int(Self.blockSize))
|
||||
|
||||
key.withUnsafeBytes { keyPtr in
|
||||
// We bind both pointers here. These binds are not technically safe, but because we
|
||||
// know the pointers don't persist they can't violate the aliasing rules. We really
|
||||
// want a "with memory rebound" function but we don't have it yet.
|
||||
let keyBytes = keyPtr.bindMemory(to: UInt8.self)
|
||||
let blockBytes = payload.bindMemory(to: UInt8.self)
|
||||
|
||||
var key = AES_KEY()
|
||||
|
||||
if permutation == .forward {
|
||||
let rc = CCryptoBoringSSL_AES_set_encrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key)
|
||||
let rc = CCryptoBoringSSL_AES_set_encrypt_key(keyBytes.baseAddress, UInt32(keyBytes.count * 8), &key)
|
||||
precondition(rc == 0)
|
||||
|
||||
CCryptoBoringSSL_AES_encrypt(payload.baseAddress, payload.baseAddress, &key)
|
||||
CCryptoBoringSSL_AES_encrypt(blockBytes.baseAddress, blockBytes.baseAddress, &key)
|
||||
} else {
|
||||
let rc = CCryptoBoringSSL_AES_set_decrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key)
|
||||
let rc = CCryptoBoringSSL_AES_set_decrypt_key(keyBytes.baseAddress, UInt32(keyBytes.count * 8), &key)
|
||||
precondition(rc == 0)
|
||||
|
||||
CCryptoBoringSSL_AES_decrypt(payload.baseAddress, payload.baseAddress, &key)
|
||||
CCryptoBoringSSL_AES_decrypt(blockBytes.baseAddress, blockBytes.baseAddress, &key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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
|
||||
@@ -130,9 +140,70 @@ extension AES {
|
||||
)
|
||||
}
|
||||
|
||||
init(_ blockBytes: BlockBytes) {
|
||||
self.blockBytes = blockBytes
|
||||
}
|
||||
|
||||
init(_ iv: AES._CBC.IV) {
|
||||
self.blockBytes = iv.ivBytes
|
||||
}
|
||||
|
||||
init<BlockBytes: Collection>(blockBytes: BlockBytes) where BlockBytes.Element == UInt8 {
|
||||
// The block size is always 16. Pad out past there.
|
||||
precondition(blockBytes.count <= Self.blockSize)
|
||||
|
||||
self.blockBytes = (
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0
|
||||
)
|
||||
|
||||
Swift.withUnsafeMutableBytes(of: &self.blockBytes) { bytesPtr in
|
||||
bytesPtr.copyBytes(from: blockBytes)
|
||||
|
||||
// Early exit here.
|
||||
if blockBytes.count == Self.blockSize {
|
||||
return
|
||||
}
|
||||
|
||||
var remainingBytes = bytesPtr.dropFirst(blockBytes.count)
|
||||
let padByte = UInt8(remainingBytes.count)
|
||||
|
||||
for index in remainingBytes.indices {
|
||||
remainingBytes[index] = padByte
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static var paddingBlock: Block {
|
||||
// The padding block is a full block of value blocksize.
|
||||
let value = UInt8(truncatingIfNeeded: Self.blockSize)
|
||||
return Block((
|
||||
value, value, value, value, value, value, value, value,
|
||||
value, value, value, value, value, value, value, value
|
||||
))
|
||||
}
|
||||
|
||||
func withUnsafeBytes<ReturnType>(_ body: (UnsafeRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
|
||||
return try Swift.withUnsafeBytes(of: self.blockBytes, body)
|
||||
}
|
||||
|
||||
mutating func withUnsafeMutableBytes<ReturnType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
|
||||
return try Swift.withUnsafeMutableBytes(of: &self.blockBytes, body)
|
||||
}
|
||||
|
||||
static func ^= (lhs: inout Block, rhs: Block) {
|
||||
// Ideally we'd not use raw pointers for this.
|
||||
lhs.withUnsafeMutableBytes { lhsPtr in
|
||||
rhs.withUnsafeBytes { rhsPtr in
|
||||
assert(lhsPtr.count == Self.blockSize)
|
||||
assert(rhsPtr.count == Self.blockSize)
|
||||
|
||||
for index in 0..<Self.blockSize {
|
||||
lhsPtr[index] ^= rhsPtr[index]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static func isValidKey(_ key: SymmetricKey) -> Bool {
|
||||
@@ -144,3 +215,52 @@ extension AES {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension AES.Block: RandomAccessCollection, MutableCollection {
|
||||
var startIndex: Int {
|
||||
0
|
||||
}
|
||||
|
||||
var endIndex: Int {
|
||||
Self.blockSize
|
||||
}
|
||||
|
||||
subscript(position: Int) -> UInt8 {
|
||||
get {
|
||||
precondition(position >= 0)
|
||||
precondition(position < Self.blockSize)
|
||||
|
||||
return self.withUnsafeBytes { $0[position] }
|
||||
}
|
||||
|
||||
set {
|
||||
precondition(position >= 0)
|
||||
precondition(position < Self.blockSize)
|
||||
|
||||
self.withUnsafeMutableBytes { $0[position] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
func withContiguousStorageIfAvailable<ReturnValue>(
|
||||
_ body: (UnsafeBufferPointer<UInt8>) throws -> ReturnValue)
|
||||
rethrows -> ReturnValue? {
|
||||
return try withUnsafePointer(to: self.blockBytes) { tuplePtr in
|
||||
// Homogeneous tuples are always bound to the element type as well as to their own type.
|
||||
let retyped = UnsafeRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
|
||||
let bufferised = UnsafeBufferPointer(start: retyped, count: Self.blockSize)
|
||||
return try body(bufferised)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func withContiguousMutableStorageIfAvailable<ReturnValue>(
|
||||
_ body: (inout UnsafeMutableBufferPointer<UInt8>) throws -> ReturnValue)
|
||||
rethrows -> ReturnValue? {
|
||||
return try withUnsafeMutablePointer(to: &self.blockBytes) { tuplePtr in
|
||||
// Homogeneous tuples are always bound to the element type as well as to their own type.
|
||||
let retyped = UnsafeMutableRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
|
||||
var bufferised = UnsafeMutableBufferPointer(start: retyped, count: Self.blockSize)
|
||||
return try body(&bufferised)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Crypto
|
||||
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
#endif
|
||||
|
||||
#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)
|
||||
}
|
||||
@@ -19,8 +19,10 @@ import CryptoBoringWrapper
|
||||
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
|
||||
@@ -108,8 +108,8 @@ extension ARC {
|
||||
let T = H2G.hashToGroup(presentationContext, domainSeparationString: Data(("HashToGroup-" + ciphersuite.domain + "Tag").utf8))
|
||||
|
||||
// Recompute m1Tag = H2G(presentationContext) - nonce * tag
|
||||
let nonceScalar = try Group.Scalar(bytes: I2OSP(value: nonce, outputByteCount: ciphersuite.scalarByteCount), reductionIsModOrder: true)
|
||||
let m1Tag = T - nonceScalar * self.tag
|
||||
var m1Tag = T
|
||||
for _ in 0..<nonce { m1Tag = m1Tag - self.tag }
|
||||
|
||||
// Create a verifier, and allocate variables for the constrained scalars.
|
||||
var verifier = Verifier<H2G>(label: ciphersuite.domain + ciphersuite.domain + "CredentialPresentation")
|
||||
|
||||
@@ -18,7 +18,6 @@ add_library(CryptoExtras
|
||||
"AES/AES_CTR.swift"
|
||||
"AES/AES_GCM_SIV.swift"
|
||||
"AES/Block Function.swift"
|
||||
"AES/BoringSSL/AES_CBC_boring.swift"
|
||||
"AES/BoringSSL/AES_CFB_boring.swift"
|
||||
"AES/BoringSSL/AES_CTR_boring.swift"
|
||||
"AES/BoringSSL/AES_GCM_SIV_boring.swift"
|
||||
@@ -87,13 +86,15 @@ add_library(CryptoExtras
|
||||
target_compile_options(CryptoExtras PRIVATE -DCRYPTO_IN_SWIFTPM)
|
||||
|
||||
target_include_directories(CryptoExtras PRIVATE
|
||||
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>)
|
||||
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
|
||||
$<TARGET_PROPERTY:CCryptoBoringSSLShims,INCLUDE_DIRECTORIES>)
|
||||
|
||||
target_link_libraries(CryptoExtras PUBLIC
|
||||
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
|
||||
Crypto
|
||||
CryptoBoringWrapper
|
||||
CCryptoBoringSSL)
|
||||
CCryptoBoringSSL
|
||||
CCryptoBoringSSLShims)
|
||||
|
||||
target_compile_options(CryptoExtras PRIVATE ${SWIFT_CRYPTO_COMPILE_OPTIONS})
|
||||
|
||||
|
||||
@@ -17,8 +17,10 @@ import CryptoBoringWrapper
|
||||
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
@@ -70,15 +72,22 @@ enum OpenSSLChaCha20CTRImpl {
|
||||
key.withUnsafeBytes { keyPtr in
|
||||
nonce.withUnsafeBytes { noncePtr in
|
||||
message.withUnsafeBytes { plaintextPtr in
|
||||
var ciphertext = Data(repeating: 0, count: plaintextPtr.count)
|
||||
// We bind all three pointers here. These binds are not technically safe, but because we
|
||||
// know the pointers don't persist they can't violate the aliasing rules. We really
|
||||
// want a "with memory rebound" function but we don't have it yet.
|
||||
let keyBytes = keyPtr.bindMemory(to: UInt8.self)
|
||||
let nonceBytes = noncePtr.bindMemory(to: UInt8.self)
|
||||
let plaintext = plaintextPtr.bindMemory(to: UInt8.self)
|
||||
|
||||
var ciphertext = Data(repeating: 0, count: plaintext.count)
|
||||
|
||||
ciphertext.withUnsafeMutableBytes { ciphertext in
|
||||
CCryptoBoringSSL_CRYPTO_chacha_20(
|
||||
ciphertext.baseAddress,
|
||||
plaintextPtr.baseAddress,
|
||||
plaintextPtr.count,
|
||||
keyPtr.baseAddress,
|
||||
noncePtr.baseAddress,
|
||||
plaintext.baseAddress,
|
||||
plaintext.count,
|
||||
keyBytes.baseAddress,
|
||||
nonceBytes.baseAddress,
|
||||
counter
|
||||
)
|
||||
}
|
||||
|
||||
@@ -14,8 +14,10 @@
|
||||
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
import Crypto
|
||||
import CryptoBoringWrapper
|
||||
|
||||
@@ -161,7 +161,7 @@ struct OpenSSLGroupScalar<C: OpenSSLSupportedNISTCurve>: GroupScalar, CustomStri
|
||||
|
||||
/// Deserializes a scalar from data.
|
||||
/// - Parameters:
|
||||
/// - bytes: The serialized scalar
|
||||
/// - data: 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 {
|
||||
@@ -276,9 +276,6 @@ extension OpenSSLCurvePoint {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension OpenSSLCurvePoint: OPRFGroupElement {
|
||||
init(oprfRepresentation data: Data) throws {
|
||||
guard data.count == C.compressedx962PointByteCount else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
let point = try EllipticCurvePoint(x962Representation: data, on: C.group, context: C.__ffac)
|
||||
self.init(ecPoint: point)
|
||||
}
|
||||
|
||||
@@ -22,8 +22,10 @@ import Foundation
|
||||
#if !canImport(CommonCrypto)
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
|
||||
@@ -16,8 +16,10 @@ import Crypto
|
||||
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
|
||||
@@ -105,15 +105,9 @@ 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 {
|
||||
@@ -212,15 +206,9 @@ 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.
|
||||
|
||||
@@ -117,14 +117,8 @@ 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 {
|
||||
@@ -254,14 +248,8 @@ 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.
|
||||
@@ -547,7 +535,6 @@ 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 }
|
||||
@@ -557,7 +544,6 @@ 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)
|
||||
@@ -568,7 +554,6 @@ 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 }
|
||||
@@ -578,7 +563,6 @@ 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)
|
||||
@@ -586,14 +570,8 @@ 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 }
|
||||
@@ -601,7 +579,6 @@ 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 {
|
||||
@@ -619,7 +596,6 @@ 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 }
|
||||
@@ -629,7 +605,6 @@ 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)
|
||||
@@ -640,7 +615,6 @@ 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 }
|
||||
@@ -650,7 +624,6 @@ 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)
|
||||
@@ -659,14 +632,8 @@ 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.
|
||||
@@ -774,8 +741,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.
|
||||
/// 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 (e.g.
|
||||
/// `keySizeInBits / 8`). 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)
|
||||
}
|
||||
@@ -797,17 +764,17 @@ extension _RSA.Encryption.PublicKey {
|
||||
switch padding.backing {
|
||||
case ._weakAndInsecure_pkcs1v1_5:
|
||||
// https://www.rfc-editor.org/rfc/rfc8017#section-7.2
|
||||
return self.modulusByteCount - 11
|
||||
return (self.keySizeInBits / 8) - 11
|
||||
case let .pkcs1_oaep(Digest):
|
||||
// https://datatracker.ietf.org/doc/html/rfc8017#section-7.1.1
|
||||
return self.modulusByteCount - (2 * Digest.hashBitLength / 8) - 2
|
||||
return (self.keySizeInBits / 8) - (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 block size of the key,
|
||||
/// minus any additional space required by the padding mode. Attempting to
|
||||
/// > 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
|
||||
/// 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 {
|
||||
@@ -834,37 +801,21 @@ extension _RSA {
|
||||
d: ArbitraryPrecisionInteger
|
||||
) throws -> (p: ArbitraryPrecisionInteger, q: ArbitraryPrecisionInteger) {
|
||||
// This is based on the proof of fact 1 in https://www.ams.org/notices/199902/boneh.pdf
|
||||
|
||||
// Valid keys have e < n, and BoringSSL rejects d >= n and moduli over its maximum. Larger
|
||||
// values let the caller pick the cost of the exponentiations and squaring loop below.
|
||||
guard n.byteCount <= _RSA.maximumModulusBitCount / 8, e < n, d < n else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
let k = (d * e) - 1
|
||||
|
||||
// k == 0 (that is, e * d == 1) gives r == 0 below, for which every base is trivial.
|
||||
guard k > 0, k.isEven else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
let t = k.trailingZeroBitCount
|
||||
let r = k >> t
|
||||
|
||||
guard k.isEven else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
var y: ArbitraryPrecisionInteger = 0
|
||||
var i = 1
|
||||
|
||||
let context = try FiniteFieldArithmeticContext(fieldSize: n)
|
||||
|
||||
// Every attempt must count towards the limit, including those where g^r is trivially
|
||||
// 1 or n - 1. Inputs for which that holds for every base would otherwise never return.
|
||||
for _ in 0..<100 {
|
||||
while i <= 100 {
|
||||
let g = try ArbitraryPrecisionInteger.random(inclusiveMin: 2, exclusiveMax: n)
|
||||
|
||||
// The check at the end of this attempt only holds for bases coprime to n.
|
||||
guard try ArbitraryPrecisionInteger.gcd(g, n) == 1 else {
|
||||
continue
|
||||
}
|
||||
|
||||
y = try context.pow(g, r)
|
||||
|
||||
guard y != 1, y != n - 1 else {
|
||||
@@ -893,11 +844,7 @@ extension _RSA {
|
||||
return (p, q)
|
||||
}
|
||||
|
||||
// Here x is g^k unless the loop stopped at n - 1. For a valid key g^k == 1 for every
|
||||
// base coprime to n, so any other value means the numbers do not form a key.
|
||||
guard x == n - 1 else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
i &+= 1
|
||||
}
|
||||
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
|
||||
@@ -18,8 +18,10 @@ import CryptoBoringWrapper
|
||||
// NOTE: This file is unconditionally compiled because RSABSSA is implemented using BoringSSL on all platforms.
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
@@ -81,10 +83,6 @@ internal struct BoringSSLRSAPublicKey: Sendable {
|
||||
self.backing.keySizeInBits
|
||||
}
|
||||
|
||||
var modulusByteCount: Int {
|
||||
self.backing.modulusByteCount
|
||||
}
|
||||
|
||||
fileprivate init(_ backing: Backing) {
|
||||
self.backing = backing
|
||||
}
|
||||
@@ -230,17 +228,17 @@ extension BoringSSLRSAPublicKey {
|
||||
self.pointer = pointer
|
||||
}
|
||||
|
||||
fileprivate convenience init(copying other: Backing) {
|
||||
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
|
||||
fileprivate init(copying other: Backing) {
|
||||
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
|
||||
let rsaPublicKey = CCryptoBoringSSL_RSAPublicKey_dup(
|
||||
CCryptoBoringSSL_EVP_PKEY_get0_RSA(other.pointer)
|
||||
)
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
|
||||
}
|
||||
|
||||
fileprivate convenience init(pemRepresentation: String) throws {
|
||||
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
|
||||
fileprivate init(pemRepresentation: String) throws {
|
||||
var pemRepresentation = pemRepresentation
|
||||
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
|
||||
|
||||
// There are two encodings for RSA public keys: PKCS#1 and the SPKI form.
|
||||
// The SPKI form is what we support for EC keys, so we try that first, then we
|
||||
@@ -256,15 +254,20 @@ extension BoringSSLRSAPublicKey {
|
||||
}
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
|
||||
} catch {
|
||||
let rsaPublicKey = try pemRepresentation.withUTF8 { utf8Ptr in
|
||||
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
|
||||
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPublicKey(bio, nil, nil, nil) else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
do {
|
||||
let rsaPublicKey = try pemRepresentation.withUTF8 { utf8Ptr in
|
||||
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
|
||||
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPublicKey(bio, nil, nil, nil) else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
return key
|
||||
}
|
||||
return key
|
||||
}
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
|
||||
} catch {
|
||||
CCryptoBoringSSL_EVP_PKEY_free(self.pointer)
|
||||
throw error
|
||||
}
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -277,8 +280,8 @@ extension BoringSSLRSAPublicKey {
|
||||
}
|
||||
}
|
||||
|
||||
private convenience init<Bytes: ContiguousBytes>(contiguousDerRepresentation: Bytes) throws {
|
||||
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
|
||||
private init<Bytes: ContiguousBytes>(contiguousDerRepresentation: Bytes) throws {
|
||||
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
|
||||
// There are two encodings for RSA public keys: PKCS#1 and the SPKI form.
|
||||
// The SPKI form is what we support for EC keys, so we try that first, then we
|
||||
// fall back to the PKCS#1 form if that parse fails.
|
||||
@@ -293,20 +296,25 @@ extension BoringSSLRSAPublicKey {
|
||||
}
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
|
||||
} catch {
|
||||
let rsaPublicKey = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
|
||||
try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
|
||||
guard let key = CCryptoBoringSSL_d2i_RSAPublicKey_bio(bio, nil) else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
do {
|
||||
let rsaPublicKey = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
|
||||
try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
|
||||
guard let key = CCryptoBoringSSL_d2i_RSAPublicKey_bio(bio, nil) else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
return key
|
||||
}
|
||||
return key
|
||||
}
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
|
||||
} catch {
|
||||
CCryptoBoringSSL_EVP_PKEY_free(self.pointer)
|
||||
throw error
|
||||
}
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate convenience init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
|
||||
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
|
||||
fileprivate init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
|
||||
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
|
||||
let n = try ArbitraryPrecisionInteger(bytes: n)
|
||||
let e = try ArbitraryPrecisionInteger(bytes: e)
|
||||
|
||||
@@ -353,12 +361,7 @@ extension BoringSSLRSAPublicKey {
|
||||
|
||||
fileprivate var keySizeInBits: Int {
|
||||
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
|
||||
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))
|
||||
return Int(CCryptoBoringSSL_RSA_size(rsaPublicKey)) * 8
|
||||
}
|
||||
|
||||
fileprivate func isValidSignature<D: Digest>(
|
||||
@@ -373,7 +376,7 @@ extension BoringSSLRSAPublicKey {
|
||||
let rc: CInt = digest.withUnsafeBytes { digestPtr in
|
||||
switch padding.backing {
|
||||
case .pkcs1v1_5:
|
||||
return CCryptoBoringSSL_RSA_verify(
|
||||
return CCryptoBoringSSLShims_RSA_verify(
|
||||
hashDigestType.nid,
|
||||
digestPtr.baseAddress,
|
||||
digestPtr.count,
|
||||
@@ -382,7 +385,7 @@ extension BoringSSLRSAPublicKey {
|
||||
rsaPublicKey
|
||||
)
|
||||
case .pss:
|
||||
return CCryptoBoringSSL_RSA_verify_pss_mgf1(
|
||||
return CCryptoBoringSSLShims_RSA_verify_pss_mgf1(
|
||||
rsaPublicKey,
|
||||
digestPtr.baseAddress,
|
||||
digestPtr.count,
|
||||
@@ -393,7 +396,7 @@ extension BoringSSLRSAPublicKey {
|
||||
signaturePtr.count
|
||||
)
|
||||
case .pssZero:
|
||||
return CCryptoBoringSSL_RSA_verify_pss_mgf1(
|
||||
return CCryptoBoringSSLShims_RSA_verify_pss_mgf1(
|
||||
rsaPublicKey,
|
||||
digestPtr.baseAddress,
|
||||
digestPtr.count,
|
||||
@@ -445,7 +448,7 @@ extension BoringSSLRSAPublicKey {
|
||||
}
|
||||
|
||||
var writtenLength = bufferPtr.count
|
||||
let rc = CCryptoBoringSSL_EVP_PKEY_encrypt(
|
||||
let rc = CCryptoBoringSSLShims_EVP_PKEY_encrypt(
|
||||
ctx,
|
||||
bufferPtr.baseAddress,
|
||||
&writtenLength,
|
||||
@@ -470,6 +473,7 @@ 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)
|
||||
@@ -527,6 +531,7 @@ 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)
|
||||
|
||||
@@ -826,7 +831,7 @@ extension BoringSSLRSAPrivateKey {
|
||||
|
||||
fileprivate var keySizeInBits: Int {
|
||||
let rsaPrivateKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
|
||||
return Int(CCryptoBoringSSL_RSA_bits(rsaPrivateKey))
|
||||
return Int(CCryptoBoringSSL_RSA_size(rsaPrivateKey)) * 8
|
||||
}
|
||||
|
||||
fileprivate var publicKey: BoringSSLRSAPublicKey {
|
||||
@@ -858,10 +863,10 @@ extension BoringSSLRSAPrivateKey {
|
||||
switch padding.backing {
|
||||
case .pkcs1v1_5:
|
||||
var writtenLength = CUnsignedInt(0)
|
||||
let rc = CCryptoBoringSSL_RSA_sign(
|
||||
let rc = CCryptoBoringSSLShims_RSA_sign(
|
||||
hashDigestType.nid,
|
||||
digestPtr.baseAddress,
|
||||
digestPtr.count,
|
||||
CUnsignedInt(digestPtr.count),
|
||||
bufferPtr.baseAddress,
|
||||
&writtenLength,
|
||||
rsaPrivateKey
|
||||
@@ -869,7 +874,7 @@ extension BoringSSLRSAPrivateKey {
|
||||
outputLength = Int(writtenLength)
|
||||
return rc
|
||||
case .pss:
|
||||
return CCryptoBoringSSL_RSA_sign_pss_mgf1(
|
||||
return CCryptoBoringSSLShims_RSA_sign_pss_mgf1(
|
||||
rsaPrivateKey,
|
||||
&outputLength,
|
||||
bufferPtr.baseAddress,
|
||||
@@ -881,7 +886,7 @@ extension BoringSSLRSAPrivateKey {
|
||||
CInt(hashDigestType.digestLength)
|
||||
)
|
||||
case .pssZero:
|
||||
return CCryptoBoringSSL_RSA_sign_pss_mgf1(
|
||||
return CCryptoBoringSSLShims_RSA_sign_pss_mgf1(
|
||||
rsaPrivateKey,
|
||||
&outputLength,
|
||||
bufferPtr.baseAddress,
|
||||
@@ -938,7 +943,7 @@ extension BoringSSLRSAPrivateKey {
|
||||
|
||||
var writtenLength = bufferPtr.count
|
||||
|
||||
let rc = CCryptoBoringSSL_EVP_PKEY_decrypt(
|
||||
let rc = CCryptoBoringSSLShims_EVP_PKEY_decrypt(
|
||||
ctx,
|
||||
bufferPtr.baseAddress,
|
||||
&writtenLength,
|
||||
@@ -1131,8 +1136,3 @@ enum BlindSigningHelpers {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension _RSA {
|
||||
static let maximumModulusBitCount = Int(OPENSSL_RSA_MAX_MODULUS_BITS)
|
||||
}
|
||||
@@ -15,8 +15,10 @@
|
||||
// NOTE: This file is unconditionally compiled because RSABSSA is implemented using BoringSSL on all platforms.
|
||||
#if hasFeature(SourceWarningControl)
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
||||
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSLShims
|
||||
#else
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
#endif
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
|
||||
@@ -29,7 +29,7 @@ final class ThreadSpecificVariable<Value: AnyObject> {
|
||||
// the actual type in there is `Box<(ThreadSpecificVariable<T>, T)>` but we can't use that as C functions can't capture (even types)
|
||||
private typealias BoxedType = Box<(AnyObject, AnyObject)>
|
||||
|
||||
private final class Key {
|
||||
private class Key {
|
||||
private var underlyingKey: ThreadOpsSystem.ThreadSpecificKey
|
||||
|
||||
internal init(destructor: @escaping ThreadOpsSystem.ThreadSpecificKeyDestructor) {
|
||||
|
||||
@@ -24,7 +24,7 @@ final class CXKCPTests: XCTestCase {
|
||||
var output = [UInt8](repeating: 0, count: 32)
|
||||
|
||||
let result = input.withUnsafeBytes { inputBytes in
|
||||
SHA3_256(&output, inputBytes.baseAddress, inputBytes.count)
|
||||
SHA3_256(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
|
||||
}
|
||||
|
||||
// Should return 0 on success
|
||||
@@ -43,7 +43,7 @@ final class CXKCPTests: XCTestCase {
|
||||
var output = [UInt8](repeating: 0, count: 28)
|
||||
|
||||
let result = input.withUnsafeBytes { inputBytes in
|
||||
SHA3_224(&output, inputBytes.baseAddress, inputBytes.count)
|
||||
SHA3_224(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
|
||||
}
|
||||
|
||||
// Should return 0 on success
|
||||
@@ -62,7 +62,7 @@ final class CXKCPTests: XCTestCase {
|
||||
var output = [UInt8](repeating: 0, count: 48)
|
||||
|
||||
let result = input.withUnsafeBytes { inputBytes in
|
||||
SHA3_384(&output, inputBytes.baseAddress, inputBytes.count)
|
||||
SHA3_384(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
|
||||
}
|
||||
|
||||
// Should return 0 on success
|
||||
@@ -82,7 +82,7 @@ final class CXKCPTests: XCTestCase {
|
||||
var output = [UInt8](repeating: 0, count: 64)
|
||||
|
||||
let result = input.withUnsafeBytes { inputBytes in
|
||||
SHA3_512(&output, inputBytes.baseAddress, inputBytes.count)
|
||||
SHA3_512(&output, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
|
||||
}
|
||||
|
||||
// Should return 0 on success
|
||||
@@ -102,7 +102,7 @@ final class CXKCPTests: XCTestCase {
|
||||
var output = [UInt8](repeating: 0, count: 32) // 256 bits output
|
||||
|
||||
let result = input.withUnsafeBytes { inputBytes in
|
||||
SHAKE128(&output, output.count, inputBytes.baseAddress, inputBytes.count)
|
||||
SHAKE128(&output, output.count, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
|
||||
}
|
||||
|
||||
// Should return 0 on success
|
||||
@@ -121,7 +121,7 @@ final class CXKCPTests: XCTestCase {
|
||||
var output = [UInt8](repeating: 0, count: 32) // 256 bits output
|
||||
|
||||
let result = input.withUnsafeBytes { inputBytes in
|
||||
SHAKE256(&output, output.count, inputBytes.baseAddress, inputBytes.count)
|
||||
SHAKE256(&output, output.count, inputBytes.bindMemory(to: UInt8.self).baseAddress, inputBytes.count)
|
||||
}
|
||||
|
||||
// Should return 0 on success
|
||||
|
||||
@@ -163,85 +163,6 @@ final class CBCTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testDecryptRejectsPaddingLengthGreaterThanBlockSize() throws {
|
||||
// A plaintext whose final block claims a PKCS#7 pad length of 17 (0x11)
|
||||
// is invalid for a 16-byte block: the maximum valid PKCS#7 pad is one
|
||||
// full block (16). Correct unpadding must reject it. Regression guard:
|
||||
// the previous `trimPadding` accepted any pad length up to 255 and
|
||||
// scanned across blocks, so it wrongly stripped 17 bytes here.
|
||||
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
|
||||
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
|
||||
|
||||
// 32-byte (block-multiple) plaintext ending in 17 bytes of 0x11.
|
||||
var plaintext = Data(repeating: 0xAB, count: 15)
|
||||
plaintext.append(Data(repeating: 0x11, count: 17))
|
||||
precondition(plaintext.count == 32)
|
||||
|
||||
let ciphertext = try AES._CBC.encrypt(plaintext, using: key, iv: iv, noPadding: true)
|
||||
|
||||
XCTAssertThrowsError(
|
||||
try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false)
|
||||
) { error in
|
||||
guard let error = error as? CryptoKitError, case .incorrectParameterSize = error else {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testUnpadAcceptsAllValidPaddingLengths() throws {
|
||||
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
|
||||
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
|
||||
|
||||
// For every valid PKCS#7 pad length (1...16), round-trip a message that
|
||||
// pads to exactly that length and assert exact recovery.
|
||||
for padLength in 1...16 {
|
||||
let messageLength = 32 - padLength // pads to 32 bytes (two blocks)
|
||||
let message = Data((0..<messageLength).map { UInt8(truncatingIfNeeded: $0) })
|
||||
|
||||
let ciphertext = try AES._CBC.encrypt(message, using: key, iv: iv, noPadding: false)
|
||||
let decrypted = try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false)
|
||||
XCTAssertEqual(decrypted, message, "round-trip failed for pad length \(padLength)")
|
||||
}
|
||||
}
|
||||
|
||||
func testUnpadRejectsCorruptedPaddingByte() throws {
|
||||
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
|
||||
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
|
||||
|
||||
// Build a validly-padded block-multiple plaintext, then corrupt each
|
||||
// padding byte except the last (which encodes the claimed length). The
|
||||
// constant-time scan must reject a mismatch at any position.
|
||||
for padLength in 2...16 {
|
||||
var padded = Data((0..<(32 - padLength)).map { UInt8(truncatingIfNeeded: $0) })
|
||||
padded.append(Data(repeating: UInt8(padLength), count: padLength))
|
||||
precondition(padded.count == 32)
|
||||
|
||||
for position in (32 - padLength)..<31 {
|
||||
var corrupted = padded
|
||||
corrupted[position] = UInt8(padLength) ^ 0xFF // guaranteed != padLength
|
||||
let ciphertext = try AES._CBC.encrypt(corrupted, using: key, iv: iv, noPadding: true)
|
||||
|
||||
XCTAssertThrowsError(
|
||||
try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false),
|
||||
"corruption at pad length \(padLength), position \(position) was not rejected"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testUnpadRejectsZeroPaddingLength() throws {
|
||||
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
|
||||
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
|
||||
|
||||
// A final byte of 0x00 claims a pad length of zero, which is invalid PKCS#7.
|
||||
var padded = Data((0..<31).map { UInt8(truncatingIfNeeded: $0) })
|
||||
padded.append(0x00)
|
||||
let ciphertext = try AES._CBC.encrypt(padded, using: key, iv: iv, noPadding: true)
|
||||
|
||||
XCTAssertThrowsError(try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false))
|
||||
}
|
||||
|
||||
func testToDataConversion() throws {
|
||||
let randomBytes = (0..<16).map { _ in UInt8.random(in: UInt8.min...UInt8.max) }
|
||||
let dataIn = Data(randomBytes)
|
||||
|
||||
@@ -158,61 +158,6 @@ class ARCTests: XCTestCase {
|
||||
// try endToEndWorkflow(CurveType: P521.self)
|
||||
}
|
||||
|
||||
func testVerifyCostIsIndependentOfTheNonce() async throws {
|
||||
let ciphersuite = ARC.Ciphersuite(HashToCurveImpl<P256>.self)
|
||||
let (generatorG, generatorH) = ARC.getGenerators(suite: ciphersuite)
|
||||
let x0 = GroupImpl<P256>.Scalar.random
|
||||
let x1 = GroupImpl<P256>.Scalar.random
|
||||
let x2 = GroupImpl<P256>.Scalar.random
|
||||
let x0Blinding = GroupImpl<P256>.Scalar.random
|
||||
let serverPrivateKey = ARC.ServerPrivateKey(x0: x0, x1: x1, x2: x2, x0Blinding: x0Blinding)
|
||||
let server = ARC.Server(ciphersuite: ciphersuite, x0: x0, x1: x1, x2: x2, x0Blinding: x0Blinding)
|
||||
let requestContext = Data("test request context".utf8)
|
||||
let precredential = try ARC.Precredential(
|
||||
ciphersuite: ciphersuite,
|
||||
m1: GroupImpl<P256>.Scalar.random,
|
||||
requestContext: requestContext,
|
||||
r1: GroupImpl<P256>.Scalar.random,
|
||||
r2: GroupImpl<P256>.Scalar.random,
|
||||
serverPublicKey: server.serverPublicKey
|
||||
)
|
||||
let credential = try precredential.makeCredential(
|
||||
credentialResponse: try server.respond(credentialRequest: precredential.credentialRequest)
|
||||
)
|
||||
|
||||
// The nonce comes from the client, so presentation verification cost must not scale with nonce.
|
||||
// This test uses such a large nonce that the test would hit the timeout if verification was correlated.
|
||||
let nonce = 1 << 62
|
||||
let presentationContext = Data("0123456789".utf8)
|
||||
let presentation = try ARC.Presentation(
|
||||
credential: credential,
|
||||
presentationContext: presentationContext,
|
||||
nonce: nonce,
|
||||
generatorG: generatorG,
|
||||
generatorH: generatorH
|
||||
)
|
||||
|
||||
let verificationResult: LockedBox<Bool?> = .init(initialValue: nil)
|
||||
let finished = expectation(description: "verification finished")
|
||||
let thread = Thread {
|
||||
let result = try? presentation.verify(
|
||||
serverPrivateKey: serverPrivateKey,
|
||||
X1: x1 * generatorH,
|
||||
m2: precredential.clientSecrets.m2,
|
||||
presentationContext: presentationContext,
|
||||
presentationLimit: Int.max,
|
||||
nonce: nonce,
|
||||
generatorG: generatorG,
|
||||
generatorH: generatorH,
|
||||
ciphersuite: ciphersuite)
|
||||
verificationResult.withLockedValue { $0 = result }
|
||||
finished.fulfill()
|
||||
}
|
||||
thread.start()
|
||||
await fulfillment(of: [finished], timeout: 10)
|
||||
XCTAssertEqual(verificationResult.withLockedValue { $0 }, true)
|
||||
}
|
||||
|
||||
func testPresentationState() throws {
|
||||
let context1 = Data("context1".utf8)
|
||||
let context2 = Data("context2".utf8)
|
||||
|
||||
@@ -79,21 +79,4 @@ final class VOPRFPublicAPITests: XCTestCase {
|
||||
// [Server] Compute the PRF for the input, without blinding or proof generation.
|
||||
let _: Data = try privateKey.evaluate(input)
|
||||
}
|
||||
|
||||
func testBlindedElementRejectsUncompressedOPRFRepresentation() throws {
|
||||
/// Check we only accept compressed encoded elements, as per RFC 9497:
|
||||
///
|
||||
/// > SerializeElement(A): Implemented using the compressed Elliptic-Curve-Point-to-Octet-String method...
|
||||
/// >
|
||||
/// > DeserializeElement(buf): Implemented by attempting to deserialize a 49-byte array to a public key
|
||||
/// using the compressed Octet-String-to-Elliptic-Curve-Point method...
|
||||
///
|
||||
/// - See: https://www.rfc-editor.org/rfc/rfc9497.html#name-oprfp-384-sha-384
|
||||
let publicKey = P384._VOPRF.PrivateKey().publicKey
|
||||
let blindedElement = try publicKey.blind(Data("This is some input data".utf8)).blindedElement
|
||||
let compressed = blindedElement.oprfRepresentation
|
||||
let uncompressed = try P384.Signing.PublicKey(compressedRepresentation: compressed).x963Representation
|
||||
|
||||
XCTAssertThrowsError(try P384._VOPRF.BlindedElement(oprfRepresentation: uncompressed))
|
||||
}
|
||||
}
|
||||
@@ -201,17 +201,6 @@ 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,13 +111,6 @@ 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 {
|
||||
@@ -177,77 +170,6 @@ 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+0keFtdLvSsdsBAZlq7VT8vHyfxqhcpb0RkjThWfVhR2BjzO8TNLA+mlKGKZJ
|
||||
foTE3r7o99Ev4X+H4QxCyAC8oyAKy1lyDA4wT7OFBBXtXJmeQ/PbYCuMMyqrCWUg
|
||||
VL48rK150QxHQ0U9XsGCnF70X/PMPebKY60OS36pTYhmi77h0maiY4yW2kHNfgeG
|
||||
Mbc3XQ19Sr42f5zKe0AIQfzK91v6M5PaEIpJAfm+JPDNWf2+RKEVa93gNiuTZ2+p
|
||||
gUjf7ut8mY5MEn7fZhCeZeNBjNTuKXj3JqdP3wIDAQABAoIBAQC252vPakq7XeOc
|
||||
0vdx+ISye99GAs6aP+z/pgvbtR+yYbxxg/ndR2bXDBBDYT/I1YFZzFh9HUWnWJIC
|
||||
CljlFl2onfDE7pBVQdV9moaMfK+8Ilgz4PUEhbHKCgpClJM3H05nTmUN83qwyXtf
|
||||
EhJhX2s/sfezpP/Op+HyfbfspW4CZrrJmv1zfqIjDiV7LMaoDDU+UDHexcgwoXCa
|
||||
HKC/U7RcbNYE3hOg/Fjx+nevprXthhf8mpnkAzTcpXsMcATuvh7sSqdFnHkF9egw
|
||||
CBnlx+iH9J/6Q3VwoZgwggi9S6qT5yrS0/JVWVic4KaiE81dDr+KLmXIpOFRNuYf
|
||||
8sP79cfRAoGBAcwBZ+XfX5H8Ii7tSjCJWJ+sw6cevH4YQhYWDEgodsmzj2hDRoRj
|
||||
EaGdATP5dry7RWePTuhN0KlvMYX/xI2kvoRrK6sR4bad0V2J8lKBFxAil55w531L
|
||||
wZUAhxzAChWZ6uRMR694yati/8wIG+BMdwBPA+00+pMH2Kd9HGN8xoBHAoGBAYrA
|
||||
0sfOCNqvkf7OsoiShjSdeTYkTqjHrVR7m6DJg2FUL6E9VnaSLG0esnAYGAozKfFl
|
||||
rQz7gEGckMG2dILOAY9z3wv4ltX12RxmAJMHoO/ENDVxiqSKC7utiKzcii9qy626
|
||||
RIuAvOwSOeU25VVTOzOm35wabuLAThMYBqdYl9epAoGAYsWKgZlM9BOnY1wgKfvT
|
||||
w7Vc7W10G78psYRabsQBfZ3IlSKc6aA8EO+daoOOM0gixvHGh6rtuvPdNmCM270c
|
||||
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-----
|
||||
|
||||
@@ -361,10 +361,8 @@ final class TestRSASigning: XCTestCase {
|
||||
try XCTAssertThrowsError((_RSA.Signing.PrivateKey(keySize: .init(bitCount: 1024)), 1024))
|
||||
}
|
||||
|
||||
// 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 = """
|
||||
func testRejectSmallKeys() throws {
|
||||
let smallRSAPrivateKeyPEM = """
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIBPAIBAAJBAOJMTCxw5nMxXCQgsOIRVCu8z1t58s5r2qSqwpZQvQZLlVrhYTpE
|
||||
nHFD6QbX8lHkk1Z3HZ1vjxW89ARPh94cG+0CAwEAAQJBAMdmOVyTYswvuyPuVk3s
|
||||
@@ -376,14 +374,14 @@ final class TestRSASigning: XCTestCase {
|
||||
-----END RSA PRIVATE KEY-----
|
||||
"""
|
||||
|
||||
let _512BitRSAPublicKeyPEM = """
|
||||
let smallRSAPublicKeyPEM = """
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOJMTCxw5nMxXCQgsOIRVCu8z1t58s5r
|
||||
2qSqwpZQvQZLlVrhYTpEnHFD6QbX8lHkk1Z3HZ1vjxW89ARPh94cG+0CAwEAAQ==
|
||||
-----END PUBLIC KEY-----
|
||||
"""
|
||||
|
||||
let _512BitRSAPrivateKeyPKCS8PEM = """
|
||||
let smallRSAPrivateKeyPKCS8PEM = """
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA4kxMLHDmczFcJCCw
|
||||
4hFUK7zPW3nyzmvapKrCllC9BkuVWuFhOkSccUPpBtfyUeSTVncdnW+PFbz0BE+H
|
||||
@@ -396,7 +394,7 @@ final class TestRSASigning: XCTestCase {
|
||||
-----END PRIVATE KEY-----
|
||||
"""
|
||||
|
||||
let _512BitRSAPrivateKeyDER = Data(base64Encoded:
|
||||
let smallRSAPrivateKeyDER = Data(base64Encoded:
|
||||
"MIIBPAIBAAJBAOJMTCxw5nMxXCQgsOIRVCu8z1t58s5r2qSqwpZQvQZLlVr" +
|
||||
"hYTpEnHFD6QbX8lHkk1Z3HZ1vjxW89ARPh94cG+0CAwEAAQJBAMdmOVyTYs" +
|
||||
"wvuyPuVk3svQEJDqFpFATFTlP4TxuKKvTmbdQuVCorMmLLKThDI3pDNWKuA" +
|
||||
@@ -407,7 +405,7 @@ final class TestRSASigning: XCTestCase {
|
||||
"7MWbrFpUouirbQ="
|
||||
)!
|
||||
|
||||
let _512BitRSAPrivateKeyPKCS8DER = Data(base64Encoded:
|
||||
let smallRSAPrivateKeyPKCS8DER = Data(base64Encoded:
|
||||
"MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA4kxMLHDmczF" +
|
||||
"cJCCw4hFUK7zPW3nyzmvapKrCllC9BkuVWuFhOkSccUPpBtfyUeSTVncdnW" +
|
||||
"+PFbz0BE+H3hwb7QIDAQABAkEAx2Y5XJNizC+7I+5WTey9AQkOoWkUBMVOU" +
|
||||
@@ -418,282 +416,18 @@ final class TestRSASigning: XCTestCase {
|
||||
"w8CIQCNHhOCOnp3lmwZQr0gcaw1Y/XJKtqDsxZusWlSi6KttA=="
|
||||
)!
|
||||
|
||||
let _512BitRSAPublicKeyDER = Data(base64Encoded:
|
||||
let smallRSAPublicKeyDER = Data(base64Encoded:
|
||||
"MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOJMTCxw5nMxXCQgsOIRVCu8z1t" +
|
||||
"58s5r2qSqwpZQvQZLlVrhYTpEnHFD6QbX8lHkk1Z3HZ1vjxW89ARPh94cG+" +
|
||||
"0CAwEAAQ=="
|
||||
)!
|
||||
|
||||
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/dtxXYLFyozm0Az98A37nGGTSt9tphKsTPiHS1jOB3f9DbwKBgGomcW7T
|
||||
Slq0+VSGniD+ciB71UMrW9FcF9qsnTPXQGZV4JqpLvE/tEq7uyr/Dp6l3mstVmtL
|
||||
tBjkPef32oz3JXo32IWS37VZlu+3I2v7VQThFLnc3F0KUcZmH1Uy1my8itjP6jIf
|
||||
wNwiUObilCubgiGEVxfMb0G7juMETZYyuRLfAoGAVwIFcRfvZ4rrBagc5yOyg6Le
|
||||
cgtVqSbVvl1Xwts7lslw6ABZyo2fTHPeLKxHafFjpHIEqkPCDtPNdlcOKpP1jP+R
|
||||
ZYPsL8VslpCpqWKyogH07uReParfzwUqbX1FJH7lxd9cDqseZXr01vSFeVS0pX/m
|
||||
B/IDkF+DA08GU4/2uGcCgYAV1CP9e1vN/WtMc4ZvGIQVpAF+F5uBGSQapuaI85nd
|
||||
sYlHpMTvfX8w4xwhQmQaQdfUSHV+CQpXGBCW9EQwOt6tHHDdPw/b9jlwwEN7gCrC
|
||||
nxqpAf8a7vVUDEojNhocMEWJQnBRsG/zlOb4I93+fbMr+1ABp9u1M8G1c3wVCAdB
|
||||
FwKBgF8sJlG58EKSfdvhVNDRq4hC/yjcI6987rg2fmeX9QUYiwReniaesEoBdeHz
|
||||
OYWR3DtC5SNiDKuj7QmnRvNcbFwBz5dGOdiXytRtLkpwDArY/hV/hqeSH1nHU0fp
|
||||
LUScnTZr95HkLFIle1JCFXw0viGHKEBkdFvcuXIFON9KNTA/
|
||||
-----END RSA PRIVATE KEY-----
|
||||
"""
|
||||
|
||||
let _2047BitRSAPublicKeyPEM = """
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBXog86uwpuCobeXXokHAeP
|
||||
Mu15O2Cwfvwx7/EzZl6jY70ConNXmzR5U39kQQpFa0dxRQdgUA8YpU5/8aILp3Yv
|
||||
0S2BssiuqdL5IkzdBzLNRhSQabuM+vyCQjImHF/bA28+5DKJ9uzIhywA9JS2o/4T
|
||||
tE6mLqWbFAY+dM716llarKJgzLh/Vg0mH6H5vDoo4D6z+M2jQRiUbV+yIiiaY8/S
|
||||
MyLltsZeEl/hx/NyACPSUAClVlsjvRRZzQl8oDybMVvUAbrIwR+ZVQltdqVgx5zV
|
||||
f8G3BHi7lUdyqxIt0QWQRBTTd1tYsSOKmVhYB+DvPv2IJKGXqKo+XKQBLmm9UIux
|
||||
AgMBAAE=
|
||||
-----END PUBLIC KEY-----
|
||||
"""
|
||||
|
||||
let _2047BitRSAPrivateKeyPKCS8PEM = """
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAFeiDzq7Cm4Kht5d
|
||||
eiQcB48y7Xk7YLB+/DHv8TNmXqNjvQKic1ebNHlTf2RBCkVrR3FFB2BQDxilTn/x
|
||||
ogundi/RLYGyyK6p0vkiTN0HMs1GFJBpu4z6/IJCMiYcX9sDbz7kMon27MiHLAD0
|
||||
lLaj/hO0TqYupZsUBj50zvXqWVqsomDMuH9WDSYfofm8OijgPrP4zaNBGJRtX7Ii
|
||||
KJpjz9IzIuW2xl4SX+HH83IAI9JQAKVWWyO9FFnNCXygPJsxW9QBusjBH5lVCW12
|
||||
pWDHnNV/wbcEeLuVR3KrEi3RBZBEFNN3W1ixI4qZWFgH4O8+/YgkoZeoqj5cpAEu
|
||||
ab1Qi7ECAwEAAQKCAQA3/qFkkac0cR2EcI5fDFn4Mj5zPHGn1TwoXHzurvbByDU5
|
||||
vbudutpou+WmlbiOauIXilgQPpem09m4/xjgAX0PSMWfHjIFCRZ5gmVCxhq794+k
|
||||
RytEBgva35lTqMXHGAa5VO7GITVjXJvNcHqlyVvME2Y94YiH8t+agODNWZUGzoWE
|
||||
GuXzP55ZyIhKCyRNoRKRuiJX4cDMMEnbeA8sPR+OTr0PDvkxLtAcFibmMMilcW+H
|
||||
6c8k5/AgC5oRD1loXdSHzOME7KG05I71x1XBcwTiwi8DsiqUahpzFS2PKhZqs+qT
|
||||
9XhRaXv9DyBmVFqCqNon4OqmqsPpQULHC/AoLInRAoGBANNXuOgEe67D9G4N7xXD
|
||||
FS5ElMhx2ufqDYqfcLFX1gsmHGvV2gSbDdgMBJjvN12SAmOyxuS5vkWHJICWo4jP
|
||||
miTrZ6scyzIL3RVepYMLW4UdboRCH839L8C+AS7Ign923FdgsXKjObQDP3wDfucY
|
||||
ZNK322mEqxM+IdLWM4Hd/0NvAoGAaiZxbtNKWrT5VIaeIP5yIHvVQytb0VwX2qyd
|
||||
M9dAZlXgmqku8T+0Sru7Kv8OnqXeay1Wa0u0GOQ95/fajPclejfYhZLftVmW77cj
|
||||
a/tVBOEUudzcXQpRxmYfVTLWbLyK2M/qMh/A3CJQ5uKUK5uCIYRXF8xvQbuO4wRN
|
||||
ljK5Et8CgYBXAgVxF+9niusFqBznI7KDot5yC1WpJtW+XVfC2zuWyXDoAFnKjZ9M
|
||||
c94srEdp8WOkcgSqQ8IO0812Vw4qk/WM/5Flg+wvxWyWkKmpYrKiAfTu5F49qt/P
|
||||
BSptfUUkfuXF31wOqx5levTW9IV5VLSlf+YH8gOQX4MDTwZTj/a4ZwKBgBXUI/17
|
||||
W839a0xzhm8YhBWkAX4Xm4EZJBqm5ojzmd2xiUekxO99fzDjHCFCZBpB19RIdX4J
|
||||
ClcYEJb0RDA63q0ccN0/D9v2OXDAQ3uAKsKfGqkB/xru9VQMSiM2GhwwRYlCcFGw
|
||||
b/OU5vgj3f59syv7UAGn27UzwbVzfBUIB0EXAoGAXywmUbnwQpJ92+FU0NGriEL/
|
||||
KNwjr3zuuDZ+Z5f1BRiLBF6eJp6wSgF14fM5hZHcO0LlI2IMq6PtCadG81xsXAHP
|
||||
l0Y52JfK1G0uSnAMCtj+FX+Gp5IfWcdTR+ktRJydNmv3keQsUiV7UkIVfDS+IYco
|
||||
QGR0W9y5cgU430o1MD8=
|
||||
-----END PRIVATE KEY-----
|
||||
"""
|
||||
|
||||
let _2047BitRSAPrivateKeyDER = Data(base64Encoded:
|
||||
"MIIEoAIBAAKCAQBXog86uwpuCobeXXokHAePMu15O2Cwfvwx7/EzZl6jY70" +
|
||||
"ConNXmzR5U39kQQpFa0dxRQdgUA8YpU5/8aILp3Yv0S2BssiuqdL5IkzdBz" +
|
||||
"LNRhSQabuM+vyCQjImHF/bA28+5DKJ9uzIhywA9JS2o/4TtE6mLqWbFAY+d" +
|
||||
"M716llarKJgzLh/Vg0mH6H5vDoo4D6z+M2jQRiUbV+yIiiaY8/SMyLltsZe" +
|
||||
"El/hx/NyACPSUAClVlsjvRRZzQl8oDybMVvUAbrIwR+ZVQltdqVgx5zVf8G" +
|
||||
"3BHi7lUdyqxIt0QWQRBTTd1tYsSOKmVhYB+DvPv2IJKGXqKo+XKQBLmm9UI" +
|
||||
"uxAgMBAAECggEAN/6hZJGnNHEdhHCOXwxZ+DI+czxxp9U8KFx87q72wcg1O" +
|
||||
"b27nbraaLvlppW4jmriF4pYED6XptPZuP8Y4AF9D0jFnx4yBQkWeYJlQsYa" +
|
||||
"u/ePpEcrRAYL2t+ZU6jFxxgGuVTuxiE1Y1ybzXB6pclbzBNmPeGIh/LfmoD" +
|
||||
"gzVmVBs6FhBrl8z+eWciISgskTaESkboiV+HAzDBJ23gPLD0fjk69Dw75MS" +
|
||||
"7QHBYm5jDIpXFvh+nPJOfwIAuaEQ9ZaF3Uh8zjBOyhtOSO9cdVwXME4sIvA" +
|
||||
"7IqlGoacxUtjyoWarPqk/V4UWl7/Q8gZlRagqjaJ+DqpqrD6UFCxwvwKCyJ" +
|
||||
"0QKBgQDTV7joBHuuw/RuDe8VwxUuRJTIcdrn6g2Kn3CxV9YLJhxr1doEmw3" +
|
||||
"YDASY7zddkgJjssbkub5FhySAlqOIz5ok62erHMsyC90VXqWDC1uFHW6EQh" +
|
||||
"/N/S/AvgEuyIJ/dtxXYLFyozm0Az98A37nGGTSt9tphKsTPiHS1jOB3f9Db" +
|
||||
"wKBgGomcW7TSlq0+VSGniD+ciB71UMrW9FcF9qsnTPXQGZV4JqpLvE/tEq7" +
|
||||
"uyr/Dp6l3mstVmtLtBjkPef32oz3JXo32IWS37VZlu+3I2v7VQThFLnc3F0" +
|
||||
"KUcZmH1Uy1my8itjP6jIfwNwiUObilCubgiGEVxfMb0G7juMETZYyuRLfAo" +
|
||||
"GAVwIFcRfvZ4rrBagc5yOyg6LecgtVqSbVvl1Xwts7lslw6ABZyo2fTHPeL" +
|
||||
"KxHafFjpHIEqkPCDtPNdlcOKpP1jP+RZYPsL8VslpCpqWKyogH07uReParf" +
|
||||
"zwUqbX1FJH7lxd9cDqseZXr01vSFeVS0pX/mB/IDkF+DA08GU4/2uGcCgYA" +
|
||||
"V1CP9e1vN/WtMc4ZvGIQVpAF+F5uBGSQapuaI85ndsYlHpMTvfX8w4xwhQm" +
|
||||
"QaQdfUSHV+CQpXGBCW9EQwOt6tHHDdPw/b9jlwwEN7gCrCnxqpAf8a7vVUD" +
|
||||
"EojNhocMEWJQnBRsG/zlOb4I93+fbMr+1ABp9u1M8G1c3wVCAdBFwKBgF8s" +
|
||||
"JlG58EKSfdvhVNDRq4hC/yjcI6987rg2fmeX9QUYiwReniaesEoBdeHzOYW" +
|
||||
"R3DtC5SNiDKuj7QmnRvNcbFwBz5dGOdiXytRtLkpwDArY/hV/hqeSH1nHU0" +
|
||||
"fpLUScnTZr95HkLFIle1JCFXw0viGHKEBkdFvcuXIFON9KNTA/"
|
||||
)!
|
||||
|
||||
let _2047BitRSAPrivateKeyPKCS8DER = Data(base64Encoded:
|
||||
"MIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAFeiDzq7Cm4" +
|
||||
"Kht5deiQcB48y7Xk7YLB+/DHv8TNmXqNjvQKic1ebNHlTf2RBCkVrR3FFB2" +
|
||||
"BQDxilTn/xogundi/RLYGyyK6p0vkiTN0HMs1GFJBpu4z6/IJCMiYcX9sDb" +
|
||||
"z7kMon27MiHLAD0lLaj/hO0TqYupZsUBj50zvXqWVqsomDMuH9WDSYfofm8" +
|
||||
"OijgPrP4zaNBGJRtX7IiKJpjz9IzIuW2xl4SX+HH83IAI9JQAKVWWyO9FFn" +
|
||||
"NCXygPJsxW9QBusjBH5lVCW12pWDHnNV/wbcEeLuVR3KrEi3RBZBEFNN3W1" +
|
||||
"ixI4qZWFgH4O8+/YgkoZeoqj5cpAEuab1Qi7ECAwEAAQKCAQA3/qFkkac0c" +
|
||||
"R2EcI5fDFn4Mj5zPHGn1TwoXHzurvbByDU5vbudutpou+WmlbiOauIXilgQ" +
|
||||
"Ppem09m4/xjgAX0PSMWfHjIFCRZ5gmVCxhq794+kRytEBgva35lTqMXHGAa" +
|
||||
"5VO7GITVjXJvNcHqlyVvME2Y94YiH8t+agODNWZUGzoWEGuXzP55ZyIhKCy" +
|
||||
"RNoRKRuiJX4cDMMEnbeA8sPR+OTr0PDvkxLtAcFibmMMilcW+H6c8k5/AgC" +
|
||||
"5oRD1loXdSHzOME7KG05I71x1XBcwTiwi8DsiqUahpzFS2PKhZqs+qT9XhR" +
|
||||
"aXv9DyBmVFqCqNon4OqmqsPpQULHC/AoLInRAoGBANNXuOgEe67D9G4N7xX" +
|
||||
"DFS5ElMhx2ufqDYqfcLFX1gsmHGvV2gSbDdgMBJjvN12SAmOyxuS5vkWHJI" +
|
||||
"CWo4jPmiTrZ6scyzIL3RVepYMLW4UdboRCH839L8C+AS7Ign923FdgsXKjO" +
|
||||
"bQDP3wDfucYZNK322mEqxM+IdLWM4Hd/0NvAoGAaiZxbtNKWrT5VIaeIP5y" +
|
||||
"IHvVQytb0VwX2qydM9dAZlXgmqku8T+0Sru7Kv8OnqXeay1Wa0u0GOQ95/f" +
|
||||
"ajPclejfYhZLftVmW77cja/tVBOEUudzcXQpRxmYfVTLWbLyK2M/qMh/A3C" +
|
||||
"JQ5uKUK5uCIYRXF8xvQbuO4wRNljK5Et8CgYBXAgVxF+9niusFqBznI7KDo" +
|
||||
"t5yC1WpJtW+XVfC2zuWyXDoAFnKjZ9Mc94srEdp8WOkcgSqQ8IO0812Vw4q" +
|
||||
"k/WM/5Flg+wvxWyWkKmpYrKiAfTu5F49qt/PBSptfUUkfuXF31wOqx5levT" +
|
||||
"W9IV5VLSlf+YH8gOQX4MDTwZTj/a4ZwKBgBXUI/17W839a0xzhm8YhBWkAX" +
|
||||
"4Xm4EZJBqm5ojzmd2xiUekxO99fzDjHCFCZBpB19RIdX4JClcYEJb0RDA63" +
|
||||
"q0ccN0/D9v2OXDAQ3uAKsKfGqkB/xru9VQMSiM2GhwwRYlCcFGwb/OU5vgj" +
|
||||
"3f59syv7UAGn27UzwbVzfBUIB0EXAoGAXywmUbnwQpJ92+FU0NGriEL/KNw" +
|
||||
"jr3zuuDZ+Z5f1BRiLBF6eJp6wSgF14fM5hZHcO0LlI2IMq6PtCadG81xsXA" +
|
||||
"HPl0Y52JfK1G0uSnAMCtj+FX+Gp5IfWcdTR+ktRJydNmv3keQsUiV7UkIVf" +
|
||||
"DS+IYcoQGR0W9y5cgU430o1MD8="
|
||||
)!
|
||||
|
||||
let _2047BitRSAPublicKeyDER = Data(base64Encoded:
|
||||
"MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBXog86uwpuCobeXXo" +
|
||||
"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
|
||||
ISTDJsR6prKpRq+KEUcu7dKz9e5TFWiyLnOWfPFu1rXuTxZclhdrs5kLiOJzFB6v
|
||||
nGtmv06nWT33OUlRsy3OeX4GJJEqgA6OaxCYs9Tl6vWEXUycdQmxLVKChNtHQIs8
|
||||
U2HhqLta05jpta/+T0HTfE095FUCAwEAAQKBgACG8dxhZkvQMQukpKg90M8tXk9K
|
||||
UTt8SMkPft1yy+1cEhpdpGxHJtxn+PETaqp28coemGqn++19lgX3Ioxl33FyzFx4
|
||||
ZNFZH2TFB0p7qv3LWDMXWmJEDJThRzKPMVyHjDimxfcCqo3iqlAmBhRlqZJGeegn
|
||||
dWru7+hHdbQ/48vdAkAZOcO3pQAdqGZ2vKMowXJBqf4ZT96jooMPzhuWTUvxrGwQ
|
||||
e0pS+1UE5Y9FpHZYkj6rbpp1ltW+nvTtutbyxr73AkANhONk7DkDYL6ZeVsHBXvx
|
||||
wutfCxn/7nOuUYfl0y4Nhu4kfcidcr9KC4t/86pCau1TBKYvlB9D/9A9tSmyKggT
|
||||
AkAGDWHz8daxRvIuktvir2cmcg7RK+STBi7D4AOmcC1EcsYKvkn61upzHlDduLPc
|
||||
VFpM72CHzgTCk4jYcPeZkC3JAkAGTexFCivkOV9o7sDWW2ZbbcyZe/HZ+fcUWY0I
|
||||
ThzxzfSMK+Q8GGDARPX+60CAzKBz0H03Ptn9ufQActVI8nTlAkAUmoVot3qP2/9Y
|
||||
ruegmTR/uVZNmd95GRk/EmHgCht+cYpXXI76YHqYsmj9K04GszzYh0IFdMdFhhLb
|
||||
NQIKgkbV
|
||||
-----END PRIVATE KEY-----
|
||||
"""
|
||||
|
||||
let _1017BitRSAPrivateKeyDER = Data(base64Encoded:
|
||||
"MIICWAIBAAKBgAFVByFodT87fB0oWSEkwybEeqayqUavihFHLu3Ss/XuUxV" +
|
||||
"osi5zlnzxbta17k8WXJYXa7OZC4jicxQer5xrZr9Op1k99zlJUbMtznl+Bi" +
|
||||
"SRKoAOjmsQmLPU5er1hF1MnHUJsS1SgoTbR0CLPFNh4ai7WtOY6bWv/k9B0" +
|
||||
"3xNPeRVAgMBAAECgYAAhvHcYWZL0DELpKSoPdDPLV5PSlE7fEjJD37dcsvt" +
|
||||
"XBIaXaRsRybcZ/jxE2qqdvHKHphqp/vtfZYF9yKMZd9xcsxceGTRWR9kxQd" +
|
||||
"Ke6r9y1gzF1piRAyU4UcyjzFch4w4psX3AqqN4qpQJgYUZamSRnnoJ3Vq7u" +
|
||||
"/oR3W0P+PL3QJAGTnDt6UAHahmdryjKMFyQan+GU/eo6KDD84blk1L8axsE" +
|
||||
"HtKUvtVBOWPRaR2WJI+q26adZbVvp707brW8sa+9wJADYTjZOw5A2C+mXlb" +
|
||||
"BwV78cLrXwsZ/+5zrlGH5dMuDYbuJH3InXK/SguLf/OqQmrtUwSmL5QfQ//" +
|
||||
"QPbUpsioIEwJABg1h8/HWsUbyLpLb4q9nJnIO0SvkkwYuw+ADpnAtRHLGCr" +
|
||||
"5J+tbqcx5Q3biz3FRaTO9gh84EwpOI2HD3mZAtyQJABk3sRQor5DlfaO7A1" +
|
||||
"ltmW23MmXvx2fn3FFmNCE4c8c30jCvkPBhgwET1/utAgMygc9B9Nz7Z/bn0" +
|
||||
"AHLVSPJ05QJAFJqFaLd6j9v/WK7noJk0f7lWTZnfeRkZPxJh4AobfnGKV1y" +
|
||||
"O+mB6mLJo/StOBrM82IdCBXTHRYYS2zUCCoJG1Q=="
|
||||
)!
|
||||
|
||||
let _1017BitRSAPrivateKeyPKCS8DER = Data(base64Encoded:
|
||||
"MIICcgIBADANBgkqhkiG9w0BAQEFAASCAlwwggJYAgEAAoGAAVUHIWh1Pzt" +
|
||||
"8HShZISTDJsR6prKpRq+KEUcu7dKz9e5TFWiyLnOWfPFu1rXuTxZclhdrs5" +
|
||||
"kLiOJzFB6vnGtmv06nWT33OUlRsy3OeX4GJJEqgA6OaxCYs9Tl6vWEXUycd" +
|
||||
"QmxLVKChNtHQIs8U2HhqLta05jpta/+T0HTfE095FUCAwEAAQKBgACG8dxh" +
|
||||
"ZkvQMQukpKg90M8tXk9KUTt8SMkPft1yy+1cEhpdpGxHJtxn+PETaqp28co" +
|
||||
"emGqn++19lgX3Ioxl33FyzFx4ZNFZH2TFB0p7qv3LWDMXWmJEDJThRzKPMV" +
|
||||
"yHjDimxfcCqo3iqlAmBhRlqZJGeegndWru7+hHdbQ/48vdAkAZOcO3pQAdq" +
|
||||
"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)
|
||||
)
|
||||
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))
|
||||
}
|
||||
|
||||
func testHandlingNonStandardKeys() throws {
|
||||
@@ -841,12 +575,12 @@ final class TestRSASigning: XCTestCase {
|
||||
"En7fZhCeZeNBjNTuKXj3JqdP3wIDAQAB"
|
||||
)!
|
||||
|
||||
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)
|
||||
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)
|
||||
}
|
||||
|
||||
func testMangledPKCS8DERKey() throws {
|
||||
@@ -1036,13 +770,6 @@ 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 {
|
||||
@@ -1062,70 +789,6 @@ final class TestRSASigning: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testConstructKeyFromRSANumbersWithDegenerateExponentsThrows() throws {
|
||||
// e * d == 1 makes g^(e * d - 1) == 1 for every base, so prime recovery can never
|
||||
// make progress. This must throw rather than retry forever.
|
||||
var n = [UInt8](repeating: 0xA7, count: 256)
|
||||
n[255] = 0x01
|
||||
|
||||
XCTAssertThrowsError(
|
||||
try _RSA.Signing.PrivateKey._createFromNumbers(n: n, e: [1] as [UInt8], d: [1] as [UInt8])
|
||||
)
|
||||
XCTAssertThrowsError(
|
||||
try _RSA.Encryption.PrivateKey._createFromNumbers(n: n, e: [1] as [UInt8], d: [1] as [UInt8])
|
||||
)
|
||||
XCTAssertThrowsError(
|
||||
try _RSA.BlindSigning.PrivateKey<SHA384>._createFromNumbers(
|
||||
n: n, e: [1] as [UInt8], d: [1] as [UInt8], parameters: .RSABSSA_SHA384_PSS_Randomized
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
func testExtractPrimeFactorsGivesUpWhenEveryBaseIsTrivial() throws {
|
||||
// n = 7 is prime and e * d - 1 == 24 == 2^3 * 3, so g^3 is 1 or n - 1 for every base g
|
||||
// (the only cubic residues mod 7). The attempt limit must still apply.
|
||||
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 7, e: 5, d: 5))
|
||||
|
||||
// e * d == 1 gives an exponent of 0, so g^0 == 1 for every base.
|
||||
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 3233, e: 1, d: 1))
|
||||
}
|
||||
|
||||
func testExtractPrimeFactorsRejectsOversizedNumbers() throws {
|
||||
// d == 2753 is valid for n == 3233, e == 17. Adding lambda(n) == 780 keeps the numbers
|
||||
// consistent, so only the range check rejects d >= n.
|
||||
XCTAssertNoThrow(try _RSA.extractPrimeFactors(n: 3233, e: 17, d: 2753))
|
||||
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 3233, e: 17, d: 2753 + 780))
|
||||
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 3233, e: 17 + 780 * 5, d: 2753))
|
||||
|
||||
// e * d - 1 == 2^9992, so without the range check the squaring loop runs 9991 times
|
||||
// per attempt.
|
||||
var n = [UInt8](repeating: 0xA7, count: 256)
|
||||
n[255] = 0x01
|
||||
var d = [UInt8](repeating: 0, count: 1250)
|
||||
d[0] = 0x01
|
||||
d[1249] = 0x01
|
||||
XCTAssertThrowsError(try _RSA.Signing.PrivateKey._createFromNumbers(n: n, e: [1] as [UInt8], d: d))
|
||||
|
||||
// A modulus over 8192 bits with d < n would otherwise make each attempt arbitrarily slow.
|
||||
var bigN = [UInt8](repeating: 0xA7, count: 1025)
|
||||
bigN[1024] = 0x01
|
||||
var bigD = [UInt8](repeating: 0, count: 1025)
|
||||
bigD[1] = 0x01
|
||||
bigD[1024] = 0x01
|
||||
XCTAssertThrowsError(try _RSA.Signing.PrivateKey._createFromNumbers(n: bigN, e: [1] as [UInt8], d: bigD))
|
||||
}
|
||||
|
||||
func testExtractPrimeFactorsRejectsInconsistentNumbers() throws {
|
||||
for testVector in RFC9474TestVector.allValues {
|
||||
let n = try ArbitraryPrecisionInteger(bytes: Data(hexString: testVector.n))
|
||||
let e = try ArbitraryPrecisionInteger(bytes: Data(hexString: testVector.e))
|
||||
let d = try ArbitraryPrecisionInteger(bytes: Data(hexString: testVector.d))
|
||||
|
||||
// Using d = d + 2 means d is still even but no longer a multiple of lambda(n).
|
||||
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: n, e: e, d: d + 2))
|
||||
}
|
||||
}
|
||||
|
||||
func testGetKeyPrimitives() throws {
|
||||
for testVector in RFC9474TestVector.allValues {
|
||||
let n = try Data(hexString: testVector.n)
|
||||
@@ -1247,23 +910,6 @@ final class TestRSASigning: XCTestCase {
|
||||
|
||||
return pemLines.joined(separator: "\n")
|
||||
}
|
||||
|
||||
func test_invalidDERPublicKeyThrowsWithoutDoubleFree() throws {
|
||||
// SEQUENCE { INTEGER 0, INTEGER 0 }
|
||||
let badBase64 = "MAYCAQACAQ=="
|
||||
let badDER = Array(Data(base64Encoded: badBase64)!)
|
||||
XCTAssertThrowsError(try BoringSSLRSAPublicKey(derRepresentation: badDER))
|
||||
}
|
||||
|
||||
func test_invalidPEMPublicKeyThrowsWithoutDoubleFree() throws {
|
||||
// SEQUENCE { INTEGER 0, INTEGER 0 }
|
||||
let badPEM = """
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MAYCAQACAQ==
|
||||
-----END PUBLIC KEY-----
|
||||
"""
|
||||
XCTAssertThrowsError(try BoringSSLRSAPublicKey(pemRepresentation: badPEM))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
import XCTest
|
||||
|
||||
#if canImport(CryptoKit)
|
||||
// Skip tests that require @testable imports of CryptoKit.
|
||||
#else
|
||||
@testable import Crypto
|
||||
|
||||
extension ECKeyEncodingsTests {
|
||||
func testCompactRepresentabilityIsDecidedByTheFieldPrime() throws {
|
||||
// y = n + 1, the larger of the two square roots, so not compact representable.
|
||||
let aboveMidpointX = try Data(hexString: "d1db3668128866847e66864aa97c37a04f65f6ff201a7d02345dffd738908975")
|
||||
let aboveMidpointY = try Data(hexString: "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632552")
|
||||
let aboveMidpoint = try P256.Signing.PublicKey(rawRepresentation: aboveMidpointX + aboveMidpointY)
|
||||
XCTAssertNil(aboveMidpoint.compactRepresentation)
|
||||
|
||||
// n/2 < y <= (p-1)/2, the smaller of the two square roots, so compact representable.
|
||||
let belowMidpointX = try Data(hexString: "ce2afeafa686293c6c93f644b3f6d796c659a9277ca4af6c15ef3bfdc6e00f89")
|
||||
let belowMidpointY = try Data(hexString: "7fffffff800000007fffffffffffffffde737d56d38bcf4279dce5617e3192aa")
|
||||
let belowMidpoint = try P256.Signing.PublicKey(rawRepresentation: belowMidpointX + belowMidpointY)
|
||||
XCTAssertEqual(belowMidpoint.compactRepresentation, belowMidpointX)
|
||||
}
|
||||
}
|
||||
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -93,37 +93,6 @@ final class XWingTests: XCTestCase {
|
||||
let importedKey = try XWingMLKEM768X25519.PrivateKey.init(integrityCheckedRepresentation: exportedFormat)
|
||||
XCTAssertEqual(importedKey.seedRepresentation, privateKey.seedRepresentation)
|
||||
}
|
||||
|
||||
func testDecapsulateInputValidation() throws {
|
||||
let ciphersuite = HPKE.Ciphersuite.XWingMLKEM768X25519_SHA256_AES_GCM_256
|
||||
let skR = try XWingMLKEM768X25519.PrivateKey.generate()
|
||||
|
||||
// Dummy key with the correct size fails with an error from the underlying implementation.
|
||||
let corretlySizedKey = Data(repeating: 0x00, count: 1120)
|
||||
XCTAssertThrowsError(
|
||||
try HPKE.Recipient(
|
||||
privateKey: skR,
|
||||
ciphersuite: ciphersuite,
|
||||
info: Data(),
|
||||
encapsulatedKey: corretlySizedKey
|
||||
)
|
||||
)
|
||||
|
||||
// Keys with the wrong size fail input validation.
|
||||
let keySizesToTest = [0, 1, 1119, 1221, 2000]
|
||||
for keySize in keySizesToTest {
|
||||
let wronglySizedKey = Data(repeating: 0x00, count: keySize)
|
||||
XCTAssertThrowsError(
|
||||
try HPKE.Recipient(
|
||||
privateKey: skR,
|
||||
ciphersuite: ciphersuite,
|
||||
info: Data(),
|
||||
encapsulatedKey: wronglySizedKey
|
||||
),
|
||||
"Unexpectedly returned from malformed decapsulation path for keySize \(keySize)"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Struct to parse KAT file
|
||||
|
||||
Reference in new issue
Block a user