mirror of
https://github.com/apple/swift-crypto
synced 2026-11-28 05:04:21 +00:00
### 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>
243 lines
11 KiB
Swift
243 lines
11 KiB
Swift
//===----------------------------------------------------------------------===//
|
||
//
|
||
// This source file is part of the SwiftCrypto open source project
|
||
//
|
||
// Copyright (c) 2019-2020 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(CryptoKit)
|
||
@_exported import CryptoKit
|
||
#else
|
||
#if canImport(FoundationEssentials)
|
||
public import FoundationEssentials
|
||
#else
|
||
public import Foundation
|
||
#endif
|
||
|
||
/// A hash-based message authentication algorithm.
|
||
///
|
||
/// Use hash-based message authentication to create a code with a value that’s
|
||
/// dependent on both a block of data and a symmetric cryptographic key. Another
|
||
/// party with access to the data and the same secret key can compute the code
|
||
/// again and compare it to the original to detect whether the data changed.
|
||
/// This serves a purpose similar to digital signing and verification, but
|
||
/// depends on a shared symmetric key instead of public-key cryptography.
|
||
///
|
||
/// As with digital signing, the data isn’t hidden by this process. When you
|
||
/// need to encrypt the data as well as authenticate it, use a cipher like
|
||
/// ``AES`` or ``ChaChaPoly`` to put the data into a sealed box (an instance of
|
||
/// ``AES/GCM/SealedBox`` or ``ChaChaPoly/SealedBox``).
|
||
public struct HMAC<H: HashFunction>: MACAlgorithm, Sendable {
|
||
/// An alias for the symmetric key type used to compute or verify a message
|
||
/// authentication code.
|
||
public typealias Key = SymmetricKey
|
||
/// An alias for a hash-based message authentication code.
|
||
public typealias MAC = HashedAuthenticationCode<H>
|
||
var outerHasher: H
|
||
var innerHasher: H
|
||
|
||
/// Returns a Boolean value indicating whether the given message
|
||
/// authentication code is valid for a block of data stored in a buffer.
|
||
///
|
||
/// - Parameters:
|
||
/// - mac: The authentication code to compare.
|
||
/// - bufferPointer: A pointer to the block of data to compare.
|
||
/// - key: The symmetric key for the authentication code.
|
||
///
|
||
/// - Returns: A Boolean value that’s `true` if the message authentication
|
||
/// code is valid for the data within the specified buffer.
|
||
public static func isValidAuthenticationCode(_ mac: MAC, authenticating bufferPointer: UnsafeRawBufferPointer, using key: SymmetricKey) -> Bool {
|
||
return isValidAuthenticationCode(authenticationCodeBytes: mac, authenticatedData: bufferPointer, key: key)
|
||
}
|
||
|
||
/// Creates a message authentication code generator.
|
||
///
|
||
/// - Parameters:
|
||
/// - key: The symmetric key used to secure the computation.
|
||
public init(key: SymmetricKey) {
|
||
#if os(iOS) && (arch(arm) || arch(i386))
|
||
fatalError("Unsupported architecture")
|
||
#else
|
||
// 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()
|
||
self.outerHasher = H()
|
||
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)
|
||
}
|
||
#endif
|
||
}
|
||
|
||
/// Computes a message authentication code for the given data.
|
||
///
|
||
/// - Parameters:
|
||
/// - data: The data for which to compute the authentication code.
|
||
/// - key: The symmetric key used to secure the computation.
|
||
///
|
||
/// - Returns: The message authentication code.
|
||
public static func authenticationCode<D: DataProtocol>(for data: D, using key: SymmetricKey) -> MAC {
|
||
var authenticator = Self(key: key)
|
||
authenticator.update(data: data)
|
||
return authenticator.finalize()
|
||
}
|
||
|
||
/// Computes a message authentication code for the given data.
|
||
///
|
||
/// - Parameters:
|
||
/// - data: The data for which to compute the authentication code.
|
||
/// - key: The symmetric key used to secure the computation.
|
||
///
|
||
/// - Returns: The message authentication code.
|
||
public static func authenticationCode(for data: RawSpan, using key: SymmetricKey) -> MAC {
|
||
var authenticator = Self(key: key)
|
||
authenticator.update(bytes: data)
|
||
return authenticator.finalize()
|
||
}
|
||
|
||
/// Returns a Boolean value indicating whether the given message
|
||
/// authentication code is valid for a block of data.
|
||
///
|
||
/// - Parameters:
|
||
/// - authenticationCode: The authentication code to compare.
|
||
/// - authenticatedData: The block of data to compare.
|
||
/// - key: The symmetric key for the authentication code.
|
||
///
|
||
/// - Returns: A Boolean value that’s `true` if the message authentication
|
||
/// code is valid for the specified block of data.
|
||
public static func isValidAuthenticationCode<D: DataProtocol>(_ authenticationCode: MAC, authenticating authenticatedData: D, using key: SymmetricKey) -> Bool {
|
||
return isValidAuthenticationCode(authenticationCodeBytes: authenticationCode, authenticatedData: authenticatedData, key: key)
|
||
}
|
||
|
||
/// Returns a Boolean value indicating whether the given message
|
||
/// authentication code represented as contiguous bytes is valid for a block
|
||
/// of data.
|
||
///
|
||
/// - Parameters:
|
||
/// - authenticationCode: The authentication code to compare.
|
||
/// - authenticatedData: The block of data to compare.
|
||
/// - key: The symmetric key for the authentication code.
|
||
///
|
||
/// - Returns: A Boolean value that’s `true` if the message authentication
|
||
/// code is valid for the specified block of data.
|
||
public static func isValidAuthenticationCode<C: ContiguousBytes, D: DataProtocol>(_ authenticationCode: C,
|
||
authenticating authenticatedData: D,
|
||
using key: SymmetricKey) -> Bool {
|
||
return isValidAuthenticationCode(authenticationCodeBytes: authenticationCode, authenticatedData: authenticatedData, key: key)
|
||
}
|
||
|
||
/// Updates the message authentication code computation with a block of
|
||
/// data.
|
||
///
|
||
/// - Parameters:
|
||
/// - data: The data for which to compute the authentication code.
|
||
public mutating func update<D: DataProtocol>(data: D) {
|
||
data.regions.forEach { (memoryRegion) in
|
||
memoryRegion.withUnsafeBytes({ (bp) in
|
||
self.update(bufferPointer: bp)
|
||
})
|
||
}
|
||
}
|
||
|
||
public mutating func update(bytes: RawSpan) {
|
||
innerHasher.update(bytes: bytes)
|
||
}
|
||
|
||
/// Finalizes the message authentication computation and returns the
|
||
/// computed code.
|
||
///
|
||
/// - Returns: The message authentication code.
|
||
public func finalize() -> MAC {
|
||
let innerHash = innerHasher.finalize()
|
||
var outerHashForFinalization = outerHasher
|
||
|
||
let mac = innerHash.withUnsafeBytes { buffer -> H.Digest in
|
||
outerHashForFinalization.update(bufferPointer: (buffer))
|
||
return outerHashForFinalization.finalize()
|
||
}
|
||
|
||
return HashedAuthenticationCode(digest: mac)
|
||
}
|
||
|
||
/// Adds data to be authenticated by MAC function. This can be called one or more times to append additional data.
|
||
///
|
||
/// - Parameters:
|
||
/// - data: The data to be authenticated.
|
||
/// - Throws: Throws if the HMAC has already been finalized.
|
||
mutating func update(bufferPointer: UnsafeRawBufferPointer) {
|
||
innerHasher.update(bufferPointer: bufferPointer)
|
||
}
|
||
|
||
/// A common implementation of isValidAuthenticationCode shared by the various entry points.
|
||
private static func isValidAuthenticationCode<C: ContiguousBytes, D: DataProtocol>(authenticationCodeBytes: C,
|
||
authenticatedData: D,
|
||
key: SymmetricKey) -> Bool {
|
||
var authenticator = Self(key: key)
|
||
authenticator.update(data: authenticatedData)
|
||
let computedMac = authenticator.finalize()
|
||
return safeCompare(authenticationCodeBytes, computedMac)
|
||
}
|
||
|
||
private static func isValidAuthenticationCode<C: ContiguousBytes>(authenticationCodeBytes: C,
|
||
authenticatedData: UnsafeRawBufferPointer,
|
||
key: SymmetricKey) -> Bool {
|
||
var authenticator = Self(key: key)
|
||
authenticator.update(bufferPointer: authenticatedData)
|
||
let computedMac = authenticator.finalize()
|
||
return safeCompare(authenticationCodeBytes, computedMac)
|
||
}
|
||
}
|
||
|
||
/// A hash-based message authentication code.
|
||
public struct HashedAuthenticationCode<H: HashFunction>: MessageAuthenticationCode, Sendable {
|
||
let digest: H.Digest
|
||
|
||
/// The number of bytes in the message authentication code.
|
||
public var byteCount: Int {
|
||
return H.Digest.byteCount
|
||
}
|
||
|
||
#if !hasFeature(Embedded)
|
||
/// A human-readable description of the code.
|
||
public var description: String {
|
||
return "HMAC with \(H.self): \(Array(digest).hexString)"
|
||
}
|
||
#endif
|
||
|
||
/// Invokes the given closure with a buffer pointer covering the raw bytes
|
||
/// of the code.
|
||
///
|
||
/// - Parameters:
|
||
/// - body: A closure that takes a raw buffer pointer to the bytes of the
|
||
/// code and returns the code.
|
||
///
|
||
/// - Returns: The code, as returned from the body closure.
|
||
#if hasFeature(Embedded)
|
||
public func withUnsafeBytes<R, E: Error>(_ body: (UnsafeRawBufferPointer) throws(E) -> R) throws(E) -> R {
|
||
return try digest.withUnsafeBytes(body)
|
||
}
|
||
#else
|
||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||
return try digest.withUnsafeBytes(body)
|
||
}
|
||
#endif
|
||
}
|
||
#endif // canImport(CryptoKit)
|