mirror of
https://github.com/apple/swift-crypto
synced 2026-11-22 04:30:39 +00:00
Use a scoped zeroing allocation for the HMAC pad (#490)
### 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<SHA256>.authenticationCode`: was 5 allocations, now 3, ~20% faster. - `HKDF<SHA256>.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>
This commit is contained in:
1 parent
c2cbadd726
commit
47df2f1f6d
6 files changed
+131
-25
No files matched your search
@@ -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
|
||||
|
||||
@@ -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<SHA256>.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<SHA256>.deriveKey(
|
||||
inputKeyMaterial: inputKeyMaterial,
|
||||
salt: salt,
|
||||
info: info,
|
||||
outputByteCount: 1024
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
@@ -65,34 +65,24 @@ public struct HMAC<H: HashFunction>: 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
|
||||
}
|
||||
|
||||
|
||||
@@ -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<R>(_ 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
|
||||
@@ -54,4 +54,26 @@ extension Data: Zeroization {
|
||||
}
|
||||
}
|
||||
|
||||
func withUnsafeTemporaryZeroingAllocation<R>(
|
||||
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<R>(
|
||||
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)
|
||||
Reference in new issue
Block a user