mirror of
https://github.com/apple/swift-crypto
synced 2026-11-22 04:30:39 +00:00
perf: Add benchmarks and reduce allocations by ~50% for ARC and VOPRF (#346)
### Motivation We've recently added some EC operations internally to support some schemes, including ARC and VOPRF. Some of this code is quite allocation-heavy, which could be avoided with some minimally invasive changes. ### Modifications - Add package benchmarks for ARC and VOPRF. - Make use of the `consuming` keyword in some targeted places to reduce allocations in arithmetic- and append-chains. - Use a Thread-/Task-local FiniteFieldArithmeticContext for EC operations, and thread this through as a `BN_CTX` to BoringSSL functions when available. - Replace EC static computed properties with stored properties for things that are statically knowable about the EC group. ### Result This has resulted in a 50% reduction in allocations for ARC issuance and VOPRF evaluation, and a 34% reduction in ARC verification. ```none SwiftCryptoBenchmarks ============================================================================================================================ ---------------------------------------------------------------------------------------------------------------------------- arc-issue-p384 metrics ---------------------------------------------------------------------------------------------------------------------------- ╒══════════════════════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕ │ Malloc (total) * │ p0 │ p25 │ p50 │ p75 │ p90 │ p99 │ p100 │ Samples │ ╞══════════════════════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡ │ alpha │ 945 │ 945 │ 945 │ 945 │ 945 │ 945 │ 945 │ 3 │ ├──────────────────────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤ │ beta │ 464 │ 464 │ 464 │ 464 │ 464 │ 464 │ 464 │ 3 │ ├──────────────────────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤ │ Δ │ -481 │ -481 │ -481 │ -481 │ -481 │ -481 │ -481 │ 0 │ ├──────────────────────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤ │ Improvement % │ 51 │ 51 │ 51 │ 51 │ 51 │ 51 │ 51 │ 0 │ ╘══════════════════════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛ ---------------------------------------------------------------------------------------------------------------------------- arc-verify-p384 metrics ---------------------------------------------------------------------------------------------------------------------------- ╒══════════════════════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕ │ Malloc (total) * │ p0 │ p25 │ p50 │ p75 │ p90 │ p99 │ p100 │ Samples │ ╞══════════════════════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡ │ alpha │ 410 │ 410 │ 410 │ 415 │ 415 │ 415 │ 415 │ 10 │ ├──────────────────────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤ │ beta │ 271 │ 271 │ 271 │ 275 │ 275 │ 275 │ 275 │ 10 │ ├──────────────────────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤ │ Δ │ -139 │ -139 │ -139 │ -140 │ -140 │ -140 │ -140 │ 0 │ ├──────────────────────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤ │ Improvement % │ 34 │ 34 │ 34 │ 34 │ 34 │ 34 │ 34 │ 0 │ ╘══════════════════════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛ ---------------------------------------------------------------------------------------------------------------------------- voprf-evaluate-p384 metrics ---------------------------------------------------------------------------------------------------------------------------- ╒══════════════════════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕ │ Malloc (total) * │ p0 │ p25 │ p50 │ p75 │ p90 │ p99 │ p100 │ Samples │ ╞══════════════════════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡ │ alpha │ 331 │ 331 │ 331 │ 331 │ 331 │ 331 │ 331 │ 3 │ ├──────────────────────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤ │ beta │ 168 │ 168 │ 168 │ 168 │ 168 │ 168 │ 168 │ 3 │ ├──────────────────────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤ │ Δ │ -163 │ -163 │ -163 │ -163 │ -163 │ -163 │ -163 │ 0 │ ├──────────────────────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤ │ Improvement % │ 49 │ 49 │ 49 │ 49 │ 49 │ 49 │ 49 │ 0 │ ╘══════════════════════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛ ``` --------- Co-authored-by: Cory Benfield <lukasa@apple.com>
This commit is contained in:
1 parent
e8d6eba1fe
commit
6db5a75258
8 files changed
+312
-113
No files matched your search
@@ -0,0 +1,102 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2025 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
import Benchmark
|
||||
import Crypto
|
||||
import Foundation
|
||||
import _CryptoExtras
|
||||
|
||||
let benchmarks = {
|
||||
let defaultMetrics: [BenchmarkMetric] = [.mallocCountTotal, .cpuTotal]
|
||||
|
||||
Benchmark(
|
||||
"arc-issue-p384",
|
||||
configuration: Benchmark.Configuration(
|
||||
metrics: defaultMetrics,
|
||||
scalingFactor: .kilo,
|
||||
maxDuration: .seconds(10_000_000),
|
||||
maxIterations: 3
|
||||
)
|
||||
) { benchmark in
|
||||
let privateKey = P384._ARCV1.PrivateKey()
|
||||
let publicKey = privateKey.publicKey
|
||||
let requestContext = Data("shared request context".utf8)
|
||||
let precredential = try publicKey.prepareCredentialRequest(requestContext: requestContext)
|
||||
let credentialRequest = precredential.credentialRequest
|
||||
|
||||
benchmark.startMeasurement()
|
||||
|
||||
for _ in benchmark.scaledIterations {
|
||||
blackHole(try privateKey.issue(credentialRequest))
|
||||
}
|
||||
}
|
||||
|
||||
Benchmark(
|
||||
"arc-verify-p384",
|
||||
configuration: Benchmark.Configuration(
|
||||
metrics: defaultMetrics,
|
||||
scalingFactor: .kilo,
|
||||
maxDuration: .seconds(10_000_000),
|
||||
maxIterations: 10
|
||||
)
|
||||
) { benchmark in
|
||||
let privateKey = P384._ARCV1.PrivateKey()
|
||||
let publicKey = privateKey.publicKey
|
||||
let requestContext = Data("shared request context".utf8)
|
||||
let (presentationContext, presentationLimit) = (Data("shared presentation context".utf8), 2)
|
||||
let precredential = try publicKey.prepareCredentialRequest(requestContext: requestContext)
|
||||
let credentialRequest = precredential.credentialRequest
|
||||
let credentialResponse = try privateKey.issue(credentialRequest)
|
||||
var credential = try publicKey.finalize(credentialResponse, for: precredential)
|
||||
let (presentation, nonce) = try credential.makePresentation(
|
||||
context: presentationContext,
|
||||
presentationLimit: presentationLimit
|
||||
)
|
||||
|
||||
benchmark.startMeasurement()
|
||||
|
||||
for _ in benchmark.scaledIterations {
|
||||
blackHole(
|
||||
try privateKey.verify(
|
||||
presentation,
|
||||
requestContext: requestContext,
|
||||
presentationContext: presentationContext,
|
||||
presentationLimit: presentationLimit,
|
||||
nonce: nonce
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Benchmark(
|
||||
"voprf-evaluate-p384",
|
||||
configuration: Benchmark.Configuration(
|
||||
metrics: defaultMetrics,
|
||||
scalingFactor: .kilo,
|
||||
maxDuration: .seconds(10_000_000),
|
||||
maxIterations: 3
|
||||
)
|
||||
) { benchmark in
|
||||
let privateKey = P384._VOPRF.PrivateKey()
|
||||
let publicKey = privateKey.publicKey
|
||||
let privateInput = Data("This is some input data".utf8)
|
||||
let blindedInput = try publicKey.blind(privateInput)
|
||||
let blindedElement = blindedInput.blindedElement
|
||||
|
||||
benchmark.startMeasurement()
|
||||
|
||||
for _ in benchmark.scaledIterations {
|
||||
blackHole(try privateKey.evaluate(blindedElement))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// swift-tools-version: 5.9
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "swift-crypto-benchmarks",
|
||||
platforms: [.macOS("14")],
|
||||
dependencies: [
|
||||
.package(name: "swift-crypto", path: "../"),
|
||||
.package(url: "https://github.com/ordo-one/package-benchmark", from: "1.22.0"),
|
||||
],
|
||||
targets: [
|
||||
.executableTarget(
|
||||
name: "SwiftCryptoBenchmarks",
|
||||
dependencies: [
|
||||
.product(name: "Benchmark", package: "package-benchmark"),
|
||||
.product(name: "Crypto", package: "swift-crypto"),
|
||||
.product(name: "_CryptoExtras", package: "swift-crypto"),
|
||||
],
|
||||
path: "Benchmarks/",
|
||||
plugins: [
|
||||
.plugin(name: "BenchmarkPlugin", package: "package-benchmark")
|
||||
]
|
||||
)
|
||||
]
|
||||
)
|
||||
@@ -20,6 +20,10 @@
|
||||
package final class BoringSSLEllipticCurveGroup {
|
||||
@usableFromInline var _group: OpaquePointer
|
||||
|
||||
@usableFromInline package let order: ArbitraryPrecisionInteger
|
||||
|
||||
@usableFromInline package let generator: EllipticCurvePoint
|
||||
|
||||
@usableFromInline
|
||||
package init(_ curve: CurveName) throws {
|
||||
guard let group = CCryptoBoringSSL_EC_GROUP_new_by_curve_name(curve.baseNID) else {
|
||||
@@ -27,6 +31,11 @@ package final class BoringSSLEllipticCurveGroup {
|
||||
}
|
||||
|
||||
self._group = group
|
||||
|
||||
let baseOrder = CCryptoBoringSSL_EC_GROUP_get0_order(self._group)!
|
||||
self.order = try! ArbitraryPrecisionInteger(copying: baseOrder)
|
||||
|
||||
self.generator = try EllipticCurvePoint(_generatorOf: self._group)
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -68,23 +77,6 @@ extension BoringSSLEllipticCurveGroup {
|
||||
try body(self._group)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package var order: ArbitraryPrecisionInteger {
|
||||
// Groups must have an order.
|
||||
let baseOrder = CCryptoBoringSSL_EC_GROUP_get0_order(self._group)!
|
||||
return try! ArbitraryPrecisionInteger(copying: baseOrder)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package var generator: EllipticCurvePoint {
|
||||
get throws {
|
||||
guard let generatorPtr = CCryptoBoringSSL_EC_GROUP_get0_generator(self._group) else {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
return try EllipticCurvePoint(copying: generatorPtr, on: self)
|
||||
}
|
||||
}
|
||||
|
||||
/// An elliptic curve can be represented in a Weierstrass form: `y² = x³ + ax + b`. This
|
||||
/// property provides the values of a and b on the curve.
|
||||
@usableFromInline
|
||||
|
||||
@@ -53,16 +53,27 @@ package final class EllipticCurvePoint {
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package init(_generatorOf groupPtr: OpaquePointer) throws {
|
||||
guard
|
||||
let generatorPtr = CCryptoBoringSSL_EC_GROUP_get0_generator(groupPtr),
|
||||
let pointPtr = CCryptoBoringSSL_EC_POINT_dup(generatorPtr, groupPtr)
|
||||
else {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
self._basePoint = pointPtr
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package convenience init(
|
||||
multiplying scalar: ArbitraryPrecisionInteger,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws {
|
||||
try self.init(_pointAtInfinityOn: group)
|
||||
try group.withUnsafeGroupPointer { groupPtr in
|
||||
try scalar.withUnsafeBignumPointer { scalarPtr in
|
||||
guard
|
||||
CCryptoBoringSSL_EC_POINT_mul(groupPtr, self._basePoint, scalarPtr, nil, nil, nil) == 1
|
||||
guard CCryptoBoringSSL_EC_POINT_mul(groupPtr, self._basePoint, scalarPtr, nil, nil, context?.bnCtx) == 1
|
||||
else {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
@@ -77,14 +88,13 @@ package final class EllipticCurvePoint {
|
||||
@usableFromInline
|
||||
package func multiply(
|
||||
by rhs: ArbitraryPrecisionInteger,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
)
|
||||
throws
|
||||
{
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws {
|
||||
try self.withPointPointer { selfPtr in
|
||||
try rhs.withUnsafeBignumPointer { rhsPtr in
|
||||
try group.withUnsafeGroupPointer { groupPtr in
|
||||
guard CCryptoBoringSSL_EC_POINT_mul(groupPtr, selfPtr, nil, selfPtr, rhsPtr, nil) != 0
|
||||
guard CCryptoBoringSSL_EC_POINT_mul(groupPtr, selfPtr, nil, selfPtr, rhsPtr, context?.bnCtx) != 0
|
||||
else {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
@@ -97,37 +107,46 @@ package final class EllipticCurvePoint {
|
||||
package convenience init(
|
||||
multiplying lhs: EllipticCurvePoint,
|
||||
by rhs: ArbitraryPrecisionInteger,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws {
|
||||
try self.init(copying: lhs, on: group)
|
||||
try self.multiply(by: rhs, on: group)
|
||||
try self.multiply(by: rhs, on: group, context: context)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func multiplying(
|
||||
package consuming func multiplying(
|
||||
by rhs: ArbitraryPrecisionInteger,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
)
|
||||
throws -> EllipticCurvePoint
|
||||
{
|
||||
try EllipticCurvePoint(multiplying: self, by: rhs, on: group)
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws -> EllipticCurvePoint {
|
||||
guard isKnownUniquelyReferenced(&self) else {
|
||||
return try EllipticCurvePoint(multiplying: self, by: rhs, on: group, context: context)
|
||||
}
|
||||
try self.multiply(by: rhs, on: group, context: context)
|
||||
return self
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package static func multiplying(
|
||||
_ lhs: EllipticCurvePoint,
|
||||
by rhs: ArbitraryPrecisionInteger,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws -> EllipticCurvePoint {
|
||||
try EllipticCurvePoint(multiplying: lhs, by: rhs, on: group)
|
||||
try EllipticCurvePoint(multiplying: lhs, by: rhs, on: group, context: context)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func add(_ rhs: EllipticCurvePoint, on group: BoringSSLEllipticCurveGroup) throws {
|
||||
package func add(
|
||||
_ rhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws {
|
||||
try self.withPointPointer { selfPtr in
|
||||
try group.withUnsafeGroupPointer { groupPtr in
|
||||
try rhs.withPointPointer { rhsPtr in
|
||||
guard CCryptoBoringSSL_EC_POINT_add(groupPtr, selfPtr, selfPtr, rhsPtr, nil) != 0 else {
|
||||
guard CCryptoBoringSSL_EC_POINT_add(groupPtr, selfPtr, selfPtr, rhsPtr, context?.bnCtx) != 0 else {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
}
|
||||
@@ -139,36 +158,41 @@ package final class EllipticCurvePoint {
|
||||
package convenience init(
|
||||
adding lhs: EllipticCurvePoint,
|
||||
_ rhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws {
|
||||
try self.init(copying: lhs, on: group)
|
||||
try self.add(rhs, on: group)
|
||||
try self.add(rhs, on: group, context: context)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func adding(
|
||||
_ rhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
) throws
|
||||
-> EllipticCurvePoint
|
||||
{
|
||||
try EllipticCurvePoint(adding: self, rhs, on: group)
|
||||
package consuming func adding(
|
||||
_ rhs: consuming EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws -> EllipticCurvePoint {
|
||||
guard isKnownUniquelyReferenced(&self) else {
|
||||
return try EllipticCurvePoint(adding: self, rhs, on: group, context: context)
|
||||
}
|
||||
try self.add(rhs, on: group, context: context)
|
||||
return self
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package static func adding(
|
||||
_ lhs: EllipticCurvePoint,
|
||||
_ rhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws -> EllipticCurvePoint {
|
||||
try EllipticCurvePoint(adding: lhs, rhs, on: group)
|
||||
try EllipticCurvePoint(adding: lhs, rhs, on: group, context: context)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func invert(on group: BoringSSLEllipticCurveGroup) throws {
|
||||
package func invert(on group: BoringSSLEllipticCurveGroup, context: FiniteFieldArithmeticContext? = nil) throws {
|
||||
try self.withPointPointer { selfPtr in
|
||||
try group.withUnsafeGroupPointer { groupPtr in
|
||||
guard CCryptoBoringSSL_EC_POINT_invert(groupPtr, selfPtr, nil) != 0 else {
|
||||
guard CCryptoBoringSSL_EC_POINT_invert(groupPtr, selfPtr, context?.bnCtx) != 0 else {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
}
|
||||
@@ -178,59 +202,71 @@ package final class EllipticCurvePoint {
|
||||
@usableFromInline
|
||||
package convenience init(
|
||||
inverting point: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws {
|
||||
try self.init(copying: point, on: group)
|
||||
try self.invert(on: group)
|
||||
try self.invert(on: group, context: context)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func inverting(on group: BoringSSLEllipticCurveGroup) throws -> EllipticCurvePoint {
|
||||
try EllipticCurvePoint(inverting: self, on: group)
|
||||
package func inverting(
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws -> EllipticCurvePoint {
|
||||
try EllipticCurvePoint(inverting: self, on: group, context: context)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package static func inverting(
|
||||
_ point: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
)
|
||||
throws -> EllipticCurvePoint
|
||||
{
|
||||
try EllipticCurvePoint(inverting: point, on: group)
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws -> EllipticCurvePoint {
|
||||
try EllipticCurvePoint(inverting: point, on: group, context: context)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func subtract(_ rhs: EllipticCurvePoint, on group: BoringSSLEllipticCurveGroup) throws {
|
||||
try self.add(rhs.inverting(on: group), on: group)
|
||||
package func subtract(
|
||||
_ rhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws {
|
||||
try self.add(rhs.inverting(on: group), on: group, context: context)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package convenience init(
|
||||
subtracting rhs: EllipticCurvePoint,
|
||||
from lhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws {
|
||||
try self.init(copying: lhs, on: group)
|
||||
try self.subtract(rhs, on: group)
|
||||
try self.subtract(rhs, on: group, context: context)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func subtracting(
|
||||
_ rhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
) throws
|
||||
-> EllipticCurvePoint
|
||||
{
|
||||
try EllipticCurvePoint(subtracting: rhs, from: self, on: group)
|
||||
package consuming func subtracting(
|
||||
_ rhs: consuming EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws -> EllipticCurvePoint {
|
||||
guard isKnownUniquelyReferenced(&self) else {
|
||||
return try EllipticCurvePoint(subtracting: rhs, from: self, on: group, context: context)
|
||||
}
|
||||
try self.subtract(rhs, on: group, context: context)
|
||||
return self
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package static func subtracting(
|
||||
_ rhs: EllipticCurvePoint,
|
||||
from lhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws -> EllipticCurvePoint {
|
||||
try EllipticCurvePoint(subtracting: rhs, from: lhs, on: group)
|
||||
try EllipticCurvePoint(subtracting: rhs, from: lhs, on: group, context: context)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
@@ -267,11 +303,15 @@ package final class EllipticCurvePoint {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func isEqual(to rhs: EllipticCurvePoint, on group: BoringSSLEllipticCurveGroup) -> Bool {
|
||||
package func isEqual(
|
||||
to rhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) -> Bool {
|
||||
self.withPointPointer { selfPtr in
|
||||
group.withUnsafeGroupPointer { groupPtr in
|
||||
rhs.withPointPointer { rhsPtr in
|
||||
switch CCryptoBoringSSL_EC_POINT_cmp(groupPtr, selfPtr, rhsPtr, nil) {
|
||||
switch CCryptoBoringSSL_EC_POINT_cmp(groupPtr, selfPtr, rhsPtr, context?.bnCtx) {
|
||||
case 0: return true
|
||||
case 1: return false
|
||||
default:
|
||||
@@ -288,7 +328,8 @@ package final class EllipticCurvePoint {
|
||||
@usableFromInline
|
||||
package convenience init<Bytes: ContiguousBytes>(
|
||||
x962Representation bytes: Bytes,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws {
|
||||
try self.init(_pointAtInfinityOn: group)
|
||||
guard
|
||||
@@ -299,7 +340,7 @@ package final class EllipticCurvePoint {
|
||||
self._basePoint,
|
||||
dataPtr.baseAddress,
|
||||
dataPtr.count,
|
||||
nil
|
||||
context?.bnCtx
|
||||
)
|
||||
}
|
||||
}) == 1
|
||||
@@ -311,10 +352,9 @@ package final class EllipticCurvePoint {
|
||||
@usableFromInline
|
||||
package func x962RepresentationByteCount(
|
||||
compressed: Bool,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
)
|
||||
throws -> Int
|
||||
{
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws -> Int {
|
||||
let numBytesNeeded = group.withUnsafeGroupPointer { groupPtr in
|
||||
CCryptoBoringSSL_EC_POINT_point2oct(
|
||||
groupPtr,
|
||||
@@ -322,7 +362,7 @@ package final class EllipticCurvePoint {
|
||||
compressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED,
|
||||
nil,
|
||||
0,
|
||||
nil
|
||||
context?.bnCtx
|
||||
)
|
||||
}
|
||||
guard numBytesNeeded != 0 else {
|
||||
@@ -334,11 +374,10 @@ package final class EllipticCurvePoint {
|
||||
@usableFromInline
|
||||
package func x962Representation(
|
||||
compressed: Bool,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
) throws
|
||||
-> Data
|
||||
{
|
||||
let numBytesNeeded = try self.x962RepresentationByteCount(compressed: compressed, on: group)
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws -> Data {
|
||||
let numBytesNeeded = try self.x962RepresentationByteCount(compressed: compressed, on: group, context: context)
|
||||
|
||||
var buf = Data(repeating: 0, count: numBytesNeeded)
|
||||
|
||||
@@ -350,7 +389,7 @@ package final class EllipticCurvePoint {
|
||||
compressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED,
|
||||
bufPtr.baseAddress,
|
||||
numBytesNeeded,
|
||||
nil
|
||||
context?.bnCtx
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ import Foundation
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
package class FiniteFieldArithmeticContext {
|
||||
private var fieldSize: ArbitraryPrecisionInteger
|
||||
private var bnCtx: OpaquePointer
|
||||
package var bnCtx: OpaquePointer
|
||||
|
||||
@usableFromInline
|
||||
package init(fieldSize: ArbitraryPrecisionInteger) throws {
|
||||
|
||||
@@ -53,6 +53,7 @@ add_library(_CryptoExtras
|
||||
"RSA/RSA_security.swift"
|
||||
"Util/BoringSSLHelpers.swift"
|
||||
"Util/CryptoKitErrors_boring.swift"
|
||||
"Util/Data+Extensions.swift"
|
||||
"Util/DigestType.swift"
|
||||
"Util/Error.swift"
|
||||
"Util/I2OSP.swift"
|
||||
|
||||
@@ -39,6 +39,9 @@ protocol OpenSSLSupportedNISTCurve {
|
||||
// TODO: could this be moved to the group or to the HashFunction?
|
||||
@inlinable
|
||||
static var hashToFieldByteCount: Int { get }
|
||||
|
||||
@inlinable
|
||||
static var __ffac: FiniteFieldArithmeticContext { get }
|
||||
}
|
||||
|
||||
/// NOTE: This conformance applies to this type from the Crypto module even if it comes from the SDK.
|
||||
@@ -47,8 +50,8 @@ extension P256: OpenSSLSupportedNISTCurve {
|
||||
@usableFromInline
|
||||
typealias H = SHA256
|
||||
|
||||
@inlinable
|
||||
static var group: BoringSSLEllipticCurveGroup { try! BoringSSLEllipticCurveGroup(.p256) }
|
||||
@usableFromInline
|
||||
static let group: BoringSSLEllipticCurveGroup = try! BoringSSLEllipticCurveGroup(.p256)
|
||||
|
||||
@inlinable
|
||||
static var cofactor: Int { 1 }
|
||||
@@ -61,6 +64,11 @@ extension P256: OpenSSLSupportedNISTCurve {
|
||||
|
||||
@inlinable
|
||||
static var hashToFieldByteCount: Int { 48 }
|
||||
|
||||
@TaskLocal
|
||||
@usableFromInline
|
||||
// NOTE: This could be a let when Swift 6.0 is the minimum supported version.
|
||||
static var __ffac = try! FiniteFieldArithmeticContext(fieldSize: P256.group.order)
|
||||
}
|
||||
|
||||
/// NOTE: This conformance applies to this type from the Crypto module even if it comes from the SDK.
|
||||
@@ -69,8 +77,8 @@ extension P384: OpenSSLSupportedNISTCurve {
|
||||
@usableFromInline
|
||||
typealias H = SHA384
|
||||
|
||||
@inlinable
|
||||
static var group: BoringSSLEllipticCurveGroup { try! BoringSSLEllipticCurveGroup(.p384) }
|
||||
@usableFromInline
|
||||
static let group: BoringSSLEllipticCurveGroup = try! BoringSSLEllipticCurveGroup(.p384)
|
||||
|
||||
@inlinable
|
||||
static var cofactor: Int { 1 }
|
||||
@@ -83,6 +91,11 @@ extension P384: OpenSSLSupportedNISTCurve {
|
||||
|
||||
@inlinable
|
||||
static var hashToFieldByteCount: Int { 72 }
|
||||
|
||||
@TaskLocal
|
||||
@usableFromInline
|
||||
// NOTE: This could be a let when Swift 6.0 is the minimum supported version.
|
||||
static var __ffac = try! FiniteFieldArithmeticContext(fieldSize: P384.group.order)
|
||||
}
|
||||
|
||||
/// NOTE: This conformance applies to this type from the Crypto module even if it comes from the SDK.
|
||||
@@ -91,8 +104,8 @@ extension P521: OpenSSLSupportedNISTCurve {
|
||||
@usableFromInline
|
||||
typealias H = SHA512
|
||||
|
||||
@inlinable
|
||||
static var group: BoringSSLEllipticCurveGroup { try! BoringSSLEllipticCurveGroup(.p521) }
|
||||
@usableFromInline
|
||||
static let group: BoringSSLEllipticCurveGroup = try! BoringSSLEllipticCurveGroup(.p521)
|
||||
|
||||
@inlinable
|
||||
static var cofactor: Int { 1 }
|
||||
@@ -105,6 +118,11 @@ extension P521: OpenSSLSupportedNISTCurve {
|
||||
|
||||
@inlinable
|
||||
static var hashToFieldByteCount: Int { 98 }
|
||||
|
||||
@TaskLocal
|
||||
@usableFromInline
|
||||
// NOTE: This could be a let when Swift 6.0 is the minimum supported version.
|
||||
static var __ffac = try! FiniteFieldArithmeticContext(fieldSize: P521.group.order)
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
@@ -126,7 +144,7 @@ struct OpenSSLGroupScalar<C: OpenSSLSupportedNISTCurve>: GroupScalar, CustomStri
|
||||
try ArbitraryPrecisionInteger(bytes: bytes).modulo(C.group.weierstrassCoefficients.field)
|
||||
)
|
||||
} else {
|
||||
self.init(try ArbitraryPrecisionInteger(bytes: bytes).modulo(C.group.order))
|
||||
self.init(try C.__ffac.residue(ArbitraryPrecisionInteger(bytes: bytes)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,28 +155,29 @@ struct OpenSSLGroupScalar<C: OpenSSLSupportedNISTCurve>: GroupScalar, CustomStri
|
||||
|
||||
static func + (left: Self, right: Self) -> Self {
|
||||
// Force-try: Protocol requires non-throwing and this can only throw if modulus is invalid.
|
||||
try! Self(left.openSSLScalar.add(right.openSSLScalar, modulo: C.group.order))
|
||||
try! Self(C.__ffac.add(left.openSSLScalar, right.openSSLScalar))
|
||||
|
||||
}
|
||||
|
||||
static func - (left: Self, right: Self) -> Self {
|
||||
// Force-try: Protocol requires non-throwing and this can only throw if modulus is invalid.
|
||||
try! Self(left.openSSLScalar.sub(right.openSSLScalar, modulo: C.group.order))
|
||||
try! Self(C.__ffac.subtract(right.openSSLScalar, from: left.openSSLScalar))
|
||||
}
|
||||
|
||||
static func ^ (left: Self, right: Int) -> Self {
|
||||
precondition(right == -1, "Unimplemented arbitrary exponentiation")
|
||||
// Force-try: Protocol requires non-throwing and this can only throw if modulus is invalid.
|
||||
return try! Self(left.openSSLScalar.inverse(modulo: C.group.order))
|
||||
return try! Self(C.__ffac.inverse(left.openSSLScalar)!)
|
||||
}
|
||||
|
||||
static func * (left: Self, right: Self) -> Self {
|
||||
// Force-try: Protocol requires non-throwing and this can only throw if modulus is invalid.
|
||||
try! Self(left.openSSLScalar.mul(right.openSSLScalar, modulo: C.group.order))
|
||||
try! Self(C.__ffac.multiply(left.openSSLScalar, right.openSSLScalar))
|
||||
}
|
||||
|
||||
static prefix func - (left: Self) -> Self {
|
||||
// Force-try: Protocol requires non-throwing and this can only throw if modulus is invalid.
|
||||
try! Self(.zero.sub(left.openSSLScalar, modulo: C.group.order))
|
||||
try! Self(C.__ffac.subtract(left.openSSLScalar, from: ArbitraryPrecisionInteger.zero))
|
||||
}
|
||||
|
||||
static func == (left: Self, right: Self) -> Bool {
|
||||
@@ -185,9 +204,7 @@ struct OpenSSLCurvePoint<C: OpenSSLSupportedNISTCurve>: GroupElement {
|
||||
}
|
||||
|
||||
static var generator: Self {
|
||||
// Force-try: Protocol requires non-throwing and this can only throw if group has no generator.
|
||||
// TODO: `BoringSSLEllipticCurveGroup.generator` should probably be non-throwing, like `.order`.
|
||||
try! Self(ecPoint: C.group.generator)
|
||||
Self(ecPoint: C.group.generator)
|
||||
}
|
||||
|
||||
static var random: Self {
|
||||
@@ -198,42 +215,42 @@ struct OpenSSLCurvePoint<C: OpenSSLSupportedNISTCurve>: GroupElement {
|
||||
return Self(ecPoint: point)
|
||||
}
|
||||
|
||||
static func + (left: Self, right: Self) -> Self {
|
||||
static func + (left: consuming Self, right: consuming Self) -> Self {
|
||||
// Force-try: Protocol requires non-throwing.
|
||||
try! Self(ecPoint: left.ecPoint.adding(right.ecPoint, on: C.group))
|
||||
try! Self(ecPoint: left.ecPoint.adding(right.ecPoint, on: C.group, context: C.__ffac))
|
||||
}
|
||||
|
||||
static func - (left: Self, right: Self) -> Self {
|
||||
static func - (left: consuming Self, right: consuming Self) -> Self {
|
||||
// Force-try: Protocol requires non-throwing.
|
||||
try! Self(ecPoint: left.ecPoint.subtracting(right.ecPoint, on: C.group))
|
||||
try! Self(ecPoint: left.ecPoint.subtracting(right.ecPoint, on: C.group, context: C.__ffac))
|
||||
}
|
||||
|
||||
static prefix func - (left: Self) -> Self {
|
||||
// Force-try: Protocol requires non-throwing.
|
||||
try! Self(ecPoint: left.ecPoint.inverting(on: C.group))
|
||||
try! Self(ecPoint: left.ecPoint.inverting(on: C.group, context: C.__ffac))
|
||||
}
|
||||
|
||||
static func * (left: Scalar, right: Self) -> Self {
|
||||
static func * (left: consuming Scalar, right: consuming Self) -> Self {
|
||||
// Force-try: Protocol requires non-throwing.
|
||||
try! Self(ecPoint: .multiplying(right.ecPoint, by: left.openSSLScalar, on: C.group))
|
||||
try! Self(ecPoint: right.ecPoint.multiplying(by: left.openSSLScalar, on: C.group, context: C.__ffac))
|
||||
}
|
||||
|
||||
static func == (left: Self, right: Self) -> Bool {
|
||||
left.ecPoint.isEqual(to: right.ecPoint, on: C.group)
|
||||
left.ecPoint.isEqual(to: right.ecPoint, on: C.group, context: C.__ffac)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension OpenSSLCurvePoint {
|
||||
var compressedRepresentation: Data {
|
||||
try! self.ecPoint.x962Representation(compressed: true, on: C.group)
|
||||
try! self.ecPoint.x962Representation(compressed: true, on: C.group, context: C.__ffac)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension OpenSSLCurvePoint: OPRFGroupElement {
|
||||
init(oprfRepresentation data: Data) throws {
|
||||
let point = try EllipticCurvePoint(x962Representation: data, on: C.group)
|
||||
let point = try EllipticCurvePoint(x962Representation: data, on: C.group, context: C.__ffac)
|
||||
self.init(ecPoint: point)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2025 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Foundation
|
||||
|
||||
extension Data {
|
||||
// This overload reduces allocations when used in a chain of infix operations.
|
||||
static func + (lhs: consuming Data, rhs: consuming Data) -> Data {
|
||||
lhs.append(contentsOf: rhs)
|
||||
return lhs
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user