mirror of
https://github.com/apple/swift-crypto
synced 2026-11-22 04:30:39 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47d3869a72 | ||
|
|
c3d9fc8938 | ||
|
|
1ca42a1885 | ||
|
|
1b6b2e274e | ||
|
|
2d37b1192f | ||
|
|
c5b1d7f0cb | ||
|
|
476538ccb8 | ||
|
|
5ef6059b2b | ||
|
|
bb4ba815da |
No files matched your search
@@ -15,19 +15,19 @@ jobs:
|
||||
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
|
||||
with:
|
||||
linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_6_0_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_6_1_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_6_2_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_6_3_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_6_0_enabled: true
|
||||
windows_6_1_enabled: true
|
||||
windows_6_2_enabled: true
|
||||
windows_6_3_enabled: true
|
||||
windows_nightly_next_enabled: true
|
||||
windows_nightly_main_enabled: true
|
||||
windows_6_0_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_6_1_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_6_2_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_6_3_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
|
||||
@@ -35,9 +35,9 @@ jobs:
|
||||
name: Release builds
|
||||
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
|
||||
with:
|
||||
windows_6_0_enabled: true
|
||||
windows_6_1_enabled: true
|
||||
windows_6_2_enabled: true
|
||||
windows_6_3_enabled: true
|
||||
windows_nightly_next_enabled: true
|
||||
windows_nightly_main_enabled: true
|
||||
|
||||
|
||||
@@ -20,19 +20,19 @@ jobs:
|
||||
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
|
||||
with:
|
||||
linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_6_0_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_6_1_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_6_2_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_6_3_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_6_0_enabled: true
|
||||
windows_6_1_enabled: true
|
||||
windows_6_2_enabled: true
|
||||
windows_6_3_enabled: true
|
||||
windows_nightly_next_enabled: true
|
||||
windows_nightly_main_enabled: true
|
||||
windows_6_0_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_6_1_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_6_2_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_6_3_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
|
||||
@@ -40,9 +40,9 @@ jobs:
|
||||
name: Release builds
|
||||
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
|
||||
with:
|
||||
windows_6_0_enabled: true
|
||||
windows_6_1_enabled: true
|
||||
windows_6_2_enabled: true
|
||||
windows_6_3_enabled: true
|
||||
windows_nightly_next_enabled: true
|
||||
windows_nightly_main_enabled: true
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// swift-tools-version:5.10
|
||||
// swift-tools-version:6.1
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
// swift-tools-version:6.0
|
||||
// swift-tools-version:6.1
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
|
||||
@@ -31,10 +31,11 @@ When building Swift Crypto for use on an Apple platform where CryptoKit is alrea
|
||||
When building Swift Crypto for use on Linux or Windows, Swift Crypto builds substantially more code. In particular, we build:
|
||||
|
||||
1. A vendored copy of BoringSSL's libcrypto.
|
||||
2. The common API of Swift Crypto and CryptoKit.
|
||||
3. The backing implementation of this common API, which calls into BoringSSL.
|
||||
2. A vendored copy of XKCP's libXKCP.
|
||||
3. The common API of Swift Crypto and CryptoKit.
|
||||
4. The backing implementation of this common API, which calls into BoringSSL or XKCP.
|
||||
|
||||
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The backing BoringSSL-based implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIS predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL implementation of the library in your application, no matter the platform.
|
||||
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The BoringSSL/XKCP backing implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIs predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL/XKCP implementation of the library in your application, no matter the platform.
|
||||
|
||||
## Evolution
|
||||
|
||||
@@ -48,11 +49,11 @@ Note that Swift Crypto does not intend to support all possible cryptographic pri
|
||||
|
||||
### Code Organisation
|
||||
|
||||
Files in this repository are divided into two groups, based on whether they have a name that ends in `_boring` or are in a `BoringSSL` directory, or if they are not.
|
||||
Files in this repository are divided into two groups, based on whether they have a name that ends in `_boring`/`_xkcp` or are in a `BoringSSL`/`XKCP` directory, or if they are not.
|
||||
|
||||
Files that meet the above criteria are specific to the Swift Crypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or access a BoringSSL API, it needs to be marked this way.
|
||||
Files that meet the above criteria are specific to the Swift Crypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or `import CXKCP` or access a BoringSSL or XKCP API, it needs to be marked this way.
|
||||
|
||||
Files that do not have the `_boring` suffix are part of the public API of CryptoKit. Changing these requires passing a higher bar, as any change in these files must be accompanied by a change in CryptoKit itself.
|
||||
Files that do not have the `_boring` or `_xkcp` suffix are part of the public API of CryptoKit. Changing these requires passing a higher bar, as any change in these files must be accompanied by a change in CryptoKit itself.
|
||||
|
||||
## Contributing
|
||||
|
||||
@@ -146,3 +147,7 @@ To do so, please use the following dependency in your `Package.swift`:
|
||||
|
||||
Swift Crypto normally defers to the OS implementation of CryptoKit on macOS. Naturally, this makes developing Swift Crypto on macOS tricky. To get Swift Crypto to build the open source implementation on macOS, in `Package.swift`, change `let development = false` to `let development = true`, as this will force Swift Crypto to build its public API.
|
||||
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
This project contains source code from the BoringSSL and XKCP projects.
|
||||
@@ -102,6 +102,7 @@ add_library(Crypto
|
||||
"Util/BoringSSL/RNG_boring.swift"
|
||||
"Util/BoringSSL/SafeCompare_boring.swift"
|
||||
"Util/BoringSSL/Zeroization_boring.swift"
|
||||
"Util/BoringSSL/_CryptoModuleAnchor.swift"
|
||||
"Util/PrettyBytes.swift"
|
||||
"Util/SafeCompare.swift"
|
||||
"Util/SecureBytes.swift"
|
||||
|
||||
@@ -173,10 +173,10 @@ private final class DigestContext<H: BoringSSLBackedHashFunction> {
|
||||
private var context: H.Context
|
||||
|
||||
init() {
|
||||
guard let contex = H.initialize() else {
|
||||
guard let context = H.initialize() else {
|
||||
preconditionFailure("Unable to initialize digest state")
|
||||
}
|
||||
self.context = contex
|
||||
self.context = context
|
||||
}
|
||||
|
||||
init(copying original: DigestContext) {
|
||||
|
||||
@@ -236,7 +236,13 @@ extension OpenSSLXWingPrivateKeyImpl {
|
||||
}
|
||||
|
||||
func decapsulate(_ encapsulated: Data) throws -> SymmetricKey {
|
||||
try SymmetricKey(unsafeUninitializedCapacity: Int(XWING_SHARED_SECRET_BYTES)) { sharedSecretBytes, count in
|
||||
guard encapsulated.count == Int(XWING_CIPHERTEXT_BYTES) else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
return try SymmetricKey(unsafeUninitializedCapacity: Int(XWING_SHARED_SECRET_BYTES)) {
|
||||
sharedSecretBytes,
|
||||
count in
|
||||
try encapsulated.withUnsafeBytes { encapsulatedSecretBytes in
|
||||
let rc = CCryptoBoringSSL_XWING_decap(
|
||||
sharedSecretBytes.baseAddress,
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2024-2026 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// On Apple platforms the Crypto module re-exports CryptoKit and produces no
|
||||
// symbols of its own. When Xcode 26+ builds SPM packages as dynamic
|
||||
// frameworks (e.g. for test-target dependencies), an empty module generates a
|
||||
// framework directory with no Mach-O binary, causing a linker error.
|
||||
//
|
||||
// This symbol ensures at least one exported entry is always present in the
|
||||
// binary, regardless of how the package is linked.
|
||||
// See: https://github.com/apple/swift-crypto/issues/435
|
||||
|
||||
@usableFromInline
|
||||
internal func _cryptoModuleAnchor() {}
|
||||
@@ -14,8 +14,13 @@
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import protocol FoundationEssentials.ContiguousBytes
|
||||
import struct FoundationEssentials.Data
|
||||
#else
|
||||
import protocol Foundation.ContiguousBytes
|
||||
import struct Foundation.Data
|
||||
#endif
|
||||
|
||||
/// A wrapper around BoringSSL's EC_POINT with some lifetime management and value semantics.
|
||||
@usableFromInline
|
||||
|
||||
@@ -25,19 +25,6 @@ extension AES {
|
||||
/// suite.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public enum _CBC {
|
||||
private static var blockSize: Int { 16 }
|
||||
|
||||
private static func encryptBlockInPlace(
|
||||
_ plaintext: inout Block,
|
||||
priorCiphertextBlock: Block,
|
||||
using key: SymmetricKey
|
||||
) throws {
|
||||
assert([128, 192, 256].contains(key.bitCount))
|
||||
|
||||
plaintext ^= priorCiphertextBlock
|
||||
try AES.permute(&plaintext, key: key)
|
||||
}
|
||||
|
||||
/// Encrypts data using AES-CBC.
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -60,44 +47,7 @@ extension AES {
|
||||
///
|
||||
/// - Note: If `noPadding` is set to `true`, `plainText` has to be a multiple of the blockSize (16 bytes). Otherwise an error will be thrown.
|
||||
public static func encrypt<Plaintext: DataProtocol>(_ plaintext: Plaintext, using key: SymmetricKey, iv: AES._CBC.IV, noPadding: Bool) throws -> Data {
|
||||
guard [128, 192, 256].contains(key.bitCount) else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
let requiresFullPaddingBlock = (plaintext.count % AES._CBC.blockSize) == 0
|
||||
|
||||
if noPadding && !requiresFullPaddingBlock {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
var ciphertext = Data()
|
||||
ciphertext.reserveCapacity(plaintext.count + Self.blockSize) // Room for padding.
|
||||
|
||||
var previousBlock = Block(iv)
|
||||
var plaintext = plaintext[...]
|
||||
|
||||
while plaintext.count > 0 {
|
||||
var block = Block(blockBytes: plaintext.prefix(Self.blockSize))
|
||||
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
|
||||
ciphertext.append(contentsOf: block)
|
||||
previousBlock = block
|
||||
plaintext = plaintext.dropFirst(Self.blockSize)
|
||||
}
|
||||
|
||||
if requiresFullPaddingBlock && !noPadding {
|
||||
var block = Block.paddingBlock
|
||||
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
|
||||
ciphertext.append(contentsOf: block)
|
||||
}
|
||||
|
||||
return ciphertext
|
||||
}
|
||||
|
||||
private static func decryptBlockInPlace(_ ciphertext: inout Block, priorCiphertextBlock: Block, using key: SymmetricKey) throws {
|
||||
assert([128, 192, 256].contains(key.bitCount))
|
||||
|
||||
try AES.inversePermute(&ciphertext, key: key)
|
||||
ciphertext ^= priorCiphertextBlock
|
||||
try OpenSSLAESCBCImpl.encrypt(plaintext, using: key, iv: iv, noPadding: noPadding)
|
||||
}
|
||||
|
||||
/// Decrypts data using AES-CBC.
|
||||
@@ -120,29 +70,7 @@ extension AES {
|
||||
/// - noPadding: If this is set to `true`, padding won't be removed.
|
||||
/// - Returns: The decrypted message.
|
||||
public static func decrypt<Ciphertext: DataProtocol>(_ ciphertext: Ciphertext, using key: SymmetricKey, iv: AES._CBC.IV, noPadding: Bool) throws -> Data {
|
||||
guard [128, 192, 256].contains(key.bitCount) else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
var plaintext = Data()
|
||||
plaintext.reserveCapacity(ciphertext.count)
|
||||
|
||||
var previousBlock = Block(iv)
|
||||
var ciphertext = ciphertext[...]
|
||||
|
||||
while ciphertext.count > 0 {
|
||||
let ctBlock = Block(blockBytes: ciphertext.prefix(Self.blockSize))
|
||||
var block = ctBlock
|
||||
try Self.decryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
|
||||
plaintext.append(contentsOf: block)
|
||||
previousBlock = ctBlock
|
||||
ciphertext = ciphertext.dropFirst(Self.blockSize)
|
||||
}
|
||||
|
||||
if !noPadding {
|
||||
try plaintext.trimPadding()
|
||||
}
|
||||
return plaintext
|
||||
try OpenSSLAESCBCImpl.decrypt(ciphertext, using: key, iv: iv, noPadding: noPadding)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -194,7 +122,7 @@ extension AES._CBC {
|
||||
0, 0, 0, 0, 0, 0, 0, 0
|
||||
)
|
||||
|
||||
withUnsafeMutableBytes(of: &self.ivBytes) { bytesPtr in
|
||||
Swift.withUnsafeMutableBytes(of: &self.ivBytes) { bytesPtr in
|
||||
bytesPtr.copyBytes(from: ivBytes)
|
||||
}
|
||||
}
|
||||
@@ -205,24 +133,10 @@ extension AES._CBC {
|
||||
Array(unsafeRawBufferPointer).makeIterator()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Data {
|
||||
fileprivate mutating func trimPadding() throws {
|
||||
guard let paddingBytes = self.last else {
|
||||
// Degenerate case, empty string. This is forbidden:
|
||||
// we must always pad.
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
mutating func withUnsafeMutableBytes<ReturnType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
|
||||
return try Swift.withUnsafeMutableBytes(of: &self.ivBytes, body)
|
||||
}
|
||||
|
||||
guard paddingBytes > 0 &&
|
||||
self.count >= paddingBytes &&
|
||||
self.suffix(Int(paddingBytes)).allSatisfy({ $0 == paddingBytes }) else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
self = self.dropLast(Int(paddingBytes))
|
||||
}
|
||||
}
|
||||
@@ -118,8 +118,6 @@ extension AES {
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct Block {
|
||||
private static var blockSize: Int { 16 }
|
||||
|
||||
typealias BlockBytes = (
|
||||
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
|
||||
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8
|
||||
@@ -135,70 +133,9 @@ extension AES {
|
||||
)
|
||||
}
|
||||
|
||||
init(_ blockBytes: BlockBytes) {
|
||||
self.blockBytes = blockBytes
|
||||
}
|
||||
|
||||
init(_ iv: AES._CBC.IV) {
|
||||
self.blockBytes = iv.ivBytes
|
||||
}
|
||||
|
||||
init<BlockBytes: Collection>(blockBytes: BlockBytes) where BlockBytes.Element == UInt8 {
|
||||
// The block size is always 16. Pad out past there.
|
||||
precondition(blockBytes.count <= Self.blockSize)
|
||||
|
||||
self.blockBytes = (
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0
|
||||
)
|
||||
|
||||
Swift.withUnsafeMutableBytes(of: &self.blockBytes) { bytesPtr in
|
||||
bytesPtr.copyBytes(from: blockBytes)
|
||||
|
||||
// Early exit here.
|
||||
if blockBytes.count == Self.blockSize {
|
||||
return
|
||||
}
|
||||
|
||||
var remainingBytes = bytesPtr.dropFirst(blockBytes.count)
|
||||
let padByte = UInt8(remainingBytes.count)
|
||||
|
||||
for index in remainingBytes.indices {
|
||||
remainingBytes[index] = padByte
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static var paddingBlock: Block {
|
||||
// The padding block is a full block of value blocksize.
|
||||
let value = UInt8(truncatingIfNeeded: Self.blockSize)
|
||||
return Block((
|
||||
value, value, value, value, value, value, value, value,
|
||||
value, value, value, value, value, value, value, value
|
||||
))
|
||||
}
|
||||
|
||||
func withUnsafeBytes<ReturnType>(_ body: (UnsafeRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
|
||||
return try Swift.withUnsafeBytes(of: self.blockBytes, body)
|
||||
}
|
||||
|
||||
mutating func withUnsafeMutableBytes<ReturnType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
|
||||
return try Swift.withUnsafeMutableBytes(of: &self.blockBytes, body)
|
||||
}
|
||||
|
||||
static func ^= (lhs: inout Block, rhs: Block) {
|
||||
// Ideally we'd not use raw pointers for this.
|
||||
lhs.withUnsafeMutableBytes { lhsPtr in
|
||||
rhs.withUnsafeBytes { rhsPtr in
|
||||
assert(lhsPtr.count == Self.blockSize)
|
||||
assert(rhsPtr.count == Self.blockSize)
|
||||
|
||||
for index in 0..<Self.blockSize {
|
||||
lhsPtr[index] ^= rhsPtr[index]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static func isValidKey(_ key: SymmetricKey) -> Bool {
|
||||
@@ -210,52 +147,3 @@ extension AES {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension AES.Block: RandomAccessCollection, MutableCollection {
|
||||
var startIndex: Int {
|
||||
0
|
||||
}
|
||||
|
||||
var endIndex: Int {
|
||||
Self.blockSize
|
||||
}
|
||||
|
||||
subscript(position: Int) -> UInt8 {
|
||||
get {
|
||||
precondition(position >= 0)
|
||||
precondition(position < Self.blockSize)
|
||||
|
||||
return self.withUnsafeBytes { $0[position] }
|
||||
}
|
||||
|
||||
set {
|
||||
precondition(position >= 0)
|
||||
precondition(position < Self.blockSize)
|
||||
|
||||
self.withUnsafeMutableBytes { $0[position] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
func withContiguousStorageIfAvailable<ReturnValue>(
|
||||
_ body: (UnsafeBufferPointer<UInt8>) throws -> ReturnValue)
|
||||
rethrows -> ReturnValue? {
|
||||
return try withUnsafePointer(to: self.blockBytes) { tuplePtr in
|
||||
// Homogeneous tuples are always bound to the element type as well as to their own type.
|
||||
let retyped = UnsafeRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
|
||||
let bufferised = UnsafeBufferPointer(start: retyped, count: Self.blockSize)
|
||||
return try body(bufferised)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func withContiguousMutableStorageIfAvailable<ReturnValue>(
|
||||
_ body: (inout UnsafeMutableBufferPointer<UInt8>) throws -> ReturnValue)
|
||||
rethrows -> ReturnValue? {
|
||||
return try withUnsafeMutablePointer(to: &self.blockBytes) { tuplePtr in
|
||||
// Homogeneous tuples are always bound to the element type as well as to their own type.
|
||||
let retyped = UnsafeMutableRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
|
||||
var bufferised = UnsafeMutableBufferPointer(start: retyped, count: Self.blockSize)
|
||||
return try body(&bufferised)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
import Crypto
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
@usableFromInline
|
||||
enum OpenSSLAESCBCImpl {
|
||||
private static let blockSize = 16
|
||||
|
||||
@usableFromInline
|
||||
enum Direction {
|
||||
case encrypt
|
||||
case decrypt
|
||||
|
||||
@usableFromInline
|
||||
var _boringSSLParameter: Int32 {
|
||||
switch self {
|
||||
case .encrypt: AES_ENCRYPT
|
||||
case .decrypt: AES_DECRYPT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Encrypts plaintext using AES-CBC.
|
||||
///
|
||||
/// PKCS#7 padding is added unless `noPadding` is set, in which case the plaintext must
|
||||
/// already be a whole number of blocks.
|
||||
static func encrypt<Plaintext: DataProtocol>(
|
||||
_ plaintext: Plaintext,
|
||||
using key: SymmetricKey,
|
||||
iv: AES._CBC.IV,
|
||||
noPadding: Bool
|
||||
) throws -> Data {
|
||||
guard [128, 192, 256].contains(key.bitCount) else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
// With padding disabled the input must be a whole number of blocks.
|
||||
if noPadding && (plaintext.count % Self.blockSize != 0) {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
// AES_cbc_encrypt performs no padding, so PKCS#7 is applied here.
|
||||
var padded = Data(plaintext)
|
||||
if !noPadding {
|
||||
// PKCS#7 always appends 1...blockSize bytes (a full block when already aligned).
|
||||
let padLength = Self.blockSize - (plaintext.count % Self.blockSize)
|
||||
let padding = repeatElement(UInt8(padLength), count: padLength)
|
||||
padded.append(contentsOf: padding)
|
||||
}
|
||||
|
||||
return padded.withUnsafeBytes { plaintextPtr in
|
||||
Self._cipher(.encrypt, plaintextPtr, using: key, iv: iv)
|
||||
}
|
||||
}
|
||||
|
||||
/// Decrypts ciphertext using AES-CBC.
|
||||
///
|
||||
/// BoringSSL runs with padding disabled and, unless `noPadding` is set, PKCS#7 padding is
|
||||
/// removed here in constant time. BoringSSL's own PKCS#7 removal is not constant-time (it is a
|
||||
/// documented padding oracle absent authentication), so it must not be delegated.
|
||||
static func decrypt<Ciphertext: DataProtocol>(
|
||||
_ ciphertext: Ciphertext,
|
||||
using key: SymmetricKey,
|
||||
iv: AES._CBC.IV,
|
||||
noPadding: Bool
|
||||
) throws -> Data {
|
||||
guard [128, 192, 256].contains(key.bitCount) else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
// CBC ciphertext is always a whole number of non-empty blocks.
|
||||
guard ciphertext.count > 0, ciphertext.count % Self.blockSize == 0 else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
let contiguousCiphertext = Data(ciphertext)
|
||||
let plaintext = contiguousCiphertext.withUnsafeBytes { ciphertextPtr in
|
||||
Self._cipher(.decrypt, ciphertextPtr, using: key, iv: iv)
|
||||
}
|
||||
|
||||
return noPadding ? plaintext : try plaintext.removingPKCS7PaddingConstantTime(blockSize: Self.blockSize)
|
||||
}
|
||||
|
||||
/// Runs raw AES-CBC in the given direction over a single contiguous buffer.
|
||||
///
|
||||
/// `AES_cbc_encrypt` performs no padding, so `input` must be a whole number of blocks and the
|
||||
/// output has the same length. PKCS#7 is applied and removed by the callers.
|
||||
@usableFromInline
|
||||
static func _cipher(
|
||||
_ direction: Direction,
|
||||
_ input: UnsafeRawBufferPointer,
|
||||
using key: SymmetricKey,
|
||||
iv: AES._CBC.IV
|
||||
) -> Data {
|
||||
precondition(input.count % Self.blockSize == 0)
|
||||
|
||||
var output = Data(count: input.count)
|
||||
var iv = iv
|
||||
key.withUnsafeBytes { keyPtr in
|
||||
// AES_cbc_encrypt advances the IV in place, so operate on our own copy.
|
||||
iv.withUnsafeMutableBytes { ivPtr in
|
||||
var key = AES_KEY()
|
||||
switch direction {
|
||||
case .encrypt:
|
||||
precondition(
|
||||
CCryptoBoringSSL_AES_set_encrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key) == 0
|
||||
)
|
||||
case .decrypt:
|
||||
precondition(
|
||||
CCryptoBoringSSL_AES_set_decrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key) == 0
|
||||
)
|
||||
}
|
||||
output.withUnsafeMutableBytes { outputPtr in
|
||||
CCryptoBoringSSL_AES_cbc_encrypt(
|
||||
input.baseAddress,
|
||||
outputPtr.baseAddress,
|
||||
input.count,
|
||||
&key,
|
||||
ivPtr.baseAddress,
|
||||
direction._boringSSLParameter
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return output
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension Data {
|
||||
/// Removes PKCS#7 padding in constant time with respect to the padding bytes.
|
||||
fileprivate func removingPKCS7PaddingConstantTime(blockSize: Int = 16) throws -> Data {
|
||||
// The total length is not secret, so branching on it is safe.
|
||||
guard self.count >= blockSize, self.count % blockSize == 0 else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
let padLength = self.last!
|
||||
let lastBlock = self.suffix(blockSize)
|
||||
|
||||
// Validate padding in constant time.
|
||||
var bad: UInt32 = 0
|
||||
// A valid PKCS#7 pad length is 1...blockSize.
|
||||
bad |= constantTimeLessThanOrEqual(padLength, 0)
|
||||
bad |= constantTimeLessThanOrEqual(UInt8(blockSize + 1), padLength)
|
||||
// We MUST operate on every byte in the block, and each byte in the padding region MUST equal `padLength`.
|
||||
for index in lastBlock.indices {
|
||||
let byte = UInt32(lastBlock[index])
|
||||
let distanceFromEnd = self.endIndex - index
|
||||
let inPadding = constantTimeLessThanOrEqual(UInt8(distanceFromEnd), padLength)
|
||||
bad |= inPadding & (byte ^ UInt32(padLength))
|
||||
}
|
||||
|
||||
// Throw if padding was invalid.
|
||||
guard bad == 0 else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
// Drop the padding.
|
||||
return self.dropLast(Int(padLength))
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `0xFFFFFFFF` if `lhs <= rhs`, otherwise `0`, without a data-dependent branch.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
private func constantTimeLessThanOrEqual(_ lhs: UInt8, _ rhs: UInt8) -> UInt32 {
|
||||
// `lhs - rhs - 1` is negative iff `lhs <= rhs`; propagate its sign bit across the word.
|
||||
let difference = Int32(lhs) - Int32(rhs) - 1
|
||||
return UInt32(bitPattern: difference >> 31)
|
||||
}
|
||||
@@ -18,6 +18,7 @@ add_library(CryptoExtras
|
||||
"AES/AES_CTR.swift"
|
||||
"AES/AES_GCM_SIV.swift"
|
||||
"AES/Block Function.swift"
|
||||
"AES/BoringSSL/AES_CBC_boring.swift"
|
||||
"AES/BoringSSL/AES_CFB_boring.swift"
|
||||
"AES/BoringSSL/AES_CTR_boring.swift"
|
||||
"AES/BoringSSL/AES_GCM_SIV_boring.swift"
|
||||
@@ -33,6 +34,10 @@ add_library(CryptoExtras
|
||||
"ARC/ARCServer.swift"
|
||||
"ChaCha20CTR/BoringSSL/ChaCha20CTR_boring.swift"
|
||||
"ChaCha20CTR/ChaCha20CTR.swift"
|
||||
"Digests/BoringSSL/BoringSSLSHA512256Context.swift"
|
||||
"Digests/BoringSSL/BoringSSLSHA512256HashFunction.swift"
|
||||
"Digests/SHA512256.swift"
|
||||
"Digests/SHA512256Digest.swift"
|
||||
"EC/Curve25519+PEM.swift"
|
||||
"EC/ObjectIdentifier.swift"
|
||||
"EC/PKCS8DERRepresentation.swift"
|
||||
@@ -58,6 +63,7 @@ add_library(CryptoExtras
|
||||
"RSA/RSA.swift"
|
||||
"RSA/RSA_boring.swift"
|
||||
"Reexport.swift"
|
||||
"Util/BoringSSL/Zeroization_boring.swift"
|
||||
"Util/BoringSSLHelpers.swift"
|
||||
"Util/CryptoKitErrors_boring.swift"
|
||||
"Util/Data+Extensions.swift"
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
import Crypto
|
||||
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
final class BoringSSLSHA512256Context {
|
||||
private var context: SHA512_CTX
|
||||
|
||||
init() {
|
||||
guard let context = BoringSSLSHA512256HashFunction.initialize() else {
|
||||
preconditionFailure("Unable to initialize digest state")
|
||||
}
|
||||
self.context = context
|
||||
}
|
||||
|
||||
deinit {
|
||||
withUnsafeMutablePointer(to: &self.context) {
|
||||
$0.zeroize()
|
||||
}
|
||||
}
|
||||
|
||||
init(copying original: BoringSSLSHA512256Context) {
|
||||
self.context = original.context
|
||||
}
|
||||
|
||||
func update(bufferPointer data: UnsafeRawBufferPointer) {
|
||||
guard BoringSSLSHA512256HashFunction.update(&self.context, data: data) else {
|
||||
preconditionFailure("Unable to update digest state")
|
||||
}
|
||||
}
|
||||
|
||||
func finalize() -> SHA512256Digest {
|
||||
var copyContext = self.context
|
||||
defer {
|
||||
withUnsafeMutablePointer(to: ©Context) {
|
||||
$0.zeroize()
|
||||
}
|
||||
}
|
||||
return withUnsafeTemporaryAllocation(byteCount: BoringSSLSHA512256HashFunction.digestSize, alignment: 1) {
|
||||
digestPointer in
|
||||
defer {
|
||||
digestPointer.zeroize()
|
||||
}
|
||||
|
||||
guard BoringSSLSHA512256HashFunction.finalize(©Context, digest: digestPointer) else {
|
||||
preconditionFailure("Unable to finalize digest state")
|
||||
}
|
||||
// We force unwrap here because if the digest size is wrong it's an internal error.
|
||||
return SHA512256Digest(bufferPointer: UnsafeRawBufferPointer(digestPointer))!
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension UnsafeMutablePointer {
|
||||
fileprivate func zeroize() {
|
||||
let size = MemoryLayout.size(ofValue: Pointee.self)
|
||||
memset_s(self, size, 0, size)
|
||||
}
|
||||
}
|
||||
|
||||
extension UnsafeMutableRawBufferPointer {
|
||||
fileprivate func zeroize() {
|
||||
memset_s(self.baseAddress!, self.count, 0, self.count)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
import Crypto
|
||||
|
||||
struct BoringSSLSHA512256HashFunction {
|
||||
static var digestSize: Int {
|
||||
Int(SHA256_DIGEST_LENGTH)
|
||||
}
|
||||
|
||||
static func initialize() -> SHA512_CTX? {
|
||||
var context = SHA512_CTX()
|
||||
guard CCryptoBoringSSL_SHA512_256_Init(&context) == 1 else {
|
||||
return nil
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
static func update(_ context: inout SHA512_CTX, data: UnsafeRawBufferPointer) -> Bool {
|
||||
let result = CCryptoBoringSSL_SHA512_256_Update(&context, data.baseAddress, data.count)
|
||||
return result == 1
|
||||
}
|
||||
|
||||
static func finalize(_ context: inout SHA512_CTX, digest: UnsafeMutableRawBufferPointer) -> Bool {
|
||||
guard let baseAddress = digest.baseAddress, digest.count == Self.digestSize else {
|
||||
return false
|
||||
}
|
||||
let result = CCryptoBoringSSL_SHA512_256_Final(baseAddress, &context)
|
||||
return result == 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Crypto
|
||||
|
||||
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
||||
/// 256-bit digest using the SHA-512/256 variant.
|
||||
///
|
||||
/// The ``SHA512256`` hash implements the ``HashFunction`` protocol for the
|
||||
/// specific case of SHA-512/256 hashing with a 256-bit digest
|
||||
/// (``SHA512256Digest``). SHA-512/256 is a truncated variant of SHA-512 that
|
||||
/// provides the same security level as SHA-256 but can be faster on 64-bit
|
||||
/// platforms.
|
||||
///
|
||||
/// You can compute the digest by calling the static ``hash(data:)`` method
|
||||
/// once. Alternatively, if the data that you want to hash is too large to fit
|
||||
/// in memory, you can compute the digest iteratively by creating a new hash
|
||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||
/// data, and then calling the ``finalize()`` method to get the result.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA512256: HashFunction, @unchecked Sendable {
|
||||
/// The number of bytes that represents the hash function's internal state.
|
||||
public static var blockByteCount: Int {
|
||||
128
|
||||
}
|
||||
|
||||
private var context = BoringSSLSHA512256Context()
|
||||
|
||||
/// Creates a SHA512-256 hash function.
|
||||
///
|
||||
/// Initialize a new hash function by calling this method if you want to
|
||||
/// hash data iteratively, such as when you don't have a buffer large enough
|
||||
/// to hold all the data at once. Provide data blocks to the hash function
|
||||
/// using the ``update(data:)`` or ``update(bufferPointer:)`` method. After
|
||||
/// providing all the data, call ``finalize()`` to get the digest.
|
||||
///
|
||||
/// If your data fits into a single buffer, you can use the ``hash(data:)``
|
||||
/// method instead, to compute the digest in a single call.
|
||||
public init() {}
|
||||
|
||||
/// Incrementally updates the hash function with the contents of the buffer.
|
||||
///
|
||||
/// Call this method one or more times to provide data to the hash function
|
||||
/// in blocks. After providing the last block of data, call the
|
||||
/// ``finalize()`` method to get the computed digest. Don't call the update
|
||||
/// method again after finalizing the hash function.
|
||||
///
|
||||
/// - Note: Typically, it's safer to use an instance of
|
||||
/// <doc://com.apple.documentation/documentation/foundation/data>, or some
|
||||
/// other type that conforms to the
|
||||
/// <doc://com.apple.documentation/documentation/foundation/dataprotocol>,
|
||||
/// to hold your data. When possible, use the ``update(data:)`` method
|
||||
/// instead.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bufferPointer: A pointer to the next block of data for the ongoing
|
||||
/// digest calculation.
|
||||
public mutating func update(bufferPointer data: UnsafeRawBufferPointer) {
|
||||
if !isKnownUniquelyReferenced(&self.context) {
|
||||
self.context = BoringSSLSHA512256Context(copying: self.context)
|
||||
}
|
||||
self.context.update(bufferPointer: data)
|
||||
}
|
||||
|
||||
/// Finalizes the hash function and returns the computed digest.
|
||||
///
|
||||
/// Call this method after you provide the hash function with all the data
|
||||
/// to hash by making one or more calls to the ``update(data:)`` or
|
||||
/// ``update(bufferPointer:)`` method. After finalizing the hash function,
|
||||
/// discard it. To compute a new digest, create a new hash function with a
|
||||
/// call to the ``init()`` method.
|
||||
///
|
||||
/// - Returns: The computed digest of the data.
|
||||
public func finalize() -> SHA512256Digest {
|
||||
self.context.finalize()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 256-bit digest
|
||||
/// using the SHA-512/256 variant.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct SHA512256Digest: Digest {
|
||||
let bytes: (UInt64, UInt64, UInt64, UInt64)
|
||||
|
||||
/// The number of bytes in the digest.
|
||||
public static var byteCount: Int {
|
||||
32
|
||||
}
|
||||
|
||||
init?(bufferPointer: UnsafeRawBufferPointer) {
|
||||
guard bufferPointer.count == 32 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var bytes = (UInt64(0), UInt64(0), UInt64(0), UInt64(0))
|
||||
withUnsafeMutableBytes(of: &bytes) { targetPtr in
|
||||
targetPtr.copyBytes(from: bufferPointer)
|
||||
}
|
||||
self.bytes = bytes
|
||||
}
|
||||
|
||||
/// Invokes the given closure with a buffer pointer covering the raw bytes of
|
||||
/// the digest.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: A closure that takes a raw buffer pointer to the bytes of the digest
|
||||
/// and returns the digest.
|
||||
///
|
||||
/// - Returns: The digest, as returned from the body closure.
|
||||
#if !hasFeature(Embedded)
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
try Swift.withUnsafeBytes(of: bytes) {
|
||||
let boundsCheckedPtr = UnsafeRawBufferPointer(
|
||||
start: $0.baseAddress,
|
||||
count: Self.byteCount
|
||||
)
|
||||
return try body(boundsCheckedPtr)
|
||||
}
|
||||
}
|
||||
#else
|
||||
public func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
|
||||
try Swift.withUnsafeBytes(of: bytes) { ptr throws(E) -> R in
|
||||
let boundsCheckedPtr = UnsafeRawBufferPointer(
|
||||
start: ptr.baseAddress,
|
||||
count: Self.byteCount
|
||||
)
|
||||
return try body(boundsCheckedPtr)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private func toArray() -> ArraySlice<UInt8> {
|
||||
var array = [UInt8]()
|
||||
array.appendByte(bytes.0)
|
||||
array.appendByte(bytes.1)
|
||||
array.appendByte(bytes.2)
|
||||
array.appendByte(bytes.3)
|
||||
return array.prefix(SHA512256Digest.byteCount)
|
||||
}
|
||||
|
||||
#if !hasFeature(Embedded)
|
||||
/// A human-readable description of the digest.
|
||||
public var description: String {
|
||||
"SHA512-256 digest: \(toArray().hexString)"
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Hashes the essential components of the digest by feeding them into the
|
||||
/// given hash function.
|
||||
///
|
||||
/// This method is part of the digest’s conformance to Swift standard library’s
|
||||
/// <doc://com.apple.documentation/documentation/swift/hashable> protocol, making
|
||||
/// it possible to compare digests. Don’t confuse that hashing with the
|
||||
/// cryptographically secure hashing that you use to create the digest in the
|
||||
/// first place by, for example, calling ``SHA512256/hash(data:)``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - hasher: The hash function to use when combining the components of
|
||||
/// the digest.
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
self.withUnsafeBytes { hasher.combine(bytes: $0) }
|
||||
}
|
||||
}
|
||||
@@ -13,9 +13,14 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Crypto
|
||||
import Foundation
|
||||
import SwiftASN1
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *)
|
||||
extension Curve25519.Signing.PrivateKey {
|
||||
/// A Distinguished Encoding Rules (DER) encoded representation of the private key.
|
||||
|
||||
@@ -13,9 +13,14 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Crypto
|
||||
import Foundation
|
||||
import SwiftASN1
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *)
|
||||
extension Curve25519.Signing.PrivateKey {
|
||||
/// A Distinguished Encoding Rules (DER) encoded representation of the private key in PKCS#8 format.
|
||||
|
||||
@@ -222,17 +222,17 @@ extension BoringSSLRSAPublicKey {
|
||||
self.pointer = pointer
|
||||
}
|
||||
|
||||
fileprivate init(copying other: Backing) {
|
||||
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
|
||||
fileprivate convenience init(copying other: Backing) {
|
||||
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
|
||||
let rsaPublicKey = CCryptoBoringSSL_RSAPublicKey_dup(
|
||||
CCryptoBoringSSL_EVP_PKEY_get0_RSA(other.pointer)
|
||||
)
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
|
||||
}
|
||||
|
||||
fileprivate init(pemRepresentation: String) throws {
|
||||
fileprivate convenience init(pemRepresentation: String) throws {
|
||||
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
|
||||
var pemRepresentation = pemRepresentation
|
||||
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
|
||||
|
||||
// There are two encodings for RSA public keys: PKCS#1 and the SPKI form.
|
||||
// The SPKI form is what we support for EC keys, so we try that first, then we
|
||||
@@ -248,23 +248,19 @@ extension BoringSSLRSAPublicKey {
|
||||
}
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
|
||||
} catch {
|
||||
do {
|
||||
let rsaPublicKey = try pemRepresentation.withUTF8 { utf8Ptr in
|
||||
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
|
||||
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPublicKey(bio, nil, nil, nil) else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
return key
|
||||
let rsaPublicKey = try pemRepresentation.withUTF8 { utf8Ptr in
|
||||
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
|
||||
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPublicKey(bio, nil, nil, nil) else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
return key
|
||||
}
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
|
||||
} catch {
|
||||
CCryptoBoringSSL_EVP_PKEY_free(self.pointer)
|
||||
throw error
|
||||
}
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fileprivate convenience init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
|
||||
if derRepresentation.regions.count == 1 {
|
||||
try self.init(contiguousDerRepresentation: derRepresentation.regions.first!)
|
||||
@@ -274,8 +270,8 @@ extension BoringSSLRSAPublicKey {
|
||||
}
|
||||
}
|
||||
|
||||
private init<Bytes: ContiguousBytes>(contiguousDerRepresentation: Bytes) throws {
|
||||
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
|
||||
private convenience init<Bytes: ContiguousBytes>(contiguousDerRepresentation: Bytes) throws {
|
||||
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
|
||||
// There are two encodings for RSA public keys: PKCS#1 and the SPKI form.
|
||||
// The SPKI form is what we support for EC keys, so we try that first, then we
|
||||
// fall back to the PKCS#1 form if that parse fails.
|
||||
@@ -290,25 +286,20 @@ extension BoringSSLRSAPublicKey {
|
||||
}
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
|
||||
} catch {
|
||||
do {
|
||||
let rsaPublicKey = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
|
||||
try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
|
||||
guard let key = CCryptoBoringSSL_d2i_RSAPublicKey_bio(bio, nil) else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
return key
|
||||
let rsaPublicKey = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
|
||||
try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
|
||||
guard let key = CCryptoBoringSSL_d2i_RSAPublicKey_bio(bio, nil) else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
return key
|
||||
}
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
|
||||
} catch {
|
||||
CCryptoBoringSSL_EVP_PKEY_free(self.pointer)
|
||||
throw error
|
||||
}
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
|
||||
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
|
||||
fileprivate convenience init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
|
||||
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
|
||||
let n = try ArbitraryPrecisionInteger(bytes: n)
|
||||
let e = try ArbitraryPrecisionInteger(bytes: e)
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if !canImport(Darwin)
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
typealias errno_t = CInt
|
||||
|
||||
// This is a Swift wrapper for the libc function that does not exist on Linux. We shim it via a call to OPENSSL_cleanse.
|
||||
// We have the same syntax, but mostly ignore it.
|
||||
@discardableResult
|
||||
func memset_s(_ s: UnsafeMutableRawPointer!, _ smax: Int, _ byte: CInt, _ n: Int) -> errno_t {
|
||||
assert(smax == n, "memset_s invariant not met")
|
||||
assert(byte == 0, "memset_s used to not zero anything")
|
||||
CCryptoBoringSSL_OPENSSL_cleanse(s, smax)
|
||||
return 0
|
||||
}
|
||||
#endif
|
||||
@@ -163,6 +163,85 @@ final class CBCTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testDecryptRejectsPaddingLengthGreaterThanBlockSize() throws {
|
||||
// A plaintext whose final block claims a PKCS#7 pad length of 17 (0x11)
|
||||
// is invalid for a 16-byte block: the maximum valid PKCS#7 pad is one
|
||||
// full block (16). Correct unpadding must reject it. Regression guard:
|
||||
// the previous `trimPadding` accepted any pad length up to 255 and
|
||||
// scanned across blocks, so it wrongly stripped 17 bytes here.
|
||||
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
|
||||
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
|
||||
|
||||
// 32-byte (block-multiple) plaintext ending in 17 bytes of 0x11.
|
||||
var plaintext = Data(repeating: 0xAB, count: 15)
|
||||
plaintext.append(Data(repeating: 0x11, count: 17))
|
||||
precondition(plaintext.count == 32)
|
||||
|
||||
let ciphertext = try AES._CBC.encrypt(plaintext, using: key, iv: iv, noPadding: true)
|
||||
|
||||
XCTAssertThrowsError(
|
||||
try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false)
|
||||
) { error in
|
||||
guard let error = error as? CryptoKitError, case .incorrectParameterSize = error else {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testUnpadAcceptsAllValidPaddingLengths() throws {
|
||||
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
|
||||
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
|
||||
|
||||
// For every valid PKCS#7 pad length (1...16), round-trip a message that
|
||||
// pads to exactly that length and assert exact recovery.
|
||||
for padLength in 1...16 {
|
||||
let messageLength = 32 - padLength // pads to 32 bytes (two blocks)
|
||||
let message = Data((0..<messageLength).map { UInt8(truncatingIfNeeded: $0) })
|
||||
|
||||
let ciphertext = try AES._CBC.encrypt(message, using: key, iv: iv, noPadding: false)
|
||||
let decrypted = try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false)
|
||||
XCTAssertEqual(decrypted, message, "round-trip failed for pad length \(padLength)")
|
||||
}
|
||||
}
|
||||
|
||||
func testUnpadRejectsCorruptedPaddingByte() throws {
|
||||
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
|
||||
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
|
||||
|
||||
// Build a validly-padded block-multiple plaintext, then corrupt each
|
||||
// padding byte except the last (which encodes the claimed length). The
|
||||
// constant-time scan must reject a mismatch at any position.
|
||||
for padLength in 2...16 {
|
||||
var padded = Data((0..<(32 - padLength)).map { UInt8(truncatingIfNeeded: $0) })
|
||||
padded.append(Data(repeating: UInt8(padLength), count: padLength))
|
||||
precondition(padded.count == 32)
|
||||
|
||||
for position in (32 - padLength)..<31 {
|
||||
var corrupted = padded
|
||||
corrupted[position] = UInt8(padLength) ^ 0xFF // guaranteed != padLength
|
||||
let ciphertext = try AES._CBC.encrypt(corrupted, using: key, iv: iv, noPadding: true)
|
||||
|
||||
XCTAssertThrowsError(
|
||||
try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false),
|
||||
"corruption at pad length \(padLength), position \(position) was not rejected"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testUnpadRejectsZeroPaddingLength() throws {
|
||||
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
|
||||
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
|
||||
|
||||
// A final byte of 0x00 claims a pad length of zero, which is invalid PKCS#7.
|
||||
var padded = Data((0..<31).map { UInt8(truncatingIfNeeded: $0) })
|
||||
padded.append(0x00)
|
||||
let ciphertext = try AES._CBC.encrypt(padded, using: key, iv: iv, noPadding: true)
|
||||
|
||||
XCTAssertThrowsError(try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false))
|
||||
}
|
||||
|
||||
func testToDataConversion() throws {
|
||||
let randomBytes = (0..<16).map { _ in UInt8.random(in: UInt8.min...UInt8.max) }
|
||||
let dataIn = Data(randomBytes)
|
||||
|
||||
@@ -13,9 +13,14 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
import Crypto
|
||||
import CryptoExtras
|
||||
import Foundation
|
||||
import XCTest
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
final class CMACTests: XCTestCase {
|
||||
// Borrowed from CryptoKit
|
||||
func testVector1() throws {
|
||||
|
||||
@@ -12,9 +12,14 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
import Crypto
|
||||
import Foundation
|
||||
import XCTest
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
#if !canImport(Darwin) || canImport(CryptoKit, _version: 241.100.42)
|
||||
// Corresponds to the CryptoKit in XCode 16.3, which has Sendable annotations
|
||||
import Crypto
|
||||
|
||||
@@ -13,11 +13,16 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Crypto
|
||||
import Foundation
|
||||
import XCTest
|
||||
|
||||
@testable import CryptoExtras
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
final class PKCS8DERRepresentationTests: XCTestCase {
|
||||
func test_RSA() {
|
||||
let rsaPrivateKeyPEM = """
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Crypto
|
||||
import CryptoExtras
|
||||
import XCTest
|
||||
|
||||
final class SHA512256DigestTests: XCTestCase {
|
||||
func testHashFunction() throws {
|
||||
let data =
|
||||
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"
|
||||
.data(using: .ascii)!
|
||||
|
||||
var hasher = SHA512256()
|
||||
hasher.update(data: data)
|
||||
let digest = hasher.finalize()
|
||||
|
||||
let expected = try Array(hexString: "3928e184fb8690f840da3988121d31be65cb9d3ef83ee6146feac861e19b563a")
|
||||
XCTAssertEqual(Array(digest), expected)
|
||||
XCTAssertEqual(Array(SHA512256.hash(data: data)), expected)
|
||||
|
||||
let (contiguousResult, discontiguousResult) = expected.asDataProtocols()
|
||||
XCTAssert(digest == contiguousResult)
|
||||
XCTAssert(digest == discontiguousResult)
|
||||
XCTAssertFalse(digest == DispatchData.empty)
|
||||
}
|
||||
|
||||
func testNullHash() throws {
|
||||
let digest = SHA512256.hash(data: Data())
|
||||
|
||||
let expected = try Array(hexString: "c672b8d1ef56ed28ab87c3622c5114069bdd3ad7b8f9737498d0c01ecef0967a")
|
||||
XCTAssertEqual(Array(digest), expected)
|
||||
}
|
||||
|
||||
func testABC() throws {
|
||||
let digest = SHA512256.hash(data: "abc".data(using: .ascii)!)
|
||||
|
||||
let expected = try Array(hexString: "53048e2681941ef99b2e29b76b4c7dabe4c2d0c634fc6d46e0e2f13107e7af23")
|
||||
XCTAssertEqual(Array(digest), expected)
|
||||
}
|
||||
|
||||
func testTwoBlockMessage() throws {
|
||||
let data = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopmopq".data(using: .ascii)!
|
||||
let digest = SHA512256.hash(data: data)
|
||||
|
||||
let expected = try Array(hexString: "35de8c8794b9ed4b463c257fe50e62b516e07976a2931f4f78f1cd69a456dccd")
|
||||
XCTAssertEqual(Array(digest), expected)
|
||||
}
|
||||
|
||||
func testSingleByte() throws {
|
||||
let digest = SHA512256.hash(data: Data([0x61]))
|
||||
|
||||
let expected = try Array(hexString: "455e518824bc0601f9fb858ff5c37d417d67c2f8e0df2babe4808858aea830f8")
|
||||
XCTAssertEqual(Array(digest), expected)
|
||||
}
|
||||
|
||||
func testRepeatedBytes() throws {
|
||||
let data = Data(repeating: 0x61, count: 1_000_000)
|
||||
let digest = SHA512256.hash(data: data)
|
||||
|
||||
let expected = try Array(hexString: "9a59a052930187a97038cae692f30708aa6491923ef5194394dc68d56c74fb21")
|
||||
XCTAssertEqual(Array(digest), expected)
|
||||
}
|
||||
|
||||
func testCopyOnWrite() {
|
||||
var hasher = SHA512256()
|
||||
hasher.update(data: [1, 2, 3, 4])
|
||||
|
||||
var copy = hasher
|
||||
hasher.update(data: [5, 6, 7, 8])
|
||||
let digest = hasher.finalize()
|
||||
|
||||
copy.update(data: [5, 6, 7, 8])
|
||||
let copyDigest = copy.finalize()
|
||||
|
||||
XCTAssertEqual(digest, copyDigest)
|
||||
}
|
||||
|
||||
func testBlockSize() {
|
||||
XCTAssertEqual(SHA512256.blockByteCount, 128)
|
||||
}
|
||||
|
||||
func testDigestByteCount() {
|
||||
XCTAssertEqual(SHA512256Digest.byteCount, 32)
|
||||
}
|
||||
}
|
||||
@@ -910,6 +910,23 @@ final class TestRSASigning: XCTestCase {
|
||||
|
||||
return pemLines.joined(separator: "\n")
|
||||
}
|
||||
|
||||
func test_invalidDERPublicKeyThrowsWithoutDoubleFree() throws {
|
||||
// SEQUENCE { INTEGER 0, INTEGER 0 }
|
||||
let badBase64 = "MAYCAQACAQ=="
|
||||
let badDER = Array(Data(base64Encoded: badBase64)!)
|
||||
XCTAssertThrowsError(try BoringSSLRSAPublicKey(derRepresentation: badDER))
|
||||
}
|
||||
|
||||
func test_invalidPEMPublicKeyThrowsWithoutDoubleFree() throws {
|
||||
// SEQUENCE { INTEGER 0, INTEGER 0 }
|
||||
let badPEM = """
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MAYCAQACAQ==
|
||||
-----END PUBLIC KEY-----
|
||||
"""
|
||||
XCTAssertThrowsError(try BoringSSLRSAPublicKey(pemRepresentation: badPEM))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -29,7 +29,6 @@ struct RFCVectorDecoder {
|
||||
for _ in 0..<3 {
|
||||
fileURL!.deleteLastPathComponent()
|
||||
}
|
||||
#if compiler(>=6.0)
|
||||
if #available(macOS 13, iOS 16, watchOS 9, tvOS 16, visionOS 1, macCatalyst 16, *) {
|
||||
fileURL!.append(path: "CryptoExtrasVectors", directoryHint: .isDirectory)
|
||||
fileURL!.append(path: "\(fileName).txt", directoryHint: .notDirectory)
|
||||
@@ -37,10 +36,6 @@ struct RFCVectorDecoder {
|
||||
fileURL! = fileURL!.appendingPathComponent("CryptoExtrasVectors", isDirectory: true)
|
||||
fileURL! = fileURL!.appendingPathComponent("\(fileName).txt", isDirectory: false)
|
||||
}
|
||||
#else
|
||||
fileURL! = fileURL!.appendingPathComponent("CryptoExtrasVectors", isDirectory: true)
|
||||
fileURL! = fileURL!.appendingPathComponent("\(fileName).txt", isDirectory: false)
|
||||
#endif
|
||||
|
||||
let rfcVectorData = try Data(contentsOf: fileURL!)
|
||||
self.rfcVectorData = String(decoding: rfcVectorData, as: Unicode.UTF8.self)
|
||||
|
||||
@@ -25,7 +25,6 @@ extension XCTestCase {
|
||||
for _ in 0..<3 {
|
||||
fileURL.deleteLastPathComponent()
|
||||
}
|
||||
#if compiler(>=6.0)
|
||||
if #available(macOS 13, iOS 16, watchOS 9, tvOS 16, visionOS 1, macCatalyst 16, *) {
|
||||
fileURL.append(path: "CryptoExtrasVectors", directoryHint: .isDirectory)
|
||||
fileURL.append(path: "\(jsonName).json", directoryHint: .notDirectory)
|
||||
@@ -33,10 +32,6 @@ extension XCTestCase {
|
||||
fileURL = fileURL.appendingPathComponent("CryptoExtrasVectors", isDirectory: true)
|
||||
fileURL = fileURL.appendingPathComponent("\(jsonName).json", isDirectory: false)
|
||||
}
|
||||
#else
|
||||
fileURL = fileURL.appendingPathComponent("CryptoExtrasVectors", isDirectory: true)
|
||||
fileURL = fileURL.appendingPathComponent("\(jsonName).json", isDirectory: false)
|
||||
#endif
|
||||
|
||||
let data = try Data(contentsOf: fileURL)
|
||||
|
||||
|
||||
@@ -84,6 +84,39 @@ final class XWingTests: XCTestCase {
|
||||
let importedKey = try XWingMLKEM768X25519.PrivateKey.init(integrityCheckedRepresentation: exportedFormat)
|
||||
XCTAssertEqual(importedKey.seedRepresentation, privateKey.seedRepresentation)
|
||||
}
|
||||
|
||||
func testDecapsulateInputValidation() throws {
|
||||
let ciphersuite = HPKE.Ciphersuite.XWingMLKEM768X25519_SHA256_AES_GCM_256
|
||||
let skR = try XWingMLKEM768X25519.PrivateKey.generate()
|
||||
|
||||
// Dummy key with the correct size fails with an error from the underlying implementation.
|
||||
let corretlySizedKey = Data(repeating: 0x00, count: 1120)
|
||||
XCTAssertThrowsError(
|
||||
try HPKE.Recipient(
|
||||
privateKey: skR,
|
||||
ciphersuite: ciphersuite,
|
||||
info: Data(),
|
||||
encapsulatedKey: corretlySizedKey
|
||||
),
|
||||
error: CryptoKitError.underlyingCoreCryptoError(error: 0)
|
||||
)
|
||||
|
||||
// Keys with the wrong size fail input validation.
|
||||
let keySizesToTest = [0, 1, 1119, 1221, 2000]
|
||||
for keySize in keySizesToTest {
|
||||
let wronglySizedKey = Data(repeating: 0x00, count: keySize)
|
||||
XCTAssertThrowsError(
|
||||
try HPKE.Recipient(
|
||||
privateKey: skR,
|
||||
ciphersuite: ciphersuite,
|
||||
info: Data(),
|
||||
encapsulatedKey: wronglySizedKey
|
||||
),
|
||||
error: CryptoKitError.incorrectParameterSize,
|
||||
"Unexpectedly returned from malformed decapsulation path for keySize \(keySize)"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Struct to parse KAT file
|
||||
|
||||
@@ -33,7 +33,6 @@ struct RFCVectorDecoder {
|
||||
for _ in 0..<3 {
|
||||
fileURL!.deleteLastPathComponent()
|
||||
}
|
||||
#if compiler(>=6.0)
|
||||
if #available(macOS 13, iOS 16, watchOS 9, tvOS 16, visionOS 1, macCatalyst 16, *) {
|
||||
fileURL!.append(path: "Test Vectors", directoryHint: .isDirectory)
|
||||
fileURL!.append(path: "\(fileName).txt", directoryHint: .notDirectory)
|
||||
@@ -41,10 +40,6 @@ struct RFCVectorDecoder {
|
||||
fileURL! = fileURL!.appendingPathComponent("Test Vectors", isDirectory: true)
|
||||
fileURL! = fileURL!.appendingPathComponent("\(fileName).txt", isDirectory: false)
|
||||
}
|
||||
#else
|
||||
fileURL! = fileURL!.appendingPathComponent("Test Vectors", isDirectory: true)
|
||||
fileURL! = fileURL!.appendingPathComponent("\(fileName).txt", isDirectory: false)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
let rfcVectorData = try Data(contentsOf: fileURL!)
|
||||
|
||||
@@ -29,7 +29,6 @@ extension XCTestCase {
|
||||
for _ in 0..<3 {
|
||||
fileURL.deleteLastPathComponent()
|
||||
}
|
||||
#if compiler(>=6.0)
|
||||
if #available(macOS 13, iOS 16, watchOS 9, tvOS 16, visionOS 1, macCatalyst 16, *) {
|
||||
fileURL.append(path: "Test Vectors", directoryHint: .isDirectory)
|
||||
fileURL.append(path: "\(jsonName).json", directoryHint: .notDirectory)
|
||||
@@ -37,10 +36,6 @@ extension XCTestCase {
|
||||
fileURL = fileURL.appendingPathComponent("Test Vectors", isDirectory: true)
|
||||
fileURL = fileURL.appendingPathComponent("\(jsonName).json", isDirectory: false)
|
||||
}
|
||||
#else
|
||||
fileURL = fileURL.appendingPathComponent("Test Vectors", isDirectory: true)
|
||||
fileURL = fileURL.appendingPathComponent("\(jsonName).json", isDirectory: false)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
let data = try orFail(file: file, line: line) { try Data(contentsOf: unwrap(fileURL, file: file, line: line)) }
|
||||
|
||||
Reference in new issue
Block a user