Compare commits

...
10 Commits
Author SHA1 Message Date
Rick Newton-Rogers a98e4be0dd Only apply standard swift settings on valid targets (#333)
Only apply standard swift settings on valid targets. The current check
ignores plugins but that is not comprehensive enough.
2025-03-07 15:05:19 +00:00
Gus CairoandCory Benfield f4c4efd424 Replace platforms from Package manifest with availability guards (#331)
Minimum deployment versions in package manifests can be problematic for
libraries, because changing them or adding them to an existing package
that doesn't already use them forces SemVer breaking majors.

Furthermore, depending on a new library that specifies minimum
deployment targets would force the adopting library to also have to add
these platforms to its manifest (which would in turn force a major).

This PR removes the platforms stanza from the package manifest and
replaces them with availability guards.
This will allow more packages to use swift-crypto, without forcing them
to mint new majors to support the appropriate platforms.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-03-04 15:15:32 +00:00
Rick Newton-Rogers 7ba43666c5 Rename nightly_6_1 params to nightly_next (#332)
Rename nightly_6_1 params to nightly_next; see
https://github.com/apple/swift-nio/pull/3122
2025-03-03 14:49:11 +00:00
Cory Benfield 45305d32cf Add missing availability on ARC types (#330)
Motivation

We should have proper availability annotations.

Modifications

Propagate the availability annotations we need.

Result

Compiles correctly on non-macOS platforms.
2025-02-17 18:37:06 +00:00
Chris McGee b6049c0b2e Fix CMakeLists.txt for Windows (#326)
This change prepares swift-crypto for use on Windows with CMake and also
the Package.swift for use in the Swift toolchain CI system.

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

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

### Motivation:

Upgrading swift-crypto from an older version requires that Windows works
properly with CMake, and also SwiftPM.

### Modifications:

Modify the CMakeLists.txt files and the generator script so that it
conditionally adds assembly files for non-Windows platforms. Prepare the
Package.swift file for use in Swift CI pipelines, by consulting an
environment to either use the absolute URL, or a prepared version of the
swift-asn1 dependency.

### Result:

After this change it should be possible to build with the newest
swift-crypto in the Swift CI system.
2025-02-14 13:37:49 +00:00
Si Beaumont b81059d507 extras: Add API for Anonymous Rate-Limited Credentials, ARC(P-384) (#328)
## Motivation

We would like to provide support for ARCV1(P-384), as defined in [IETF
Internet Draft: Anonymous Rate-Limited
Credentials](https://datatracker.ietf.org/doc/draft-yun-cfrg-arc/).

## Modifications

- Add internal implementation, generic over the NIST curves.
- Add public API for ARC(P-384), under `P384._ARCV1`.

## Result

New API for current draft of ARC.

## Tests

- End to end tests of internal implementation and API surface.
- Test vector tests of internal implementation and API surface, from the
spec draft.
2025-02-14 10:49:59 +00:00
Chris McGee 06fc9b0a09 Add workaround for missing multi-threaded dll support on windows clang/ASM (#325)
When building using CMake with Windows, there is an error regarding
missing MultithreadedDLL support. Work around this by setting the
MSVC_RUNTIME_LIBRARY on that platform to a supported option.

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

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

### Motivation:

I'm trying to build swift-crypto on Windows with CMake.

### Modifications:

I've modified the CMakelists.txt such that the clang can compile the
assembly files on Windows.

### Result:

Hopefully, Windows builds of swift-crypto are working.
2025-02-11 13:39:38 +00:00
Chris McGee 472de789e9 Fix macos build failures cmake (#324)
Remove the extra true values for the swift defines in the CryptoExtras
modules CMakeLists.txt file.

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

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

### Motivation:

The defines don't take effect with a value. Remove the value "true" from
them.

### Modifications:

Modified the CMakeLists.txt file in the CryptoExtras module.

### Result:

After the change the swift defines will hopefully be defined correctly.
2025-02-11 12:21:43 +00:00
Chris McGee 75a3eca905 Add the necessary swift defines in CMake for Crypto module (#323)
### Checklist
- [X] I've run tests to see all new and existing tests pass
- [X] I've followed the code style of the rest of the project
- [X] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [X] I've updated the documentation if necessary

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

### Motivation:

When building SwiftPM with CMake and the swift-crypto package there are
errors being produced on macOS relating to missing imports provided by
the CryptoKit package.

### Modifications:

Modify the CMakeLists.txt file for the Crypto target so that the defines
are set like they are in the Package.swift.

### Result:

After the change, building SwiftPM with CMake on macOS should work.
2025-02-10 17:10:44 +00:00
Chris McGee b828ba476a Add missing assembly files to CMake and generator script (#322)
Update both the CMakeLists.txt for CCryptoBoringSSL and the
CMakeLists.txt generator so that it can add platform-independent
assembly files.

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

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

### Motivation:

There are downstream linker failures due to missing symbols from certain
platform neutral assembly files.

### Modifications:

The `scripts/update-cmake-lists.sh` has an updated find expression to
discover platform-independent assembly files and includes them in the
`CMakeLists.txt` files.

### Result:

There will be more symbols included from third-parties such as
BoringSSL.
2025-02-10 09:06:08 +00:00
152 changed files with 3432 additions and 26 deletions

No files matched your search

+1 -1
View File
@@ -14,7 +14,7 @@ jobs:
linux_5_9_arguments_override: "--explicit-target-dependency-import-check error"
linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_0_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_6_1_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
cxx-interop:
+3 -3
View File
@@ -26,13 +26,13 @@ jobs:
linux_5_9_arguments_override: "--explicit-target-dependency-import-check error"
linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_0_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_6_1_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
windows_6_0_enabled: true
windows_nightly_6_1_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
windows_6_0_arguments_override: "--explicit-target-dependency-import-check error"
windows_nightly_6_1_arguments_override: "--explicit-target-dependency-import-check error"
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
cxx-interop:
+18
View File
@@ -68,6 +68,18 @@ Sources/_CryptoExtras/AES/AES_CFB.swift
Sources/_CryptoExtras/AES/AES_CTR.swift
Sources/_CryptoExtras/AES/AES_GCM_SIV.swift
Sources/_CryptoExtras/AES/Block Function.swift
Sources/_CryptoExtras/ARC/ARC+API.swift
Sources/_CryptoExtras/ARC/ARC.swift
Sources/_CryptoExtras/ARC/ARCCredential.swift
Sources/_CryptoExtras/ARC/ARCEncoding.swift
Sources/_CryptoExtras/ARC/ARCPrecredential.swift
Sources/_CryptoExtras/ARC/ARCPresentation.swift
Sources/_CryptoExtras/ARC/ARCRequest.swift
Sources/_CryptoExtras/ARC/ARCResponse.swift
Sources/_CryptoExtras/ARC/ARCServer.swift
Sources/_CryptoExtras/ZKPs/Prover.swift
Sources/_CryptoExtras/ZKPs/Verifier.swift
Sources/_CryptoExtras/ZKPs/ZKPToolbox.swift
Sources/_CryptoExtras/ChaCha20CTR/ChaCha20CTR.swift
Sources/_CryptoExtras/ECToolbox/ECToolbox.swift
Sources/_CryptoExtras/H2G/HashToField.swift
@@ -123,6 +135,11 @@ Tests/_CryptoExtrasTests/AES-GCM-SIV-Runner.swift
Tests/_CryptoExtrasTests/AES_CBCTests.swift
Tests/_CryptoExtrasTests/AES_CFBTests.swift
Tests/_CryptoExtrasTests/AES_CTRTests.swift
Tests/_CryptoExtrasTests/ARC/ARCAPITests.swift
Tests/_CryptoExtrasTests/ARC/ARCEncodingTests.swift
Tests/_CryptoExtrasTests/ARC/ARCPublicAPITests.swift
Tests/_CryptoExtrasTests/ARC/ARCTestVectors.swift
Tests/_CryptoExtrasTests/ARC/ARCTests.swift
Tests/_CryptoExtrasTests/ChaCha20CTRTests.swift
Tests/_CryptoExtrasTests/ECToolbox/HashToCurveTests.swift
Tests/_CryptoExtrasTests/OPRFs/ECVOPRFTests.swift
@@ -139,3 +156,4 @@ Tests/_CryptoExtrasTests/Utils/RFCVector.swift
Tests/_CryptoExtrasTests/Utils/SplitData.swift
Tests/_CryptoExtrasTests/Utils/Wycheproof.swift
Tests/_CryptoExtrasTests/Utils/XCTestUtils.swift
Tests/_CryptoExtrasTests/ZKPs/ZKPToolbox.swift
+2 -2
View File
@@ -15,7 +15,7 @@
cmake_minimum_required(VERSION 3.15.1)
project(SwiftCrypto
LANGUAGES ASM C Swift)
LANGUAGES ASM C CXX Swift)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules)
@@ -58,7 +58,7 @@ if(NOT SwiftASN1_FOUND)
message("-- Vending swift-asn1")
FetchContent_Declare(ASN1
GIT_REPOSITORY https://github.com/apple/swift-asn1
GIT_TAG 1.1.0)
GIT_TAG 1.3.1)
FetchContent_MakeAvailable(ASN1)
endif()
+22 -10
View File
@@ -24,6 +24,8 @@
import PackageDescription
import class Foundation.ProcessInfo
// To develop this on Apple platforms, set this to true
let development = false
@@ -53,7 +55,7 @@ if development || isFreeBSD {
Platform.linux,
Platform.android,
Platform.windows,
Platform.wasi
Platform.wasi,
]
swiftSettings = [
.define("CRYPTO_IN_SWIFTPM"),
@@ -80,12 +82,6 @@ let privacyManifestResource: [PackageDescription.Resource] = []
let package = Package(
name: "swift-crypto",
platforms: [
.macOS(.v10_15),
.iOS(.v13),
.watchOS(.v6),
.tvOS(.v13),
],
products: [
.library(name: "Crypto", targets: ["Crypto"]),
.library(name: "_CryptoExtras", targets: ["_CryptoExtras"]),
@@ -94,7 +90,7 @@ let package = Package(
MANGLE_END */
],
dependencies: [
.package(url: "https://github.com/apple/swift-asn1.git", from: "1.2.0")
// Dependencies are added below so that they can be switched between local and absolute URLs
],
targets: [
.target(
@@ -109,7 +105,7 @@ let package = Package(
*/
"crypto/bio/connect.cc",
"crypto/bio/socket_helper.cc",
"crypto/bio/socket.cc"
"crypto/bio/socket.cc",
],
resources: privacyManifestResource,
cSettings: [
@@ -201,13 +197,29 @@ let package = Package(
cxxLanguageStandard: .cxx14
)
// Switch between local and remote dependencies depending on an environment variable
if ProcessInfo.processInfo.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil {
package.dependencies += [
.package(url: "https://github.com/apple/swift-asn1.git", from: "1.2.0")
]
} else {
package.dependencies += [
.package(path: "../swift-asn1")
]
}
// --- STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- //
for target in package.targets {
if target.type != .plugin {
switch target.type {
case .regular, .test, .executable:
var settings = target.swiftSettings ?? []
// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0444-member-import-visibility.md
settings.append(.enableUpcomingFeature("MemberImportVisibility"))
target.swiftSettings = settings
case .macro, .plugin, .system, .binary:
() // not applicable
@unknown default:
() // we don't know what to do here, do nothing
}
}
// --- END: STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- //
+10 -1
View File
@@ -253,7 +253,12 @@ add_library(CCryptoBoringSSL STATIC
"crypto/x509/x_val.cc"
"crypto/x509/x_x509.cc"
"crypto/x509/x_x509a.cc"
"gen/crypto/err_data.cc")
"gen/crypto/err_data.cc"
"$<$<NOT:$<PLATFORM_ID:Windows>>:crypto/hrss/asm/poly_rq_mul.S>"
"$<$<NOT:$<PLATFORM_ID:Windows>>:third_party/fiat/asm/fiat_curve25519_adx_mul.S>"
"$<$<NOT:$<PLATFORM_ID:Windows>>:third_party/fiat/asm/fiat_curve25519_adx_square.S>"
"$<$<NOT:$<PLATFORM_ID:Windows>>:third_party/fiat/asm/fiat_p256_adx_mul.S>"
"$<$<NOT:$<PLATFORM_ID:Windows>>:third_party/fiat/asm/fiat_p256_adx_sqr.S>")
if(CMAKE_SYSTEM_NAME STREQUAL Darwin AND CMAKE_SYSTEM_PROCESSOR MATCHES "amd64|x86_64")
target_sources(CCryptoBoringSSL PRIVATE
@@ -336,6 +341,10 @@ target_include_directories(CCryptoBoringSSL PUBLIC
target_compile_definitions(CCryptoBoringSSL PRIVATE
$<$<PLATFORM_ID:Windows>:WIN32_LEAN_AND_MEAN>)
target_link_libraries(CCryptoBoringSSL PUBLIC
$<$<NOT:$<PLATFORM_ID:Darwin>>:dispatch>
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
SwiftASN1)
set_target_properties(CCryptoBoringSSL PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/include;${CMAKE_Swift_MODULE_DIRECTORY}")
+2 -1
View File
@@ -13,7 +13,8 @@
##===----------------------------------------------------------------------===##
add_library(CCryptoBoringSSLShims STATIC
"shims.c")
"shims.c"
)
target_include_directories(CCryptoBoringSSLShims PUBLIC
include
@@ -15,17 +15,21 @@
@_exported import CryptoKit
#else
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
typealias AESGCMImpl = CoreCryptoGCMImpl
import Security
#else
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
typealias AESGCMImpl = OpenSSLAESGCMImpl
#endif
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension AES {
/// The Advanced Encryption Standard (AES) Galois Counter Mode (GCM) cipher
/// suite.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum GCM: Cipher {
static let tagByteCount = 16
static let defaultNonceByteCount = 12
@@ -91,6 +95,7 @@ extension AES {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension AES.GCM {
/// A secure container for your data that you can access using a cipher.
///
@@ -106,6 +111,7 @@ extension AES.GCM {
///
/// The receiver uses another instance of the same cipher, like the
/// ``open(_:using:)`` method, to open the box.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct SealedBox: AEADSealedBox {
private let combinedRepresentation: Data
private let nonceByteCount: Int
@@ -18,6 +18,7 @@
import CryptoBoringWrapper
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
enum OpenSSLAESGCMImpl {
@inlinable
static func seal<Plaintext: DataProtocol, AuthenticatedData: DataProtocol>(
@@ -19,6 +19,7 @@
import CryptoBoringWrapper
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension BoringSSLAEAD {
/// Seal a given message.
func seal<Plaintext: DataProtocol, Nonce: ContiguousBytes, AuthenticatedData: DataProtocol>(
@@ -61,6 +62,7 @@ extension BoringSSLAEAD {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
enum OpenSSLChaChaPolyImpl {
static func encrypt<M: DataProtocol, AD: DataProtocol>(
key: SymmetricKey,
@@ -15,15 +15,18 @@
@_exported import CryptoKit
#else
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
typealias ChaChaPolyImpl = CoreCryptoChaChaPolyImpl
import Security
#else
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
typealias ChaChaPolyImpl = OpenSSLChaChaPolyImpl
#endif
import Foundation
/// An implementation of the ChaCha20-Poly1305 cipher.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum ChaChaPoly: Cipher {
static let tagByteCount = 16
static let keyBitsCount = 256
@@ -90,6 +93,7 @@ public enum ChaChaPoly: Cipher {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ChaChaPoly {
/// A secure container for your data that you access using a cipher.
///
@@ -106,6 +110,7 @@ extension ChaChaPoly {
/// The receiver uses another instance of the same cipher, like the
/// ``open(_:using:)`` method, to open the box.
@frozen
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct SealedBox: AEADSealedBox {
/// A combined element composed of the tag, the nonce, and the
/// ciphertext.
+2
View File
@@ -16,6 +16,7 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol AEADSealedBox {
associatedtype Nonce: Sequence
/// The authentication tag
@@ -35,6 +36,7 @@ protocol AEADSealedBox {
}
/// A type representing authenticated encryption with associated data.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol Cipher {
associatedtype Key
associatedtype SealedBox: AEADSealedBox
+4
View File
@@ -20,12 +20,14 @@ import Foundation
// see section `gyb` in `README` for details.
// MARK: - AES.GCM + Nonce
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension AES.GCM {
/// A value used once during a cryptographic operation and then discarded.
///
/// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical
/// that nonces are unique per call to encryption APIs in order to protect the
/// integrity of the encryption.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct Nonce: ContiguousBytes, Sequence {
let bytes: Data
@@ -82,12 +84,14 @@ extension AES.GCM {
}
// MARK: - ChaChaPoly + Nonce
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ChaChaPoly {
/// A value used once during a cryptographic operation and then discarded.
///
/// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical
/// that nonces are unique per call to encryption APIs in order to protect the
/// integrity of the encryption.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct Nonce: ContiguousBytes, Sequence {
let bytes: Data
+30
View File
@@ -103,15 +103,18 @@ import Foundation
// generally: that is, we don't hard-code special knowledge of these formats as part of the parsing process. Instead we have written a
// parser that can divide the world of ASN.1 into parseable chunks, and then we try to decode specific formats from those chunks. This
// allows us to extend things in the future without too much pain.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal enum ASN1 { }
// MARK: - Parser Node
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
/// An `ASN1ParserNode` is a representation of a parsed ASN.1 TLV section. An `ASN1ParserNode` may be primitive, or may be composed of other `ASN1ParserNode`s.
/// In our representation, we keep track of this by storing a node "depth", which allows rapid forward and backward scans to hop over sections
/// we're uninterested in.
///
/// This type is not exposed to users of the API: it is only used internally for implementation of the user-level API.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
fileprivate struct ASN1ParserNode {
/// The identifier.
var identifier: ASN1Identifier
@@ -126,6 +129,7 @@ extension ASN1 {
extension ASN1.ASN1ParserNode: Hashable { }
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1.ASN1ParserNode: CustomStringConvertible {
var description: String {
return "ASN1.ASN1ParserNode(identifier: \(self.identifier), depth: \(self.depth), dataBytes: \(self.dataBytes?.count ?? 0))"
@@ -133,6 +137,7 @@ extension ASN1.ASN1ParserNode: CustomStringConvertible {
}
// MARK: - Sequence, SequenceOf, and Set
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
/// Parse the node as an ASN.1 sequence.
internal static func sequence<T>(_ node: ASN1Node, identifier: ASN1.ASN1Identifier, _ builder: (inout ASN1.ASN1NodeCollection.Iterator) throws -> T) throws -> T {
@@ -176,6 +181,7 @@ extension ASN1 {
}
// MARK: - Optional explicitly tagged
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
/// Parses an optional explicitly tagged element. Throws on a tag mismatch, returns nil if the element simply isn't there.
///
@@ -213,6 +219,7 @@ extension ASN1 {
}
// MARK: - DEFAULT
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
/// Parses a value that is encoded with a DEFAULT. Such a value is optional, and if absent will
/// be replaced with its default.
@@ -261,8 +268,10 @@ extension ASN1 {
}
// MARK: - Parsing
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
/// A parsed representation of ASN.1.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
fileprivate struct ASN1ParseResult {
private static let maximumNodeDepth = 10
@@ -328,6 +337,7 @@ extension ASN1 {
extension ASN1.ASN1ParseResult: Hashable { }
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
static func parse(_ data: [UInt8]) throws -> ASN1Node {
return try parse(data[...])
@@ -356,11 +366,13 @@ extension ASN1 {
}
// MARK: - ASN1NodeCollection
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
/// Represents a collection of ASN.1 nodes contained in a constructed ASN.1 node.
///
/// Constructed ASN.1 nodes are made up of multiple child nodes. This object represents the collection of those child nodes.
/// It allows us to lazily construct the child nodes, potentially skipping over them when we don't care about them.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal struct ASN1NodeCollection {
private var nodes: ArraySlice<ASN1ParserNode>
@@ -378,7 +390,9 @@ extension ASN1 {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1.ASN1NodeCollection: Sequence {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct Iterator: IteratorProtocol {
private var nodes: ArraySlice<ASN1.ASN1ParserNode>
private var depth: Int
@@ -412,6 +426,7 @@ extension ASN1.ASN1NodeCollection: Sequence {
}
// MARK: - ASN1Node
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
/// An `ASN1Node` is a single entry in the ASN.1 representation of a data structure.
///
@@ -421,6 +436,7 @@ extension ASN1 {
///
/// In this way, ASN.1 objects tend to form a "tree", where each object is represented by a single top-level constructed
/// node that contains other objects and primitives, eventually reaching the bottom which is made up of primitive objects.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal struct ASN1Node {
internal var identifier: ASN1Identifier
@@ -429,8 +445,10 @@ extension ASN1 {
}
// MARK: - ASN1Node.Content
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1.ASN1Node {
/// The content of a single ASN1Node.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
enum Content {
case constructed(ASN1.ASN1NodeCollection)
case primitive(ArraySlice<UInt8>)
@@ -438,7 +456,9 @@ extension ASN1.ASN1Node {
}
// MARK: - Serializing
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct Serializer {
var serializedBytes: [UInt8]
@@ -546,10 +566,12 @@ extension ASN1 {
}
// MARK: - Helpers
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal protocol ASN1Parseable {
init(asn1Encoded: ASN1.ASN1Node) throws
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1Parseable {
internal init(asn1Encoded sequenceNodeIterator: inout ASN1.ASN1NodeCollection.Iterator) throws {
guard let node = sequenceNodeIterator.next() else {
@@ -568,11 +590,13 @@ extension ASN1Parseable {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal protocol ASN1Serializable {
func serialize(into coder: inout ASN1.Serializer) throws
}
/// Covers ASN.1 types that may be implicitly tagged. Not all nodes can be!
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal protocol ASN1ImplicitlyTaggable: ASN1Parseable, ASN1Serializable {
/// The tag that the first node will use "by default" if the grammar omits
/// any more specific tag definition.
@@ -583,6 +607,7 @@ internal protocol ASN1ImplicitlyTaggable: ASN1Parseable, ASN1Serializable {
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1ImplicitlyTaggable {
internal init(asn1Encoded sequenceNodeIterator: inout ASN1.ASN1NodeCollection.Iterator,
withIdentifier identifier: ASN1.ASN1Identifier = Self.defaultIdentifier) throws {
@@ -610,6 +635,7 @@ extension ASN1ImplicitlyTaggable {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArraySlice where Element == UInt8 {
fileprivate mutating func readASN1Length() throws -> UInt? {
guard let firstByte = self.popFirst() else {
@@ -658,6 +684,7 @@ extension ArraySlice where Element == UInt8 {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension FixedWidthInteger {
internal init<Bytes: Collection>(bigEndianBytes bytes: Bytes) throws where Bytes.Element == UInt8 {
guard bytes.count <= (Self.bitWidth / 8) else {
@@ -675,6 +702,7 @@ extension FixedWidthInteger {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Array where Element == UInt8 {
fileprivate mutating func writeIdentifier(_ identifier: ASN1.ASN1Identifier) {
self.append(identifier.baseTag)
@@ -700,6 +728,7 @@ extension Array where Element == UInt8 {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Int {
fileprivate var bytesNeededToEncode: Int {
// ASN.1 lengths are in two forms. If we can store the length in 7 bits, we should:
@@ -717,6 +746,7 @@ extension Int {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension FixedWidthInteger {
// Bytes needed to store a given integer.
internal var neededBytes: Int {
@@ -16,6 +16,7 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
/// An ASN1 ANY represents...well, anything.
///
@@ -24,6 +25,7 @@ extension ASN1 {
///
/// The only things we allow users to do with ASN.1 ANYs is to try to decode them as something else,
/// to create them from something else, or to serialize them.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct ASN1Any: ASN1Parseable, ASN1Serializable, Hashable {
fileprivate var serializedBytes: ArraySlice<UInt8>
@@ -55,12 +57,14 @@ extension ASN1 {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1Parseable {
init(asn1Any: ASN1.ASN1Any) throws {
try self.init(asn1Encoded: asn1Any.serializedBytes)
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1ImplicitlyTaggable {
init(asn1Any: ASN1.ASN1Any, withIdentifier identifier: ASN1.ASN1Identifier) throws {
try self.init(asn1Encoded: asn1Any.serializedBytes, withIdentifier: identifier)
@@ -16,8 +16,10 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
/// A bitstring is a representation of...well...some bits.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct ASN1BitString: ASN1ImplicitlyTaggable {
static var defaultIdentifier: ASN1.ASN1Identifier {
.primitiveBitString
@@ -58,6 +60,7 @@ extension ASN1 {
extension ASN1.ASN1BitString: Hashable { }
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1.ASN1BitString: ContiguousBytes {
func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try self.bytes.withUnsafeBytes(body)
@@ -16,6 +16,7 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Bool: ASN1ImplicitlyTaggable {
static var defaultIdentifier: ASN1.ASN1Identifier {
.boolean
@@ -16,9 +16,11 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
/// An `ASN1Identifier` is a representation of the abstract notion of an ASN.1 identifier. Identifiers have a number of properties that relate to both the specific
/// tag number as well as the properties of the identifier in the stream.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal struct ASN1Identifier {
/// The base tag. In a general ASN.1 implementation we'd need an arbitrary precision integer here as the tag number can be arbitrarily large, but
/// we don't need the full generality here.
@@ -111,6 +113,7 @@ extension ASN1 {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1.ASN1Identifier {
internal static let objectIdentifier = try! ASN1.ASN1Identifier(rawIdentifier: 0x06)
internal static let primitiveBitString = try! ASN1.ASN1Identifier(rawIdentifier: 0x03)
@@ -137,6 +140,7 @@ extension ASN1.ASN1Identifier {
extension ASN1.ASN1Identifier: Hashable { }
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1.ASN1Identifier: CustomStringConvertible {
var description: String {
return "ASN1Identifier(\(self.baseTag))"
@@ -22,6 +22,7 @@ import Foundation
/// This is not a very good solution for a fully-fledged ASN.1 library: we'd rather have a better numerics
/// protocol that could both initialize from and serialize to either bytes or words. However, no such
/// protocol exists today.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol ASN1IntegerRepresentable: ASN1ImplicitlyTaggable {
associatedtype IntegerBytes: RandomAccessCollection where IntegerBytes.Element == UInt8
@@ -34,6 +35,7 @@ protocol ASN1IntegerRepresentable: ASN1ImplicitlyTaggable {
func withBigEndianIntegerBytes<ReturnType>(_ body: (IntegerBytes) throws -> ReturnType) rethrows -> ReturnType
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1IntegerRepresentable {
static var defaultIdentifier: ASN1.ASN1Identifier {
.integer
@@ -102,6 +104,7 @@ extension ASN1IntegerRepresentable {
}
// MARK: - Auto-conformance for FixedWidthInteger with fixed width magnitude.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1IntegerRepresentable where Self: FixedWidthInteger {
init(asn1IntegerBytes bytes: ArraySlice<UInt8>) throws {
// Defer to the FixedWidthInteger constructor.
@@ -122,6 +125,7 @@ extension ASN1IntegerRepresentable where Self: FixedWidthInteger {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct IntegerBytesCollection<Integer: FixedWidthInteger> {
private var integer: Integer
@@ -130,7 +134,9 @@ struct IntegerBytesCollection<Integer: FixedWidthInteger> {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension IntegerBytesCollection: RandomAccessCollection {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct Index {
fileprivate var byteNumber: Int
@@ -166,6 +172,7 @@ extension IntegerBytesCollection: RandomAccessCollection {
extension IntegerBytesCollection.Index: Equatable { }
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension IntegerBytesCollection.Index: Comparable {
// Comparable here is backwards to the original ordering.
static func <(lhs: Self, rhs: Self) -> Bool {
@@ -185,6 +192,7 @@ extension IntegerBytesCollection.Index: Comparable {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension IntegerBytesCollection.Index: Strideable {
func advanced(by n: Int) -> IntegerBytesCollection<Integer>.Index {
return IntegerBytesCollection.Index(byteNumber: self.byteNumber - n)
@@ -216,6 +224,7 @@ extension Int: ASN1IntegerRepresentable { }
extension UInt: ASN1IntegerRepresentable { }
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension RandomAccessCollection where Element == UInt8 {
fileprivate func trimLeadingExcessBytes() -> SubSequence {
var slice = self[...]
@@ -263,6 +272,7 @@ extension RandomAccessCollection where Element == UInt8 {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension UInt8 {
fileprivate var topBitSet: Bool {
return (self & 0x80) != 0
@@ -16,8 +16,10 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
/// An ASN1 NULL represents nothing.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct ASN1Null: ASN1ImplicitlyTaggable, Hashable {
static var defaultIdentifier: ASN1.ASN1Identifier {
.null
@@ -16,8 +16,10 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
/// An octet string is a representation of a string of octets.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct ASN1OctetString: ASN1ImplicitlyTaggable {
static var defaultIdentifier: ASN1.ASN1Identifier {
.primitiveOctetString
@@ -51,6 +53,7 @@ extension ASN1 {
extension ASN1.ASN1OctetString: Hashable { }
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1.ASN1OctetString: ContiguousBytes {
func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try self.bytes.withUnsafeBytes(body)
@@ -16,9 +16,11 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
/// A UTF8String is roughly what it sounds like. We note that all the string types are encoded as implicitly tagged
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct ASN1UTF8String: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes, ExpressibleByStringLiteral {
static var defaultIdentifier: ASN1.ASN1Identifier {
.primitiveUTF8String
@@ -54,6 +56,7 @@ extension ASN1 {
/// We note that all the string types are encoded as implicitly tagged
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct ASN1TeletexString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes, ExpressibleByStringLiteral {
static var defaultIdentifier: ASN1.ASN1Identifier {
.primitiveTeletexString
@@ -89,6 +92,7 @@ extension ASN1 {
/// We note that all the string types are encoded as implicitly tagged
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct ASN1PrintableString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes, ExpressibleByStringLiteral {
static var defaultIdentifier: ASN1.ASN1Identifier {
.primitivePrintableString
@@ -124,6 +128,7 @@ extension ASN1 {
/// We note that all the string types are encoded as implicitly tagged
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct ASN1UniversalString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes, ExpressibleByStringLiteral {
static var defaultIdentifier: ASN1.ASN1Identifier {
.primitiveUniversalString
@@ -159,6 +164,7 @@ extension ASN1 {
/// We note that all the string types are encoded as implicitly tagged
/// octet strings, and so for now we just piggyback on the decoder and encoder for that type.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct ASN1BMPString: ASN1ImplicitlyTaggable, Hashable, ContiguousBytes, ExpressibleByStringLiteral {
static var defaultIdentifier: ASN1.ASN1Identifier {
.primitiveBMPString
@@ -22,6 +22,7 @@ extension ArraySlice: ASN1Parseable where Element == UInt8 { }
extension ArraySlice: ASN1ImplicitlyTaggable where Element == UInt8 { }
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 {
// We only use unsigned "bigint"s
static var isSigned: Bool {
@@ -16,7 +16,9 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct GeneralizedTime: ASN1ImplicitlyTaggable, Hashable {
static var defaultIdentifier: ASN1.ASN1Identifier {
.generalizedTime
@@ -169,6 +171,7 @@ extension ASN1 {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1.GeneralizedTime {
fileprivate static func parseDateBytes(_ bytes: ArraySlice<UInt8>) throws -> ASN1.GeneralizedTime {
var bytes = bytes
@@ -251,6 +254,7 @@ extension ASN1.GeneralizedTime {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArraySlice where Element == UInt8 {
fileprivate mutating func readFourDigitDecimalInteger() -> Int? {
guard let first = self.readTwoDigitDecimalInteger(),
@@ -316,6 +320,7 @@ extension ArraySlice where Element == UInt8 {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Array where Element == UInt8 {
fileprivate mutating func append(_ generalizedTime: ASN1.GeneralizedTime) {
self.appendFourDigitDecimal(generalizedTime.year)
@@ -365,6 +370,7 @@ extension Array where Element == UInt8 {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Int {
fileprivate init?(fromDecimalASCII ascii: UInt8) {
let asciiZero = UInt8(ascii: "0")
@@ -16,12 +16,14 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
/// An Object Identifier is a representation of some kind of object: really any kind of object.
///
/// It represents a node in an OID hierarchy, and is usually represented as an ordered sequence of numbers.
///
/// We mostly don't care about the semantics of the thing, we just care about being able to store and compare them.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct ASN1ObjectIdentifier: ASN1ImplicitlyTaggable {
static var defaultIdentifier: ASN1.ASN1Identifier {
.objectIdentifier
@@ -133,13 +135,16 @@ extension ASN1 {
extension ASN1.ASN1ObjectIdentifier: Hashable {}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1.ASN1ObjectIdentifier: ExpressibleByArrayLiteral {
init(arrayLiteral elements: UInt...) {
self.oidComponents = elements
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1.ASN1ObjectIdentifier {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
enum NamedCurves {
static let secp256r1: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10_045, 3, 1, 7]
@@ -148,16 +153,19 @@ extension ASN1.ASN1ObjectIdentifier {
static let secp521r1: ASN1.ASN1ObjectIdentifier = [1, 3, 132, 0, 35]
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
enum HashFunctions {
static let sha256: ASN1.ASN1ObjectIdentifier = [2, 16, 840, 1, 101, 3, 4, 2, 1]
static let sha384: ASN1.ASN1ObjectIdentifier = [2, 16, 840, 1, 101, 3, 4, 2, 2]
static let sha512: ASN1.ASN1ObjectIdentifier = [2, 16, 840, 1, 101, 3, 4, 2, 3]
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
enum AlgorithmIdentifier {
static let idEcPublicKey: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10_045, 2, 1]
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
enum NameAttributes {
static let name: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 41]
static let surname: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 4]
@@ -180,6 +188,7 @@ extension ASN1.ASN1ObjectIdentifier {
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArraySlice where Element == UInt8 {
mutating fileprivate func readOIDSubidentifier() throws -> UInt {
// In principle OID subidentifiers can be too large to fit into a UInt. We are choosing to not care about that
@@ -196,6 +205,7 @@ extension ArraySlice where Element == UInt8 {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension UInt {
fileprivate init<Bytes: Collection>(sevenBitBigEndianBytes bytes: Bytes) throws where Bytes.Element == UInt8 {
// We need to know how many bytes we _need_ to store this "int".
+2
View File
@@ -16,6 +16,7 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
/// An ECDSA signature is laid out as follows:
///
@@ -25,6 +26,7 @@ extension ASN1 {
/// }
///
/// This type is generic because our different backends want to use different bignum representations.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct ECDSASignature<IntegerType: ASN1IntegerRepresentable>: ASN1ImplicitlyTaggable {
static var defaultIdentifier: ASN1.ASN1Identifier {
.sequence
+3
View File
@@ -16,8 +16,10 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
/// A PEM document is some data, and a discriminator type that is used to advertise the content.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct PEMDocument {
private static let lineLength = 64
@@ -86,6 +88,7 @@ extension ASN1 {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Substring {
fileprivate var pemStartDiscriminator: String? {
return self.pemDiscriminator(expectedPrefix: "-----BEGIN ", expectedSuffix: "-----")
@@ -16,6 +16,7 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
// A PKCS#8 private key is one of two formats, depending on the version:
//
@@ -39,6 +40,7 @@ extension ASN1 {
//
// The private key octet string contains (surprise!) a SEC1-encoded private key! So we recursively invoke the
// ASN.1 parser and go again.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct PKCS8PrivateKey: ASN1ImplicitlyTaggable {
static var defaultIdentifier: ASN1.ASN1Identifier {
return .sequence
+2
View File
@@ -16,6 +16,7 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
// For private keys, SEC 1 uses:
//
@@ -25,6 +26,7 @@ extension ASN1 {
// parameters [0] EXPLICIT ECDomainParameters OPTIONAL,
// publicKey [1] EXPLICIT BIT STRING OPTIONAL
// }
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct SEC1PrivateKey: ASN1ImplicitlyTaggable {
static var defaultIdentifier: ASN1.ASN1Identifier {
return .sequence
@@ -16,7 +16,9 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1 {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct SubjectPublicKeyInfo: ASN1ImplicitlyTaggable {
static var defaultIdentifier: ASN1.ASN1Identifier {
.sequence
@@ -59,6 +61,7 @@ extension ASN1 {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct RFC5480AlgorithmIdentifier: ASN1ImplicitlyTaggable, Hashable {
static var defaultIdentifier: ASN1.ASN1Identifier {
.sequence
@@ -109,6 +112,7 @@ extension ASN1 {
}
// MARK: Algorithm Identifier Statics
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ASN1.RFC5480AlgorithmIdentifier {
static let ecdsaP256 = ASN1.RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey,
parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp256r1))
+2 -1
View File
@@ -91,7 +91,8 @@ add_library(Crypto
"Util/PrettyBytes.swift"
"Util/SafeCompare.swift"
"Util/SecureBytes.swift"
"Util/Zeroization.swift")
"Util/Zeroization.swift"
)
target_compile_definitions(Crypto PRIVATE
"$<$<COMPILE_LANGUAGE:Swift>:CRYPTO_IN_SWIFTPM>")
+2
View File
@@ -15,6 +15,7 @@
@_exported import CryptoKit
#else
/// General cryptography errors used by CryptoKit.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum CryptoKitError: Error {
/// The key size is incorrect.
case incorrectKeySize
@@ -36,6 +37,7 @@ public enum CryptoKitError: Error {
extension CryptoKitError: Equatable, Hashable {}
/// Errors from decoding ASN.1 content.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum CryptoKitASN1Error: Equatable, Error, Hashable {
/// The ASN.1 tag for this field is invalid or unsupported.
case invalidFieldIdentifier
@@ -16,8 +16,10 @@
#else
@_implementationOnly import CCryptoBoringSSL
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol HashFunctionImplementationDetails: HashFunction where Digest: DigestPrivate {}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol BoringSSLBackedHashFunction: HashFunctionImplementationDetails {
associatedtype Context
static var digestSize: Int { get }
@@ -26,6 +28,7 @@ protocol BoringSSLBackedHashFunction: HashFunctionImplementationDetails {
static func finalize(_ context: inout Context, digest: UnsafeMutableRawBufferPointer) -> Bool
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Insecure.MD5: BoringSSLBackedHashFunction {
static var digestSize: Int {
Int(MD5_DIGEST_LENGTH)
@@ -48,6 +51,7 @@ extension Insecure.MD5: BoringSSLBackedHashFunction {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Insecure.SHA1: BoringSSLBackedHashFunction {
static var digestSize: Int {
Int(SHA_DIGEST_LENGTH)
@@ -70,6 +74,7 @@ extension Insecure.SHA1: BoringSSLBackedHashFunction {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SHA256: BoringSSLBackedHashFunction {
static var digestSize: Int {
Int(SHA256_DIGEST_LENGTH)
@@ -92,6 +97,7 @@ extension SHA256: BoringSSLBackedHashFunction {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SHA384: BoringSSLBackedHashFunction {
static var digestSize: Int {
Int(SHA384_DIGEST_LENGTH)
@@ -114,6 +120,7 @@ extension SHA384: BoringSSLBackedHashFunction {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SHA512: BoringSSLBackedHashFunction {
static var digestSize: Int {
Int(SHA512_DIGEST_LENGTH)
@@ -136,6 +143,7 @@ extension SHA512: BoringSSLBackedHashFunction {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct OpenSSLDigestImpl<H: BoringSSLBackedHashFunction> {
private var context: DigestContext<H>
@@ -155,6 +163,7 @@ struct OpenSSLDigestImpl<H: BoringSSLBackedHashFunction> {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
private final class DigestContext<H: BoringSSLBackedHashFunction> {
private var context: H.Context
+5
View File
@@ -17,15 +17,18 @@
import Foundation
/// A type that represents the output of a hash.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public protocol Digest: Hashable, ContiguousBytes, CustomStringConvertible, Sequence where Element == UInt8 {
/// The number of bytes in the digest.
static var byteCount: Int { get }
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol DigestPrivate: Digest {
init?(bufferPointer: UnsafeRawBufferPointer)
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension DigestPrivate {
@inlinable
init?(bytes: [UInt8]) {
@@ -41,6 +44,7 @@ extension DigestPrivate {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Digest {
public func makeIterator() -> Array<UInt8>.Iterator {
self.withUnsafeBytes({ (buffPtr) in
@@ -50,6 +54,7 @@ extension Digest {
}
// We want to implement constant-time comparison for digests.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Digest {
/// Determines whether two digests are equal.
///
+7
View File
@@ -20,6 +20,7 @@
// MARK: - SHA256Digest + DigestPrivate
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 256-bit digest.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct SHA256Digest: DigestPrivate {
let bytes: (UInt64, UInt64, UInt64, UInt64)
@@ -90,6 +91,7 @@ public struct SHA256Digest: DigestPrivate {
// MARK: - SHA384Digest + DigestPrivate
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 384-bit digest.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct SHA384Digest: DigestPrivate {
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
@@ -162,6 +164,7 @@ public struct SHA384Digest: DigestPrivate {
// MARK: - SHA512Digest + DigestPrivate
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 512-bit digest.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct SHA512Digest: DigestPrivate {
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
@@ -233,9 +236,11 @@ public struct SHA512Digest: DigestPrivate {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Insecure {
// MARK: - SHA1Digest + DigestPrivate
/// The output of a SHA1 hash.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct SHA1Digest: DigestPrivate {
let bytes: (UInt64, UInt64, UInt64)
@@ -302,9 +307,11 @@ public struct SHA1Digest: DigestPrivate {
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Insecure {
// MARK: - MD5Digest + DigestPrivate
/// The output of a MD5 hash.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct MD5Digest: DigestPrivate {
let bytes: (UInt64, UInt64)
@@ -15,8 +15,10 @@
@_exported import CryptoKit
#else
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
typealias DigestImpl = CoreCryptoDigestImpl
#else
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
typealias DigestImpl = OpenSSLDigestImpl
#endif
@@ -40,6 +42,7 @@ import Foundation
/// authentication code (MAC) like ``HMAC`` instead. MACs rely on hashing, but
/// incorporate a secret cryptographic key into the digest computation. Only a
/// user that has the key can generate a valid MAC.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public protocol HashFunction {
/// The number of bytes that represents the hash function’s internal state.
static var blockByteCount: Int { get }
@@ -94,6 +97,7 @@ public protocol HashFunction {
func finalize() -> Digest
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension HashFunction {
/// Computes a digest of the buffer.
///
@@ -26,6 +26,7 @@
/// in memory, you can compute the digest iteratively by creating a new hash
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
/// data, and then calling the ``finalize()`` method to get the result.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct SHA256: HashFunctionImplementationDetails {
/// The number of bytes that represents the hash function’s internal state.
public static var blockByteCount: Int {
@@ -108,6 +109,7 @@ public struct SHA256: HashFunctionImplementationDetails {
/// in memory, you can compute the digest iteratively by creating a new hash
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
/// data, and then calling the ``finalize()`` method to get the result.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct SHA384: HashFunctionImplementationDetails {
/// The number of bytes that represents the hash function’s internal state.
public static var blockByteCount: Int {
@@ -191,6 +193,7 @@ public struct SHA384: HashFunctionImplementationDetails {
/// in memory, you can compute the digest iteratively by creating a new hash
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
/// data, and then calling the ``finalize()`` method to get the result.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct SHA512: HashFunctionImplementationDetails {
/// The number of bytes that represents the hash function’s internal state.
public static var blockByteCount: Int {
@@ -17,8 +17,10 @@
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension HPKE {
/// The authenticated encryption with associated data (AEAD) algorithms to use in HPKE.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum AEAD: CaseIterable, Hashable {
/// An Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 128 bits.
case AES_GCM_128
@@ -17,6 +17,7 @@
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension HPKE {
/// Cipher suites to use in hybrid public key encryption.
///
@@ -24,6 +25,7 @@ extension HPKE {
/// and decrypting messages, the key derivation function (KDF) for deriving the shared key, and the key encapsulation
/// mechanism (KEM) for sharing the symmetric key. The sender and recipient of encrypted messages need to use the
/// same cipher suite.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct Ciphersuite {
/// A cipher suite for HPKE that uses NIST P-256 elliptic curve key agreement, SHA-2 key derivation
/// with a 256-bit digest, and the Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 256 bits.
@@ -16,8 +16,10 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension HPKE {
/// The key derivation functions to use in HPKE.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum KDF: CaseIterable, Hashable {
/// An HMAC-based key derivation function that uses SHA-2 hashing with a 256-bit digest.
case HKDF_SHA256
@@ -16,9 +16,12 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
private let suiteIDLabel = Data("KEM".utf8)
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension HPKE {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct KexUtils {
static func ExtractAndExpand(dh: ContiguousBytes, enc: Data,
pkRm: Data, pkSm: Data? = nil, kem: HPKE.KEM, kdf: HPKE.KDF) -> SymmetricKey {
@@ -16,24 +16,32 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
private let protocolLabel = Data("HPKE-v1".utf8)
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
private let eaePRKLabel = Data("eae_prk".utf8)
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
private let sharedSecretLabel = Data("shared_secret".utf8)
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Data {
internal init(unsafeFromContiguousBytes cb: ContiguousBytes) {
self = cb.withUnsafeBytes { return Data($0) }
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal func ExtractAndExpand(zz: ContiguousBytes, kemContext: Data, suiteID: Data, kem: HPKE.KEM, kdf: HPKE.KDF) -> SymmetricKey {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
let eaePrk = LabeledExtract(salt: Data(), label: eaePRKLabel, ikm: zz, suiteID: suiteID, kdf: kdf)
return LabeledExpand(prk: eaePrk, label: sharedSecretLabel,
info: kemContext, outputByteCount: kem.nSecret, suiteID: suiteID, kdf: kdf)
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal func LabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, suiteID: Data, kdf: HPKE.KDF) -> SymmetricKey {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
var labeled_ikm = protocolLabel
labeled_ikm.append(suiteID)
labeled_ikm.append(label)
@@ -41,7 +49,9 @@ internal func LabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, su
return kdf.extract(salt: salt ?? Data(), ikm: SymmetricKey(data: labeled_ikm))
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal func LabeledExpand<Info: DataProtocol>(prk: SymmetricKey, label: Data, info: Info, outputByteCount: UInt16, suiteID: Data, kdf: HPKE.KDF) -> SymmetricKey {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
var labeled_info = I2OSP(value: Int(outputByteCount), outputByteCount: 2)
labeled_info.append(protocolLabel)
labeled_info.append(suiteID)
@@ -50,10 +60,12 @@ internal func LabeledExpand<Info: DataProtocol>(prk: SymmetricKey, label: Data,
return kdf.expand(prk: prk, info: labeled_info, outputByteCount: Int(outputByteCount))
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal func NonSecretOutputLabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, suiteID: Data, kdf: HPKE.KDF) -> Data {
return Data(unsafeFromContiguousBytes: LabeledExtract(salt: salt, label: label, ikm: ikm, suiteID: suiteID, kdf: kdf))
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal func NonSecretOutputLabeledExpand(prk: SymmetricKey, label: Data, info: Data, outputByteCount: UInt16, suiteID: Data, kdf: HPKE.KDF) -> Data {
return Data(unsafeFromContiguousBytes: LabeledExpand(prk: prk, label: label, info: info, outputByteCount: outputByteCount, suiteID: suiteID, kdf: kdf))
}
@@ -16,13 +16,16 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal func I2OSP(value: Int, outputByteCount: Int) -> Data {
precondition(outputByteCount > 0, "Cannot I2OSP with no output length.")
precondition(value >= 0, "I2OSP requires a non-null value.")
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
let requiredBytes = Int(ceil(log2(Double(max(value, 1) + 1)) / 8))
precondition(outputByteCount >= requiredBytes)
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
var data = Data(repeating: 0, count: outputByteCount)
for i in (outputByteCount - requiredBytes)...(outputByteCount - 1) {
@@ -17,6 +17,7 @@
import Foundation
/// A type that ``HPKE`` uses to encode the public key.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public protocol HPKEPublicKeySerialization {
/// Creates a public key from an encoded representation.
///
@@ -34,6 +35,7 @@ public protocol HPKEPublicKeySerialization {
}
/// A type that represents the public key in a Diffie-Hellman key exchange.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public protocol HPKEDiffieHellmanPublicKey: HPKEPublicKeySerialization where EphemeralPrivateKey.PublicKey == Self {
/// The type of the ephemeral private key.
associatedtype EphemeralPrivateKey: HPKEDiffieHellmanPrivateKeyGeneration
@@ -41,17 +43,22 @@ public protocol HPKEDiffieHellmanPublicKey: HPKEPublicKeySerialization where Eph
/// A type that represents the private key in a Diffie-Hellman key exchange.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public protocol HPKEDiffieHellmanPrivateKey: DiffieHellmanKeyAgreement where PublicKey: HPKEDiffieHellmanPublicKey {}
/// A type that represents the generation of private keys in a Diffie-Hellman key exchange.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public protocol HPKEDiffieHellmanPrivateKeyGeneration: HPKEDiffieHellmanPrivateKey {
/// Creates a private key generator.
init()
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension HPKE {
/// A container for Diffie-Hellman key encapsulation mechanisms (KEMs).
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum DHKEM {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct PublicKey<DHPK: HPKEDiffieHellmanPublicKey>: KEMPublicKey where DHPK == DHPK.EphemeralPrivateKey.PublicKey {
let kem: HPKE.KEM
let key: DHPK
@@ -84,6 +91,7 @@ extension HPKE {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct PrivateKey<DHSK: HPKEDiffieHellmanPrivateKey>: KEMPrivateKey {
let kem: HPKE.KEM
let key: DHSK
@@ -19,6 +19,7 @@ import Foundation
extension Curve25519.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Curve25519.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
/// The type of the ephemeral private key associated with this public key.
public typealias EphemeralPrivateKey = Curve25519.KeyAgreement.PrivateKey
@@ -18,6 +18,7 @@ import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P256.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
/// Creates a NIST P-256 elliptic curve private key for use with Diffie-Hellman key exchange.
public init() {
@@ -26,6 +27,7 @@ extension P256.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P256.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
/// The type of the ephemeral private key associated with this public key.
public typealias EphemeralPrivateKey = P256.KeyAgreement.PrivateKey
@@ -66,6 +68,7 @@ extension P256.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P384.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
/// Creates a NIST P-384 elliptic curve private key for use with Diffie-Hellman key exchange.
public init() {
@@ -74,6 +77,7 @@ extension P384.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P384.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
/// The type of the ephemeral private key associated with this public key.
public typealias EphemeralPrivateKey = P384.KeyAgreement.PrivateKey
@@ -114,6 +118,7 @@ extension P384.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P521.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
/// Creates a NIST P-521 elliptic curve private key for use with Diffie-Hellman key exchange.
public init() {
@@ -122,6 +127,7 @@ extension P521.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P521.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
/// The type of the ephemeral private key associated with this public key.
public typealias EphemeralPrivateKey = P521.KeyAgreement.PrivateKey
@@ -16,8 +16,10 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension HPKE {
/// The key encapsulation mechanisms to use in HPKE.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum KEM: CaseIterable, Hashable {
/// A key encapsulation mechanism using NIST P-256 elliptic curve key agreement
/// and SHA-2 hashing with a 256-bit digest.
+2
View File
@@ -16,8 +16,10 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension HPKE {
/// Hybrid public key encryption (HPKE) errors that CryptoKit uses.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum Errors: Error {
/// The parameters for initializing an HPKE sender or receiver are inconsistent.
case inconsistentParameters
+4
View File
@@ -45,8 +45,10 @@ import Foundation
///
/// ### Handling errors
/// - ``Errors``
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum HPKE {}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension HPKE {
/// A type that represents the sending side of an HPKE message exchange.
///
@@ -56,6 +58,7 @@ extension HPKE {
/// in turn to retrieve its ciphertext. The recipient of the messages needs to process them in the
/// same order as the `Sender`, using the same encryption mode, cipher suite, and key schedule information
/// (`info`), as well as the `Sender`'s ``encapsulatedKey``.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct Sender {
private var context: Context
/// The encapsulated symmetric key that the recipient uses to decrypt messages.
@@ -193,6 +196,7 @@ extension HPKE {
/// same order as the `Sender`, using the same cipher suite, encryption mode, and key schedule information
/// (`info` data).
/// Use a separate `Recipient` instance for each stream of messages.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct Recipient {
private var context: Context
@@ -16,7 +16,9 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension HPKE {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct Context {
var keySchedule: KeySchedule
var encapsulated: Data
@@ -16,7 +16,9 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension HPKE {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal struct KeySchedule {
fileprivate static let pksIDHashLabel = Data("psk_id_hash".utf8)
fileprivate static let infoHashLabel = Data("info_hash".utf8)
@@ -15,8 +15,10 @@
@_exported import CryptoKit
#else
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension HPKE {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal enum Mode: CaseIterable {
case base
case psk
+1
View File
@@ -19,5 +19,6 @@
/// - Important: These algorithms aren’t considered cryptographically secure,
/// but the framework provides them for backward compatibility with older
/// services that require them. For new services, avoid these algorithms.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum Insecure {}
#endif // Linux or !SwiftPM
@@ -14,6 +14,7 @@
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Insecure {
/// An implementation of SHA1 hashing.
///
@@ -31,6 +32,7 @@ extension Insecure {
/// secure, but is provided for backward compatibility with older services
/// that require it. For new services, prefer one of the secure hashes, like
/// ``SHA512``.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct SHA1: HashFunctionImplementationDetails {
/// The number of bytes that represents the hash function’s internal
/// state.
@@ -119,6 +121,7 @@ extension Insecure {
/// secure, but is provided for backward compatibility with older services
/// that require it. For new services, prefer one of the secure hashes, like
/// ``SHA512``.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct MD5: HashFunctionImplementationDetails {
/// The number of bytes that represents the hash function’s internal
/// state.
+4
View File
@@ -17,8 +17,10 @@
import Foundation
/// A Key Encapsulation Mechanism
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum KEM {
/// The result of an encapsulation operation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct EncapsulationResult {
/// The shared secret
public let sharedSecret: SymmetricKey
@@ -33,6 +35,7 @@ public enum KEM {
}
/// A Key Encapsulation Mechanism's Public Key
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public protocol KEMPublicKey {
/// Encapsulates the generated shared secret
/// - Returns: The shared secret and its encapsulated version
@@ -40,6 +43,7 @@ public protocol KEMPublicKey {
}
/// A Key Encapsulation Mechanism's Private Key
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public protocol KEMPrivateKey {
associatedtype PublicKey: KEMPublicKey
@@ -16,6 +16,7 @@
#else
@_implementationOnly import CCryptoBoringSSL
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P256.KeyAgreement.PrivateKey {
internal func openSSLSharedSecretFromKeyAgreement(
with publicKeyShare: P256.KeyAgreement.PublicKey
@@ -25,6 +26,7 @@ extension P256.KeyAgreement.PrivateKey {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P384.KeyAgreement.PrivateKey {
internal func openSSLSharedSecretFromKeyAgreement(
with publicKeyShare: P384.KeyAgreement.PublicKey
@@ -34,6 +36,7 @@ extension P384.KeyAgreement.PrivateKey {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P521.KeyAgreement.PrivateKey {
internal func openSSLSharedSecretFromKeyAgreement(
with publicKeyShare: P521.KeyAgreement.PublicKey
+5
View File
@@ -17,6 +17,7 @@
import Foundation
/// A Diffie-Hellman Key Agreement Key
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public protocol DiffieHellmanKeyAgreement {
/// The public key share type to perform the DH Key Agreement
associatedtype PublicKey
@@ -47,6 +48,7 @@ public protocol DiffieHellmanKeyAgreement {
/// symmetric key suitable for creating a message authentication code like
/// ``HMAC``, or for opening and closing a sealed box with a cipher like
/// ``ChaChaPoly`` or ``AES``.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct SharedSecret: ContiguousBytes {
var ss: SecureBytes
@@ -144,6 +146,7 @@ public struct SharedSecret: ContiguousBytes {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SharedSecret: Hashable {
public func hash(into hasher: inout Hasher) {
ss.withUnsafeBytes { hasher.combine(bytes: $0) }
@@ -151,6 +154,7 @@ extension SharedSecret: Hashable {
}
// We want to implement constant-time comparison for digests.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SharedSecret: CustomStringConvertible, Equatable {
public static func == (lhs: Self, rhs: Self) -> Bool {
return safeCompare(lhs, rhs)
@@ -179,6 +183,7 @@ extension SharedSecret: CustomStringConvertible, Equatable {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension HashFunction {
// A wrapper function to keep the unsafe code in one place.
mutating func update(_ secret: SharedSecret) {
+31
View File
@@ -15,10 +15,14 @@
@_exported import CryptoKit
#else
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
typealias NISTCurvePublicKeyImpl = CoreCryptoNISTCurvePublicKeyImpl
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
typealias NISTCurvePrivateKeyImpl = CoreCryptoNISTCurvePrivateKeyImpl
#else
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
typealias NISTCurvePublicKeyImpl = OpenSSLNISTCurvePublicKeyImpl
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
typealias NISTCurvePrivateKeyImpl = OpenSSLNISTCurvePrivateKeyImpl
#endif
@@ -29,13 +33,16 @@ import Foundation
// see section `gyb` in `README` for details.
// MARK: - P256 + Signing
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P256 {
/// A mechanism used to create or verify a cryptographic signature using
/// the NIST P-256 elliptic curve digital signature algorithm (ECDSA).
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum Signing {
/// A P-256 public key used to verify cryptographic signatures.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct PublicKey: NISTECPublicKey {
var impl: NISTCurvePublicKeyImpl<P256>
@@ -135,6 +142,7 @@ extension P256 {
}
/// A P-256 private key used to create cryptographic signatures.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct PrivateKey: NISTECPrivateKey {
let impl: NISTCurvePrivateKeyImpl<P256>
@@ -243,14 +251,17 @@ extension P256 {
}
}
// MARK: - P256 + KeyAgreement
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P256 {
/// A mechanism used to create a shared secret between two users by
/// performing NIST P-256 elliptic curve Diffie Hellman (ECDH) key
/// exchange.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum KeyAgreement {
/// A P-256 public key used for key agreement.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct PublicKey: NISTECPublicKey {
var impl: NISTCurvePublicKeyImpl<P256>
@@ -350,6 +361,7 @@ extension P256 {
}
/// A P-256 private key used for key agreement.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct PrivateKey: NISTECPrivateKey {
let impl: NISTCurvePrivateKeyImpl<P256>
@@ -458,13 +470,16 @@ extension P256 {
}
}
// MARK: - P384 + Signing
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P384 {
/// A mechanism used to create or verify a cryptographic signature using
/// the NIST P-384 elliptic curve digital signature algorithm (ECDSA).
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum Signing {
/// A P-384 public key used to verify cryptographic signatures.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct PublicKey: NISTECPublicKey {
var impl: NISTCurvePublicKeyImpl<P384>
@@ -564,6 +579,7 @@ extension P384 {
}
/// A P-384 private key used to create cryptographic signatures.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct PrivateKey: NISTECPrivateKey {
let impl: NISTCurvePrivateKeyImpl<P384>
@@ -672,14 +688,17 @@ extension P384 {
}
}
// MARK: - P384 + KeyAgreement
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P384 {
/// A mechanism used to create a shared secret between two users by
/// performing NIST P-384 elliptic curve Diffie Hellman (ECDH) key
/// exchange.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum KeyAgreement {
/// A P-384 public key used for key agreement.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct PublicKey: NISTECPublicKey {
var impl: NISTCurvePublicKeyImpl<P384>
@@ -779,6 +798,7 @@ extension P384 {
}
/// A P-384 private key used for key agreement.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct PrivateKey: NISTECPrivateKey {
let impl: NISTCurvePrivateKeyImpl<P384>
@@ -887,13 +907,16 @@ extension P384 {
}
}
// MARK: - P521 + Signing
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P521 {
/// A mechanism used to create or verify a cryptographic signature using
/// the NIST P-521 elliptic curve digital signature algorithm (ECDSA).
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum Signing {
/// A P-521 public key used to verify cryptographic signatures.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct PublicKey: NISTECPublicKey {
var impl: NISTCurvePublicKeyImpl<P521>
@@ -993,6 +1016,7 @@ extension P521 {
}
/// A P-521 private key used to create cryptographic signatures.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct PrivateKey: NISTECPrivateKey {
let impl: NISTCurvePrivateKeyImpl<P521>
@@ -1101,14 +1125,17 @@ extension P521 {
}
}
// MARK: - P521 + KeyAgreement
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P521 {
/// A mechanism used to create a shared secret between two users by
/// performing NIST P-521 elliptic curve Diffie Hellman (ECDH) key
/// exchange.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum KeyAgreement {
/// A P-521 public key used for key agreement.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct PublicKey: NISTECPublicKey {
var impl: NISTCurvePublicKeyImpl<P521>
@@ -1208,6 +1235,7 @@ extension P521 {
}
/// A P-521 private key used for key agreement.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct PrivateKey: NISTECPrivateKey {
let impl: NISTCurvePrivateKeyImpl<P521>
@@ -1317,6 +1345,7 @@ extension P521 {
}
// MARK: - P256 + DH
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P256.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
/// Computes a shared secret with the provided public key from another party.
///
@@ -1333,6 +1362,7 @@ extension P256.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
}
}
// MARK: - P384 + DH
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P384.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
/// Computes a shared secret with the provided public key from another party.
///
@@ -1349,6 +1379,7 @@ extension P384.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
}
}
// MARK: - P521 + DH
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P521.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
/// Computes a shared secret with the provided public key from another party.
///
+1
View File
@@ -34,6 +34,7 @@ import Android
/// material in the form of a hashed authentication code, then call
/// ``expand(pseudoRandomKey:info:outputByteCount:)`` using that key material to
/// generate a symmetric key of the length you specify.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct HKDF<H: HashFunction> {
/// Derives a symmetric encryption key from a main key or passcode using
/// HKDF key derivation with information and salt you specify.
@@ -17,14 +17,18 @@
import Foundation
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
typealias AESWRAPImpl = CoreCryptoAESWRAPImpl
#else
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
typealias AESWRAPImpl = BoringSSLAESWRAPImpl
#endif
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension AES {
/// An implementation of AES Key Wrapping in accordance with the IETF RFC
/// 3394 specification.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum KeyWrap {
/// Wraps a key using the AES wrap algorithm.
///
@@ -17,6 +17,7 @@
@_implementationOnly import CCryptoBoringSSL
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
enum BoringSSLAESWRAPImpl {
static func wrap(key: SymmetricKey, keyToWrap: SymmetricKey) throws -> Data {
// There's a flat 8-byte overhead to AES KeyWrap.
@@ -95,7 +96,9 @@ enum BoringSSLAESWRAPImpl {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SymmetricKey {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
fileprivate enum AESKeyMode {
case encrypting
case decrypting
@@ -19,8 +19,10 @@
import Foundation
// For signing and verifying, we use BoringSSL's Ed25519, not the X25519 stuff.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Curve25519.Signing {
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct OpenSSLCurve25519PrivateKeyImpl {
var _privateKey: SecureBytes
@usableFromInline var _publicKey: [UInt8]
@@ -92,6 +94,7 @@ extension Curve25519.Signing {
}
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct OpenSSLCurve25519PublicKeyImpl {
@usableFromInline
var keyBytes: [UInt8]
@@ -20,11 +20,13 @@ import CryptoBoringWrapper
import Foundation
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol OpenSSLSupportedNISTCurve {
@inlinable
static var group: BoringSSLEllipticCurveGroup { get }
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension OpenSSLSupportedNISTCurve {
@inlinable
static var coordinateByteCount: Int {
@@ -32,6 +34,7 @@ extension OpenSSLSupportedNISTCurve {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P256: OpenSSLSupportedNISTCurve {
@inlinable
static var group: BoringSSLEllipticCurveGroup {
@@ -39,6 +42,7 @@ extension P256: OpenSSLSupportedNISTCurve {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P384: OpenSSLSupportedNISTCurve {
@inlinable
static var group: BoringSSLEllipticCurveGroup {
@@ -46,6 +50,7 @@ extension P384: OpenSSLSupportedNISTCurve {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P521: OpenSSLSupportedNISTCurve {
@inlinable
static var group: BoringSSLEllipticCurveGroup {
@@ -54,6 +59,7 @@ extension P521: OpenSSLSupportedNISTCurve {
}
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct OpenSSLNISTCurvePrivateKeyImpl<Curve: OpenSSLSupportedNISTCurve> {
@usableFromInline
var key: BoringSSLECPrivateKeyWrapper<Curve>
@@ -84,6 +90,7 @@ struct OpenSSLNISTCurvePrivateKeyImpl<Curve: OpenSSLSupportedNISTCurve> {
}
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct OpenSSLNISTCurvePublicKeyImpl<Curve: OpenSSLSupportedNISTCurve> {
@usableFromInline
var key: BoringSSLECPublicKeyWrapper<Curve>
@@ -133,6 +140,7 @@ struct OpenSSLNISTCurvePublicKeyImpl<Curve: OpenSSLSupportedNISTCurve> {
/// A simple wrapper for an EC_KEY pointer for a private key. This manages the lifetime of that pointer and
/// allows some helper operations.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
@usableFromInline
var key: OpaquePointer
@@ -337,6 +345,7 @@ class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
/// A simple wrapper for an EC_KEY pointer for a public key. This manages the lifetime of that pointer and
/// allows some helper operations.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
@usableFromInline
var key: OpaquePointer
@@ -572,6 +581,7 @@ class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ContiguousBytes {
func readx963PrivateNumbers() throws -> (
x: ArbitraryPrecisionInteger, y: ArbitraryPrecisionInteger, k: ArbitraryPrecisionInteger
@@ -641,19 +651,26 @@ extension ContiguousBytes {
}
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func readRawPublicNumbers(
copyingBytes bytesPtr: UnsafeRawBufferPointer
) throws -> (
x: ArbitraryPrecisionInteger, y: ArbitraryPrecisionInteger
) {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
let stride = bytesPtr.count / 2
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
var offset = 0
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
let xPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset..<(offset + stride)])
offset += stride
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
let yPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset..<(offset + stride)])
// We cannot handle allocation errors, so we check for fatal error.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
let x = try ArbitraryPrecisionInteger(bytes: xPointer)
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
let y = try ArbitraryPrecisionInteger(bytes: yPointer)
return (x: x, y: y)
@@ -664,6 +681,7 @@ func readRawPublicNumbers(
/// 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 order of the prime field.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func _isCompactRepresentable(
group: BoringSSLEllipticCurveGroup,
publicKeyPoint: EllipticCurvePoint
@@ -671,8 +689,11 @@ func _isCompactRepresentable(
// We have three try!s here: any of those failing is the result of an allocation error, and we cannot recover from
// those.
let (_, y) = try! publicKeyPoint.affineCoordinates(group: group)
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
let p = group.weierstrassCoefficients.field
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
let context = try! FiniteFieldArithmeticContext(fieldSize: p)
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
let newY = try! context.subtract(y, from: group.order)
// The point is compact representable if y is less than or equal to newY.
@@ -18,11 +18,13 @@
@_implementationOnly import CCryptoBoringSSLShims
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Curve25519.KeyAgreement {
@usableFromInline
static let keySizeBytes = 32
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct OpenSSLCurve25519PublicKeyImpl {
@usableFromInline
var keyBytes: [UInt8]
@@ -50,6 +52,7 @@ extension Curve25519.KeyAgreement {
}
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct OpenSSLCurve25519PrivateKeyImpl {
var key: SecureBytes
+1
View File
@@ -15,5 +15,6 @@
@_exported import CryptoKit
#else
/// An elliptic curve that enables X25519 key agreement and Ed25519 signatures.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum Curve25519 {}
#endif // Linux or !SwiftPM
+5
View File
@@ -16,15 +16,18 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Curve25519.Signing {
static var keyByteCount: Int {
return 32
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Curve25519 {
/// A mechanism used to create or verify a cryptographic signature using
/// Ed25519.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum Signing {
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
typealias Curve25519PrivateKeyImpl = Curve25519.Signing.CoreCryptoCurve25519PrivateKeyImpl
@@ -35,6 +38,7 @@ extension Curve25519 {
#endif
/// A Curve25519 private key used to create cryptographic signatures.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct PrivateKey: ECPrivateKey {
private var baseKey: Curve25519.Signing.Curve25519PrivateKeyImpl
@@ -70,6 +74,7 @@ extension Curve25519 {
}
/// A Curve25519 public key used to verify cryptographic signatures.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct PublicKey {
private var baseKey: Curve25519.Signing.Curve25519PublicKeyImpl
@@ -17,21 +17,26 @@ import Foundation
@_exported import CryptoKit
#else
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
typealias SupportedCurveDetailsImpl = CorecryptoSupportedNISTCurve
#else
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
typealias SupportedCurveDetailsImpl = OpenSSLSupportedNISTCurve
#endif
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol ECPublicKey {
init <Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws
var rawRepresentation: Data { get }
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol ECPrivateKey {
associatedtype PK
var publicKey: PK { get }
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol NISTECPublicKey: ECPublicKey {
init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws
init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws
@@ -41,17 +46,21 @@ protocol NISTECPublicKey: ECPublicKey {
var x963Representation: Data { get }
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol NISTECPrivateKey: ECPrivateKey where PK: NISTECPublicKey {
init <Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws
var rawRepresentation: Data { get }
}
/// An elliptic curve that enables NIST P-256 signatures and key agreement.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum P256 { }
/// An elliptic curve that enables NIST P-384 signatures and key agreement.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum P384 { }
/// An elliptic curve that enables NIST P-521 signatures and key agreement.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum P521 { }
#endif // Linux or !SwiftPM
+5
View File
@@ -16,15 +16,18 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Curve25519.KeyAgreement {
static var keyByteCount: Int {
return 32
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Curve25519 {
/// A mechanism used to create a shared secret between two users by
/// performing X25519 key agreement.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum KeyAgreement {
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
typealias Curve25519PrivateKeyImpl = Curve25519.KeyAgreement.CoreCryptoCurve25519PrivateKeyImpl
@@ -35,6 +38,7 @@ extension Curve25519 {
#endif
/// A Curve25519 public key used for key agreement.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct PublicKey: ECPublicKey {
fileprivate var baseKey: Curve25519PublicKeyImpl
@@ -68,6 +72,7 @@ extension Curve25519 {
}
/// A Curve25519 private key used for key agreement.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct PrivateKey: DiffieHellmanKeyAgreement {
fileprivate var baseKey: Curve25519PrivateKeyImpl
@@ -23,6 +23,7 @@ import Foundation
/// standard key sizes, like ``bits128``, ``bits192``, or ``bits256``. When you
/// need a key with a non-standard length, use the ``init(bitCount:)``
/// initializer to create a `SymmetricKeySize` instance with a custom bit count.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct SymmetricKeySize {
/// The number of bits in the key.
public let bitCount: Int
@@ -63,6 +64,7 @@ public struct SymmetricKeySize {
/// symmetric key to compute a message authentication code like ``HMAC``, or to
/// open and close a sealed box (``ChaChaPoly/SealedBox`` or
/// ``AES/GCM/SealedBox``) using a cipher like ``ChaChaPoly`` or ``AES``.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct SymmetricKey: ContiguousBytes {
let sb: SecureBytes
@@ -122,6 +124,7 @@ public struct SymmetricKey: ContiguousBytes {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SymmetricKey: Equatable {
public static func == (lhs: Self, rhs: Self) -> Bool {
return safeCompare(lhs, rhs)
@@ -29,6 +29,7 @@ import Foundation
/// need to encrypt the data as well as authenticate it, use a cipher like
/// ``AES`` or ``ChaChaPoly`` to put the data into a sealed box (an instance of
/// ``AES/GCM/SealedBox`` or ``ChaChaPoly/SealedBox``).
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct HMAC<H: HashFunction>: MACAlgorithm {
/// An alias for the symmetric key type used to compute or verify a message
/// authentication code.
@@ -193,6 +194,7 @@ public struct HMAC<H: HashFunction>: MACAlgorithm {
}
/// A hash-based message authentication code.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct HashedAuthenticationCode<H: HashFunction>: MessageAuthenticationCode {
let digest: H.Digest
@@ -16,6 +16,7 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol MACAlgorithm {
associatedtype Key
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@@ -40,6 +41,7 @@ protocol MACAlgorithm {
func finalize() -> MAC
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension MACAlgorithm {
/// Computes a Message Authentication Code.
///
@@ -17,11 +17,13 @@
import Foundation
/// A type that represents a message authentication code.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public protocol MessageAuthenticationCode: Hashable, ContiguousBytes, CustomStringConvertible, Sequence where Element == UInt8 {
/// The number of bytes in the message authentication code.
var byteCount: Int { get }
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension MessageAuthenticationCode {
/// Returns a Boolean value indicating whether two message authentication
/// codes are equal.
+2
View File
@@ -15,10 +15,12 @@
@_exported import CryptoKit
#else
/// A container for Advanced Encryption Standard (AES) ciphers.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum AES {
static let blockSizeByteCount = 16
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension AES {
static func isValidKey(_ key: SymmetricKey) -> Bool {
switch key.bitCount {
@@ -20,6 +20,7 @@ import CryptoBoringWrapper
import Foundation
/// A wrapper around BoringSSL's ECDSA_SIG with some lifetime management.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
class ECDSASignature {
private var _baseSig: UnsafeMutablePointer<ECDSA_SIG>
@@ -18,6 +18,7 @@
import CryptoBoringWrapper
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Data {
init<D: DataProtocol, Curve: OpenSSLSupportedNISTCurve>(
derSignature derBytes: D,
@@ -58,6 +59,7 @@ extension Data {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P256.Signing.ECDSASignature {
init<D: DataProtocol>(openSSLDERSignature derRepresentation: D) throws {
self.rawRepresentation = try Data(derSignature: derRepresentation, over: P256.self)
@@ -68,6 +70,7 @@ extension P256.Signing.ECDSASignature {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P256.Signing.PrivateKey {
func openSSLSignature<D: Digest>(for digest: D) throws -> P256.Signing.ECDSASignature {
let baseSignature = try self.impl.key.sign(digest: digest)
@@ -75,6 +78,7 @@ extension P256.Signing.PrivateKey {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P256.Signing.PublicKey {
func openSSLIsValidSignature<D: Digest>(
_ signature: P256.Signing.ECDSASignature,
@@ -92,6 +96,7 @@ extension P256.Signing.PublicKey {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P384.Signing.ECDSASignature {
init<D: DataProtocol>(openSSLDERSignature derRepresentation: D) throws {
self.rawRepresentation = try Data(derSignature: derRepresentation, over: P384.self)
@@ -102,6 +107,7 @@ extension P384.Signing.ECDSASignature {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P384.Signing.PrivateKey {
func openSSLSignature<D: Digest>(for digest: D) throws -> P384.Signing.ECDSASignature {
let baseSignature = try self.impl.key.sign(digest: digest)
@@ -109,6 +115,7 @@ extension P384.Signing.PrivateKey {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P384.Signing.PublicKey {
func openSSLIsValidSignature<D: Digest>(
_ signature: P384.Signing.ECDSASignature,
@@ -126,6 +133,7 @@ extension P384.Signing.PublicKey {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P521.Signing.ECDSASignature {
init<D: DataProtocol>(openSSLDERSignature derRepresentation: D) throws {
self.rawRepresentation = try Data(derSignature: derRepresentation, over: P521.self)
@@ -136,6 +144,7 @@ extension P521.Signing.ECDSASignature {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P521.Signing.PrivateKey {
func openSSLSignature<D: Digest>(for digest: D) throws -> P521.Signing.ECDSASignature {
let baseSignature = try self.impl.key.sign(digest: digest)
@@ -143,6 +152,7 @@ extension P521.Signing.PrivateKey {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P521.Signing.PublicKey {
func openSSLIsValidSignature<D: Digest>(
_ signature: P521.Signing.ECDSASignature,
@@ -18,6 +18,7 @@
@_implementationOnly import CCryptoBoringSSLShims
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Curve25519.Signing.PublicKey {
// We do this to enable inlinability on these methods.
@usableFromInline
@@ -96,6 +97,7 @@ extension Curve25519.Signing.PublicKey {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Curve25519.Signing.PrivateKey {
@inlinable
func openSSLSignature<D: DataProtocol>(for data: D) throws -> Data {
+20
View File
@@ -19,6 +19,7 @@ import Foundation
// any edits of this file WILL be overwritten and thus discarded
// see section `gyb` in `README` for details.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol NISTECDSASignature {
init<D: DataProtocol>(rawRepresentation: D) throws
init<D: DataProtocol>(derRepresentation: D) throws
@@ -26,6 +27,7 @@ protocol NISTECDSASignature {
var rawRepresentation: Data { get }
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol NISTSigning {
associatedtype PublicKey: NISTECPublicKey & DataValidator & DigestValidator
associatedtype PrivateKey: NISTECPrivateKey & Signer
@@ -33,9 +35,11 @@ protocol NISTSigning {
}
// MARK: - P256 + Signing
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P256.Signing {
/// A P-256 elliptic curve digital signature algorithm (ECDSA) signature.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct ECDSASignature: ContiguousBytes, NISTECDSASignature {
/// A raw data representation of a P-256 digital signature.
@@ -130,6 +134,7 @@ extension P256.Signing {
extension P256.Signing: NISTSigning {}
// MARK: - P256 + PrivateKey
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P256.Signing.PrivateKey: DigestSigner {
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
/// signature of the digest you provide over the P-256 elliptic curve.
@@ -148,6 +153,7 @@ extension P256.Signing.PrivateKey: DigestSigner {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P256.Signing.PrivateKey: Signer {
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
/// signature of the data you provide over the P-256 elliptic curve,
@@ -163,6 +169,7 @@ extension P256.Signing.PrivateKey: Signer {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P256.Signing.PublicKey: DigestValidator {
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
/// signature on a digest over the P-256 elliptic curve.
@@ -181,6 +188,7 @@ extension P256.Signing.PublicKey: DigestValidator {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P256.Signing.PublicKey: DataValidator {
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
/// signature on a block of data over the P-256 elliptic curve.
@@ -196,9 +204,11 @@ extension P256.Signing.PublicKey: DataValidator {
}
// MARK: - P384 + Signing
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P384.Signing {
/// A P-384 elliptic curve digital signature algorithm (ECDSA) signature.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct ECDSASignature: ContiguousBytes, NISTECDSASignature {
/// A raw data representation of a P-384 digital signature.
@@ -293,6 +303,7 @@ extension P384.Signing {
extension P384.Signing: NISTSigning {}
// MARK: - P384 + PrivateKey
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P384.Signing.PrivateKey: DigestSigner {
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
/// signature of the digest you provide over the P-384 elliptic curve.
@@ -311,6 +322,7 @@ extension P384.Signing.PrivateKey: DigestSigner {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P384.Signing.PrivateKey: Signer {
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
/// signature of the data you provide over the P-384 elliptic curve,
@@ -326,6 +338,7 @@ extension P384.Signing.PrivateKey: Signer {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P384.Signing.PublicKey: DigestValidator {
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
/// signature on a digest over the P-384 elliptic curve.
@@ -344,6 +357,7 @@ extension P384.Signing.PublicKey: DigestValidator {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P384.Signing.PublicKey: DataValidator {
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
/// signature on a block of data over the P-384 elliptic curve.
@@ -359,9 +373,11 @@ extension P384.Signing.PublicKey: DataValidator {
}
// MARK: - P521 + Signing
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P521.Signing {
/// A P-521 elliptic curve digital signature algorithm (ECDSA) signature.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct ECDSASignature: ContiguousBytes, NISTECDSASignature {
/// A raw data representation of a P-521 digital signature.
@@ -456,6 +472,7 @@ extension P521.Signing {
extension P521.Signing: NISTSigning {}
// MARK: - P521 + PrivateKey
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P521.Signing.PrivateKey: DigestSigner {
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
/// signature of the digest you provide over the P-521 elliptic curve.
@@ -474,6 +491,7 @@ extension P521.Signing.PrivateKey: DigestSigner {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P521.Signing.PrivateKey: Signer {
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
/// signature of the data you provide over the P-521 elliptic curve,
@@ -489,6 +507,7 @@ extension P521.Signing.PrivateKey: Signer {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P521.Signing.PublicKey: DigestValidator {
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
/// signature on a digest over the P-521 elliptic curve.
@@ -507,6 +526,7 @@ extension P521.Signing.PublicKey: DigestValidator {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension P521.Signing.PublicKey: DataValidator {
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
/// signature on a block of data over the P-521 elliptic curve.
+5
View File
@@ -16,22 +16,26 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol DigestValidator {
associatedtype Signature
func isValidSignature<D: Digest>(_ signature: Signature, for digest: D) -> Bool
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol DataValidator {
associatedtype Signature
func isValidSignature<D: DataProtocol>(_ signature: Signature, for signedData: D) -> Bool
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Curve25519.Signing {
static var signatureByteCount: Int {
return 64
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Curve25519.Signing.PublicKey: DataValidator {
typealias Signature = Data
@@ -52,6 +56,7 @@ extension Curve25519.Signing.PublicKey: DataValidator {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Curve25519.Signing.PrivateKey: Signer {
/// Generates an EdDSA signature over Curve25519.
///
@@ -16,15 +16,18 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol SignatureVerification {
func verifySignature(signature: Data, data: Data) throws -> Bool
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol DigestSigner {
associatedtype Signature
func signature<D: Digest>(for digest: D) throws -> Signature
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol Signer {
associatedtype Signature
func signature<D: DataProtocol>(for data: D) throws -> Signature
@@ -16,6 +16,7 @@
#else
@_implementationOnly import CCryptoBoringSSL
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension CryptoKitError {
/// A helper function that packs the value of `ERR_get_error` into the internal error field.
@usableFromInline
@@ -15,6 +15,7 @@
@_exported import CryptoKit
#else
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension UnsafeMutableRawBufferPointer {
func initializeWithRandomBytes(count: Int) {
guard count > 0 else {
@@ -16,6 +16,7 @@ import Foundation
/// This function performs a safe comparison between two buffers of bytes. It exists as a temporary shim until we refactor
/// some of the usage sites to pass better data structures to us.
@inlinable
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal func openSSLSafeCompare<LHS: ContiguousBytes, RHS: ContiguousBytes>(
_ lhs: LHS,
_ rhs: RHS
@@ -31,6 +32,7 @@ internal func openSSLSafeCompare<LHS: ContiguousBytes, RHS: ContiguousBytes>(
/// A straightforward constant-time comparison function for any two collections of bytes.
@inlinable
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal func constantTimeCompare<LHS: Collection, RHS: Collection>(_ lhs: LHS, _ rhs: RHS) -> Bool
where LHS.Element == UInt8, RHS.Element == UInt8 {
guard lhs.count == rhs.count else {
@@ -14,6 +14,7 @@
#if !canImport(Darwin)
@_implementationOnly import CCryptoBoringSSL
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
typealias errno_t = CInt
// This is a Swift wrapper for the libc function that does not exist on Linux. We shim it via a call to OPENSSL_cleanse.
+9
View File
@@ -13,18 +13,23 @@
//===----------------------------------------------------------------------===//
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
enum ByteHexEncodingErrors: Error {
case incorrectHexValue
case incorrectString
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
let charA = UInt8(UnicodeScalar("a").value)
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
let char0 = UInt8(UnicodeScalar("0").value)
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
private func itoh(_ value: UInt8) -> UInt8 {
return (value > 9) ? (charA + value - 10) : (char0 + value)
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
private func htoi(_ value: UInt8) throws -> UInt8 {
switch value {
case char0...char0 + 9:
@@ -36,6 +41,7 @@ private func htoi(_ value: UInt8) throws -> UInt8 {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension DataProtocol {
var hexString: String {
let hexLen = self.count * 2
@@ -54,12 +60,14 @@ extension DataProtocol {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension MutableDataProtocol {
mutating func appendByte(_ byte: UInt64) {
withUnsafePointer(to: byte.littleEndian, { self.append(contentsOf: UnsafeRawBufferPointer(start: $0, count: 8)) })
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Data {
init(hexString: String) throws {
self.init()
@@ -79,6 +87,7 @@ extension Data {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Array where Element == UInt8 {
init(hexString: String) throws {
self.init()
+1
View File
@@ -16,6 +16,7 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal func safeCompare<LHS: ContiguousBytes, RHS: ContiguousBytes>(_ lhs: LHS, _ rhs: RHS) -> Bool {
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
return coreCryptoSafeCompare(lhs, rhs)
+19
View File
@@ -16,8 +16,10 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
private let emptyStorage:SecureBytes.Backing = SecureBytes.Backing.createEmpty()
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct SecureBytes {
@usableFromInline
var backing: Backing
@@ -55,6 +57,7 @@ struct SecureBytes {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SecureBytes {
@inlinable
mutating func append<C: Collection>(_ data: C) where C.Element == UInt8 {
@@ -80,6 +83,7 @@ extension SecureBytes {
}
// MARK: - Equatable conformance, constant-time
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SecureBytes: Equatable {
public static func == (lhs: SecureBytes, rhs: SecureBytes) -> Bool {
return safeCompare(lhs, rhs)
@@ -87,8 +91,10 @@ extension SecureBytes: Equatable {
}
// MARK: - Collection conformance
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SecureBytes: Collection {
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct Index {
/* fileprivate but usableFromInline */ @usableFromInline var offset: Int
@@ -129,6 +135,7 @@ extension SecureBytes: Collection {
}
// MARK: - BidirectionalCollection conformance
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SecureBytes: BidirectionalCollection {
@inlinable
func index(before index: Index) -> Index {
@@ -143,6 +150,7 @@ extension SecureBytes: RandomAccessCollection { }
extension SecureBytes: MutableCollection { }
// MARK: - RangeReplaceableCollection conformance
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SecureBytes: RangeReplaceableCollection {
@inlinable
mutating func replaceSubrange<C: Collection>(_ subrange: Range<Index>, with newElements: C) where C.Element == UInt8 {
@@ -184,6 +192,7 @@ extension SecureBytes: RangeReplaceableCollection {
}
// MARK: - ContiguousBytes conformance
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SecureBytes: ContiguousBytes {
@inlinable
func withUnsafeBytes<T>(_ body: (UnsafeRawBufferPointer) throws -> T) rethrows -> T {
@@ -206,6 +215,7 @@ extension SecureBytes: ContiguousBytes {
}
// MARK: - DataProtocol conformance
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SecureBytes: DataProtocol {
@inlinable
var regions: CollectionOfOne<SecureBytes> {
@@ -219,12 +229,14 @@ extension SecureBytes: MutableDataProtocol { }
// MARK: - Index conformances
extension SecureBytes.Index: Hashable { }
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SecureBytes.Index: Comparable {
static func <(lhs: SecureBytes.Index, rhs: SecureBytes.Index) -> Bool {
return lhs.offset < rhs.offset
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SecureBytes.Index: Strideable {
func advanced(by n: Int) -> SecureBytes.Index {
return SecureBytes.Index(offset: self.offset + n)
@@ -236,8 +248,10 @@ extension SecureBytes.Index: Strideable {
}
// MARK: - Heap allocated backing storage.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SecureBytes {
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal struct BackingHeader {
@usableFromInline
internal var count: Int
@@ -247,6 +261,7 @@ extension SecureBytes {
}
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal class Backing: ManagedBuffer<BackingHeader, UInt8> {
@usableFromInline
@@ -322,6 +337,7 @@ extension SecureBytes {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SecureBytes.Backing {
func replaceSubrangeFittingWithinCapacity<C: Collection>(_ subrange: Range<Int>, with newElements: C) where C.Element == UInt8 {
// This function is called when have a unique reference to the backing storage, and we have enough room to store these bytes without
@@ -419,6 +435,7 @@ extension SecureBytes.Backing {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SecureBytes.Backing: ContiguousBytes {
func withUnsafeBytes<T>(_ body: (UnsafeRawBufferPointer) throws -> T) rethrows -> T {
let count = self.count
@@ -455,6 +472,7 @@ extension SecureBytes.Backing: ContiguousBytes {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension UInt32 {
/// Returns the next power of two unless that would overflow, in which case UInt32.max (on 64-bit systems) or
/// Int32.max (on 32-bit systems) is returned. The returned value is always safe to be cast to Int and passed
@@ -488,6 +506,7 @@ extension UInt32 {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Data {
/// A custom initializer for Data that attempts to share the same storage as the current SecureBytes instance.
/// This is our best-effort attempt to expose the data in an auto-zeroing fashion. Any mutating function called on
+5
View File
@@ -16,10 +16,12 @@
#else
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
protocol Zeroization {
mutating func zeroize()
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension UnsafeMutablePointer: Zeroization {
/// Zeroizes the pointee
func zeroize() {
@@ -28,12 +30,14 @@ extension UnsafeMutablePointer: Zeroization {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension UnsafeMutableRawBufferPointer: Zeroization {
func zeroize() {
memset_s(self.baseAddress, self.count, 0, self.count)
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Array: Zeroization where Element == UInt8 {
/// Zeroizes the array
mutating func zeroize() {
@@ -41,6 +45,7 @@ extension Array: Zeroization where Element == UInt8 {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Data: Zeroization {
internal mutating func zeroize() {
_ = self.withUnsafeMutableBytes {
@@ -17,6 +17,7 @@
import Foundation
/// An abstraction over a BoringSSL AEAD
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum BoringSSLAEAD {
/// The supported AEAD ciphers for BoringSSL.
case aes128gcm
@@ -27,9 +28,11 @@ public enum BoringSSLAEAD {
case chacha20
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
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, *)
public class AEADContext {
private var context: EVP_AEAD_CTX
@@ -65,6 +68,7 @@ extension BoringSSLAEAD {
// MARK: - Sealing
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension BoringSSLAEAD.AEADContext {
/// The main entry point for sealing data. Covers the full gamut of types, including discontiguous data types. This must be inlinable.
public func seal<
@@ -198,6 +202,7 @@ extension BoringSSLAEAD.AEADContext {
// MARK: - Opening
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension BoringSSLAEAD.AEADContext {
/// The main entry point for opening data. Covers the full gamut of types, including discontiguous data types. This must be inlinable.
@inlinable
@@ -398,6 +403,7 @@ extension BoringSSLAEAD.AEADContext {
// MARK: - Supported ciphers
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension BoringSSLAEAD {
var boringSSLCipher: OpaquePointer {
switch self {
+2 -1
View File
@@ -19,7 +19,8 @@ add_library(CryptoBoringWrapper STATIC
"EC/EllipticCurvePoint.swift"
"Util/ArbitraryPrecisionInteger.swift"
"Util/FiniteFieldArithmeticContext.swift"
"Util/RandomBytes.swift")
"Util/RandomBytes.swift"
)
target_include_directories(CryptoBoringWrapper PUBLIC
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
@@ -14,6 +14,7 @@
@_implementationOnly import CCryptoBoringSSL
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum CryptoBoringWrapperError: Error {
/// The key size is incorrect.
case incorrectKeySize
@@ -32,6 +33,7 @@ public enum CryptoBoringWrapperError: Error {
case invalidParameter
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension CryptoBoringWrapperError {
/// A helper function that packs the value of `ERR_get_error` into the internal error field.
@usableFromInline
@@ -16,6 +16,7 @@
/// A wrapper around BoringSSL's EC_GROUP object that handles reference counting and
/// liveness.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
package final class BoringSSLEllipticCurveGroup {
@usableFromInline var _group: OpaquePointer
@@ -35,6 +36,7 @@ package final class BoringSSLEllipticCurveGroup {
// MARK: - Helpers
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension BoringSSLEllipticCurveGroup {
@usableFromInline
package var coordinateByteCount: Int {
@@ -108,8 +110,10 @@ extension BoringSSLEllipticCurveGroup {
// MARK: - CurveName
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension BoringSSLEllipticCurveGroup {
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
package enum CurveName {
case p256
case p384
@@ -131,6 +135,7 @@ extension BoringSSLEllipticCurveGroup {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension BoringSSLEllipticCurveGroup.CurveName {
@usableFromInline
var baseNID: CInt {
@@ -19,6 +19,7 @@ import struct Foundation.Data
/// A wrapper around BoringSSL's EC_POINT with some lifetime management.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
package final class EllipticCurvePoint {
@usableFromInline var _basePoint: OpaquePointer
@@ -363,6 +364,7 @@ package final class EllipticCurvePoint {
// MARK: - Helpers
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension EllipticCurvePoint {
@inlinable
package func withPointPointer<T>(_ body: (OpaquePointer) throws -> T) rethrows -> T {
@@ -21,6 +21,7 @@ import Foundation
/// A wrapper around the OpenSSL BIGNUM object that is appropriately lifetime managed,
/// and that provides better Swift types for this object.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
package struct ArbitraryPrecisionInteger {
private var _backing: BackingStorage
@@ -46,7 +47,9 @@ package struct ArbitraryPrecisionInteger {
// MARK: - BackingStorage
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArbitraryPrecisionInteger {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
fileprivate final class BackingStorage {
private var _backing: BIGNUM
@@ -90,6 +93,7 @@ extension ArbitraryPrecisionInteger {
// MARK: - Extra initializers
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArbitraryPrecisionInteger {
@usableFromInline
package init<Bytes: ContiguousBytes>(bytes: Bytes) throws {
@@ -105,6 +109,7 @@ extension ArbitraryPrecisionInteger {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArbitraryPrecisionInteger.BackingStorage {
convenience init<Bytes: ContiguousBytes>(bytes: Bytes) throws {
self.init()
@@ -141,6 +146,7 @@ extension ArbitraryPrecisionInteger.BackingStorage {
// MARK: - Pointer helpers
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArbitraryPrecisionInteger {
package func withUnsafeBignumPointer<T>(
_ body: (UnsafePointer<BIGNUM>) throws -> T
@@ -162,6 +168,7 @@ extension ArbitraryPrecisionInteger {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArbitraryPrecisionInteger.BackingStorage {
func withUnsafeBignumPointer<T>(_ body: (UnsafePointer<BIGNUM>) throws -> T) rethrows -> T {
try body(&self._backing)
@@ -178,6 +185,7 @@ extension ArbitraryPrecisionInteger.BackingStorage {
// MARK: - Other helpers
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArbitraryPrecisionInteger {
@usableFromInline static func _compare(
lhs: ArbitraryPrecisionInteger,
@@ -250,6 +258,7 @@ extension ArbitraryPrecisionInteger {
// MARK: - Equatable
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArbitraryPrecisionInteger: Equatable {
@inlinable
package static func == (lhs: ArbitraryPrecisionInteger, rhs: ArbitraryPrecisionInteger) -> Bool {
@@ -259,6 +268,7 @@ extension ArbitraryPrecisionInteger: Equatable {
// MARK: - Comparable
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArbitraryPrecisionInteger: Comparable {
@inlinable
package static func < (lhs: ArbitraryPrecisionInteger, rhs: ArbitraryPrecisionInteger) -> Bool {
@@ -283,10 +293,12 @@ extension ArbitraryPrecisionInteger: Comparable {
// MARK: - ExpressibleByIntegerLiteral
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArbitraryPrecisionInteger: ExpressibleByIntegerLiteral {}
// MARK: - AdditiveArithmetic
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArbitraryPrecisionInteger: AdditiveArithmetic {
@inlinable
package static var zero: ArbitraryPrecisionInteger {
@@ -358,6 +370,7 @@ extension ArbitraryPrecisionInteger: AdditiveArithmetic {
// MARK: - Numeric
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArbitraryPrecisionInteger: Numeric {
@usableFromInline
package typealias Magnitude = Self
@@ -420,6 +433,7 @@ extension ArbitraryPrecisionInteger: Numeric {
// MARK: - Modular arithmetic
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArbitraryPrecisionInteger {
@usableFromInline
package func modulo(
@@ -549,6 +563,7 @@ extension ArbitraryPrecisionInteger {
// MARK: - SignedNumeric
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArbitraryPrecisionInteger: SignedNumeric {
@usableFromInline
package mutating func negate() {
@@ -562,6 +577,7 @@ extension ArbitraryPrecisionInteger: SignedNumeric {
// MARK: - Other arithmetic operations
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArbitraryPrecisionInteger {
@usableFromInline
package var trailingZeroBitCount: Int32 {
@@ -671,6 +687,7 @@ extension ArbitraryPrecisionInteger {
// MARK: - Serializing
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Data {
/// Serializes an ArbitraryPrecisionInteger padded out to a certain minimum size.
@usableFromInline
@@ -709,6 +726,7 @@ extension Data {
// MARK: - Printing
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension ArbitraryPrecisionInteger: CustomDebugStringConvertible {
@usableFromInline
package var debugDescription: String {
@@ -29,6 +29,7 @@ import Foundation
/// Annoyingly, because of the way we have implemented ArbitraryPrecisionInteger, we can't actually use these temporary bignums
/// ourselves.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
package class FiniteFieldArithmeticContext {
private var fieldSize: ArbitraryPrecisionInteger
private var bnCtx: OpaquePointer
@@ -51,6 +52,7 @@ package class FiniteFieldArithmeticContext {
// MARK: - Arithmetic operations
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension FiniteFieldArithmeticContext {
@usableFromInline
package func residue(_ x: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
@@ -12,6 +12,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension UnsafeMutableRawBufferPointer {
@inlinable
package func initializeWithRandomBytes(count: Int) {
@@ -44,6 +45,7 @@ extension UnsafeMutableRawBufferPointer {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension SystemRandomNumberGenerator {
@inlinable
package static func randomBytes(count: Int) -> [UInt8] {
+5
View File
@@ -15,9 +15,11 @@
import Crypto
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension AES {
/// The Advanced Encryption Standard (AES) Cipher Block Chaining (CBC) cipher
/// suite.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum _CBC {
private static var blockSize: Int { 16 }
@@ -141,8 +143,10 @@ extension AES {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension AES._CBC {
/// An initialization vector.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct IV: Sendable {
// AES CBC uses a 128-bit IV.
var ivBytes: (
@@ -192,6 +196,7 @@ extension AES._CBC {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension Data {
fileprivate mutating func trimPadding() throws {
guard let paddingBytes = self.last else {
+5
View File
@@ -16,9 +16,12 @@ import Crypto
import Foundation
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
typealias AESCFBImpl = OpenSSLAESCFBImpl
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension AES {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum _CFB {
@inlinable
public static func encrypt<Plaintext: DataProtocol>(
@@ -42,7 +45,9 @@ extension AES {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension AES._CFB {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct IV: Sendable {
// AES CFB uses a 128-bit IV.
private var ivBytes: (UInt64, UInt64)
+5
View File
@@ -16,10 +16,13 @@ import Crypto
import Foundation
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
typealias AESCTRImpl = OpenSSLAESCTRImpl
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension AES {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum _CTR {
@inlinable
public static func encrypt<Plaintext: DataProtocol>(
@@ -43,7 +46,9 @@ extension AES {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension AES._CTR {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct Nonce: Sendable {
// AES CTR uses a 128-bit counter. It's most usual to use a 96-bit nonce
// and a 32-bit counter at the end, so we support that specific mode of
@@ -19,8 +19,10 @@ import CryptoBoringWrapper
import Foundation
/// Types associated with the AES GCM SIV algorithm
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension AES.GCM {
/// AES in GCM SIV mode with 128-bit tags.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public enum _SIV {
static let tagByteCount = 16
static let nonceByteCount = 12
@@ -80,7 +82,9 @@ extension AES.GCM {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension AES.GCM._SIV {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct Nonce: Sendable, ContiguousBytes, Sequence {
let bytes: Data
@@ -114,7 +118,9 @@ extension AES.GCM._SIV {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension AES.GCM._SIV {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct SealedBox: Sendable {
/// The combined representation ( nonce || ciphertext || tag)
public let combined: Data
@@ -18,6 +18,7 @@ import Crypto
import CryptoBoringWrapper
import Foundation
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension AES {
private static let blockSize = 128 / 8
@@ -78,6 +79,7 @@ extension AES {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
enum Permutation {
case forward
case backward
@@ -110,6 +112,7 @@ extension AES {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
struct Block {
private static var blockSize: Int { 16 }
@@ -204,6 +207,7 @@ extension AES {
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension AES.Block: RandomAccessCollection, MutableCollection {
var startIndex: Int {
0
Loaded 100 of 152 files, more files were not shown because too many files have changed in this diff. Show more