mirror of
https://github.com/apple/swift-crypto
synced 2026-11-22 04:30:39 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2cbadd726 | ||
|
|
deb49b961e | ||
|
|
0f6f68df04 | ||
|
|
1c80d3aff5 | ||
|
|
25847ff705 | ||
|
|
8c018d0882 | ||
|
|
a629920495 |
No files matched your search
@@ -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)
|
||||
}
|
||||
|
||||
@@ -35,6 +35,9 @@ extension P384 {
|
||||
|
||||
static var ciphersuite: Ciphersuite { Ciphersuite(H2G.self) }
|
||||
|
||||
/// The maximum length, in bytes, of an input, imposed by the two-byte length prefix in the RFC 9497 framing.
|
||||
static let maximumInputByteCount = 0xFFFF
|
||||
|
||||
/// A P-384 public key used to blind inputs and finalize blinded elements.
|
||||
public struct PublicKey {
|
||||
fileprivate typealias BackingPublicKey = P384.Signing.PublicKey
|
||||
@@ -367,6 +370,9 @@ extension P384._VOPRF {
|
||||
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
|
||||
extension P384._VOPRF.PublicKey {
|
||||
internal func blind<D: DataProtocol>(_ input: D, with fixedBlind: P384._VOPRF.H2G.G.Scalar) throws -> P384._VOPRF.BlindedInput {
|
||||
guard input.count <= P384._VOPRF.maximumInputByteCount else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
let input = Data(input)
|
||||
let (blind, blindedElement) = Self.client.blindMessage(input, blind: fixedBlind)
|
||||
return P384._VOPRF.BlindedInput(
|
||||
@@ -436,6 +442,9 @@ extension P384._VOPRF.PrivateKey {
|
||||
///
|
||||
/// - Seealso: [RFC 9497: VOPRF Protocol - Evaluate]( https://cfrg.github.io/draft-irtf-cfrg-voprf/draft-irtf-cfrg-voprf.html#section-3.3.2-7).
|
||||
public func evaluate<D: DataProtocol>(_ input: D) throws -> Data {
|
||||
guard input.count <= P384._VOPRF.maximumInputByteCount else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
let inputElement = P384._VOPRF.H2G.hashToGroup(
|
||||
Data(input),
|
||||
domainSeparationString: Self.hashToGroupDST
|
||||
|
||||
@@ -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,38 @@ 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))
|
||||
}
|
||||
|
||||
func testInputLongerThanRFC9497LimitThrows() throws {
|
||||
let privateKey = P384._VOPRF.PrivateKey()
|
||||
let publicKey = privateKey.publicKey
|
||||
|
||||
// RFC 9497 caps inputs at 2^16 - 1 bytes, the most the two-byte length prefix in the framing can encode.
|
||||
let maximumInput = Data(repeating: 0x41, count: 0xFFFF)
|
||||
let blindedInput = try publicKey.blind(maximumInput)
|
||||
let blindEvaluation = try privateKey.evaluate(blindedInput.blindedElement)
|
||||
XCTAssertNoThrow(try publicKey.finalize(blindedInput, using: blindEvaluation))
|
||||
XCTAssertNoThrow(try privateKey.evaluate(maximumInput))
|
||||
|
||||
// Oversized inputs are rejected where they enter, so finalize can never be given one.
|
||||
let oversizedInput = Data(repeating: 0x41, count: 0x1_0000)
|
||||
XCTAssertThrowsError(try publicKey.blind(oversizedInput))
|
||||
XCTAssertThrowsError(try privateKey.evaluate(oversizedInput))
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user