From 47df2f1f6d54f0a6c9fb90e9652da28a6b7ed5a1 Mon Sep 17 00:00:00 2001 From: Si Beaumont Date: Thu, 22 Oct 2026 09:36:54 +0100 Subject: [PATCH] Use a scoped zeroing allocation for the HMAC pad (#490) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Motivation: Currently HMAC heap allocates twice per construction for temporary storage. `HMAC.init(key:)` builds the inner and outer pads using two `SecureBytes` allocations. This is a bottleneck for both HMAC and HKDF, which constructs an HMAC per output block. Both pads never escape the initializer, so neither needs to be on the heap at all. A scoped temporary allocation that zeroes after use does the same job with no allocations. ### Modifications: - Fix the Benchmarks package build (missing `Sendable` annotation) - Add benchmarks for HMAC and HKDF - Add scoped zeroing temporary allocation helpers - Use a scoped zeroing allocation for the HMAC pad ### Result: - `HMAC.authenticationCode`: was 5 allocations, now 3, ~20% faster. - `HKDF.deriveKey`, 1 KiB output: was 170 allocations, now 104, ~30% faster. ### Benchmarks: ``` hmac-sha256-authenticate (before) ╒═════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕ │ Metric │ p0 │ p25 │ p50 │ p75 │ p90 │ p99 │ p100 │ Samples │ ╞═════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡ │ Malloc (total) * │ 5 │ 5 │ 5 │ 5 │ 5 │ 5 │ 5 │ 5 │ ├─────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤ │ Time (total CPU) (ns) * │ 1170 │ 1251 │ 1251 │ 1271 │ 1340 │ 1340 │ 1340 │ 5 │ ╘═════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛ hmac-sha256-authenticate (after) ╒═════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕ │ Metric │ p0 │ p25 │ p50 │ p75 │ p90 │ p99 │ p100 │ Samples │ ╞═════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡ │ Malloc (total) * │ 3 │ 3 │ 3 │ 3 │ 3 │ 3 │ 3 │ 5 │ ├─────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤ │ Time (total CPU) (ns) * │ 870 │ 910 │ 970 │ 1030 │ 1030 │ 1030 │ 1030 │ 5 │ ╘═════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛ hkdf-sha256-derive (before) ╒═════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕ │ Metric │ p0 │ p25 │ p50 │ p75 │ p90 │ p99 │ p100 │ Samples │ ╞═════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡ │ Malloc (total) * │ 170 │ 170 │ 170 │ 170 │ 170 │ 170 │ 170 │ 10 │ ├─────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤ │ Time (total CPU) (μs) * │ 20 │ 20 │ 30 │ 30 │ 30 │ 30 │ 30 │ 10 │ ╘═════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛ hkdf-sha256-derive (after) ╒═════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕ │ Metric │ p0 │ p25 │ p50 │ p75 │ p90 │ p99 │ p100 │ Samples │ ╞═════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡ │ Malloc (total) * │ 104 │ 104 │ 104 │ 104 │ 104 │ 104 │ 104 │ 10 │ ├─────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤ │ Time (total CPU) (μs) * │ 10 │ 20 │ 20 │ 20 │ 20 │ 20 │ 20 │ 10 │ ╘═════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛ ``` ### Credits: This PR is a re-work of the original contribution by @ptoffy. The merge-commit will show him as a co-author. --------- Co-authored-by: Paul Toffoloni <69189821+ptoffy@users.noreply.github.com> --- .github/workflows/pull_request.yml | 1 + Benchmarks/Benchmarks/Benchmarks.swift | 48 ++++++++++++++++++- Sources/Crypto/CMakeLists.txt | 1 + .../HMAC/HMAC.swift | 38 ++++++--------- Sources/Crypto/Util/Backports.swift | 46 ++++++++++++++++++ Sources/Crypto/Util/Zeroization.swift | 22 +++++++++ 6 files changed, 131 insertions(+), 25 deletions(-) create mode 100644 Sources/Crypto/Util/Backports.swift 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)