Compare commits

...
6 Commits
Author SHA1 Message Date
deadcaf3 deb49b961e Bound the cost of RSA prime factor recovery (#484)
### Motivation:

`extractPrimeFactors` squares `t` times per attempt, where `t` is the
number of trailing zero bits of `e * d - 1`. Nothing bounds `e`, `d` or
`n`, so the caller picks the cost. A 2.5 KB `d` takes about 45 s before
throwing.

### Modifications:

- Reject `e >= n`, `d >= n`, and moduli over 8192 bits before factoring
- Throw once `g^(e * d - 1) != 1`, since then the numbers cannot form a
key
- Add tests for oversized and inconsistent numbers
- Keep the #482 attempt-limit test reaching the limit now that `e >= n`
is rejected

### Result:

These inputs now throw immediately. No public API change.

Valid keys aren't affected: they always have `e < n` and `d < n`, and
BoringSSL already rejects moduli over 8192 bits.

The oversized-number test fails on `main` and passes with this change.
The RSA tests pass on macOS.

Fixes #483
2026-10-20 09:38:39 +01:00
deadcaf3 0f6f68df04 Bound prime factor recovery in RSA _createFromNumbers (#482)
### Motivation:

`_createFromNumbers(n:e:d:)` can hang forever on some inputs. `e = 1, d
= 1` is enough to trigger it

`extractPrimeFactors` is meant to stop after 100 tries, but the
`continue` for a trivial base (`y` is `1` or `n - 1`) skipped the
counter. If every base is trivial, the loop never ends

### Modifications:

- Use `for _ in 0..<100` so every try counts
- Throw early when `e * d == 1`
- Add tests for both failing inputs

### Result:

These inputs now throw instead of hanging. No public API change.

The new tests hang on `main` and pass with this change. The full suite
passes on macOS and Linux.

Valid keys arent affected. Each try works at least half the time, so 100
failed tries wont happen in practice.

Fixes a hang in `_createFromNumbers(n:e:d:)`.

Fixes #481
2026-10-16 13:53:27 +00:00
Si Beaumont 1c80d3aff5 Require compressed encoding when deserializing OPRF elements (#479)
### Motivation:

`P384._VOPRF.BlindedElement(oprfRepresentation:)` accepts uncompressed
x9.63 encoded inputs, but RFC 9497 states
only inputs using compressed encoding should be accepted:

```
SerializeElement(A): Implemented using the compressed Elliptic-Curve-Point-to-Octet-String method...

DeserializeElement(buf): Implemented by attempting to deserialize a 49-byte array to a public key
                         using the compressed Octet-String-to-Elliptic-Curve-Point method...
```

### Modifications:

- Add input guard to only accept points using compressed representation.
- Extend the tests.

### Result:

- OPRF element deserialization accepts only the compressed encoding.
- Uncompressed encodings now throw
`CryptoKitError.incorrectParameterSize`.
2026-10-09 11:38:27 +00:00
Si Beaumont 25847ff705 Make ARC presentation verification cost independent of the nonce (#478)
### Motivation:

ARC presentation verification derives the tag using a loop that scales
with the client-provided nonce, but it has everything it needs to
recompute it with a scalar multiplication.

### Modifications:

- Add a failing test.
- Recompute `m1Tag` as `T - nonceScalar * self.tag`, the same way the
prover does.

### Result:

ARC presentation verification computation independent of magnitude of
nonce.
2026-10-09 11:17:31 +00:00
Si Beaumont 8c018d0882 Fix compact representability for points above the field midpoint (#477)
### Motivation:

An EC point has a compact representation if a condition holds based on
the field prime, but `_isCompactReprestable` mistakenly uses the group
order, which is not the same. This is an issue in our BoringSSL backend
only.

### Modifications:

- Subtract `y` from the field prime rather than `group.order` in
`_isCompactRepresentable`.
- Add tests.

### Result:

`compactRepresentation` now aligns with `init(compactRepresentation:)`,
the draft, and CryptoKit for all curve points.
2026-10-09 11:57:20 +01:00
apple-ospo[bot] a629920495 Housekeeping: replace repo-level CODE_OF_CONDUCT (#476) 2026-09-25 22:47:28 +01:00
10 changed files with 212 additions and 14 deletions

No files matched your search

-3
View File
@@ -1,3 +0,0 @@
# Code of Conduct
The code of conduct for this project can be found at https://swift.org/code-of-conduct.
@@ -684,7 +684,7 @@ func readRawPublicNumbers(
/// In a number of places we need to know if an EC key is compact representable. This function implements that check.
///
/// The check is defined in https://tools.ietf.org/id/draft-jivsov-ecc-compact-05.html#rfc.section.4.2.1. Specifically, a
/// point is compact representable if its y coordinate is the smaller of min(y, p-y) where p is the order of the prime field.
/// point is compact representable if its y coordinate is the smaller of min(y, p-y) where p is the prime of the base field.
@usableFromInline
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
func _isCompactRepresentable(
@@ -699,7 +699,7 @@ func _isCompactRepresentable(
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
let context = try! FiniteFieldArithmeticContext(fieldSize: p)
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
let newY = try! context.subtract(y, from: group.order)
let newY = try! context.subtract(y, from: p)
// The point is compact representable if y is less than or equal to newY.
return y <= newY
@@ -108,8 +108,8 @@ extension ARC {
let T = H2G.hashToGroup(presentationContext, domainSeparationString: Data(("HashToGroup-" + ciphersuite.domain + "Tag").utf8))
// Recompute m1Tag = H2G(presentationContext) - nonce * tag
var m1Tag = T
for _ in 0..<nonce { m1Tag = m1Tag - self.tag }
let nonceScalar = try Group.Scalar(bytes: I2OSP(value: nonce, outputByteCount: ciphersuite.scalarByteCount), reductionIsModOrder: true)
let m1Tag = T - nonceScalar * self.tag
// Create a verifier, and allocate variables for the constrained scalars.
var verifier = Verifier<H2G>(label: ciphersuite.domain + ciphersuite.domain + "CredentialPresentation")
@@ -276,6 +276,9 @@ extension OpenSSLCurvePoint {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension OpenSSLCurvePoint: OPRFGroupElement {
init(oprfRepresentation data: Data) throws {
guard data.count == C.compressedx962PointByteCount else {
throw CryptoKitError.incorrectParameterSize
}
let point = try EllipticCurvePoint(x962Representation: data, on: C.group, context: C.__ffac)
self.init(ecPoint: point)
}
+27 -7
View File
@@ -834,21 +834,37 @@ extension _RSA {
d: ArbitraryPrecisionInteger
) throws -> (p: ArbitraryPrecisionInteger, q: ArbitraryPrecisionInteger) {
// This is based on the proof of fact 1 in https://www.ams.org/notices/199902/boneh.pdf
let k = (d * e) - 1
let t = k.trailingZeroBitCount
let r = k >> t
guard k.isEven else {
// Valid keys have e < n, and BoringSSL rejects d >= n and moduli over its maximum. Larger
// values let the caller pick the cost of the exponentiations and squaring loop below.
guard n.byteCount <= _RSA.maximumModulusBitCount / 8, e < n, d < n else {
throw CryptoKitError.incorrectParameterSize
}
let k = (d * e) - 1
// k == 0 (that is, e * d == 1) gives r == 0 below, for which every base is trivial.
guard k > 0, k.isEven else {
throw CryptoKitError.incorrectParameterSize
}
let t = k.trailingZeroBitCount
let r = k >> t
var y: ArbitraryPrecisionInteger = 0
var i = 1
let context = try FiniteFieldArithmeticContext(fieldSize: n)
while i <= 100 {
// Every attempt must count towards the limit, including those where g^r is trivially
// 1 or n - 1. Inputs for which that holds for every base would otherwise never return.
for _ in 0..<100 {
let g = try ArbitraryPrecisionInteger.random(inclusiveMin: 2, exclusiveMax: n)
// The check at the end of this attempt only holds for bases coprime to n.
guard try ArbitraryPrecisionInteger.gcd(g, n) == 1 else {
continue
}
y = try context.pow(g, r)
guard y != 1, y != n - 1 else {
@@ -877,7 +893,11 @@ extension _RSA {
return (p, q)
}
i &+= 1
// Here x is g^k unless the loop stopped at n - 1. For a valid key g^k == 1 for every
// base coprime to n, so any other value means the numbers do not form a key.
guard x == n - 1 else {
throw CryptoKitError.incorrectParameterSize
}
}
throw CryptoKitError.incorrectParameterSize
@@ -1131,3 +1131,8 @@ enum BlindSigningHelpers {
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension _RSA {
static let maximumModulusBitCount = Int(OPENSSL_RSA_MAX_MODULUS_BITS)
}
@@ -158,6 +158,61 @@ class ARCTests: XCTestCase {
// try endToEndWorkflow(CurveType: P521.self)
}
func testVerifyCostIsIndependentOfTheNonce() async throws {
let ciphersuite = ARC.Ciphersuite(HashToCurveImpl<P256>.self)
let (generatorG, generatorH) = ARC.getGenerators(suite: ciphersuite)
let x0 = GroupImpl<P256>.Scalar.random
let x1 = GroupImpl<P256>.Scalar.random
let x2 = GroupImpl<P256>.Scalar.random
let x0Blinding = GroupImpl<P256>.Scalar.random
let serverPrivateKey = ARC.ServerPrivateKey(x0: x0, x1: x1, x2: x2, x0Blinding: x0Blinding)
let server = ARC.Server(ciphersuite: ciphersuite, x0: x0, x1: x1, x2: x2, x0Blinding: x0Blinding)
let requestContext = Data("test request context".utf8)
let precredential = try ARC.Precredential(
ciphersuite: ciphersuite,
m1: GroupImpl<P256>.Scalar.random,
requestContext: requestContext,
r1: GroupImpl<P256>.Scalar.random,
r2: GroupImpl<P256>.Scalar.random,
serverPublicKey: server.serverPublicKey
)
let credential = try precredential.makeCredential(
credentialResponse: try server.respond(credentialRequest: precredential.credentialRequest)
)
// The nonce comes from the client, so presentation verification cost must not scale with nonce.
// This test uses such a large nonce that the test would hit the timeout if verification was correlated.
let nonce = 1 << 62
let presentationContext = Data("0123456789".utf8)
let presentation = try ARC.Presentation(
credential: credential,
presentationContext: presentationContext,
nonce: nonce,
generatorG: generatorG,
generatorH: generatorH
)
let verificationResult: LockedBox<Bool?> = .init(initialValue: nil)
let finished = expectation(description: "verification finished")
let thread = Thread {
let result = try? presentation.verify(
serverPrivateKey: serverPrivateKey,
X1: x1 * generatorH,
m2: precredential.clientSecrets.m2,
presentationContext: presentationContext,
presentationLimit: Int.max,
nonce: nonce,
generatorG: generatorG,
generatorH: generatorH,
ciphersuite: ciphersuite)
verificationResult.withLockedValue { $0 = result }
finished.fulfill()
}
thread.start()
await fulfillment(of: [finished], timeout: 10)
XCTAssertEqual(verificationResult.withLockedValue { $0 }, true)
}
func testPresentationState() throws {
let context1 = Data("context1".utf8)
let context2 = Data("context2".utf8)
@@ -79,4 +79,21 @@ final class VOPRFPublicAPITests: XCTestCase {
// [Server] Compute the PRF for the input, without blinding or proof generation.
let _: Data = try privateKey.evaluate(input)
}
func testBlindedElementRejectsUncompressedOPRFRepresentation() throws {
/// Check we only accept compressed encoded elements, as per RFC 9497:
///
/// > SerializeElement(A): Implemented using the compressed Elliptic-Curve-Point-to-Octet-String method...
/// >
/// > DeserializeElement(buf): Implemented by attempting to deserialize a 49-byte array to a public key
/// using the compressed Octet-String-to-Elliptic-Curve-Point method...
///
/// - See: https://www.rfc-editor.org/rfc/rfc9497.html#name-oprfp-384-sha-384
let publicKey = P384._VOPRF.PrivateKey().publicKey
let blindedElement = try publicKey.blind(Data("This is some input data".utf8)).blindedElement
let compressed = blindedElement.oprfRepresentation
let uncompressed = try P384.Signing.PublicKey(compressedRepresentation: compressed).x963Representation
XCTAssertThrowsError(try P384._VOPRF.BlindedElement(oprfRepresentation: uncompressed))
}
}
@@ -1062,6 +1062,70 @@ final class TestRSASigning: XCTestCase {
}
}
func testConstructKeyFromRSANumbersWithDegenerateExponentsThrows() throws {
// e * d == 1 makes g^(e * d - 1) == 1 for every base, so prime recovery can never
// make progress. This must throw rather than retry forever.
var n = [UInt8](repeating: 0xA7, count: 256)
n[255] = 0x01
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey._createFromNumbers(n: n, e: [1] as [UInt8], d: [1] as [UInt8])
)
XCTAssertThrowsError(
try _RSA.Encryption.PrivateKey._createFromNumbers(n: n, e: [1] as [UInt8], d: [1] as [UInt8])
)
XCTAssertThrowsError(
try _RSA.BlindSigning.PrivateKey<SHA384>._createFromNumbers(
n: n, e: [1] as [UInt8], d: [1] as [UInt8], parameters: .RSABSSA_SHA384_PSS_Randomized
)
)
}
func testExtractPrimeFactorsGivesUpWhenEveryBaseIsTrivial() throws {
// n = 7 is prime and e * d - 1 == 24 == 2^3 * 3, so g^3 is 1 or n - 1 for every base g
// (the only cubic residues mod 7). The attempt limit must still apply.
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 7, e: 5, d: 5))
// e * d == 1 gives an exponent of 0, so g^0 == 1 for every base.
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 3233, e: 1, d: 1))
}
func testExtractPrimeFactorsRejectsOversizedNumbers() throws {
// d == 2753 is valid for n == 3233, e == 17. Adding lambda(n) == 780 keeps the numbers
// consistent, so only the range check rejects d >= n.
XCTAssertNoThrow(try _RSA.extractPrimeFactors(n: 3233, e: 17, d: 2753))
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 3233, e: 17, d: 2753 + 780))
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 3233, e: 17 + 780 * 5, d: 2753))
// e * d - 1 == 2^9992, so without the range check the squaring loop runs 9991 times
// per attempt.
var n = [UInt8](repeating: 0xA7, count: 256)
n[255] = 0x01
var d = [UInt8](repeating: 0, count: 1250)
d[0] = 0x01
d[1249] = 0x01
XCTAssertThrowsError(try _RSA.Signing.PrivateKey._createFromNumbers(n: n, e: [1] as [UInt8], d: d))
// A modulus over 8192 bits with d < n would otherwise make each attempt arbitrarily slow.
var bigN = [UInt8](repeating: 0xA7, count: 1025)
bigN[1024] = 0x01
var bigD = [UInt8](repeating: 0, count: 1025)
bigD[1] = 0x01
bigD[1024] = 0x01
XCTAssertThrowsError(try _RSA.Signing.PrivateKey._createFromNumbers(n: bigN, e: [1] as [UInt8], d: bigD))
}
func testExtractPrimeFactorsRejectsInconsistentNumbers() throws {
for testVector in RFC9474TestVector.allValues {
let n = try ArbitraryPrecisionInteger(bytes: Data(hexString: testVector.n))
let e = try ArbitraryPrecisionInteger(bytes: Data(hexString: testVector.e))
let d = try ArbitraryPrecisionInteger(bytes: Data(hexString: testVector.d))
// Using d = d + 2 means d is still even but no longer a multiple of lambda(n).
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: n, e: e, d: d + 2))
}
}
func testGetKeyPrimitives() throws {
for testVector in RFC9474TestVector.allValues {
let n = try Data(hexString: testVector.n)
@@ -0,0 +1,37 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import XCTest
#if canImport(CryptoKit)
// Skip tests that require @testable imports of CryptoKit.
#else
@testable import Crypto
extension ECKeyEncodingsTests {
func testCompactRepresentabilityIsDecidedByTheFieldPrime() throws {
// y = n + 1, the larger of the two square roots, so not compact representable.
let aboveMidpointX = try Data(hexString: "d1db3668128866847e66864aa97c37a04f65f6ff201a7d02345dffd738908975")
let aboveMidpointY = try Data(hexString: "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632552")
let aboveMidpoint = try P256.Signing.PublicKey(rawRepresentation: aboveMidpointX + aboveMidpointY)
XCTAssertNil(aboveMidpoint.compactRepresentation)
// n/2 < y <= (p-1)/2, the smaller of the two square roots, so compact representable.
let belowMidpointX = try Data(hexString: "ce2afeafa686293c6c93f644b3f6d796c659a9277ca4af6c15ef3bfdc6e00f89")
let belowMidpointY = try Data(hexString: "7fffffff800000007fffffffffffffffde737d56d38bcf4279dce5617e3192aa")
let belowMidpoint = try P256.Signing.PublicKey(rawRepresentation: belowMidpointX + belowMidpointY)
XCTAssertEqual(belowMidpoint.compactRepresentation, belowMidpointX)
}
}
#endif // canImport(CryptoKit)