diff --git a/.swiftformatignore b/.swiftformatignore index 5a490f50..b943b74d 100644 --- a/.swiftformatignore +++ b/.swiftformatignore @@ -68,6 +68,18 @@ Sources/_CryptoExtras/AES/AES_CFB.swift Sources/_CryptoExtras/AES/AES_CTR.swift Sources/_CryptoExtras/AES/AES_GCM_SIV.swift Sources/_CryptoExtras/AES/Block Function.swift +Sources/_CryptoExtras/ARC/ARC+API.swift +Sources/_CryptoExtras/ARC/ARC.swift +Sources/_CryptoExtras/ARC/ARCCredential.swift +Sources/_CryptoExtras/ARC/ARCEncoding.swift +Sources/_CryptoExtras/ARC/ARCPrecredential.swift +Sources/_CryptoExtras/ARC/ARCPresentation.swift +Sources/_CryptoExtras/ARC/ARCRequest.swift +Sources/_CryptoExtras/ARC/ARCResponse.swift +Sources/_CryptoExtras/ARC/ARCServer.swift +Sources/_CryptoExtras/ZKPs/Prover.swift +Sources/_CryptoExtras/ZKPs/Verifier.swift +Sources/_CryptoExtras/ZKPs/ZKPToolbox.swift Sources/_CryptoExtras/ChaCha20CTR/ChaCha20CTR.swift Sources/_CryptoExtras/ECToolbox/ECToolbox.swift Sources/_CryptoExtras/H2G/HashToField.swift @@ -123,6 +135,11 @@ Tests/_CryptoExtrasTests/AES-GCM-SIV-Runner.swift Tests/_CryptoExtrasTests/AES_CBCTests.swift Tests/_CryptoExtrasTests/AES_CFBTests.swift Tests/_CryptoExtrasTests/AES_CTRTests.swift +Tests/_CryptoExtrasTests/ARC/ARCAPITests.swift +Tests/_CryptoExtrasTests/ARC/ARCEncodingTests.swift +Tests/_CryptoExtrasTests/ARC/ARCPublicAPITests.swift +Tests/_CryptoExtrasTests/ARC/ARCTestVectors.swift +Tests/_CryptoExtrasTests/ARC/ARCTests.swift Tests/_CryptoExtrasTests/ChaCha20CTRTests.swift Tests/_CryptoExtrasTests/ECToolbox/HashToCurveTests.swift Tests/_CryptoExtrasTests/OPRFs/ECVOPRFTests.swift @@ -139,3 +156,4 @@ Tests/_CryptoExtrasTests/Utils/RFCVector.swift Tests/_CryptoExtrasTests/Utils/SplitData.swift Tests/_CryptoExtrasTests/Utils/Wycheproof.swift Tests/_CryptoExtrasTests/Utils/XCTestUtils.swift +Tests/_CryptoExtrasTests/ZKPs/ZKPToolbox.swift diff --git a/Sources/_CryptoExtras/ARC/ARC+API.swift b/Sources/_CryptoExtras/ARC/ARC+API.swift new file mode 100644 index 00000000..0e13034b --- /dev/null +++ b/Sources/_CryptoExtras/ARC/ARC+API.swift @@ -0,0 +1,397 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +import Crypto +import Foundation + +// MARK: - P384 + ARC(P-384) +@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, *) +extension P384 { + /// Anonymous Rate-Limited Credentials (ARC). + /// + /// A specialization of keyed-verification anonymous credentials with support for rate limiting. + /// + /// - Seealso: [IETF Internet Draft: draft-yun-cfrg-arc-00](https://datatracker.ietf.org/doc/draft-yun-cfrg-arc). + public enum _ARCV1 { + internal typealias H2G = HashToCurveImpl + // TODO: are these typealiases doing anything useful? + fileprivate typealias Ciphersuite = ARC.Ciphersuite + fileprivate typealias Server = ARC.Server + + fileprivate static var ciphersuite: Ciphersuite { Ciphersuite(H2G.self) } + } +} + +@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, *) +extension P384._ARCV1 { + /// The server secrets used to issue and verify credentials. + public struct PrivateKey { + fileprivate var backing: ARC.Server + + /// Creates a random private key for ARC(P-384). + public init() { + self.backing = ARC.Server(ciphersuite: P384._ARCV1.ciphersuite) + } + + // The spec does not define a serialization of the private key since, unlike the public key, it is not an + // interop concern. + // + // This initializer expects a concatenation of the binary representations of the private scalars: + // + // struct { + // uint8 x0[Ne]; + // uint8 x1[Ne]; + // uint8 x2[Ne]; + // uint8 x0Blinding[Ne]; + // } ServerPrivateKey; + // + // TODO: Confirm requiremnts for private key serialization format(s) and/or document binary scalar format. + public init(rawRepresentation: D) throws { + guard rawRepresentation.count == 4 * P384.orderByteCount else { + throw ARC.Errors.incorrectPrivateKeyDataSize + } + + var bytes = Data(rawRepresentation)[...] + let x0 = try H2G.G.Scalar(bytes: bytes[.. + + fileprivate init(backing: ARC.ServerPublicKey) { + self.backing = backing + } + + fileprivate static var serializedByteCount: Int { 3 * P384.compressedx962PointByteCount } + + // The spec defines this serialization of the public key: + // + // struct { + // uint8 X0[Ne]; + // uint8 X1[Ne]; + // uint8 X2[Ne]; + // } ServerPublicKey; + // + // TODO: Do we need other initializers over P384 elements, e.g. PEM? + public init(rawRepresentation: D) throws { + guard rawRepresentation.count == Self.serializedByteCount else { throw ARC.Errors.incorrectPublicKeyDataSize } + + var bytes = Data(rawRepresentation)[...] + let X0 = try H2G.G.Element(oprfRepresentation: bytes[.. + + fileprivate init(backing: ARC.CredentialRequest) { + self.backing = backing + } + + public init(rawRepresentation: D) throws { + self.backing = try ARC.CredentialRequest.deserialize(requestData: rawRepresentation) + } + + public var rawRepresentation: Data { + self.backing.serialize() + } + } + + /// A credential request to be sent to the server, and associated client secrets. + /// + /// Users cannot create values of this type manually; they are created using the prepare method on the public key. + public struct Precredential { + /// This backing type binds many things together, including the server commitments, client secrets, credential + /// request, and presentation limit. + fileprivate var backing: ARC.Precredential + + /// The credential request to be sent to the server. + public var credentialRequest: CredentialRequest { + CredentialRequest(backing: self.backing.credentialRequest) + } + } + + /// A credential response, created by the server, to be sent to the client. + /// + /// Servers should not create values of this type manually; they should use the issue method on the private key. + /// + /// Clients should reconstruct values of this type from the serialized bytes sent by the server. + public struct CredentialResponse { + var backing: ARC.CredentialResponse + + fileprivate init(backing: ARC.CredentialResponse) { + self.backing = backing + } + + public init(rawRepresentation: D) throws { + self.backing = try ARC.CredentialResponse.deserialize(responseData: rawRepresentation) + } + + public var rawRepresentation: Data { + self.backing.serialize() + } + } + + + /// A credential, created by the client using the response from the server. + /// + /// Users cannot create values of this type manually; they are created using the issue method on the public key. + public struct Credential { + var backing: ARC.Credential + + fileprivate init(backing: ARC.Credential) { + self.backing = backing + } + + /// The presentation limit enforced for this credential. + public var presentationLimit: Int { self.backing.presentationLimit } + } + + /// A presentation, created by the client from a credential, to be sent to the server to verify. + /// + /// Users cannot create values of this type manually; they are created using the present method on the credential. + public struct Presentation { + internal var backing: ARC.Presentation + + fileprivate init(backing: ARC.Presentation) { + self.backing = backing + } + + public init(rawRepresentation: D) throws { + self.backing = try ARC.Presentation.deserialize(presentationData: rawRepresentation) + } + + public var rawRepresentation: Data { + self.backing.serialize() + } + + // TODO: Confirm if we need/want to expose this to adopters. + // There's been some churn around nonce-management being in- or out-of-band, and we need to confirm what the + // server needs access to in order to enforce rate-limiting. Now that nonces are sent out-of-band, does the + // server also need access to the tag? If not, we should remove it from the API. + public var tag: Data { + self.backing.tag.compressedRepresentation + } + } +} + +@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, *) +extension P384._ARCV1.PublicKey { + internal func prepareCredentialRequest( + requestContext: D, + presentationLimit: Int, + m1: P384._ARCV1.H2G.G.Scalar, + r1: P384._ARCV1.H2G.G.Scalar, + r2: P384._ARCV1.H2G.G.Scalar + ) throws -> P384._ARCV1.Precredential { + let precedential = try ARC.Precredential( + ciphersuite: P384._ARCV1.ciphersuite, + m1: m1, + requestContext: Data(requestContext), + r1: r1, + r2: r2, + serverPublicKey: self.backing, + presentationLimit: presentationLimit + ) + return P384._ARCV1.Precredential(backing: precedential) + } + + /// Prepare a credential request for a given request context. + /// + /// - Parameters: + /// - requestContext: Request context, agreed with the server. + /// - presentationLimit: The presentation limit, agreed with the server. + /// + /// - Returns: A precredential containing the client secrets, and request to be sent to the server. + public func prepareCredentialRequest( + requestContext: D, + presentationLimit: Int + ) throws -> P384._ARCV1.Precredential { + try self.prepareCredentialRequest( + requestContext: requestContext, + presentationLimit: presentationLimit, + m1: .random, + r1: .random, + r2: .random + ) + } +} + +@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, *) +extension P384._ARCV1.PrivateKey { + internal func issue( + _ credentialRequest: P384._ARCV1.CredentialRequest, + b: P384._ARCV1.H2G.G.Scalar + ) throws -> P384._ARCV1.CredentialResponse { + let response = try self.backing.respond(credentialRequest: credentialRequest.backing, b: b) + return P384._ARCV1.CredentialResponse(backing: response) + } + + /// Generate a credential response from a credential request. + public func issue(_ credentialRequest: P384._ARCV1.CredentialRequest) throws -> P384._ARCV1.CredentialResponse { + try self.issue(credentialRequest, b: .random) + } +} + +@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, *) +extension P384._ARCV1.PublicKey { + /// Create a credential from the issuer response. + public func finalize( + _ credentialResponse: P384._ARCV1.CredentialResponse, + for precredential: P384._ARCV1.Precredential + ) throws -> P384._ARCV1.Credential { + let credential = try precredential.backing.makeCredential(credentialResponse: credentialResponse.backing) + return P384._ARCV1.Credential(backing: credential) + } +} + +@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, *) +extension P384._ARCV1.Credential { + internal mutating func makePresentation( + context: D, + fixedNonce: Int?, + a: P384._ARCV1.H2G.G.Scalar, + r: P384._ARCV1.H2G.G.Scalar, + z: P384._ARCV1.H2G.G.Scalar + ) throws -> (presentation: P384._ARCV1.Presentation, nonce: Int) { + let (presentation, nonce) = try self.backing.makePresentation( + presentationContext: Data(context), + a: a, r: r, z: z, optionalNonce: fixedNonce + ) + return (P384._ARCV1.Presentation(backing: presentation), nonce) + } + + /// Create a presentation to provide to a verifier. + /// + /// - Parameter context: The presentation context agreed with the verifier. + /// + /// - Returns: A presentation of this credential. + /// + /// - Throws: An error if the presentation limit for this credential has been exceeded. + // TODO: Should makePresentation return a nominal type instead of a tuple? + public mutating func makePresentation( + context: D + ) throws -> (presentation: P384._ARCV1.Presentation, nonce: Int) { + try self.makePresentation(context: context, fixedNonce: nil, a: .random, r: .random, z: .random) + } +} + +@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, *) +extension P384._ARCV1.PrivateKey { + /// Verify a presentation is valid for a given attribute. + /// + /// Presentation verification includes checking that: + /// 1. The presentation is for the expected request context. + /// 2. The presentation is for the expected presentation context. + /// 3. The presentation nonce is appropriate for the presentation limit. + /// 4. The presentation proof is valid. + /// + /// - Parameters: + /// - presentation: The presentation to verify. + /// - requestContext: The expected request context encoded within the presentation. + /// - presentationContext: The expected presentation context encoded within the presentation. + /// - presentationLimit: The presentation limit to enforce. + /// - nonce: The expected nonce encoded within the presentation. + /// + /// - Returns: True if the presentation is valid, false otherwise. + public func verify( + _ presentation: P384._ARCV1.Presentation, + requestContext: D1, + presentationContext: D2, + presentationLimit: Int, + nonce: Int + ) throws -> Bool { + try self.backing.verify( + presentation: presentation.backing, + requestContext: Data(requestContext), + presentationContext: Data(presentationContext), + presentationLimit: presentationLimit, + nonce: nonce + ) + } +} diff --git a/Sources/_CryptoExtras/ARC/ARC.swift b/Sources/_CryptoExtras/ARC/ARC.swift new file mode 100644 index 00000000..b85238c4 --- /dev/null +++ b/Sources/_CryptoExtras/ARC/ARC.swift @@ -0,0 +1,63 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +import Crypto +import Foundation + +/// Anonymous Rate-Limited Credentials (ARC) using the CMZ14 MACGGM construction, as defined in +/// https://chris-wood.github.io/draft-arc/draft-yun-cfrg-arc.html +enum ARC {} + +extension ARC { + static let domain = "ARCV1-P384" + + enum Errors: Error { + case invalidProof + case invalidPresentationLimit + case presentationLimitExceeded + case incorrectRequestDataSize + case incorrectResponseDataSize + case incorrectCredentialDataSize + case incorrectPresentationDataSize + case incorrectProofDataSize + case incorrectServerCommitmentsSize + case incorrectPrivateKeyDataSize + case incorrectPublicKeyDataSize + } + + /// Ciphersuites for Anonymous Rate-Limited Credentials (ARC) + struct Ciphersuite { + let suiteID: Int + + init(_ h2g: H2G.Type) { + switch h2g.self { + case is HashToCurveImpl.Type: + self.suiteID = 3 + case is HashToCurveImpl.Type: + self.suiteID = 4 + case is HashToCurveImpl.Type: + self.suiteID = 5 + default: + fatalError("Anonymous Rate-Limited Credentials (ARC) only support corecrypto H2G.") + } + } + } + + static func getGenerators(suite _: Ciphersuite) -> ( + generatorG: H2G.G.Element, generatorH: H2G.G.Element + ) { + let generatorG = H2G.G.Element.generator + let generatorH = H2G.hashToGroup(generatorG.oprfRepresentation, domainSeparationString: Data(("HashToGroup-" + ARC.domain + "generatorH").utf8)) + return (generatorG, generatorH) + } +} diff --git a/Sources/_CryptoExtras/ARC/ARCCredential.swift b/Sources/_CryptoExtras/ARC/ARCCredential.swift new file mode 100644 index 00000000..96c79ade --- /dev/null +++ b/Sources/_CryptoExtras/ARC/ARCCredential.swift @@ -0,0 +1,85 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +import Crypto +import Foundation + +extension ARC { + struct Credential { + typealias Group = H2G.G + let m1: Group.Scalar + let U: Group.Element + let UPrime: Group.Element + let X1: Group.Element + let ciphersuite: Ciphersuite + let generatorG: Group.Element + let generatorH: Group.Element + let presentationLimit: Int + var presentationNonces: [Data: Set] + + init(credentialResponse: CredentialResponse, credentialRequest: CredentialRequest, clientSecrets: ClientSecrets, serverPublicKey: ServerPublicKey, ciphersuite: Ciphersuite, generatorG: Group.Element, generatorH: Group.Element, presentationLimit: Int) throws { + // Verify credential response proof + guard + try credentialResponse.verify(request: credentialRequest, serverPublicKey: serverPublicKey, generatorG: generatorG, generatorH: generatorH) + else { + throw ARC.Errors.invalidProof + } + + // Decrypt Enc(U') from the credential response, to get U' + let UPrime = credentialResponse.encUPrime - credentialResponse.X0Aux - clientSecrets.r1 * credentialResponse.X1Aux - clientSecrets.r2 * credentialResponse.X2Aux + + let presentationNonces = [Data: Set]() + self = Self(m1: clientSecrets.m1, U: credentialResponse.U, UPrime: UPrime, X1: serverPublicKey.X1, presentationLimit: presentationLimit, presentationNonces: presentationNonces, ciphersuite: ciphersuite, generatorG: generatorG, generatorH: generatorH) + } + + internal init(m1: Group.Scalar, U: Group.Element, UPrime: Group.Element, X1: Group.Element, presentationLimit: Int, presentationNonces: [Data: Set], ciphersuite: Ciphersuite, generatorG: Group.Element, generatorH: Group.Element) { + self.m1 = m1 + self.U = U + self.UPrime = UPrime + self.X1 = X1 + self.presentationLimit = presentationLimit + self.presentationNonces = presentationNonces + self.ciphersuite = ciphersuite + self.generatorG = generatorG + self.generatorH = generatorH + } + + mutating func makePresentation(presentationContext: Data, a: Group.Scalar = Group.Scalar.random, r: Group.Scalar = Group.Scalar.random, z: Group.Scalar = Group.Scalar.random, optionalNonce: Int? = nil) throws -> (Presentation, Int) { + // If optionalNonce is set, use that nonce (eg for test vectors). + // Otherwise, generate a random nonce that has not yet been used. + var nonce = optionalNonce != nil ? optionalNonce! : Int.random(in: 0..= self.presentationLimit { + throw ARC.Errors.presentationLimitExceeded + } + while self.presentationNonces[presentationContext]!.contains(nonce) { + if optionalNonce == nil { + // Randomly generated nonce collides with existing nonce for presentationContext + nonce = Int.random(in: 0..(credential: self, a: a, r: r, z: z, presentationContext: presentationContext, nonce: nonce, generatorG: self.generatorG, generatorH: self.generatorH) + return (presentation, nonce) + } + } +} diff --git a/Sources/_CryptoExtras/ARC/ARCEncoding.swift b/Sources/_CryptoExtras/ARC/ARCEncoding.swift new file mode 100644 index 00000000..c2e32e9e --- /dev/null +++ b/Sources/_CryptoExtras/ARC/ARCEncoding.swift @@ -0,0 +1,281 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +import Foundation +import Crypto + +typealias ARCCurve = P384 +typealias ARCH2G = HashToCurveImpl + +internal func DecodeInt(value: Data) -> Int { + var result = Int(0) + + for i in 0.. Data { + return I2OSP(value: value, outputByteCount: 4) +} + +extension ARC.CredentialRequest where H2G == ARCH2G { + static let scalarCount = 5 + static let pointCount = 2 + static let serializedByteCount = pointCount * ARCCurve.compressedx962PointByteCount + 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 + } + + static func deserialize(requestData: D) throws -> ARC.CredentialRequest { + 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 + + let proofData = self.proof.serialize() + return responsePoints + proofData + } + + 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 + + let presentationProofData = self.proof.serialize() + return U + UPrimeCommit + m1Commit + tag + presentationProofData + } + + 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 + + return X0 + X1 + X2 + } + + 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.. Data { + let scalarCount = self.responses.count + 1 + var result = Data(capacity: scalarCount * ARCCurve.orderByteCount) + + // Serialize challenge + result.append(self.challenge.rawRepresentation) + // Serialize responses + for response in self.responses { + result.append(response.rawRepresentation) + } + return result + } + + static func deserialize(proofData: D, scalarCount: Int) throws -> Proof { + guard proofData.count == scalarCount * ARCCurve.orderByteCount else { + throw ARC.Errors.incorrectProofDataSize + } + let proofData = Data(proofData) + var startPointer = 0 + + // Deserialize challenge + let challenge = try GroupImpl.Scalar(bytes: proofData.subdata(in: startPointer...Scalar] = [] + 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 presentationLimit = EncodeInt(value: self.presentationLimit) + let noncesData = try ARCNonces.serialize(noncesDict: self.presentationNonces) + + return m1 + U + UPrime + X1 + genG + genH + presentationLimit + noncesData + } + + static func deserialize(credentialData: D) throws -> ARC.Credential { + let noncesByteCount = credentialData.count - self.scalarCount * ARCCurve.orderByteCount - self.pointCount * ARCCurve.compressedx962PointByteCount - integerByteCount + guard noncesByteCount >= 0 else { + throw ARC.Errors.incorrectCredentialDataSize + } + let credentialData = Data(credentialData) + + var startPointer = 0 + let m1 = try GroupImpl.Scalar(bytes: credentialData.subdata(in: startPointer..]) throws -> Data { + // Convert Set to Array for encoding + let dictForEncoding = noncesDict.mapValues {Array($0) } + let encoder = PropertyListEncoder() + encoder.outputFormat = .binary + return try encoder.encode(dictForEncoding) + } + + static func deserialize(noncesData: D) throws -> [Data: Set] { + let decoder = PropertyListDecoder() + // Decode as [Data: [Int]] and convert Array back to Set + let decodedDictionary = try decoder.decode([Data: [Int]].self, from: Data(noncesData)) + return decodedDictionary.mapValues { Set($0) } + } +} diff --git a/Sources/_CryptoExtras/ARC/ARCPrecredential.swift b/Sources/_CryptoExtras/ARC/ARCPrecredential.swift new file mode 100644 index 00000000..f15d9dde --- /dev/null +++ b/Sources/_CryptoExtras/ARC/ARCPrecredential.swift @@ -0,0 +1,59 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +import Crypto +import Foundation + +extension ARC { + struct ClientSecrets { + let m1: Scalar // secret at request and verification + let m2: Scalar // secret at request, public at verification (server expected to know value) + let r1: Scalar // secret blinding factor for m1 + let r2: Scalar // secret blinding factor for m2 + + init(m1: Scalar, m2: Scalar, r1: Scalar, r2: Scalar) { + self.m1 = m1 + self.m2 = m2 + self.r1 = r1 + self.r2 = r2 + } + } + + struct Precredential { + typealias Group = H2G.G + let clientSecrets: ClientSecrets + let serverPublicKey: ServerPublicKey + let ciphersuite: Ciphersuite + let generatorG: Group.Element + let generatorH: Group.Element + let credentialRequest: CredentialRequest + let presentationLimit: Int + + init(ciphersuite: Ciphersuite, m1: Group.Scalar = Group.Scalar.random, requestContext: Data, r1: Group.Scalar = Group.Scalar.random, r2: Group.Scalar = Group.Scalar.random, serverPublicKey: ServerPublicKey, presentationLimit: Int) throws { + if presentationLimit <= 0 { + throw ARC.Errors.invalidPresentationLimit + } + let m2 = try H2G.hashToScalar(requestContext, domainSeparationString: Data((ARC.domain + "requestContext").utf8)) + self.clientSecrets = ClientSecrets(m1: m1, m2: m2, r1: r1, r2: r2) + self.serverPublicKey = serverPublicKey + self.ciphersuite = ciphersuite + (self.generatorG, self.generatorH) = ARC.getGenerators(suite: ciphersuite) + self.credentialRequest = try CredentialRequest(clientSecrets: self.clientSecrets, generatorG: generatorG, generatorH: generatorH) + self.presentationLimit = presentationLimit + } + + func makeCredential(credentialResponse: CredentialResponse) throws -> Credential { + return try Credential(credentialResponse: credentialResponse, credentialRequest: self.credentialRequest, clientSecrets: self.clientSecrets, serverPublicKey: self.serverPublicKey, ciphersuite: self.ciphersuite, generatorG: self.generatorG, generatorH: self.generatorH, presentationLimit: self.presentationLimit) + } + } +} diff --git a/Sources/_CryptoExtras/ARC/ARCPresentation.swift b/Sources/_CryptoExtras/ARC/ARCPresentation.swift new file mode 100644 index 00000000..790320b2 --- /dev/null +++ b/Sources/_CryptoExtras/ARC/ARCPresentation.swift @@ -0,0 +1,149 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +import Crypto +import Foundation + +extension ARC { + /// Presentation consists of a commitment to a MACGGC evaluation over two attributes, + /// a commitment to one of the attributes, a tag and its public inputs (presentationContext, nonce), + /// along with a zero-knowledge proof of the following statements: + /// 1. `m1Commit = m1 * U + z * generatorH`, for attribute `m1` and random `z`. + /// 2. `V = z * X1 - r * generatorG`, for random `z` and `r`. + /// 3. `H2G(presentationContext) = m1 * tag + nonce * tag` + /// 4. `m1Tag = m1 * tag` + struct Presentation { + typealias Group = H2G.G + /// Generator over which `m1Commit` commits to `m1`. + let U: Group.Element + /// Commitment to the MACGGC evaluation over the client attributes. + let UPrimeCommit: Group.Element + /// Commitment to `m1` over `U`. + let m1Commit: Group.Element + /// Group element `tag = (m1 + nonce)^(-1) * H2G(presentationContext)`, where `m1` is committed to by `m1Commit`. + let tag: Group.Element + /// Proof of correct computation of U, UPrimeCommit, m1Commit, and tag, given the presentationContext, nonce, generators, and secrets. + let proof: Proof + + init(credential: Credential, a: Group.Scalar = Group.Scalar.random, r: Group.Scalar = Group.Scalar.random, z: Group.Scalar = Group.Scalar.random, presentationContext: Data, nonce: Int, generatorG: Group.Element, generatorH: Group.Element) throws { + // Randomize (U, UPrime) + let U = a * credential.U + let m1Commit = credential.m1 * U + z * generatorH + let UPrime = a * credential.UPrime + let UPrimeCommit = UPrime + r * generatorG + let V = z * credential.X1 - r * generatorG + + // Create tag: (m1 + nonce)^(-1) * H2G(presentationContext) + let nonceScalar = try Group.Scalar(bytes: I2OSP(value: nonce, outputByteCount: ARCCurve.orderByteCount), reductionIsModOrder: true) + let inverse = (nonceScalar + credential.m1) ^ (-1) + let T = H2G.hashToGroup(presentationContext, domainSeparationString: Data(("HashToGroup-" + ARC.domain + "Tag").utf8)) + let tag = inverse * T + + // m1Tag is a helper element in the ZKP, and is needed to ensure the + // client-claimed nonce is equal to the nonce used to compute the tag. + let m1Tag = credential.m1 * tag + + // Create a prover, and allocate variables for the constrained scalars. + var prover = Prover(label: ARC.domain + ARC.domain + "CredentialPresentation") + let m1Var = prover.appendScalar(label: "m1", assignment: credential.m1) + let zVar = prover.appendScalar(label: "z", assignment: z) + let rNegVar = prover.appendScalar(label: "-r", assignment: -r) + let nonceVar = prover.appendScalar(label: "nonce", assignment: nonceScalar) + + // Allocate variables for the constrained points, and add the constraints. + Presentation.proofConstrain(participant: &prover, generatorG: generatorG, generatorH: generatorH, U: U, UPrimeCommit: UPrimeCommit, m1Commit: m1Commit, V: V, X1: credential.X1, T: T, tag: tag, m1Tag: m1Tag, m1Var: m1Var, zVar: zVar, rNegVar: rNegVar, nonceVar: nonceVar) + + let proof = try prover.prove() + self = Presentation(U: U, UPrimeCommit: UPrimeCommit, m1Commit: m1Commit, tag: tag, proof: proof) + } + + internal init(U: Group.Element, UPrimeCommit: Group.Element, m1Commit: Group.Element, tag: Group.Element, proof: Proof) { + self.U = U + self.UPrimeCommit = UPrimeCommit + self.m1Commit = m1Commit + self.tag = tag + self.proof = proof + } + + /** + - Parameters: + - serverPrivateKey: A collection of scalars representing the server private key, which it needs to verify the presentation. + - X1: Group element that is a commitment to x1, one of the server secrets. + - m2: Public value that server provides for verification. + - presentationContext: Data that is concatenated with the nonce and hashed to a group element, as input to the tag. + - presentationLimit: Integer representing the valid nonce range: `[0, presentationLimit)`. + - nonce: Integer which is used for rate limiting, which should be in `[0, presentationLimit)`. + - generatorG: Public generator G + - generatorH: Public generator H + - Returns: a boolean for if the tag is valid and the tag proof verifies correctly. + */ + func verify( + serverPrivateKey: ServerPrivateKey, X1: Group.Element, m2: Group.Scalar, presentationContext: Data, presentationLimit: Int, nonce: Int, + generatorG: Group.Element, generatorH: Group.Element + ) throws -> Bool { + if nonce < 0 || nonce >= presentationLimit { + return false // nonce is outside of the presentationLimit + } + + + if (self.U == self.U + self.U) || (self.UPrimeCommit == self.UPrimeCommit + self.UPrimeCommit) { + return false // U or UPrimeCommit are 0 + } + let V = serverPrivateKey.x0 * self.U + serverPrivateKey.x1 * self.m1Commit + serverPrivateKey.x2 * m2 * self.U - self.UPrimeCommit + + // Recompute T = H2G(presentationContext) + let T = H2G.hashToGroup(presentationContext, domainSeparationString: Data(("HashToGroup-" + ARC.domain + "Tag").utf8)) + + // Recompute m1Tag = H2G(presentationContext) - nonce * tag + var m1Tag = T + for _ in 0..(label: ARC.domain + ARC.domain + "CredentialPresentation") + let m1Var = verifier.appendScalar(label: "m1") + let zVar = verifier.appendScalar(label: "z") + let rNegVar = verifier.appendScalar(label: "-r") + let nonceVar = verifier.appendScalar(label: "nonce") + + // Allocate variables for the constrained points, and add the constraints. + Presentation.proofConstrain(participant: &verifier, generatorG: generatorG, generatorH: generatorH, U: self.U, UPrimeCommit: self.UPrimeCommit, m1Commit: self.m1Commit, V: V, X1: X1, T: T, tag: self.tag, m1Tag: m1Tag, m1Var: m1Var, zVar: zVar, rNegVar: rNegVar, nonceVar: nonceVar) + + return try verifier.verify(proof: self.proof) + } + + static internal func proofConstrain(participant: inout P, generatorG: Group.Element, generatorH: Group.Element, U: Group.Element, UPrimeCommit: Group.Element, m1Commit: Group.Element, V: Group.Element, X1: Group.Element, T: Group.Element, tag: Group.Element, m1Tag: Group.Element, m1Var: ScalarVar, zVar: ScalarVar, rNegVar: ScalarVar, nonceVar: ScalarVar) { + // Allocate point variables + let genGVar = participant.appendPoint(label: "genG", assignment: generatorG) + let genHVar = participant.appendPoint(label: "genH", assignment: generatorH) + let UVar = participant.appendPoint(label: "U", assignment: U) + // UPrimeCommit does not have to be explicitly constrained in the ZKP, as it is used in calculation of V which is constrained. + let _ = participant.appendPoint(label: "UPrimeCommit", assignment: UPrimeCommit) + let m1CommitVar = participant.appendPoint(label: "m1Commit", assignment: m1Commit) + let VVar = participant.appendPoint(label: "V", assignment: V) + let X1Var = participant.appendPoint(label: "X1", assignment: X1) + let tagVar = participant.appendPoint(label: "tag", assignment: tag) + let TVar = participant.appendPoint(label: "genT", assignment: T) + let m1TagVar = participant.appendPoint(label: "m1Tag", assignment: m1Tag) + + // 1. `m1Commit = m1 * U + z * generatorH`, for attribute `m1` and random `z`. + participant.constrain(result: m1CommitVar, linearCombination: [(m1Var, UVar), (zVar, genHVar)]) + // 2. `V = z * X1 - r * generatorG`, for random `z` and `r`. + // Simplified: `V = z * X1 + (-r) * generatorG` + participant.constrain(result: VVar, linearCombination: [(zVar, X1Var), (rNegVar, genGVar)]) + /// 3. `H2G(presentationContext) = m1 * tag + nonce * tag` + participant.constrain(result: TVar, linearCombination: [(m1Var, tagVar), (nonceVar, tagVar)]) + /// 4. `m1Tag = m1 * tag` + participant.constrain(result: m1TagVar, linearCombination: [(m1Var, tagVar)]) + } + } +} diff --git a/Sources/_CryptoExtras/ARC/ARCRequest.swift b/Sources/_CryptoExtras/ARC/ARCRequest.swift new file mode 100644 index 00000000..1e1b7dca --- /dev/null +++ b/Sources/_CryptoExtras/ARC/ARCRequest.swift @@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +import Crypto +import Foundation + +extension ARC { + /// CredentialRequest consists of encryptions of the two client attributes, in the form of Pedersen commitments, + /// along with a zero-knowledge proof of the following statements: + /// 1. `m1Enc = m1 * G + r1 * H`, for private attribute `m1` and random request blinding `r1` + /// 2. `m2Enc = m2 * G + r2 * H`, for private attribute `m2` and random request blinding `r2` + struct CredentialRequest { + typealias Group = H2G.G + let m1Enc: Group.Element + let m2Enc: Group.Element + let proof: Proof + + init(clientSecrets: ClientSecrets, generatorG: Group.Element, generatorH: Group.Element) throws { + let m1Enc = clientSecrets.m1 * generatorG + clientSecrets.r1 * generatorH + let m2Enc = clientSecrets.m2 * generatorG + clientSecrets.r2 * generatorH + + // Create a prover, and allocate variables for the constrained scalars. + var prover = Prover(label: ARC.domain + ARC.domain + "CredentialRequest") + let m1Var = prover.appendScalar(label: "m1", assignment: clientSecrets.m1) + let m2Var = prover.appendScalar(label: "m2", assignment: clientSecrets.m2) + let r1Var = prover.appendScalar(label: "r1", assignment: clientSecrets.r1) + let r2Var = prover.appendScalar(label: "r2", assignment: clientSecrets.r2) + + // Allocate variables for the constrained points, and add the constraints. + CredentialRequest.proofConstrain(participant: &prover, generatorG: generatorG, generatorH: generatorH, m1Enc: m1Enc, m2Enc: m2Enc, m1Var: m1Var, m2Var: m2Var, r1Var: r1Var, r2Var: r2Var) + + let proof = try prover.prove() + self = CredentialRequest(m1Enc: m1Enc, m2Enc: m2Enc, proof: proof) + } + + internal init(m1Enc: Group.Element, m2Enc: Group.Element, proof: Proof) { + self.m1Enc = m1Enc + self.m2Enc = m2Enc + self.proof = proof + } + + func verify(generatorG: Group.Element, generatorH: Group.Element) throws -> Bool { + // Check that the encrypted attributes were generated with nonzero `m` and `r` values. + if (self.m1Enc == generatorG || self.m1Enc == generatorH || self.m1Enc == self.m1Enc + self.m1Enc) || + (self.m2Enc == generatorG || self.m2Enc == generatorH || self.m2Enc == self.m2Enc + self.m2Enc) { + return false + } + + // Create a verifier, and allocate variables for the constrained scalars. + var verifier = Verifier(label: ARC.domain + ARC.domain + "CredentialRequest") + let m1Var = verifier.appendScalar(label: "m1") + let m2Var = verifier.appendScalar(label: "m2") + let r1Var = verifier.appendScalar(label: "r1") + let r2Var = verifier.appendScalar(label: "r2") + + // Allocate variables for the constrained points, and add the constraints. + CredentialRequest.proofConstrain(participant: &verifier, generatorG: generatorG, generatorH: generatorH, m1Enc: self.m1Enc, m2Enc: self.m2Enc, m1Var: m1Var, m2Var: m2Var, r1Var: r1Var, r2Var: r2Var) + + return try verifier.verify(proof: self.proof) + } + + static internal func proofConstrain(participant: inout P, generatorG: Group.Element, generatorH: Group.Element, m1Enc: Group.Element, m2Enc: Group.Element, m1Var: ScalarVar, m2Var: ScalarVar, r1Var: ScalarVar, r2Var: ScalarVar) { + // Allocate point variables + let genGVar = participant.appendPoint(label: "genG", assignment: generatorG) + let genHVar = participant.appendPoint(label: "genH", assignment: generatorH) + let m1EncVar = participant.appendPoint(label: "m1Enc", assignment: m1Enc) + let m2EncVar = participant.appendPoint(label: "m2Enc", assignment: m2Enc) + + // 1. `m1Enc = m1 * G + r1 * H`, for private attribute `m1` and random request blinding `r1` + participant.constrain(result: m1EncVar, linearCombination: [(m1Var, genGVar), (r1Var, genHVar)]) + // 2. `m2Enc = m2 * G + r2 * H`, for private attribute `m2` and random request blinding `r2` + participant.constrain(result: m2EncVar, linearCombination: [(m2Var, genGVar), (r2Var, genHVar)]) + } + + } +} diff --git a/Sources/_CryptoExtras/ARC/ARCResponse.swift b/Sources/_CryptoExtras/ARC/ARCResponse.swift new file mode 100644 index 00000000..4ef18351 --- /dev/null +++ b/Sources/_CryptoExtras/ARC/ARCResponse.swift @@ -0,0 +1,169 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +import Crypto +import Foundation + +extension ARC { + /// CredentialResponse consists of a MACGGM evaluation over a Pedersen commitment to a private attribute, + /// along with the corresponding proof that it was calculated correctly over the expected key commitments: + /// 1. `X0 = x0 * generatorG + x0Blinding * generatorH` + /// 2. `X1 = x1 * generatorH` + /// 3. `X2 = x2 * generatorH` + /// 4. `X0Aux = b * x0Blinding * generatorH` + /// 4a. `HAux = b * generatorH` + /// 4b: `X0Aux = x0Blinding * HAux` + /// 5. `X1Aux = b * x1 * generatorH` + /// 5a. `X1Aux = b * X1 (X1 = x1 * generatorH)` + /// 5b. `X1Aux = t1 * H (t1 = b * x1)` + /// 6. `X2Aux = b * x2 * generatorH` + /// 6a. `X2Aux = b * X2 (X2 = x2 * generatorH)` + /// 6b. `X2Aux = t2 * H (t2 = b * x2)` + /// 7. `U = b * generatorG` + /// 8. `encUPrime = b * (X0 + x1 * Enc(m1) + x2 * Enc(m2))` + struct CredentialResponse { + typealias Group = H2G.G + let U: Group.Element + let encUPrime: Group.Element + let X0Aux: Group.Element + let X1Aux: Group.Element + let X2Aux: Group.Element + let HAux: Group.Element + let proof: Proof + + init( + request: CredentialRequest, + serverPrivateKey: ServerPrivateKey, + serverPublicKey: ServerPublicKey, + generatorG: Group.Element, + generatorH: Group.Element, + b: Group.Scalar = Group.Scalar.random + ) throws { + let U = b * generatorG + let X0Aux = b * serverPrivateKey.x0Blinding * generatorH + let X1Aux = b * serverPublicKey.X1 + let X2Aux = b * serverPublicKey.X2 + let HAux = b * generatorH + + // Enc(U') = b * (Enc(x0) + x1 * Enc(m1) + x2 * Enc(m2)), for a homomorphic encryption scheme + // = b * (X0 + x1 * request.m1Enc + x2 * request.m2Enc) + let encUPrime = b * (serverPublicKey.X0 + serverPrivateKey.x1 * request.m1Enc + serverPrivateKey.x2 * request.m2Enc) + + // Create a prover, and allocate variables for the constrained scalars. + var prover = Prover(label: ARC.domain + ARC.domain + "CredentialResponse") + let x0Var = prover.appendScalar(label: "x0", assignment: serverPrivateKey.x0) + let x1Var = prover.appendScalar(label: "x1", assignment: serverPrivateKey.x1) + let x2Var = prover.appendScalar(label: "x2", assignment: serverPrivateKey.x2) + let x0BlindingVar = prover.appendScalar(label: "x0Blinding", assignment: serverPrivateKey.x0Blinding) + let bVar = prover.appendScalar(label: "b", assignment: b) + let t1Var = prover.appendScalar(label: "t1", assignment: b * serverPrivateKey.x1) + let t2Var = prover.appendScalar(label: "t2", assignment: b * serverPrivateKey.x2) + + // Allocate variables for the constrained points, and add the constraints. + CredentialResponse.proofConstrain(participant: &prover, request: request, generatorG: generatorG, generatorH: generatorH, U: U, encUPrime: encUPrime, X0: serverPublicKey.X0, X1: serverPublicKey.X1, X2: serverPublicKey.X2, X0Aux: X0Aux, X1Aux: X1Aux, X2Aux: X2Aux, HAux: HAux, x0Var: x0Var, x0BlindingVar: x0BlindingVar, x1Var: x1Var, x2Var: x2Var, bVar: bVar, t1Var: t1Var, t2Var: t2Var) + + let proof = try prover.prove() + self = CredentialResponse(U: U, encUPrime: encUPrime, X0Aux: X0Aux, X1Aux: X1Aux, X2Aux: X2Aux, HAux: HAux, proof: proof) + } + + internal init( + U: Group.Element, + encUPrime: Group.Element, + X0Aux: Group.Element, + X1Aux: Group.Element, + X2Aux: Group.Element, + HAux: Group.Element, + proof: Proof + ) { + self.U = U + self.encUPrime = encUPrime + self.X0Aux = X0Aux + self.X1Aux = X1Aux + self.X2Aux = X2Aux + self.HAux = HAux + self.proof = proof + } + + func verify(request: CredentialRequest, serverPublicKey: ServerPublicKey, generatorG: Group.Element, generatorH: Group.Element + ) throws -> Bool { + // Check that U, encUPrime are not 0 + if (self.U == self.U + self.U) || (self.encUPrime == self.encUPrime + self.encUPrime) { + return false + } + + // Create a verifier, and allocate variables for the constrained scalars. + var verifier = Verifier(label: ARC.domain + ARC.domain + "CredentialResponse") + let x0Var = verifier.appendScalar(label: "x0") + let x1Var = verifier.appendScalar(label: "x1") + let x2Var = verifier.appendScalar(label: "x2") + let x0BlindingVar = verifier.appendScalar(label: "x0Blinding") + let bVar = verifier.appendScalar(label: "b") + let t1Var = verifier.appendScalar(label: "t1") + let t2Var = verifier.appendScalar(label: "t2") + + // Allocate variables for the constrained points, and add the constraints. + CredentialResponse.proofConstrain(participant: &verifier, request: request, generatorG: generatorG, generatorH: generatorH, U: U, encUPrime: encUPrime, X0: serverPublicKey.X0, X1: serverPublicKey.X1, X2: serverPublicKey.X2, X0Aux: X0Aux, X1Aux: X1Aux, X2Aux: X2Aux, HAux: HAux, x0Var: x0Var, x0BlindingVar: x0BlindingVar, x1Var: x1Var, x2Var: x2Var, bVar: bVar, t1Var: t1Var, t2Var: t2Var) + + return try verifier.verify(proof: self.proof) + } + + static internal func proofConstrain(participant: inout P, request: CredentialRequest, generatorG: Group.Element, generatorH: Group.Element, U: Group.Element, encUPrime: Group.Element, X0: Group.Element, X1: Group.Element, X2: Group.Element, X0Aux: Group.Element, X1Aux: Group.Element, X2Aux: Group.Element, HAux: Group.Element, x0Var: ScalarVar, x0BlindingVar: ScalarVar, x1Var: ScalarVar, x2Var: ScalarVar, bVar: ScalarVar, t1Var: ScalarVar, t2Var: ScalarVar) { + // Allocate point variables + let genGVar = participant.appendPoint(label: "genG", assignment: generatorG) + let genHVar = participant.appendPoint(label: "genH", assignment: generatorH) + let m1EncVar = participant.appendPoint(label: "m1Enc", assignment: request.m1Enc) + let m2EncVar = participant.appendPoint(label: "m2Enc", assignment: request.m2Enc) + let UVar = participant.appendPoint(label: "U", assignment: U) + let encUPrimeVar = participant.appendPoint(label: "encUPrime", assignment: encUPrime) + let X0Var = participant.appendPoint(label: "X0", assignment: X0) + let X1Var = participant.appendPoint(label: "X1", assignment: X1) + let X2Var = participant.appendPoint(label: "X2", assignment: X2) + let X0AuxVar = participant.appendPoint(label: "X0Aux", assignment: X0Aux) + let X1AuxVar = participant.appendPoint(label: "X1Aux", assignment: X1Aux) + let X2AuxVar = participant.appendPoint(label: "X2Aux", assignment: X2Aux) + let HAuxVar = participant.appendPoint(label: "HAux", assignment: HAux) + + // 1. X0 = x0 * generatorG + x0Blinding * generatorH + participant.constrain(result: X0Var, linearCombination: [(x0Var, genGVar), (x0BlindingVar, genHVar)]) + // 2. X1 = x1 * generatorH + participant.constrain(result: X1Var, linearCombination: [(x1Var, genHVar)]) + // 3. X2 = x2 * generatorH + participant.constrain(result: X2Var, linearCombination: [(x2Var, genHVar)]) + + // 4. X0Aux = b * x0Blinding * generatorH + // 4a. HAux = b * generatorH + participant.constrain(result: HAuxVar, linearCombination: [(bVar, genHVar)]) + // 4b: X0Aux = x0Blinding * HAux + participant.constrain(result: X0AuxVar, linearCombination: [(x0BlindingVar, HAuxVar)]) + + // 5. X1Aux = b * x1 * generatorH + // 5b. X1Aux = t1 * generatorH, where t1 = b*x1 (NOTE: this is out of order in the spec & poc.) + participant.constrain(result: X1AuxVar, linearCombination: [(t1Var, genHVar)]) + // 5a. X1Aux = b * X1, where X1 = x1 * generatorH (as constrained in #2) + participant.constrain(result: X1AuxVar, linearCombination: [(bVar, X1Var)]) + + // 6. X2Aux = b * x2 * generatorH + // 6a. X2Aux = b * X2, where X2 = x2 * generatorH (as constrained in #3) + participant.constrain(result: X2AuxVar, linearCombination: [(bVar, X2Var)]) + // 6b. X2Aux = t2 * generatorH, where t2 = b*x2 + participant.constrain(result: X2AuxVar, linearCombination: [(t2Var, genHVar)]) + + // 7. U = b * generatorG + participant.constrain(result: UVar, linearCombination: [(bVar, genGVar)]) + // 8. encUPrime = b * (X0Var + x1 * request.encAttribute) + // 8. encUPrime = b * (X0 + x1 * Enc(m1) + x2 * Enc(m2)) + // simplified: encUPrime = b * X0 + t1 * m1Enc + t2 * m2Enc, since t1 = b * x1 and t2 = b * x2 + participant.constrain(result: encUPrimeVar, linearCombination: [(bVar, X0Var), (t1Var, m1EncVar), (t2Var, m2EncVar)]) + } + } +} diff --git a/Sources/_CryptoExtras/ARC/ARCServer.swift b/Sources/_CryptoExtras/ARC/ARCServer.swift new file mode 100644 index 00000000..d7fe9bac --- /dev/null +++ b/Sources/_CryptoExtras/ARC/ARCServer.swift @@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +import Crypto +import Foundation + +extension ARC { + struct ServerPrivateKey { + let x0: Scalar + let x1: Scalar + let x2: Scalar + let x0Blinding: Scalar + + init(x0: Scalar, x1: Scalar, x2: Scalar, x0Blinding: Scalar) { + self.x0 = x0 + self.x1 = x1 + self.x2 = x2 + self.x0Blinding = x0Blinding + } + } + + struct ServerPublicKey { + typealias Group = H2G.G + let X0: Group.Element + let X1: Group.Element + let X2: Group.Element + + init(X0: Group.Element, X1: Group.Element, X2: Group.Element) { + self.X0 = X0 + self.X1 = X1 + self.X2 = X2 + } + + init(serverPrivateKey: ServerPrivateKey, generatorG: Group.Element, generatorH: Group.Element) { + self.X0 = serverPrivateKey.x0 * generatorG + serverPrivateKey.x0Blinding * generatorH + self.X1 = serverPrivateKey.x1 * generatorH + self.X2 = serverPrivateKey.x2 * generatorH + } + } + + struct Server { + typealias Group = H2G.G + let serverPrivateKey: ServerPrivateKey + let serverPublicKey: ServerPublicKey + let ciphersuite: Ciphersuite + let generatorG: Group.Element + let generatorH: Group.Element + + init(ciphersuite: Ciphersuite, x0: Group.Scalar = Group.Scalar.random, x1: Group.Scalar = Group.Scalar.random, x2: Group.Scalar = Group.Scalar.random, x0Blinding: Group.Scalar = Group.Scalar.random + ) { + self.ciphersuite = ciphersuite + (self.generatorG, self.generatorH) = ARC.getGenerators(suite: ciphersuite) + + self.serverPrivateKey = ServerPrivateKey(x0: x0, x1: x1, x2: x2, x0Blinding: x0Blinding) + self.serverPublicKey = ServerPublicKey(serverPrivateKey: self.serverPrivateKey, generatorG: self.generatorG, generatorH: self.generatorH) + } + + func respond(credentialRequest: CredentialRequest, b: Group.Scalar = Group.Scalar.random) throws -> CredentialResponse { + guard + try credentialRequest.verify(generatorG: generatorG, generatorH: generatorH) + else { + throw ARC.Errors.invalidProof + } + return try CredentialResponse( + request: credentialRequest, + serverPrivateKey: self.serverPrivateKey, + serverPublicKey: self.serverPublicKey, + generatorG: generatorG, + generatorH: generatorH, + b: b + ) + } + + func verify(presentation: Presentation, requestContext: Data, presentationContext: Data, presentationLimit: Int, nonce: Int) throws -> Bool { + let m2 = try H2G.hashToScalar(requestContext, domainSeparationString: Data((ARC.domain + "requestContext").utf8)) + return try presentation.verify( + serverPrivateKey: self.serverPrivateKey, + X1: self.serverPublicKey.X1, + m2: m2, + presentationContext: presentationContext, + presentationLimit: presentationLimit, + nonce: nonce, + generatorG: generatorG, + generatorH: generatorH + ) + } + } +} diff --git a/Sources/_CryptoExtras/CMakeLists.txt b/Sources/_CryptoExtras/CMakeLists.txt index afe9f399..52bcb44c 100644 --- a/Sources/_CryptoExtras/CMakeLists.txt +++ b/Sources/_CryptoExtras/CMakeLists.txt @@ -21,6 +21,15 @@ add_library(_CryptoExtras "AES/BoringSSL/AES_CFB_boring.swift" "AES/BoringSSL/AES_CTR_boring.swift" "AES/BoringSSL/AES_GCM_SIV_boring.swift" + "ARC/ARC+API.swift" + "ARC/ARC.swift" + "ARC/ARCCredential.swift" + "ARC/ARCEncoding.swift" + "ARC/ARCPrecredential.swift" + "ARC/ARCPresentation.swift" + "ARC/ARCRequest.swift" + "ARC/ARCResponse.swift" + "ARC/ARCServer.swift" "ChaCha20CTR/BoringSSL/ChaCha20CTR_boring.swift" "ChaCha20CTR/ChaCha20CTR.swift" "ECToolbox/BoringSSL/ECToolbox_boring.swift" @@ -50,7 +59,10 @@ add_library(_CryptoExtras "Util/PEMDocument.swift" "Util/PrettyBytes.swift" "Util/SubjectPublicKeyInfo.swift" - "ZKPs/DLEQ.swift") + "ZKPs/DLEQ.swift" + "ZKPs/Prover.swift" + "ZKPs/Verifier.swift" + "ZKPs/ZKPToolbox.swift") target_compile_options(_CryptoExtras PRIVATE -DCRYPTO_IN_SWIFTPM) diff --git a/Sources/_CryptoExtras/H2G/HashToField.swift b/Sources/_CryptoExtras/H2G/HashToField.swift index 9c8b0fd0..895a6f65 100644 --- a/Sources/_CryptoExtras/H2G/HashToField.swift +++ b/Sources/_CryptoExtras/H2G/HashToField.swift @@ -17,7 +17,12 @@ import Crypto extension Data { static func ^ (left: Data, right: Data) -> Data { precondition(left.count == right.count) - return Data(zip(left, right).compactMap { return $0 ^ $1 }) + var result = Data() + result.reserveCapacity(left.count) + for value in zip(left, right) { + result.append(value.0 ^ value.1) + } + return result } } diff --git a/Sources/_CryptoExtras/ZKPs/Prover.swift b/Sources/_CryptoExtras/ZKPs/Prover.swift new file mode 100644 index 00000000..5627fe08 --- /dev/null +++ b/Sources/_CryptoExtras/ZKPs/Prover.swift @@ -0,0 +1,102 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +import Foundation +import Crypto + +struct Prover: ProofParticipant { + typealias Group = H2G.G + var label: String + var scalars: [Group.Scalar] + var scalarLabels: [String] + var points: [Group.Element] + var pointLabels: [String] + var constraints: [(PointVar, [(ScalarVar, PointVar)])] + + init(label: String) { + self.label = label + self.scalars = [] + self.scalarLabels = [] + self.points = [] + self.pointLabels = [] + self.constraints = [] + } + + mutating func appendScalar(label: String, assignment: Group.Scalar) -> ScalarVar { + self.scalarLabels.append(label) + self.scalars.append(assignment) + return ScalarVar(index: self.scalars.count - 1) + } + + func prove() throws -> Proof { + // Create a blinding scalar for each scalar variable. + let blindings = (0.. Proof { + // Perform size checks on proof fields. + if (self.scalars.count != self.scalarLabels.count) || (self.points.count != self.pointLabels.count) { + throw ZKPErrors.invalidProofFields + } + // Check that there is one blinding scalar for each allocated scalar variable. + if (blindings.count != self.scalars.count) { + throw ZKPErrors.invalidInputLength + } + + // For each constraint, compute the blinded version of the constraint element. + // Example: if the constraint is A=x*B, compute ABlind=xBlind*B for blinding scalar xBlind. + // Example: if the constraint is A=x*B+y*C, compute ABlind=xBlind*B + yBlind*C for blinding scalars xBlind, yBlind. + var blindedPoints: [Group.Element] = [] + var blindedPointsLabels: [String] = [] + for (constraintPoint, linearCombination) in self.constraints { + // Check that all PointVar and ScalarVar variables in the constraint have been correctly allocated. + if !(0...composeChallenge(label: self.label, points: self.points, pointLabels: self.pointLabels, blindedPoints: blindedPoints, blindedPointsLabels: blindedPointsLabels, scalarLabels: self.scalarLabels) + + // Compute response scalars from the challenge, scalars, and blindings. + // Example: if the scalar is m, compute mResponse = mBlind - challenge * m for blinding scalar xBlind. + var responses: [Group.Scalar] = [] + for (index, scalar) in self.scalars.enumerated() { + let blinding = blindings[index] + responses.append(blinding - challenge * scalar) + } + + return Proof(challenge: challenge, responses: responses) + } +} diff --git a/Sources/_CryptoExtras/ZKPs/Verifier.swift b/Sources/_CryptoExtras/ZKPs/Verifier.swift new file mode 100644 index 00000000..77f05bcb --- /dev/null +++ b/Sources/_CryptoExtras/ZKPs/Verifier.swift @@ -0,0 +1,77 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +import Foundation +import Crypto + +struct Verifier: ProofParticipant { + typealias Group = H2G.G + var label: String + var scalarLabels: [String] + var points: [Group.Element] + var pointLabels: [String] + var constraints: [(PointVar, [(ScalarVar, PointVar)])] + + init(label: String) { + self.label = label + self.scalarLabels = [] + self.points = [] + self.pointLabels = [] + self.constraints = [] + } + + mutating func appendScalar(label: String) -> ScalarVar { + self.scalarLabels.append(label) + return ScalarVar(index: self.scalarLabels.count - 1) + } + + func verify(proof: Proof) throws -> Bool { + // Perform size checks on proof fields. + if self.points.count != self.pointLabels.count { + throw ZKPErrors.invalidProofFields + } + + // For each constraint, recompute the blinded version of the constraint element. + // Example: if the constraint is A=x*B, compute ABlind=challenge*A + xResponse*B + // Example: if the constraint is A=x*B+y*C, compute ABlind=challenge*A + xResponse*B + yResponse*C + var blindedPoints: [Group.Element] = [] + var blindedPointsLabels: [String] = [] + for (constraintPoint, linearCombination) in self.constraints { + // Check that all PointVar and ScalarVar variables in the constraint have been correctly allocated. + if !(0...composeChallenge(label: self.label, points: self.points, pointLabels: self.pointLabels, blindedPoints: blindedPoints, blindedPointsLabels: blindedPointsLabels, scalarLabels: self.scalarLabels) + + return challenge == proof.challenge + } +} + + diff --git a/Sources/_CryptoExtras/ZKPs/ZKPToolbox.swift b/Sources/_CryptoExtras/ZKPs/ZKPToolbox.swift new file mode 100644 index 00000000..b0d472f1 --- /dev/null +++ b/Sources/_CryptoExtras/ZKPs/ZKPToolbox.swift @@ -0,0 +1,77 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +import Foundation +import Crypto + +struct ScalarVar { + var index: Int +} + +struct PointVar { + var index: Int +} + +enum ZKPErrors: Error { + case invalidVariableAllocation + case invalidInputLength + case invalidProofFields +} + +// A Schnorr proof, which stores the challenge instead of +// commitments to the prover's randomness (blindedPoints). +struct Proof { + typealias Group = H2G.G + public let challenge: Group.Scalar + public let responses: [Group.Scalar] + + static func composeChallenge(label: String, points: [Group.Element], pointLabels: [String], blindedPoints: [Group.Element], blindedPointsLabels: [String], scalarLabels: [String]) throws -> Group.Scalar { + var challengeInput = Data() + + // Pass the public points into the transcript. + for point in points { + let serializedPoint = point.oprfRepresentation + challengeInput.append(I2OSP(value: serializedPoint.count, outputByteCount: 2) + serializedPoint) + } + + // Pass the computed blinded points into the transcript. + for point in blindedPoints { + let serializedPoint = point.oprfRepresentation + challengeInput.append(I2OSP(value: serializedPoint.count, outputByteCount: 2) + serializedPoint) + } + + // Get the challenge output from the transcript. + return try H2G.hashToScalar(challengeInput, domainSeparationString: Data(label.utf8)) + } +} + +protocol ProofParticipant { + associatedtype Point: GroupElement + var label: String { get } + var scalarLabels: [String] { get set } + var points: [Point] { get set } + var pointLabels: [String] { get set } + var constraints: [(PointVar, [(ScalarVar, PointVar)])] { get set } +} + +extension ProofParticipant { + mutating func constrain(result: PointVar, linearCombination: [(ScalarVar, PointVar)]) { + self.constraints.append((result, linearCombination)) + } + + mutating func appendPoint(label: String, assignment: any GroupElement) -> PointVar { + self.pointLabels.append(label) + self.points.append(assignment as! Self.Point) + return PointVar(index: self.points.count - 1) + } +} diff --git a/Tests/_CryptoExtrasTests/ARC/ARCAPITests.swift b/Tests/_CryptoExtrasTests/ARC/ARCAPITests.swift new file mode 100644 index 00000000..3d87bc70 --- /dev/null +++ b/Tests/_CryptoExtrasTests/ARC/ARCAPITests.swift @@ -0,0 +1,176 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +import Crypto +@testable import _CryptoExtras +import XCTest + +@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, *) +final class ARCAPITests: XCTestCase { + + func testVectors() throws { + let data = ARCEncodedTestVector.data(using: .utf8)! + let decoder = JSONDecoder() + for vector in try decoder.decode([ARCTestVector].self, from: data) { + try testVector(vector) + } + } + + func testVector(_ vector: ARCTestVector) throws { + // [Issuer] Create the server secrets. + let privateKey = try P384._ARCV1.PrivateKey(rawRepresentation: Data( + hexString: vector.ServerKey.x0 + vector.ServerKey.x1 + vector.ServerKey.x2 + vector.ServerKey.xb + )) + + // [Issuer] Serialize public key to share with client (other serializations may be available). + let publicKeyBytes = privateKey.publicKey.rawRepresentation + + // [CHECK] Public key matches test vector. + XCTAssertEqual( + publicKeyBytes.hexString, + vector.ServerKey.X0 + vector.ServerKey.X1 + vector.ServerKey.X2 + ) + + // [Issuer] Define a request context to share with the client. + let requestContext = try Data(hexString: vector.CredentialRequest.request_context) + + // [Verifier] Define a presentation context and presentation limit (e.g. rate-limit). + let presentationContext = try Data(hexString: vector.Presentation1.presentation_context) + let presentationLimit = 2 + + // [Client] Obtain public key, request context, presentation context, and presentation limit out of band. + _ = (publicKeyBytes, requestContext, presentationContext, presentationLimit) + + // [Client] Obtain public key out of band (other serializations may be available). + let publicKey = try P384._ARCV1.PublicKey(rawRepresentation: publicKeyBytes) + + // [Client] Prepare a credential request using fixed values from test vector. + let precredential = try publicKey.prepareCredentialRequest( + requestContext: requestContext, + presentationLimit: presentationLimit, + m1: P384._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.CredentialRequest.m1)), + r1: P384._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.CredentialRequest.r1)), + r2: P384._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.CredentialRequest.r2)) + ) + + // [Client -> Issuer] Send the credential request. + let credentialRequestBytes = precredential.credentialRequest.rawRepresentation + + // [CHECK] Credential request scalars match test vector. + XCTAssertEqual( + credentialRequestBytes[..<(2 * P384.compressedx962PointByteCount)].hexString, + vector.CredentialRequest.m1_enc + vector.CredentialRequest.m2_enc + ) + + // [Issuer] Receive the credential request. + let credentialRequest = try P384._ARCV1.CredentialRequest(rawRepresentation: credentialRequestBytes) + + // [Issuer] Generate a credential response with fixed value from test vector. + let credentialResponse = try privateKey.issue( + credentialRequest, + b: P384._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.CredentialResponse.b)) + ) + + // [Issuer -> Client] Send the credential response. + let credentialResponseBytes = credentialResponse.rawRepresentation + + // [CHECK] Credential response scalars match test vector, excluding proof. + XCTAssertEqual( + credentialResponseBytes[..<(6 * P384.compressedx962PointByteCount)].hexString, + vector.CredentialResponse.U + + vector.CredentialResponse.enc_U_prime + + vector.CredentialResponse.X0_aux + + vector.CredentialResponse.X1_aux + + vector.CredentialResponse.X2_aux + + vector.CredentialResponse.H_aux + ) + + // [Client] Receive the credential response. + let _ = try P384._ARCV1.CredentialResponse(rawRepresentation: credentialResponseBytes) + + // [Client] Generate a credential. + var credential = try publicKey.finalize(credentialResponse, for: precredential) + + // [CHECK] Credential matches test vector. + XCTAssertEqual(credential.backing.U.oprfRepresentation.hexString, vector.Credential.U) + XCTAssertEqual(credential.backing.UPrime.oprfRepresentation.hexString, vector.Credential.U_prime) + XCTAssertEqual(credential.backing.X1.oprfRepresentation.hexString, vector.Credential.X1) + XCTAssertEqual(credential.backing.m1.rawRepresentation.hexString, vector.Credential.m1) + + // [Client] Make a presentation from the credential for a presentation prefix. + let (presentation, _) = try credential.makePresentation( + context: presentationContext, + fixedNonce: Int(vector.Presentation1.nonce.dropFirst(2), radix: 16)!, + a: P384._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.Presentation1.a)), + r: P384._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.Presentation1.r)), + z: P384._ARCV1.H2G.G.Scalar(bytes: Data(hexString: vector.Presentation1.z)) + ) + + // NOTE: The presentation proof depends on randomly generated blinding factors. This layer doesn't expose + // internal methods for fixing these values + // + // Here, we'll check that the presentation, excluding the proof, with the fixed scalars and nonce, matches + // the presentation from the test vector. + // + // Then, for the remainder of this test, we'll cut over to the presentation from the test vector. + // + // Proof generation and verification, in general, is well covered by other tests; and proof validity, for + // ARC specifically, is covered in the end-to-end tests in ARCPublicAPITests. + + // [CHECK]: Check presentation (excluding proof) matches test vector. + XCTAssertEqual(presentation.backing.U.oprfRepresentation.hexString, vector.Presentation1.U) + XCTAssertEqual(presentation.backing.UPrimeCommit.oprfRepresentation.hexString, vector.Presentation1.U_prime_commit) + XCTAssertEqual(presentation.backing.m1Commit.oprfRepresentation.hexString, vector.Presentation1.m1_commit) + XCTAssertEqual(presentation.backing.tag.oprfRepresentation.hexString, vector.Presentation1.tag) + + // [CHECK]: Serialization of presentation (ecluding proof) matches spec. + XCTAssertEqual( + presentation.rawRepresentation[..<(4 * P384.compressedx962PointByteCount)].hexString, + vector.Presentation1.U + + vector.Presentation1.U_prime_commit + + vector.Presentation1.m1_commit + + vector.Presentation1.tag + ) + XCTAssertEqual( + presentation.rawRepresentation[(4 * P384.compressedx962PointByteCount)...].hexString.count, + vector.Presentation1.proof.count + ) + + // [CHECK]: Full serialization of presentation, including proof from test vector, matches test vector. + let testVectorPresentationBytes = try Data( + hexString: vector.Presentation1.U + + vector.Presentation1.U_prime_commit + + vector.Presentation1.m1_commit + + vector.Presentation1.tag + + vector.Presentation1.proof + ) + XCTAssertEqual( + try P384._ARCV1.Presentation(rawRepresentation: testVectorPresentationBytes).rawRepresentation.hexString, + testVectorPresentationBytes.hexString + ) + + // [Verifier] Receive the presentation (and the nonce, out of band). + let receivedPresentation = try P384._ARCV1.Presentation(rawRepresentation: testVectorPresentationBytes) + let nonce = Int(vector.Presentation1.nonce.dropFirst(2), radix: 16)! + + // [Verifier] Verify the presentation. + let validPresentation = try privateKey.verify( + receivedPresentation, + requestContext: requestContext, + presentationContext: presentationContext, + presentationLimit: presentationLimit, + nonce: nonce + ) + XCTAssertTrue(validPresentation) + } +} diff --git a/Tests/_CryptoExtrasTests/ARC/ARCEncodingTests.swift b/Tests/_CryptoExtrasTests/ARC/ARCEncodingTests.swift new file mode 100644 index 00000000..a0531569 --- /dev/null +++ b/Tests/_CryptoExtrasTests/ARC/ARCEncodingTests.swift @@ -0,0 +1,145 @@ +//===----------------------------------------------------------------------===// +// +// 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 +import Crypto + +class ARCEncodingTests: XCTestCase { + func testserverPublicKeyEncoding() throws { + let ciphersuite = ARC.Ciphersuite(HashToCurveImpl.self) + let server = ARC.Server(ciphersuite: ciphersuite) + let publicKey = server.serverPublicKey + + let publicKeyData = publicKey.serialize() + let publicKey2 = try ARC.ServerPublicKey.deserialize(serverPublicKeyData: publicKeyData) + XCTAssert(publicKey.X0 == publicKey2.X0) + XCTAssert(publicKey.X1 == publicKey2.X1) + XCTAssert(publicKey.X2 == publicKey2.X2) + + let publicKeyData2 = publicKey2.serialize() + XCTAssertEqual(publicKeyData, publicKeyData2) + } + + func testRequestEncoding() throws { + let ciphersuite = ARC.Ciphersuite(HashToCurveImpl.self) + let server = ARC.Server(ciphersuite: ciphersuite) + let requestContext = Data("test request context".utf8) + let precredential = try ARC.Precredential(ciphersuite: ciphersuite, requestContext: requestContext, serverPublicKey: server.serverPublicKey, presentationLimit: 1) + let request = precredential.credentialRequest + + let requestData = request.serialize() + let request2 = try ARC.CredentialRequest.deserialize(requestData: requestData) + XCTAssert(request.m1Enc == request2.m1Enc) + XCTAssert(request.m2Enc == request2.m2Enc) + XCTAssert(request.proof.challenge == request2.proof.challenge) + for (index, response) in request.proof.responses.enumerated() { + XCTAssert(response == request2.proof.responses[index]) + } + + let requestData2 = request2.serialize() + XCTAssertEqual(requestData, requestData2) + } + + func testResponseEncoding() throws { + let ciphersuite = ARC.Ciphersuite(HashToCurveImpl.self) + let server = ARC.Server(ciphersuite: ciphersuite) + let requestContext = Data("test request context".utf8) + let precredential = try ARC.Precredential(ciphersuite: ciphersuite, requestContext: requestContext, serverPublicKey: server.serverPublicKey, presentationLimit: 1) + let request = precredential.credentialRequest + let response = try server.respond(credentialRequest: request) + + let responseData = response.serialize() + let response2 = try ARC.CredentialResponse.deserialize(responseData: responseData) + XCTAssert(response.U == response2.U) + XCTAssert(response.encUPrime == response2.encUPrime) + XCTAssert(response.X0Aux == response2.X0Aux) + XCTAssert(response.X1Aux == response2.X1Aux) + XCTAssert(response.X2Aux == response2.X2Aux) + XCTAssert(response.HAux == response2.HAux) + XCTAssert(response.proof.challenge == response2.proof.challenge) + for (index, response) in response.proof.responses.enumerated() { + XCTAssert(response == response2.proof.responses[index]) + } + + let responseData2 = response2.serialize() + XCTAssertEqual(responseData, responseData2) + } + + func testCredentialEncoding() throws { + let ciphersuite = ARC.Ciphersuite(HashToCurveImpl.self) + let server = ARC.Server(ciphersuite: ciphersuite) + let requestContext = Data("test request context".utf8) + let precredential = try ARC.Precredential(ciphersuite: ciphersuite, requestContext: requestContext, serverPublicKey: server.serverPublicKey, presentationLimit: 1) + let request = precredential.credentialRequest + let response = try server.respond(credentialRequest: request) + let credential = try precredential.makeCredential(credentialResponse: response) + + let credentialData = try credential.serialize() + let credential2 = try ARC.Credential.deserialize(credentialData: credentialData) + XCTAssert(credential.m1 == credential2.m1) + XCTAssert(credential.U == credential2.U) + XCTAssert(credential.UPrime == credential2.UPrime) + XCTAssert(credential.X1 == credential2.X1) + XCTAssert(credential.generatorG == credential2.generatorG) + XCTAssert(credential.generatorH == credential2.generatorH) + XCTAssert(credential.presentationLimit == credential2.presentationLimit) + XCTAssert(credential.presentationNonces == credential2.presentationNonces) + + let credentialData2 = try credential2.serialize() + XCTAssertEqual(credentialData, credentialData2) + } + + func testPresentationEncoding() throws { + let ciphersuite = ARC.Ciphersuite(HashToCurveImpl.self) + let server = ARC.Server(ciphersuite: ciphersuite) + let requestContext = Data("test request context".utf8) + let precredential = try ARC.Precredential(ciphersuite: ciphersuite, requestContext: requestContext, serverPublicKey: server.serverPublicKey, presentationLimit: 1) + let request = precredential.credentialRequest + let response = try server.respond(credentialRequest: request) + var credential = try precredential.makeCredential(credentialResponse: response) + let (presentation, _) = try credential.makePresentation(presentationContext: Data("test presentation context".utf8)) + + let presentationData = presentation.serialize() + let presentation2 = try ARC.Presentation.deserialize(presentationData: presentationData) + XCTAssert(presentation.U == presentation2.U) + XCTAssert(presentation.UPrimeCommit == presentation2.UPrimeCommit) + XCTAssert(presentation.m1Commit == presentation2.m1Commit) + XCTAssert(presentation.tag == presentation2.tag) + XCTAssert(presentation.proof.challenge == presentation2.proof.challenge) + for (index, response) in presentation.proof.responses.enumerated() { + XCTAssert(response == presentation2.proof.responses[index]) + } + + let presentationData2 = presentation2.serialize() + XCTAssertEqual(presentationData, presentationData2) + } + + func testDictionaryEncoding() throws { + let emptyDictionary: [Data: Set] = [:] + let smallDictionary: [Data: Set] = [Data("context1".utf8): [1, 2, 3], Data("context2".utf8): [4, 5, 6]] + var largeDictionary: [Data: Set] = [:] + for i in 0..<1000 { + let key = Data("key\(i)".utf8) + let value = Set(0...1000) + largeDictionary[key] = value + } + + for dictionary in [emptyDictionary, smallDictionary, largeDictionary] { + let serializedDictionary = try ARCNonces.serialize(noncesDict: dictionary) + XCTAssertNotNil(serializedDictionary, "Serialized data should not be nil") + let deserializedDictionary = try ARCNonces.deserialize(noncesData: serializedDictionary) + XCTAssertEqual(dictionary, deserializedDictionary, "Deserialized dictionary should match the original") + } + } +} diff --git a/Tests/_CryptoExtrasTests/ARC/ARCPublicAPITests.swift b/Tests/_CryptoExtrasTests/ARC/ARCPublicAPITests.swift new file mode 100644 index 00000000..733b73ec --- /dev/null +++ b/Tests/_CryptoExtrasTests/ARC/ARCPublicAPITests.swift @@ -0,0 +1,113 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +import Crypto +import _CryptoExtras // NOTE: No @testable import, because we want to test the public API. +import XCTest + +@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, *) +final class ARCPublicAPITests: XCTestCase { + + func testARCEndToEnd() throws { + // [Issuer] Create the server secrets (other initializers will be available). + let privateKey = P384._ARCV1.PrivateKey() + + // [Issuer] Serialize public key to share with client (other serializations may be available). + let publicKeyBytes = privateKey.publicKey.rawRepresentation + + // [Issuer] Define a request context to share with the client. + let requestContext = Data("shared request context".utf8) + + // [Verifier] Define a presentation context and presentation limit (e.g. rate-limit). + let (presentationContext, presentationLimit) = (Data("shared presentation context".utf8), 2) + + // [Client] Obtain public key, request context, presentation context, and presentation limit out of band. + _ = (publicKeyBytes, requestContext, presentationContext, presentationLimit) + + // [Client] Obtain public key out of band (other serializations may be available). + let publicKey = try P384._ARCV1.PublicKey(rawRepresentation: publicKeyBytes) + + // [Client] Prepare a credential request. + let precredential = try publicKey.prepareCredentialRequest( + requestContext: requestContext, + presentationLimit: presentationLimit + ) + + // [Client -> Issuer] Send the credential request. + let credentialRequestBytes = precredential.credentialRequest.rawRepresentation + + // [Issuer] Receive the credential request. + let credentialRequest = try P384._ARCV1.CredentialRequest(rawRepresentation: credentialRequestBytes) + + // [Issuer] Generate a credential response. + let credentialResponse = try privateKey.issue(credentialRequest) + + // [Issuer -> Client] Send the credential response. + let credentialResponseBytes = credentialResponse.rawRepresentation + + // [Client] Receive the credential response. + let _ = try P384._ARCV1.CredentialResponse(rawRepresentation: credentialResponseBytes) + + // [Client] Generate a credential. + // NOTE: This is a var because it enforces the presentation limit for each presentation prefix. + var credential = try publicKey.finalize(credentialResponse, for: precredential) + + // [Client] Make a presentation from the credential for a presentation prefix. + let (presentation, nonce) = try credential.makePresentation(context: presentationContext) + + // TODO: The shared code doesn't expose fixing randomness in makePresentation so we cannot assert things about it + // Instea + + // [Client -> Verifier] Send the presentation. + let presentationBytes = presentation.rawRepresentation + + // [Verifier] Receive the presentation. + let _ = try P384._ARCV1.Presentation(rawRepresentation: presentationBytes) + + // [Verifier] Verify the presentation. + let validPresentation = try privateKey.verify( + presentation, + requestContext: requestContext, + presentationContext: presentationContext, + presentationLimit: presentationLimit, + nonce: nonce + ) + XCTAssertTrue(validPresentation) + + // [Verifier] Enforce rate limit with a combination of tag, nonce, presentation context, and presentation limit. + _ = (presentation.tag, presentationContext, presentationLimit) + } + + func testCrendentialEnforcesPresentationLimitLocally() throws { + let privateKey = P384._ARCV1.PrivateKey() + let publicKey = privateKey.publicKey + let requestContext = Data("shared request context".utf8) + let presentationContext = Data("shared presentation context".utf8) + let presentationLimit = 2 + + let precredential = try publicKey.prepareCredentialRequest( + requestContext: requestContext, + presentationLimit: presentationLimit + ) + let credentialResponse = try privateKey.issue(precredential.credentialRequest) + var credential = try publicKey.finalize(credentialResponse, for: precredential) + + for _ in 0..(curveType _: Curve.Type, _ tv: ARCTestVector) throws { + let x0 = try scalarFromString(CurveType: Curve.self, value: tv.ServerKey.x0) + let x1 = try scalarFromString(CurveType: Curve.self, value: tv.ServerKey.x1) + let x2 = try scalarFromString(CurveType: Curve.self, value: tv.ServerKey.x2) + let xb = try scalarFromString(CurveType: Curve.self, value: tv.ServerKey.xb) + + // Initialize server + let ciphersuite = ARC.Ciphersuite(HashToCurveImpl.self) + let server = ARC.Server(ciphersuite: ciphersuite, x0: x0, x1: x1, x2: x2, x0Blinding: xb) + XCTAssertEqual(server.serverPublicKey.X0.oprfRepresentation.hexString, tv.ServerKey.X0) + XCTAssertEqual(server.serverPublicKey.X1.oprfRepresentation.hexString, tv.ServerKey.X1) + XCTAssertEqual(server.serverPublicKey.X2.oprfRepresentation.hexString, tv.ServerKey.X2) + + // Initialize precredential, make a credential request + let requestContext = try Data(hexString: tv.CredentialRequest.request_context) + let m1 = try scalarFromString(CurveType: Curve.self, value: tv.CredentialRequest.m1) + let m2 = try scalarFromString(CurveType: Curve.self, value: tv.CredentialRequest.m2) + let r1 = try scalarFromString(CurveType: Curve.self, value: tv.CredentialRequest.r1) + let r2 = try scalarFromString(CurveType: Curve.self, value: tv.CredentialRequest.r2) + let precredential = try ARC.Precredential(ciphersuite: ciphersuite, m1: m1, requestContext: requestContext, r1: r1, r2: r2, serverPublicKey: server.serverPublicKey, presentationLimit: 2) + XCTAssertEqual(precredential.credentialRequest.m1Enc.oprfRepresentation.hexString, tv.CredentialRequest.m1_enc) + XCTAssertEqual(precredential.credentialRequest.m2Enc.oprfRepresentation.hexString, tv.CredentialRequest.m2_enc) + XCTAssertEqual(precredential.clientSecrets.m2.rawRepresentation.hexString, tv.CredentialRequest.m2) + + // Verify request proof, by creating a new request with the + // tv.CredentialRequest.proof scalars and verifying it. + let requestProof = try proofFromString(CurveType: Curve.self, value: tv.CredentialRequest.proof, scalarCount: ARC.CredentialRequest.scalarCount) + let newRequest = ARC.CredentialRequest(m1Enc: precredential.credentialRequest.m1Enc, m2Enc: precredential.credentialRequest.m2Enc, proof: requestProof) + XCTAssert(try newRequest.verify(generatorG: precredential.generatorG, generatorH: precredential.generatorH)) + + // Make a credential response, passing in randomness b + let b = try scalarFromString(CurveType: Curve.self, value: tv.CredentialResponse.b) + let response = try server.respond(credentialRequest: precredential.credentialRequest, b: b) + XCTAssertEqual(response.HAux.oprfRepresentation.hexString, tv.CredentialResponse.H_aux) + XCTAssertEqual(response.U.oprfRepresentation.hexString, tv.CredentialResponse.U) + XCTAssertEqual(response.X0Aux.oprfRepresentation.hexString, tv.CredentialResponse.X0_aux) + XCTAssertEqual(response.X1Aux.oprfRepresentation.hexString, tv.CredentialResponse.X1_aux) + XCTAssertEqual(response.X2Aux.oprfRepresentation.hexString, tv.CredentialResponse.X2_aux) + XCTAssertEqual(response.encUPrime.oprfRepresentation.hexString, tv.CredentialResponse.enc_U_prime) + + // Verify response proof, by creating a new response with the + // tv.CredentialResponse.proof scalars and verifying it. + let responseProof = try proofFromString(CurveType: Curve.self, value: tv.CredentialResponse.proof, scalarCount: ARC.CredentialResponse.scalarCount) + let newResponse = ARC.CredentialResponse(U: response.U, encUPrime: response.encUPrime, X0Aux: response.X0Aux, X1Aux: response.X1Aux, X2Aux: response.X2Aux, HAux: response.HAux, proof: responseProof) + XCTAssert(try newResponse.verify(request: precredential.credentialRequest, serverPublicKey: server.serverPublicKey, generatorG: server.generatorG, generatorH: server.generatorH)) + + // Make a credential from the response + var credential = try precredential.makeCredential(credentialResponse: response) + XCTAssertEqual(credential.U.oprfRepresentation.hexString, tv.Credential.U) + XCTAssertEqual(credential.UPrime.oprfRepresentation.hexString, tv.Credential.U_prime) + XCTAssertEqual(credential.X1.oprfRepresentation.hexString, tv.Credential.X1) + XCTAssertEqual(credential.m1.rawRepresentation.hexString, tv.Credential.m1) + + // Make a first presentation from the credential, passing in randomness a, r, z + let presentationContext1 = try Data(hexString: tv.Presentation1.presentation_context) + let a_1 = try scalarFromString(CurveType: Curve.self, value: tv.Presentation1.a) + let r_1 = try scalarFromString(CurveType: Curve.self, value: tv.Presentation1.r) + let z_1 = try scalarFromString(CurveType: Curve.self, value: tv.Presentation1.z) + let nonce_1 = Int(tv.Presentation1.nonce.replacingOccurrences(of: "0x", with: ""), radix: 16)! + let (presentation1, nonce_1_returned) = try credential.makePresentation(presentationContext: presentationContext1, a: a_1, r: r_1, z: z_1, optionalNonce: nonce_1) + XCTAssertEqual(nonce_1, nonce_1_returned) + XCTAssertEqual(presentation1.U.oprfRepresentation.hexString, tv.Presentation1.U) + XCTAssertEqual(presentation1.UPrimeCommit.oprfRepresentation.hexString, tv.Presentation1.U_prime_commit) + XCTAssertEqual(presentation1.m1Commit.oprfRepresentation.hexString, tv.Presentation1.m1_commit) + XCTAssertEqual(presentation1.tag.oprfRepresentation.hexString, tv.Presentation1.tag) + + // Verify presentation1 proof, by creating a new presentation with the + // tv.Presentation1.proof scalars and verifying it. + let presentation1Proof = try proofFromString(CurveType: Curve.self, value: tv.Presentation1.proof, scalarCount: ARC.Presentation.scalarCount) + let newPresentation1 = ARC.Presentation(U: presentation1.U, UPrimeCommit: presentation1.UPrimeCommit, m1Commit: presentation1.m1Commit, tag: presentation1.tag, proof: presentation1Proof) + XCTAssert(try newPresentation1.verify(serverPrivateKey: server.serverPrivateKey, X1: server.serverPublicKey.X1, m2: m2, presentationContext: presentationContext1, presentationLimit: 2, nonce: nonce_1, generatorG: credential.generatorG, generatorH: credential.generatorH)) + + // Make a second presentation from the credential, passing in randomness a, r, z + let presentationContext2 = try Data(hexString: tv.Presentation2.presentation_context) + let a_2 = try scalarFromString(CurveType: Curve.self, value: tv.Presentation2.a) + let r_2 = try scalarFromString(CurveType: Curve.self, value: tv.Presentation2.r) + let z_2 = try scalarFromString(CurveType: Curve.self, value: tv.Presentation2.z) + let nonce_2 = Int(tv.Presentation2.nonce.replacingOccurrences(of: "0x", with: ""), radix: 16)! + let (presentation2, nonce_2_returned) = try credential.makePresentation(presentationContext: presentationContext1, a: a_2, r: r_2, z: z_2, optionalNonce: nonce_2) + XCTAssertEqual(nonce_2, nonce_2_returned) + XCTAssertEqual(presentation2.U.oprfRepresentation.hexString, tv.Presentation2.U) + XCTAssertEqual(presentation2.UPrimeCommit.oprfRepresentation.hexString, tv.Presentation2.U_prime_commit) + XCTAssertEqual(presentation2.m1Commit.oprfRepresentation.hexString, tv.Presentation2.m1_commit) + XCTAssertEqual(presentation2.tag.oprfRepresentation.hexString, tv.Presentation2.tag) + + // Verify presentation2 proof, by creating a new presentation with the + // tv.Presentation2.proof scalars and verifying it. + let presentation2Proof = try proofFromString(CurveType: Curve.self, value: tv.Presentation2.proof, scalarCount: ARC.Presentation.scalarCount) + let newPresentation2 = ARC.Presentation(U: presentation2.U, UPrimeCommit: presentation2.UPrimeCommit, m1Commit: presentation2.m1Commit, tag: presentation2.tag, proof: presentation2Proof) + XCTAssert(try newPresentation2.verify(serverPrivateKey: server.serverPrivateKey, X1: server.serverPublicKey.X1, m2: m2, presentationContext: presentationContext2, presentationLimit: 2, nonce: nonce_2, generatorG: credential.generatorG, generatorH: credential.generatorH)) + + // Verify both presentations + XCTAssertTrue(try server.verify(presentation: presentation1, requestContext: requestContext, presentationContext: presentationContext1, presentationLimit: 2, nonce: nonce_1)) + XCTAssertTrue(try server.verify(presentation: presentation2, requestContext: requestContext, presentationContext: presentationContext2, presentationLimit: 2, nonce: nonce_2)) + } + + func validateTestVector(_ tv: ARCTestVector) { + switch tv.suite { + case ARC.domain: XCTAssertNoThrow(try self.validate(curveType: P384.self, tv)) + default: XCTFail("Unsupported ciphersuite:" + tv.suite) + } + } +} + +private func scalarFromString(CurveType _: Curve.Type, value: String) throws -> GroupImpl.Element.Scalar { + return try GroupImpl.Scalar(bytes: Data(hexString: value)) +} + +private func elementFromString(CurveType _: Curve.Type, value: String) throws -> GroupImpl.Element { + return try GroupImpl.Element(oprfRepresentation: Data(hexString: value)) +} + +private func proofFromString(CurveType _: Curve.Type, value: String, scalarCount: Int) throws -> Proof> { + let scalarHexCharacterCount = Curve.orderByteCount * 2 + var startIndex = value.index(value.startIndex, offsetBy: 0) + var endIndex = value.index(value.startIndex, offsetBy: scalarHexCharacterCount) + + // Deserialize challenge + let challengeEnc = try Data(hexString: String(value[startIndex...Scalar(bytes: challengeEnc) + + // Deserialize responses + var responses: [GroupImpl.Scalar] = [] + for _ in (0...Scalar(bytes: responseEnc) + responses.append(response) + } + + return Proof(challenge: challenge, responses: responses) +} diff --git a/Tests/_CryptoExtrasTests/ARC/ARCTests.swift b/Tests/_CryptoExtrasTests/ARC/ARCTests.swift new file mode 100644 index 00000000..a52ed5f7 --- /dev/null +++ b/Tests/_CryptoExtrasTests/ARC/ARCTests.swift @@ -0,0 +1,157 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +import Crypto +@testable import _CryptoExtras +import XCTest + +class ARCTests: XCTestCase { + func endToEndWorkflow(CurveType _: Curve.Type) throws { + let ciphersuite = ARC.Ciphersuite(HashToCurveImpl.self) + let (generatorG, generatorH) = ARC.getGenerators(suite: ciphersuite) + + // Create a server, passing in the server keys and key blinding. + let x0 = GroupImpl.Scalar.random + let x1 = GroupImpl.Scalar.random + let x2 = GroupImpl.Scalar.random + let x0Blinding = GroupImpl.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 serverPublicKey = server.serverPublicKey + XCTAssert(serverPublicKey.X0 == x0 * generatorG + x0Blinding * generatorH) + XCTAssert(serverPublicKey.X1 == x1 * generatorH) + XCTAssert(serverPublicKey.X2 == x2 * generatorH) + + // Create a client with two private attributes. + let presentationLimit = 2 + let requestContext = Data("test request context".utf8) + let m1 = GroupImpl.Scalar.random + let r1 = GroupImpl.Scalar.random + let r2 = GroupImpl.Scalar.random + let precredential = try ARC.Precredential(ciphersuite: ciphersuite, m1: m1, requestContext: requestContext, r1: r1, r2: r2, serverPublicKey: serverPublicKey, presentationLimit: presentationLimit) + + // Client makes an CredentialRequest using its private attributes. + let request = precredential.credentialRequest + let m1Decrypted = request.m1Enc - r1 * generatorH + XCTAssert(m1Decrypted == m1 * generatorG) + let m2Decrypted = request.m2Enc - r2 * generatorH + XCTAssert(m2Decrypted == precredential.clientSecrets.m2 * generatorG) + XCTAssert(try request.verify(generatorG: generatorG, generatorH: generatorH)) + + // Server receives the CredentialRequest, and makes an CredentialResponse with its server keys. + let issuance = try server.respond(credentialRequest: request) + let decryptedUPrime = issuance.encUPrime - issuance.X0Aux - r1 * issuance.X1Aux - r2 * issuance.X2Aux + XCTAssert(decryptedUPrime == (x0 + m1 * x1 + precredential.clientSecrets.m2 * x2) * issuance.U) + + // Client receives the CredentialResponse, and uses it to make a credential from the precredential. + var credential = try precredential.makeCredential(credentialResponse: issuance) + XCTAssertNotNil(credential) + + // Client makes two Presentations from the Credential. + // Note that in practice, the definition of presentationContext would depend on the use case of the tag (e.g. rate limiting). + let presentationContext = Data("0123456789".utf8) + let (presentation1, nonce1) = try credential.makePresentation(presentationContext: presentationContext) + let (presentation2, nonce2) = try credential.makePresentation(presentationContext: presentationContext) + XCTAssertNotNil(presentation1) + XCTAssertNotNil(presentation2) + + // We hit the limit for the presentationContext, and should not receive any new presentations + XCTAssertThrowsError(try credential.makePresentation(presentationContext: presentationContext), error: ARC.Errors.presentationLimitExceeded) + // But we can make more presentations under a different presentationContext + let newPresentationContext = Data("ABCDEF".utf8) + let (presentation3, nonce3) = try credential.makePresentation(presentationContext: newPresentationContext) + XCTAssertNotNil(presentation3) + + // Server verifies Presentation1 with its server keys. + XCTAssert(try server.verify(presentation: presentation1, requestContext: requestContext, presentationContext: presentationContext, presentationLimit: presentationLimit, nonce: nonce1)) + // Verify presentation individually + XCTAssert(try presentation1.verify( + serverPrivateKey: serverPrivateKey, + X1: x1 * generatorH, + m2: precredential.clientSecrets.m2, + presentationContext: presentationContext, + presentationLimit: presentationLimit, + nonce: nonce1, + generatorG: generatorG, + generatorH: generatorH)) + + // Server verifies Presentation2 with its server keys. + XCTAssert(try server.verify( + presentation: presentation2, + requestContext: requestContext, + presentationContext: presentationContext, + presentationLimit: presentationLimit, + nonce: nonce2)) + // Verify presentation individually + XCTAssert(try presentation2.verify( + serverPrivateKey: serverPrivateKey, + X1: x1 * generatorH, + m2: precredential.clientSecrets.m2, + presentationContext: presentationContext, + presentationLimit: presentationLimit, + nonce: nonce2, + generatorG: generatorG, + generatorH: generatorH)) + + // Test that two presentations with the same presentationContext and privateAttribute, + // but difference nonces, have different tag elements + XCTAssertNotEqual(presentation1.tag.compressedRepresentation, presentation2.tag.compressedRepresentation) + + // Server verifies Presentation3 with its server keys. + XCTAssert(try server.verify(presentation: presentation3, requestContext: requestContext, presentationContext: newPresentationContext, presentationLimit: presentationLimit, nonce: nonce3)) + + // Test that verifying Presentation3 with the wrong presentationContext fails. + XCTAssertFalse(try server.verify( + presentation: presentation3, + requestContext: requestContext, + presentationContext: presentationContext, + presentationLimit: presentationLimit, + nonce: nonce3)) + // Test that verifying Presentation3 with an invalid presentationLimit fails. + XCTAssertFalse(try server.verify( + presentation: presentation3, + requestContext: requestContext, + presentationContext: newPresentationContext, + presentationLimit: 0, + nonce: nonce3)) + // Test that verifying Presentation1 with the wrong nonce fails. + XCTAssertFalse(try server.verify( + presentation: presentation1, + requestContext: requestContext, + presentationContext: newPresentationContext, + presentationLimit: presentationLimit, + nonce: nonce2)) + // Test that verifying Presentation1 with the wrong request context fails. + XCTAssertFalse(try server.verify( + presentation: presentation1, + requestContext: Data("wrong request context".utf8), + presentationContext: newPresentationContext, + presentationLimit: presentationLimit, + nonce: nonce1)) + + // Test that verifying with the wrong server (wrong server keys) fails. + let wrongServer = ARC.Server(ciphersuite: ciphersuite) + XCTAssertFalse(try wrongServer.verify( + presentation: presentation3, + requestContext: requestContext, + presentationContext: presentationContext, + presentationLimit: presentationLimit, + nonce: nonce3)) + } + + func testEndToEndWorkflow() throws { + try endToEndWorkflow(CurveType: P256.self) + try endToEndWorkflow(CurveType: P384.self) +// try endToEndWorkflow(CurveType: P521.self) + } +} diff --git a/Tests/_CryptoExtrasTests/ZKPs/ZKPToolbox.swift b/Tests/_CryptoExtrasTests/ZKPs/ZKPToolbox.swift new file mode 100644 index 00000000..aa566d3f --- /dev/null +++ b/Tests/_CryptoExtrasTests/ZKPs/ZKPToolbox.swift @@ -0,0 +1,176 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +import Crypto +@testable import _CryptoExtras +import XCTest + +class ZKPToolboxTests: XCTestCase { + typealias H2G = HashToCurveImpl + typealias Group = H2G.G + + /// Tests the workflow for proof creation and verification, for a simple DL proof: A=x*B for a secret scalar x + func DL1Workflow(CurveType _: Curve.Type) throws { + // Prover's scope + let (proof, point, result) = try { + let point = Group.Element.random + let scalar = Group.Scalar.random + let result = scalar * point + + var prover = Prover(label: "DL1Test") + let scalarVar = prover.appendScalar(label: "scalar", assignment: scalar) + let pointVar = prover.appendPoint(label: "point", assignment: point) + let resultVar = prover.appendPoint(label: "result", assignment: result) + prover.constrain(result: resultVar, linearCombination: [(scalarVar, pointVar)]) + let proof = try prover.prove() + return (proof, point, result) + }() + + // Verifier's scope + var verifier = Verifier(label: "DL1Test") + let scalarVar = verifier.appendScalar(label: "scalar") + let pointVar = verifier.appendPoint(label: "point", assignment: point) + let resultVar = verifier.appendPoint(label: "result", assignment: result) + verifier.constrain(result: resultVar, linearCombination: [(scalarVar, pointVar)]) + let proofVerifies = try verifier.verify(proof: proof) + XCTAssert(proofVerifies) + + // Test that incorrect proof elements causes proof verification to fail + var failVerifier = Verifier(label: "DL1Test") + let failScalarVar = failVerifier.appendScalar(label: "scalar") + let _ = failVerifier.appendPoint(label: "point", assignment: point) + let failResultVar = failVerifier.appendPoint(label: "result", assignment: result) + failVerifier.constrain(result: failResultVar, linearCombination: [(failScalarVar, failResultVar)]) // Incorrect point + let failProofVerifies = try failVerifier.verify(proof: proof) + XCTAssertFalse(failProofVerifies) + } + + func testDL1() throws { + try DL1Workflow(CurveType: P256.self) + try DL1Workflow(CurveType: P384.self) + try DL1Workflow(CurveType: P521.self) + } + + /// Allocate group element variables and define the constraints for a DLEQ proof: + /// result1 = scalar * point1 and result2 = scalar * point2 + /// such that log_point1(result1)==log_point2(result2), for a secret scalar. + func DLEqualityConstrain(participant: inout P, scalarVar: ScalarVar, + point1: Group.Element, result1: Group.Element, + point2: Group.Element, result2: Group.Element) { + let point1Var = participant.appendPoint(label: "point1", assignment: point1) + let result1Var = participant.appendPoint(label: "result1", assignment: result1) + let point2Var = participant.appendPoint(label: "point2", assignment: point2) + let result2Var = participant.appendPoint(label: "result2", assignment: result2) + participant.constrain(result: result1Var, linearCombination: [(scalarVar, point1Var)]) + participant.constrain(result: result2Var, linearCombination: [(scalarVar, point2Var)]) + } + + /// Tests the workflow for proof creation and verification, for a simple DLEQ proof: + /// For a secret scalar x, the relation between B=x*A and D=x*C is such that log_A(B)==log_C(D) + func DLEqualityWorkflow(CurveType _: Curve.Type) throws { + // Prover's scope + let (proof, point1, point2, result1, result2) = try { + let point1 = Group.Element.random + let point2 = Group.Element.random + let scalar = Group.Scalar.random + let result1 = scalar * point1 + let result2 = scalar * point2 + + var prover = Prover(label: "DLEqualityTest") + let scalarVar = prover.appendScalar(label: "scalar", assignment: scalar) + DLEqualityConstrain(participant: &prover, scalarVar: scalarVar, point1: point1, result1: result1, point2: point2, result2: result2) + let proof = try prover.prove() + return (proof, point1, point2, result1, result2) + }() + + // Verifier's scope + var verifier = Verifier(label: "DLEqualityTest") + let scalarVar = verifier.appendScalar(label: "scalar") + DLEqualityConstrain(participant: &verifier, scalarVar: scalarVar, point1: point1, result1: result1, point2: point2, result2: result2) + let proofVerifies = try verifier.verify(proof: proof) + XCTAssert(proofVerifies) + + // Test that incorrect ProofParticipant label causes proof verification to fail + var failVerifier = Verifier(label: "WrongTestLabel") + let failScalarVar = failVerifier.appendScalar(label: "scalar") + DLEqualityConstrain(participant: &failVerifier, scalarVar: failScalarVar, point1: point1, result1: result1, point2: point2, result2: result2) + let failProofVerifies = try failVerifier.verify(proof: proof) + XCTAssertFalse(failProofVerifies) + } + + func testDLEquality() throws { + try DLEqualityWorkflow(CurveType: P256.self) + try DLEqualityWorkflow(CurveType: P384.self) + try DLEqualityWorkflow(CurveType: P521.self) + } + + /// Tests the workflow for proof creation and verification, for a commitment proof: A=x*B+y*C for secret scalars x, y + func DL2Workflow(CurveType _: Curve.Type) throws { + // Prover's scope + let (proof, point1, point2, result) = try { + let point1 = Group.Element.random + let point2 = Group.Element.random + let scalar1 = Group.Scalar.random + let scalar2 = Group.Scalar.random + let result = scalar1 * point1 + scalar2 * point2 + + var prover = Prover(label: "DL2Test") + let scalar1Var = prover.appendScalar(label: "scalar1", assignment: scalar1) + let scalar2Var = prover.appendScalar(label: "scalar2", assignment: scalar2) + let point1Var = prover.appendPoint(label: "point1", assignment: point1) + let point2Var = prover.appendPoint(label: "point2", assignment: point2) + let resultVar = prover.appendPoint(label: "result", assignment: result) + prover.constrain(result: resultVar, linearCombination: [(scalar1Var, point1Var), (scalar2Var, point2Var)]) + let proof = try prover.prove() + return (proof, point1, point2, result) + }() + + // Verifier's scope + var verifier = Verifier(label: "DL2Test") + let scalar1Var = verifier.appendScalar(label: "scalar1") + let scalar2Var = verifier.appendScalar(label: "scalar2") + let point1Var = verifier.appendPoint(label: "point1", assignment: point1) + let point2Var = verifier.appendPoint(label: "point2", assignment: point2) + let resultVar = verifier.appendPoint(label: "result", assignment: result) + verifier.constrain(result: resultVar, linearCombination: [(scalar1Var, point1Var), (scalar2Var, point2Var)]) + let proofVerifies = try verifier.verify(proof: proof) + XCTAssert(proofVerifies) + } + + func testDL2() throws { + try DL2Workflow(CurveType: P256.self) + try DL2Workflow(CurveType: P384.self) + try DL2Workflow(CurveType: P521.self) + } + + /// Tests an empty workflow, where no variables are allocated. + func EmptyWorkflow(CurveType _: Curve.Type) throws { + // Prover's scope + let proof = try { + let prover = Prover(label: "EmptyTest") + let proof = try prover.prove() + return proof + }() + + // Verifier's scope + let verifier = Verifier(label: "EmptyTest") + let result = try verifier.verify(proof: proof) + XCTAssert(result) + } + + func testEmpty() throws { + try EmptyWorkflow(CurveType: P256.self) + try EmptyWorkflow(CurveType: P384.self) + try EmptyWorkflow(CurveType: P521.self) + } +}