diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 9d21bb17..1a9a1781 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -14,6 +14,7 @@ jobs: with: license_header_check_project_name: "SwiftCrypto" docs_check_enabled: false + format_check_container_image: "swift:latest" unit-tests: name: Unit tests diff --git a/Benchmarks/Benchmarks/Benchmarks.swift b/Benchmarks/Benchmarks/Benchmarks.swift index dffc12ae..84cbe8fe 100644 --- a/Benchmarks/Benchmarks/Benchmarks.swift +++ b/Benchmarks/Benchmarks/Benchmarks.swift @@ -21,7 +21,7 @@ import FoundationEssentials import Foundation #endif -let benchmarks = { +let benchmarks: @Sendable () -> Void = { let defaultMetrics: [BenchmarkMetric] = [.mallocCountTotal, .cpuTotal] Benchmark( @@ -208,4 +208,50 @@ let benchmarks = { blackHole(try key1.sharedSecretFromKeyAgreement(with: key2.publicKey)) } } + + Benchmark( + "hmac-sha256-authenticate", + configuration: Benchmark.Configuration( + metrics: defaultMetrics, + scalingFactor: .mega, + maxDuration: .seconds(10_000_000), + maxIterations: 5 + ) + ) { benchmark in + let key = SymmetricKey(size: .bits256) + let message = Data(repeating: 0x41, count: 1024) + + benchmark.startMeasurement() + + for _ in benchmark.scaledIterations { + blackHole(HMAC.authenticationCode(for: message, using: key)) + } + } + + Benchmark( + "hkdf-sha256-derive", + configuration: Benchmark.Configuration( + metrics: defaultMetrics, + scalingFactor: .kilo, + maxDuration: .seconds(10_000_000), + maxIterations: 10 + ) + ) { benchmark in + let inputKeyMaterial = SymmetricKey(size: .bits256) + let salt = Data("benchmark salt".utf8) + let info = Data("benchmark info".utf8) + + benchmark.startMeasurement() + + for _ in benchmark.scaledIterations { + blackHole( + HKDF.deriveKey( + inputKeyMaterial: inputKeyMaterial, + salt: salt, + info: info, + outputByteCount: 1024 + ) + ) + } + } } diff --git a/Sources/Crypto/CMakeLists.txt b/Sources/Crypto/CMakeLists.txt index c528ab9d..8f3f3e44 100644 --- a/Sources/Crypto/CMakeLists.txt +++ b/Sources/Crypto/CMakeLists.txt @@ -98,6 +98,7 @@ add_library(Crypto "Signatures/MLDSA.swift" "Signatures/Signature.swift" "Util/ArraySpanHelpers.swift" + "Util/Backports.swift" "Util/BoringSSL/CryptoKitErrors_boring.swift" "Util/BoringSSL/InlineArray+withBytes_boring.swift" "Util/BoringSSL/Optional+withUnsafeBytes_boring.swift" diff --git a/Sources/Crypto/Message Authentication Codes/HMAC/HMAC.swift b/Sources/Crypto/Message Authentication Codes/HMAC/HMAC.swift index 27acd40a..194b0dcf 100644 --- a/Sources/Crypto/Message Authentication Codes/HMAC/HMAC.swift +++ b/Sources/Crypto/Message Authentication Codes/HMAC/HMAC.swift @@ -65,34 +65,24 @@ public struct HMAC: MACAlgorithm, Sendable { #if os(iOS) && (arch(arm) || arch(i386)) fatalError("Unsupported architecture") #else - var innerKey = SecureBytes(capacity: H.blockByteCount) { keyOutput in - if key.byteCount <= keyOutput.freeCapacity { - keyOutput.append(contentsOf: key.bytes) - } else if key.byteCount > H.blockByteCount { - let hash = H.hash(bytes: key.bytes) - hash.withUnsafeBytes { - keyOutput.append(contentsOf: $0.bytes) - } - } - keyOutput.append(repeating: 0, count: keyOutput.freeCapacity, as: UInt8.self) - } - var outerKey = innerKey - + // HMAC(K, m) = H((K0 ^ opad) || H((K0 ^ ipad) || m)), where K0 is the + // key normalized to the hash block size (RFC 2104). self.innerHasher = H() - innerKey.withUnsafeMutableBytes { - for i in 0 ..< $0.count { - $0[i] ^= 0x36 - } - } - innerHasher.update(bytes: innerKey.bytes) - self.outerHasher = H() - outerKey.withUnsafeMutableBytes { - for i in 0 ..< $0.count { - $0[i] ^= 0x5c + withTemporaryZeroingAllocation(byteCount: H.blockByteCount, alignment: 1) { keyBlock in + if key.byteCount <= keyBlock.freeCapacity { + keyBlock.append(contentsOf: key.bytes) + } else if key.byteCount > H.blockByteCount { + H.hash(bytes: key.bytes).withBytes { keyBlock.append(contentsOf: $0) } } + keyBlock.append(repeating: 0, count: keyBlock.freeCapacity, as: UInt8.self) + + var k0 = keyBlock.mutableBytes + for i in 0 ..< k0.byteCount { k0[i] ^= 0x36 } // apply ipad + self.innerHasher.update(bytes: k0.bytes) + for i in 0 ..< k0.byteCount { k0[i] ^= 0x36 ^ 0x5c } // undo ipad, apply opad + self.outerHasher.update(bytes: k0.bytes) } - outerHasher.update(data: outerKey) #endif } diff --git a/Sources/Crypto/Util/Backports.swift b/Sources/Crypto/Util/Backports.swift new file mode 100644 index 00000000..878ca8fb --- /dev/null +++ b/Sources/Crypto/Util/Backports.swift @@ -0,0 +1,46 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#if canImport(FoundationEssentials) +import FoundationEssentials +#else +import Foundation +#endif + +#if swift(<6.4) +@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1.0, *) +extension ContiguousBytes { + func withBytes(_ body: (RawSpan) throws -> R) rethrows -> R { + try withUnsafeBytes { try body(RawSpan(_unsafeBytes: $0)) } + } +} +#endif + +#if swift(<6.4) +@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1.0, *) +extension MutableRawSpan { + #if swift(>=6.3) + subscript(_ byteOffset: Int) -> UInt8 { + get { unsafeLoad(fromByteOffset: byteOffset, as: UInt8.self) } + set { storeBytes(of: newValue, toByteOffset: byteOffset, as: UInt8.self) } + } + #elseif swift(<6.3) + subscript(_ byteOffset: Int) -> UInt8 { + get { unsafeLoad(fromByteOffset: byteOffset, as: UInt8.self) } + @_lifetime(&self) + set { storeBytes(of: newValue, toByteOffset: byteOffset, as: UInt8.self) } + } + #endif +} +#endif diff --git a/Sources/Crypto/Util/Zeroization.swift b/Sources/Crypto/Util/Zeroization.swift index ef870faf..a2476103 100644 --- a/Sources/Crypto/Util/Zeroization.swift +++ b/Sources/Crypto/Util/Zeroization.swift @@ -54,4 +54,26 @@ extension Data: Zeroization { } } +func withUnsafeTemporaryZeroingAllocation( + byteCount: Int, + alignment: Int, + _ body: (UnsafeMutableRawBufferPointer) throws -> R +) rethrows -> R { + try withUnsafeTemporaryAllocation(byteCount: byteCount, alignment: alignment) { buffer in + defer { buffer.zeroize() } + return try body(buffer) + } +} + +func withTemporaryZeroingAllocation( + byteCount: Int, + alignment: Int, + _ body: (inout OutputRawSpan) throws -> R +) rethrows -> R { + try withUnsafeTemporaryZeroingAllocation(byteCount: byteCount, alignment: alignment) { buffer in + var output = OutputRawSpan(buffer: buffer, initializedCount: 0) + return try body(&output) + } +} + #endif // canImport(CryptoKit)