From a8a02ac79a2791b270de758ed36e596f9f6b971f Mon Sep 17 00:00:00 2001 From: Si Beaumont Date: Wed, 12 Mar 2025 13:03:42 +0000 Subject: [PATCH] Use more efficient serialization and deserialization for ARC types (#336) ### Motivation The use of `Data.subdata(in:)` results in needless copies when decoding fields from bytes. Additionally, the use of a long chain of `Data.append(_:)` without a call to `Data.init(capacity:)` or `Data.reserveCapacity(_:)` can result in needless reallocations. ### Modifications - Remove unused `EncodeInt` and `DecodeInt` functions. They were unused before this PR but are there from when ARC credential serialization included the presentation limit. `DecodeInt` also happened to be incorrect and would crash when called with a slice. - Add some useful utility methods for popping bytes from a view without copying. - Add some generic functions for encoding and decoding `FixedWidthInteger` types along with tests for concrete types over `Data` and slices. - In ARC decoding, replace the use of `Data.subdata(in:)` with code that uses the `Data.Subsequence` slice (which happens to be `Data` since the type is self-slicing). - In ARC encoding, reserve enough capacity in the resulting `Data` when the sizes are known to reduce allocations. ## Results More performant serialization and deserialization for ARC types. --- .swiftformatignore | 2 + Sources/_CryptoExtras/ARC/ARCEncoding.swift | 217 ++++++++---------- Sources/_CryptoExtras/CMakeLists.txt | 1 + .../_CryptoExtras/Util/IntegerEncoding.swift | 88 +++++++ .../Util/IntegerEncodingTests.swift | 153 ++++++++++++ 5 files changed, 336 insertions(+), 125 deletions(-) create mode 100644 Sources/_CryptoExtras/Util/IntegerEncoding.swift create mode 100644 Tests/_CryptoExtrasTests/Util/IntegerEncodingTests.swift diff --git a/.swiftformatignore b/.swiftformatignore index b943b74d..03469d9a 100644 --- a/.swiftformatignore +++ b/.swiftformatignore @@ -99,6 +99,7 @@ Sources/_CryptoExtras/Util/BoringSSLHelpers.swift Sources/_CryptoExtras/Util/DigestType.swift Sources/_CryptoExtras/Util/Error.swift Sources/_CryptoExtras/Util/I2OSP.swift +Sources/_CryptoExtras/Util/IntegerEncoding.swift Sources/_CryptoExtras/Util/PEMDocument.swift Sources/_CryptoExtras/Util/PrettyBytes.swift Sources/_CryptoExtras/Util/SubjectPublicKeyInfo.swift @@ -151,6 +152,7 @@ Tests/_CryptoExtrasTests/TestRSABlindSigning.swift Tests/_CryptoExtrasTests/TestRSABlindSigningAPI.swift Tests/_CryptoExtrasTests/TestRSAEncryption.swift Tests/_CryptoExtrasTests/TestRSASigning.swift +Tests/_CryptoExtrasTests/Util/IntegerEncodingTests.swift Tests/_CryptoExtrasTests/Utils/BytesUtil.swift Tests/_CryptoExtrasTests/Utils/RFCVector.swift Tests/_CryptoExtrasTests/Utils/SplitData.swift diff --git a/Sources/_CryptoExtras/ARC/ARCEncoding.swift b/Sources/_CryptoExtras/ARC/ARCEncoding.swift index 97f4342e..526b6fec 100644 --- a/Sources/_CryptoExtras/ARC/ARCEncoding.swift +++ b/Sources/_CryptoExtras/ARC/ARCEncoding.swift @@ -19,50 +19,30 @@ typealias ARCCurve = P384 @available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, *) typealias ARCH2G = HashToCurveImpl -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) -internal func DecodeInt(value: Data) -> Int { - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - var result = Int(0) - - for i in 0.. Data { - return I2OSP(value: value, outputByteCount: 4) -} - @available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, *) extension ARC.CredentialRequest where H2G == ARCH2G { static let scalarCount = 5 - static let pointCount = 2 - static let serializedByteCount = pointCount * ARCCurve.compressedx962PointByteCount + scalarCount * ARCCurve.orderByteCount + static let serializedByteCount = 2 * ARCCurve.compressedx962PointByteCount + Self.scalarCount * ARCCurve.orderByteCount func serialize() -> Data { - let m1Enc = self.m1Enc.compressedRepresentation - let m2Enc = self.m2Enc.compressedRepresentation - let proofData = self.proof.serialize() - return m1Enc + m2Enc + proofData + var result = Data(capacity: Self.serializedByteCount) + result.append(self.m1Enc.compressedRepresentation) + result.append(self.m2Enc.compressedRepresentation) + result.append(self.proof.serialize()) + return result } static func deserialize(requestData: D) throws -> ARC.CredentialRequest { - guard requestData.count == self.serializedByteCount else { + guard requestData.count == Self.serializedByteCount else { throw ARC.Errors.incorrectRequestDataSize } - let requestData = Data(requestData) - var startPointer = 0 - let m1Enc = try ARCH2G.G.Element(oprfRepresentation: requestData.subdata(in: startPointer.. Data { - let U = self.U.compressedRepresentation - let encUPrime = self.encUPrime.compressedRepresentation - let X0Aux = self.X0Aux.compressedRepresentation - let X1Aux = self.X1Aux.compressedRepresentation - let X2Aux = self.X2Aux.compressedRepresentation - let HAux = self.HAux.compressedRepresentation - let responsePoints = U + encUPrime + X0Aux + X1Aux + X2Aux + HAux + var result = Data(capacity: Self.serializedByteCount) - let proofData = self.proof.serialize() - return responsePoints + proofData + result.append(self.U.compressedRepresentation) + result.append(self.encUPrime.compressedRepresentation) + result.append(self.X0Aux.compressedRepresentation) + result.append(self.X1Aux.compressedRepresentation) + result.append(self.X2Aux.compressedRepresentation) + result.append(self.HAux.compressedRepresentation) + result.append(self.proof.serialize()) + + return result } static func deserialize(responseData: D) throws -> ARC.CredentialResponse { guard responseData.count == self.serializedByteCount else { throw ARC.Errors.incorrectResponseDataSize } - let responseData = Data(responseData) - var startPointer = 0 - let U = try ARCH2G.G.Element(oprfRepresentation: responseData.subdata(in: startPointer.. Data { - // Serialize presentation elements - let U = self.U.compressedRepresentation - let UPrimeCommit = self.UPrimeCommit.compressedRepresentation - let m1Commit = self.m1Commit.compressedRepresentation - let tag = self.tag.compressedRepresentation + var result = Data(capacity: Self.serializedByteCount) - let presentationProofData = self.proof.serialize() - return U + UPrimeCommit + m1Commit + tag + presentationProofData + result.append(self.U.compressedRepresentation) + result.append(self.UPrimeCommit.compressedRepresentation) + result.append(self.m1Commit.compressedRepresentation) + result.append(self.tag.compressedRepresentation) + result.append(self.proof.serialize()) + + return result } static func deserialize(presentationData: D) throws -> ARC.Presentation { guard presentationData.count == self.serializedByteCount else { throw ARC.Errors.incorrectPresentationDataSize } - let presentationData = Data(presentationData) - var startPointer = 0 - // Deserialize presentation elements - let U = try ARCH2G.G.Element(oprfRepresentation: presentationData.subdata(in: startPointer.. Data { - // Serialize server commitment elements - let X0 = self.X0.compressedRepresentation - let X1 = self.X1.compressedRepresentation - let X2 = self.X2.compressedRepresentation + var result = Data(capacity: Self.serializedByteCount) - return X0 + X1 + X2 + result.append(self.X0.compressedRepresentation) + result.append(self.X1.compressedRepresentation) + result.append(self.X2.compressedRepresentation) + + return result } static func deserialize(serverPublicKeyData: D) throws -> ARC.ServerPublicKey { guard serverPublicKeyData.count == self.pointCount * ARCCurve.compressedx962PointByteCount else { throw ARC.Errors.incorrectServerCommitmentsSize } - let serverPublicKeyData = Data(serverPublicKeyData) - var startPointer = 0 - // Deserialize server commitment elements - let X0 = try ARCH2G.G.Element(oprfRepresentation: serverPublicKeyData.subdata(in: startPointer...Scalar(bytes: proofData.subdata(in: startPointer...Scalar] = [] + responses.reserveCapacity(scalarCount - 1) for _ in (0...Scalar(bytes: proofData.subdata(in: startPointer.. Data { - let m1 = self.m1.rawRepresentation - let U = self.U.compressedRepresentation - let UPrime = self.UPrime.compressedRepresentation - let X1 = self.X1.compressedRepresentation - let genG = self.generatorG.compressedRepresentation - let genH = self.generatorH.compressedRepresentation - let presentationState = try self.presentationState.serialize() + static let serializedByteCountExcludingPresentationState = 1 * ARCCurve.orderByteCount + 5 * ARCCurve.compressedx962PointByteCount - return m1 + U + UPrime + X1 + genG + genH + presentationState + func serialize() throws -> Data { + let presentationStateBytes = try self.presentationState.serialize() + + var result = Data(capacity: Self.serializedByteCountExcludingPresentationState + presentationStateBytes.count) + + result.append(self.m1.rawRepresentation) + result.append(self.U.compressedRepresentation) + result.append(self.UPrime.compressedRepresentation) + result.append(self.X1.compressedRepresentation) + result.append(self.generatorG.compressedRepresentation) + result.append(self.generatorH.compressedRepresentation) + result.append(presentationStateBytes) + + return result } static func deserialize(credentialData: D) throws -> ARC.Credential { - let stateByteCount = credentialData.count - self.scalarCount * ARCCurve.orderByteCount - self.pointCount * ARCCurve.compressedx962PointByteCount - guard stateByteCount >= 0 else { + guard credentialData.count - Self.serializedByteCountExcludingPresentationState >= 0 else { throw ARC.Errors.incorrectCredentialDataSize } let credentialData = Data(credentialData) - var startPointer = 0 - let m1 = try GroupImpl.Scalar(bytes: credentialData.subdata(in: startPointer..) throws { + guard bytes.count == Self.bitWidth / 8 else { + throw IntegerDecodingError.incorrectNumberOfBytes(expected: Self.bitWidth / 8, actual: bytes.count) + } + + self = 0 + var index = bytes.startIndex + for _ in 0..<(Self.bitWidth / 8) { + self <<= 8 + self |= Self(bytes[index]) + bytes.formIndex(after: &index) + } + } + + fileprivate init(bigEndianContiguousBytes bytes: some ContiguousBytes) throws { + self = try bytes.withUnsafeBytes { try Self(bigEndianBytes: $0 ) } + } + + /// Create an new value from its big endian bytes representation. + /// + /// - Parameter bytes: Big endian bytes. + /// + /// - Throws: A decoding error if the collection did not contain the exact number of bytes. + init(bigEndianBytes bytes: Data) throws { + self = try Self(bigEndianContiguousBytes: bytes) + } + + /// The big endian bytes that represent this value. + var bigEndianBytes: Data { Data(bigEndianBytesOf: self) } +} + +extension Data { + /// Creates a new instance initialized with the big endian bytes representation of the given integer. + init(bigEndianBytesOf integer: some FixedWidthInteger) { + self.init() + self.append(bigEndianBytesOf: integer) + } + + /// Appends the big endian bytes of the given integer. + mutating func append(bigEndianBytesOf integer: T) { + let previousCount = self.count + let newCount = previousCount + T.bitWidth / 8 + self.reserveCapacity(newCount) + self.count = newCount + self.withUnsafeMutableBytes { + $0.storeBytes(of: integer.bigEndian, toByteOffset: previousCount, as: T.self) + } + } + + /// Removes and returns the first k bytes. + mutating func popFirst(_ k: Int) -> Self { + let prefix = self.prefix(k) + self.removeFirst(k) + return prefix + } + + /// Removes and returns the first k bytes, decoded as a value of the given type from its big endian bytes. + mutating func popFirst(bigEndian: T.Type) throws -> T { + let value = try T(bigEndianBytes: self.prefix(T.bitWidth / 8)) + self.removeFirst(T.bitWidth / 8) + return value + } +} diff --git a/Tests/_CryptoExtrasTests/Util/IntegerEncodingTests.swift b/Tests/_CryptoExtrasTests/Util/IntegerEncodingTests.swift new file mode 100644 index 00000000..1d161300 --- /dev/null +++ b/Tests/_CryptoExtrasTests/Util/IntegerEncodingTests.swift @@ -0,0 +1,153 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2024 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 +// +//===----------------------------------------------------------------------===// +@testable import _CryptoExtras +import XCTest + +final class IntegerEncodingTests: XCTestCase { + func testIntegerDecoding() throws { + func test( + decoding bytes: [UInt8], + as: T.Type, + expect expectedResult: Swift.Result, + file: StaticString = #filePath, line: UInt = #line + ) { + let actualResult = Swift.Result { try T(bigEndianBytes: bytes) } + switch (actualResult, expectedResult) { + case (.success(let actual), .success(let expected)): + XCTAssertEqual(actual, expected, file: file, line: line) + case (.success(let actual), .failure(let error)): + XCTFail("Expected error: \(error), got \(actual)", file: file, line: line) + case (.failure(let error), .success(let expected)): + XCTFail("Decode failed; expected: \(expected), got error: \(error)", file: file, line: line) + case (.failure(let actualError), .failure(let expectedError)): + guard let typedError = actualError as? IntegerDecodingError else { + XCTFail("Expected error but not this one: \(actualError)", file: file, line: line) + return + } + XCTAssertEqual(typedError, expectedError, file: file, line: line) + } + } + + test(decoding: [0,0], as: UInt16.self, expect: .success(0)) + test(decoding: [0,1], as: UInt16.self, expect: .success(1)) + test(decoding: [1,0], as: UInt16.self, expect: .success(256)) + test(decoding: [1,1], as: UInt16.self, expect: .success(257)) + test(decoding: [0xff,0xff], as: UInt16.self, expect: .success(UInt16.max)) + + test(decoding: [], as: UInt16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 0))) + test(decoding: [0], as: UInt16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 1))) + test(decoding: [0,0,0], as: UInt16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 3))) + test(decoding: [0,0,0,0], as: UInt16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 4))) + + test(decoding: [0,0], as: Int16.self, expect: .success(0)) + test(decoding: [0,1], as: Int16.self, expect: .success(1)) + test(decoding: [1,0], as: Int16.self, expect: .success(256)) + test(decoding: [1,1], as: Int16.self, expect: .success(257)) + test(decoding: [0xff,0xff], as: Int16.self, expect: .success(-1)) + test(decoding: [0x80,0x00], as: Int16.self, expect: .success(Int16.min)) + test(decoding: [0x7f,0xff], as: Int16.self, expect: .success(Int16.max)) + + test(decoding: [], as: Int16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 0))) + test(decoding: [0], as: Int16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 1))) + test(decoding: [0,0,0], as: Int16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 3))) + test(decoding: [0,0,0,0], as: Int16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 4))) + } + + func testIntegerEncoding() throws { + func test(encoding value: T, expect bytes: [UInt8], file: StaticString = #filePath, line: UInt = #line) { + XCTAssertEqual(value.bigEndianBytes, Data(bytes), file: file, line: line) + } + + test(encoding: UInt16.zero, expect: [0,0]) + test(encoding: UInt16(1), expect: [0,1]) + test(encoding: UInt16(256), expect: [1,0]) + test(encoding: UInt16(257), expect: [1,1]) + test(encoding: UInt16.max, expect: [0xff,0xff]) + + test(encoding: Int16.zero, expect: [0,0]) + test(encoding: Int16(1), expect: [0,1]) + test(encoding: Int16(256), expect: [1,0]) + test(encoding: Int16(257), expect: [1,1]) + test(encoding: Int16(-1), expect: [0xff,0xff]) + test(encoding: Int16.min, expect: [0x80,0x00]) + test(encoding: Int16.max, expect: [0x7f,0xff]) + } + + func testIntegerEncodingDataAppend() throws { + var bytes = Data() + + bytes.append(bigEndianBytesOf: Int32(1)) + bytes.append(bigEndianBytesOf: Int16(2)) + bytes.append(bigEndianBytesOf: Int8(3)) + bytes.append(bigEndianBytesOf: Int64(4)) + + XCTAssertEqual(bytes.hexString, Data([0,0,0,1] + [0,2] + [3] + [0,0,0,0,0,0,0,4]).hexString) + } + + func testIntegerDecodingFromDataSubsequence() throws { + let data = Data([0,0,0,1] + [0,2] + [3] + [0,0,0,0,0,0,0,4]) + + var bytes = data[...] + + XCTAssertEqual(bytes.count, 15) + + XCTAssertEqual(try Int32(bigEndianBytes: bytes[..