mirror of
https://github.com/apple/swift-crypto
synced 2026-11-22 04:30:39 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b6049c0b2e | ||
|
|
b81059d507 | ||
|
|
06fc9b0a09 | ||
|
|
472de789e9 | ||
|
|
75a3eca905 |
No files matched your search
@@ -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
|
||||
+1
-1
@@ -58,7 +58,7 @@ if(NOT SwiftASN1_FOUND)
|
||||
message("-- Vending swift-asn1")
|
||||
FetchContent_Declare(ASN1
|
||||
GIT_REPOSITORY https://github.com/apple/swift-asn1
|
||||
GIT_TAG 1.1.0)
|
||||
GIT_TAG 1.3.1)
|
||||
FetchContent_MakeAvailable(ASN1)
|
||||
endif()
|
||||
|
||||
|
||||
+13
-1
@@ -22,6 +22,7 @@
|
||||
//
|
||||
// BoringSSL Commit: aefa5d24da34ef77ac797bdbe684734e5bd870f4
|
||||
|
||||
import class Foundation.ProcessInfo
|
||||
import PackageDescription
|
||||
|
||||
// To develop this on Apple platforms, set this to true
|
||||
@@ -94,7 +95,7 @@ let package = Package(
|
||||
MANGLE_END */
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-asn1.git", from: "1.2.0")
|
||||
// Dependencies are added below so that they can be switched between local and absolute URLs
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
@@ -201,6 +202,17 @@ let package = Package(
|
||||
cxxLanguageStandard: .cxx14
|
||||
)
|
||||
|
||||
// Switch between local and remote dependencies depending on an environment variable
|
||||
if ProcessInfo.processInfo.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil {
|
||||
package.dependencies += [
|
||||
.package(url: "https://github.com/apple/swift-asn1.git", from: "1.2.0"),
|
||||
]
|
||||
} else {
|
||||
package.dependencies += [
|
||||
.package(path: "../swift-asn1"),
|
||||
]
|
||||
}
|
||||
|
||||
// --- STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- //
|
||||
for target in package.targets {
|
||||
if target.type != .plugin {
|
||||
|
||||
+5
-5
@@ -123,7 +123,6 @@ add_library(CCryptoBoringSSL STATIC
|
||||
"crypto/fipsmodule/bcm.cc"
|
||||
"crypto/fipsmodule/fips_shared_support.cc"
|
||||
"crypto/hpke/hpke.cc"
|
||||
"crypto/hrss/asm/poly_rq_mul.S"
|
||||
"crypto/hrss/hrss.cc"
|
||||
"crypto/kyber/kyber.cc"
|
||||
"crypto/lhash/lhash.cc"
|
||||
@@ -255,10 +254,11 @@ add_library(CCryptoBoringSSL STATIC
|
||||
"crypto/x509/x_x509.cc"
|
||||
"crypto/x509/x_x509a.cc"
|
||||
"gen/crypto/err_data.cc"
|
||||
"third_party/fiat/asm/fiat_curve25519_adx_mul.S"
|
||||
"third_party/fiat/asm/fiat_curve25519_adx_square.S"
|
||||
"third_party/fiat/asm/fiat_p256_adx_mul.S"
|
||||
"third_party/fiat/asm/fiat_p256_adx_sqr.S")
|
||||
"$<$<NOT:$<PLATFORM_ID:Windows>>:crypto/hrss/asm/poly_rq_mul.S>"
|
||||
"$<$<NOT:$<PLATFORM_ID:Windows>>:third_party/fiat/asm/fiat_curve25519_adx_mul.S>"
|
||||
"$<$<NOT:$<PLATFORM_ID:Windows>>:third_party/fiat/asm/fiat_curve25519_adx_square.S>"
|
||||
"$<$<NOT:$<PLATFORM_ID:Windows>>:third_party/fiat/asm/fiat_p256_adx_mul.S>"
|
||||
"$<$<NOT:$<PLATFORM_ID:Windows>>:third_party/fiat/asm/fiat_p256_adx_sqr.S>")
|
||||
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL Darwin AND CMAKE_SYSTEM_PROCESSOR MATCHES "amd64|x86_64")
|
||||
target_sources(CCryptoBoringSSL PRIVATE
|
||||
|
||||
@@ -13,7 +13,8 @@
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
add_library(CCryptoBoringSSLShims STATIC
|
||||
"shims.c")
|
||||
"shims.c"
|
||||
)
|
||||
|
||||
target_include_directories(CCryptoBoringSSLShims PUBLIC
|
||||
include
|
||||
|
||||
@@ -91,7 +91,8 @@ add_library(Crypto
|
||||
"Util/PrettyBytes.swift"
|
||||
"Util/SafeCompare.swift"
|
||||
"Util/SecureBytes.swift"
|
||||
"Util/Zeroization.swift")
|
||||
"Util/Zeroization.swift"
|
||||
)
|
||||
|
||||
target_compile_definitions(Crypto PRIVATE
|
||||
"$<$<COMPILE_LANGUAGE:Swift>:CRYPTO_IN_SWIFTPM>")
|
||||
|
||||
@@ -19,7 +19,8 @@ add_library(CryptoBoringWrapper STATIC
|
||||
"EC/EllipticCurvePoint.swift"
|
||||
"Util/ArbitraryPrecisionInteger.swift"
|
||||
"Util/FiniteFieldArithmeticContext.swift"
|
||||
"Util/RandomBytes.swift")
|
||||
"Util/RandomBytes.swift"
|
||||
)
|
||||
|
||||
target_include_directories(CryptoBoringWrapper PUBLIC
|
||||
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
|
||||
|
||||
@@ -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<P384>
|
||||
// TODO: are these typealiases doing anything useful?
|
||||
fileprivate typealias Ciphersuite = ARC.Ciphersuite<H2G>
|
||||
fileprivate typealias Server = ARC.Server<H2G>
|
||||
|
||||
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<H2G>
|
||||
|
||||
/// 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<D: DataProtocol>(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[..<bytes.startIndex.advanced(by: P384.orderByteCount)])
|
||||
bytes.removeFirst(P384.orderByteCount)
|
||||
let x1 = try H2G.G.Scalar(bytes: bytes[..<bytes.startIndex.advanced(by: P384.orderByteCount)])
|
||||
bytes.removeFirst(P384.orderByteCount)
|
||||
let x2 = try H2G.G.Scalar(bytes: bytes[..<bytes.startIndex.advanced(by: P384.orderByteCount)])
|
||||
bytes.removeFirst(P384.orderByteCount)
|
||||
let x0Blinding = try H2G.G.Scalar(bytes: bytes[..<bytes.startIndex.advanced(by: P384.orderByteCount)])
|
||||
bytes.removeFirst(P384.orderByteCount)
|
||||
assert(bytes.isEmpty)
|
||||
|
||||
self.backing = ARC.Server(ciphersuite: P384._ARCV1.ciphersuite, x0: x0, x1: x1, x2: x2, x0Blinding: x0Blinding)
|
||||
}
|
||||
|
||||
// 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[Ns];
|
||||
// uint8 x1[Ns];
|
||||
// uint8 x2[Ns];
|
||||
// uint8 x0Blinding[Ns];
|
||||
// } ServerPrivateKey;
|
||||
//
|
||||
// TODO: Confirm requiremnts for private key serialization format(s) and/or document binary scalar format.
|
||||
public var rawRepresentation: Data {
|
||||
let serializedByteCount = 4 * P384.orderByteCount
|
||||
var result = Data(capacity: serializedByteCount)
|
||||
|
||||
result.append(self.backing.serverPrivateKey.x0.rawRepresentation)
|
||||
result.append(self.backing.serverPrivateKey.x1.rawRepresentation)
|
||||
result.append(self.backing.serverPrivateKey.x2.rawRepresentation)
|
||||
result.append(self.backing.serverPrivateKey.x0Blinding.rawRepresentation)
|
||||
assert(result.count == serializedByteCount)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
public var publicKey: P384._ARCV1.PublicKey {
|
||||
P384._ARCV1.PublicKey(backing: self.backing.serverPublicKey)
|
||||
}
|
||||
}
|
||||
|
||||
/// The server public key, used by clients to create anonymous credentials in conjunction with the server.
|
||||
public struct PublicKey {
|
||||
fileprivate var backing: ARC.ServerPublicKey<H2G>
|
||||
|
||||
fileprivate init(backing: ARC.ServerPublicKey<H2G>) {
|
||||
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<D: DataProtocol>(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[..<bytes.startIndex.advanced(by: P384.compressedx962PointByteCount)])
|
||||
bytes.removeFirst(P384.compressedx962PointByteCount)
|
||||
let X1 = try H2G.G.Element(oprfRepresentation: bytes[..<bytes.startIndex.advanced(by: P384.compressedx962PointByteCount)])
|
||||
bytes.removeFirst(P384.compressedx962PointByteCount)
|
||||
let X2 = try H2G.G.Element(oprfRepresentation: bytes[..<bytes.startIndex.advanced(by: P384.compressedx962PointByteCount)])
|
||||
bytes.removeFirst(P384.compressedx962PointByteCount)
|
||||
assert(bytes.isEmpty)
|
||||
|
||||
self.backing = ARC.ServerPublicKey(X0: X0, X1: X1, X2: X2)
|
||||
}
|
||||
|
||||
// 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 var rawRepresentation: Data {
|
||||
var result = Data(capacity: Self.serializedByteCount)
|
||||
|
||||
result.append(self.backing.X0.oprfRepresentation)
|
||||
result.append(self.backing.X1.oprfRepresentation)
|
||||
result.append(self.backing.X2.oprfRepresentation)
|
||||
assert(result.count == Self.serializedByteCount)
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
/// A credential request, created by the client, to be sent to the server.
|
||||
///
|
||||
/// Clients should not create values of this type manually; they should use the prepare method on the public key.
|
||||
///
|
||||
/// Servers should reconstruct values of this type from the serialized bytes sent by the client.
|
||||
public struct CredentialRequest {
|
||||
var backing: ARC.CredentialRequest<H2G>
|
||||
|
||||
fileprivate init(backing: ARC.CredentialRequest<H2G>) {
|
||||
self.backing = backing
|
||||
}
|
||||
|
||||
public init<D: DataProtocol>(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<H2G>
|
||||
|
||||
/// 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<H2G>
|
||||
|
||||
fileprivate init(backing: ARC.CredentialResponse<H2G>) {
|
||||
self.backing = backing
|
||||
}
|
||||
|
||||
public init<D: DataProtocol>(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<H2G>
|
||||
|
||||
fileprivate init(backing: ARC.Credential<H2G>) {
|
||||
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<H2G>
|
||||
|
||||
fileprivate init(backing: ARC.Presentation<H2G>) {
|
||||
self.backing = backing
|
||||
}
|
||||
|
||||
public init<D: DataProtocol>(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<D: DataProtocol>(
|
||||
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<D: DataProtocol>(
|
||||
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<D: DataProtocol>(
|
||||
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<D: DataProtocol>(
|
||||
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<D1: DataProtocol, D2: DataProtocol>(
|
||||
_ 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
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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<H2G: HashToGroup> {
|
||||
let suiteID: Int
|
||||
|
||||
init(_ h2g: H2G.Type) {
|
||||
switch h2g.self {
|
||||
case is HashToCurveImpl<P256>.Type:
|
||||
self.suiteID = 3
|
||||
case is HashToCurveImpl<P384>.Type:
|
||||
self.suiteID = 4
|
||||
case is HashToCurveImpl<P521>.Type:
|
||||
self.suiteID = 5
|
||||
default:
|
||||
fatalError("Anonymous Rate-Limited Credentials (ARC) only support corecrypto H2G.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static func getGenerators<H2G: HashToGroup>(suite _: Ciphersuite<H2G>) -> (
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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<H2G: HashToGroup> {
|
||||
typealias Group = H2G.G
|
||||
let m1: Group.Scalar
|
||||
let U: Group.Element
|
||||
let UPrime: Group.Element
|
||||
let X1: Group.Element
|
||||
let ciphersuite: Ciphersuite<H2G>
|
||||
let generatorG: Group.Element
|
||||
let generatorH: Group.Element
|
||||
let presentationLimit: Int
|
||||
var presentationNonces: [Data: Set<Int>]
|
||||
|
||||
init(credentialResponse: CredentialResponse<H2G>, credentialRequest: CredentialRequest<H2G>, clientSecrets: ClientSecrets<Group.Scalar>, serverPublicKey: ServerPublicKey<H2G>, ciphersuite: Ciphersuite<H2G>, 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<Int>]()
|
||||
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<Int>], ciphersuite: Ciphersuite<H2G>, 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<H2G>, 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)
|
||||
|
||||
// Store the nonce in presentationNonces for that presentationContext.
|
||||
if self.presentationNonces[presentationContext] != nil {
|
||||
if self.presentationNonces[presentationContext]!.count >= 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..<self.presentationLimit)
|
||||
} else {
|
||||
// optionalNonce collides with existing nonce for presentationContext
|
||||
throw ARC.Errors.presentationLimitExceeded
|
||||
}
|
||||
}
|
||||
self.presentationNonces[presentationContext]!.insert(nonce)
|
||||
} else {
|
||||
self.presentationNonces[presentationContext] = [nonce]
|
||||
}
|
||||
|
||||
let presentation = try Presentation<H2G>(credential: self, a: a, r: r, z: z, presentationContext: presentationContext, nonce: nonce, generatorG: self.generatorG, generatorH: self.generatorH)
|
||||
return (presentation, nonce)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<ARCCurve>
|
||||
|
||||
internal func DecodeInt(value: Data) -> Int {
|
||||
var result = Int(0)
|
||||
|
||||
for i in 0..<value.count {
|
||||
result = result << 8
|
||||
result += Int(value[i])
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
internal func EncodeInt(value: Int) -> 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<D: DataProtocol>(requestData: D) throws -> ARC.CredentialRequest<ARCH2G> {
|
||||
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..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
let m2Enc = try ARCH2G.G.Element(oprfRepresentation: requestData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
|
||||
let proof = try Proof.deserialize(proofData: requestData.subdata(in: startPointer..<startPointer + self.scalarCount * ARCCurve.orderByteCount), scalarCount: self.scalarCount)
|
||||
return ARC.CredentialRequest(m1Enc: m1Enc, m2Enc: m2Enc, proof: proof)
|
||||
}
|
||||
}
|
||||
|
||||
extension ARC.CredentialResponse where H2G == ARCH2G {
|
||||
static let scalarCount = 8
|
||||
static let pointCount = 6
|
||||
static let serializedByteCount = pointCount * ARCCurve.compressedx962PointByteCount + scalarCount * ARCCurve.orderByteCount
|
||||
|
||||
func serialize() -> 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<D: DataProtocol>(responseData: D) throws -> ARC.CredentialResponse<ARCH2G> {
|
||||
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..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
let encUPrime = try ARCH2G.G.Element(oprfRepresentation: responseData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
let X0Aux = try ARCH2G.G.Element(oprfRepresentation: responseData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
let X1Aux = try ARCH2G.G.Element(oprfRepresentation: responseData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
let X2Aux = try ARCH2G.G.Element(oprfRepresentation: responseData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
let HAux = try ARCH2G.G.Element(oprfRepresentation: responseData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
|
||||
let proof = try Proof.deserialize(proofData: responseData.subdata(in: startPointer..<startPointer + self.scalarCount * ARCCurve.orderByteCount), scalarCount: self.scalarCount)
|
||||
return ARC.CredentialResponse(U: U, encUPrime: encUPrime, X0Aux: X0Aux, X1Aux: X1Aux, X2Aux: X2Aux, HAux: HAux, proof: proof)
|
||||
}
|
||||
}
|
||||
|
||||
extension ARC.Presentation where H2G == ARCH2G {
|
||||
static let scalarCount = 5
|
||||
static let pointCount = 4
|
||||
static let serializedByteCount = pointCount * ARCCurve.compressedx962PointByteCount + scalarCount * ARCCurve.orderByteCount
|
||||
|
||||
func serialize() -> 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<D: DataProtocol>(presentationData: D) throws -> ARC.Presentation<ARCH2G> {
|
||||
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..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
let UPrimeCommit = try ARCH2G.G.Element(oprfRepresentation: presentationData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
let m1Commit = try ARCH2G.G.Element(oprfRepresentation: presentationData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
let tag = try ARCH2G.G.Element(oprfRepresentation: presentationData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
|
||||
let presentationProof = try Proof.deserialize(proofData: presentationData.subdata(in: startPointer..<startPointer + self.scalarCount * ARCCurve.orderByteCount), scalarCount: self.scalarCount)
|
||||
return ARC.Presentation(U: U, UPrimeCommit: UPrimeCommit, m1Commit: m1Commit, tag: tag, proof: presentationProof)
|
||||
}
|
||||
}
|
||||
|
||||
extension ARC.ServerPublicKey where H2G == ARCH2G {
|
||||
static let pointCount = 3
|
||||
|
||||
func serialize() -> 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<D: DataProtocol>(serverPublicKeyData: D) throws -> ARC.ServerPublicKey<ARCH2G> {
|
||||
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..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
let X1 = try ARCH2G.G.Element(oprfRepresentation: serverPublicKeyData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
let X2 = try ARCH2G.G.Element(oprfRepresentation: serverPublicKeyData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
|
||||
return ARC.ServerPublicKey(X0: X0, X1: X1, X2: X2)
|
||||
}
|
||||
}
|
||||
|
||||
extension Proof where H2G == ARCH2G {
|
||||
func serialize() -> 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<D: DataProtocol>(proofData: D, scalarCount: Int) throws -> Proof<ARCH2G> {
|
||||
guard proofData.count == scalarCount * ARCCurve.orderByteCount else {
|
||||
throw ARC.Errors.incorrectProofDataSize
|
||||
}
|
||||
let proofData = Data(proofData)
|
||||
var startPointer = 0
|
||||
|
||||
// Deserialize challenge
|
||||
let challenge = try GroupImpl<ARCCurve>.Scalar(bytes: proofData.subdata(in: startPointer..<startPointer+ARCCurve.orderByteCount))
|
||||
startPointer += ARCCurve.orderByteCount
|
||||
|
||||
// Deserialize responses
|
||||
var responses: [GroupImpl<ARCCurve>.Scalar] = []
|
||||
for _ in (0..<scalarCount-1) {
|
||||
let response = try GroupImpl<ARCCurve>.Scalar(bytes: proofData.subdata(in: startPointer..<startPointer+ARCCurve.orderByteCount))
|
||||
responses.append(response)
|
||||
startPointer += ARCCurve.orderByteCount
|
||||
}
|
||||
|
||||
return Proof(challenge: challenge, responses: responses)
|
||||
}
|
||||
}
|
||||
|
||||
// Serialize a ARC credential, to save and restore client state.
|
||||
// This will only be called client-side, and never be sent over the wire.
|
||||
extension ARC.Credential where H2G == ARCH2G {
|
||||
static let scalarCount = 1
|
||||
static let pointCount = 5
|
||||
static let integerByteCount = 4
|
||||
|
||||
func serialize() throws -> 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<D: DataProtocol>(credentialData: D) throws -> ARC.Credential<ARCH2G> {
|
||||
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<ARCCurve>.Scalar(bytes: credentialData.subdata(in: startPointer..<startPointer+ARCCurve.orderByteCount))
|
||||
startPointer += ARCCurve.orderByteCount
|
||||
let U = try ARCH2G.G.Element(oprfRepresentation: credentialData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
let UPrime = try ARCH2G.G.Element(oprfRepresentation: credentialData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
let X1 = try ARCH2G.G.Element(oprfRepresentation: credentialData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
let genG = try ARCH2G.G.Element(oprfRepresentation: credentialData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
let genH = try ARCH2G.G.Element(oprfRepresentation: credentialData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
|
||||
startPointer += ARCCurve.compressedx962PointByteCount
|
||||
let presentationLimit = DecodeInt(value: credentialData.subdata(in: startPointer..<startPointer+self.integerByteCount))
|
||||
startPointer += self.integerByteCount
|
||||
|
||||
// Deserialize presentationNonces dictionary
|
||||
let noncesData = credentialData.subdata(in: startPointer..<startPointer+noncesByteCount)
|
||||
let presentationNonces = try ARCNonces.deserialize(noncesData: noncesData)
|
||||
|
||||
let ciphersuite = ARC.Ciphersuite(ARCH2G.self)
|
||||
return ARC.Credential(m1: m1, U: U, UPrime: UPrime, X1: X1, presentationLimit: presentationLimit, presentationNonces: presentationNonces, ciphersuite: ciphersuite, generatorG: genG, generatorH: genH)
|
||||
}
|
||||
}
|
||||
|
||||
// A helper for serializing a ARC credential. This will only be called client-side, and never be sent over the wire.
|
||||
struct ARCNonces {
|
||||
static func serialize(noncesDict: [Data: Set<Int>]) throws -> Data {
|
||||
// Convert Set<Int> to Array<Int> for encoding
|
||||
let dictForEncoding = noncesDict.mapValues {Array($0) }
|
||||
let encoder = PropertyListEncoder()
|
||||
encoder.outputFormat = .binary
|
||||
return try encoder.encode(dictForEncoding)
|
||||
}
|
||||
|
||||
static func deserialize<D: DataProtocol>(noncesData: D) throws -> [Data: Set<Int>] {
|
||||
let decoder = PropertyListDecoder()
|
||||
// Decode as [Data: [Int]] and convert Array<Int> back to Set<Int>
|
||||
let decodedDictionary = try decoder.decode([Data: [Int]].self, from: Data(noncesData))
|
||||
return decodedDictionary.mapValues { Set($0) }
|
||||
}
|
||||
}
|
||||
@@ -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<Scalar> {
|
||||
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<H2G: HashToGroup> {
|
||||
typealias Group = H2G.G
|
||||
let clientSecrets: ClientSecrets<Group.Scalar>
|
||||
let serverPublicKey: ServerPublicKey<H2G>
|
||||
let ciphersuite: Ciphersuite<H2G>
|
||||
let generatorG: Group.Element
|
||||
let generatorH: Group.Element
|
||||
let credentialRequest: CredentialRequest<H2G>
|
||||
let presentationLimit: Int
|
||||
|
||||
init(ciphersuite: Ciphersuite<H2G>, m1: Group.Scalar = Group.Scalar.random, requestContext: Data, r1: Group.Scalar = Group.Scalar.random, r2: Group.Scalar = Group.Scalar.random, serverPublicKey: ServerPublicKey<H2G>, 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<H2G>) throws -> Credential<H2G> {
|
||||
return try Credential<H2G>(credentialResponse: credentialResponse, credentialRequest: self.credentialRequest, clientSecrets: self.clientSecrets, serverPublicKey: self.serverPublicKey, ciphersuite: self.ciphersuite, generatorG: self.generatorG, generatorH: self.generatorH, presentationLimit: self.presentationLimit)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<H2G: HashToGroup> {
|
||||
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<H2G>
|
||||
|
||||
init(credential: Credential<H2G>, 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<H2G>(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<H2G>) {
|
||||
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<Group.Scalar>, 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..<nonce { m1Tag = m1Tag - self.tag }
|
||||
|
||||
// Create a verifier, and allocate variables for the constrained scalars.
|
||||
var verifier = Verifier<H2G>(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<P: ProofParticipant>(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)])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<H2G: HashToGroup> {
|
||||
typealias Group = H2G.G
|
||||
let m1Enc: Group.Element
|
||||
let m2Enc: Group.Element
|
||||
let proof: Proof<H2G>
|
||||
|
||||
init(clientSecrets: ClientSecrets<Group.Scalar>, 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<H2G>(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<H2G>) {
|
||||
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<H2G>(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<P: ProofParticipant>(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)])
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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<H2G: HashToGroup> {
|
||||
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<H2G>
|
||||
|
||||
init(
|
||||
request: CredentialRequest<H2G>,
|
||||
serverPrivateKey: ServerPrivateKey<Group.Scalar>,
|
||||
serverPublicKey: ServerPublicKey<H2G>,
|
||||
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<H2G>(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<H2G>
|
||||
) {
|
||||
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<H2G>, serverPublicKey: ServerPublicKey<H2G>, 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<H2G>(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<P: ProofParticipant>(participant: inout P, request: CredentialRequest<H2G>, 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)])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Scalar> {
|
||||
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<H2G: HashToGroup> {
|
||||
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<Group.Scalar>, 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<H2G: HashToGroup> {
|
||||
typealias Group = H2G.G
|
||||
let serverPrivateKey: ServerPrivateKey<Group.Scalar>
|
||||
let serverPublicKey: ServerPublicKey<H2G>
|
||||
let ciphersuite: Ciphersuite<H2G>
|
||||
let generatorG: Group.Element
|
||||
let generatorH: Group.Element
|
||||
|
||||
init(ciphersuite: Ciphersuite<H2G>, 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<H2G>, b: Group.Scalar = Group.Scalar.random) throws -> CredentialResponse<H2G> {
|
||||
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<H2G>, 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
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,17 @@ 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)
|
||||
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "Linux" OR CMAKE_SYSTEM_NAME STREQUAL "Windows" OR CMAKE_SYSTEM_NAME STREQUAL "Android" OR CMAKE_SYSTEM_NAME STREQUAL "WASI" OR CMAKE_SYSTEM_NAME STREQUAL FreeBSD)
|
||||
target_compile_options(_CryptoExtras PRIVATE -DCRYPTO_IN_SWIFTPM_FORCE_BUILD_API)
|
||||
endif()
|
||||
|
||||
target_include_directories(_CryptoExtras PRIVATE
|
||||
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<H2G: HashToGroup>: 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<H2G> {
|
||||
// Create a blinding scalar for each scalar variable.
|
||||
let blindings = (0..<self.scalars.count).map { _ in Group.Scalar.random }
|
||||
return try self.proveWithFixedRandomness(blindings: blindings)
|
||||
}
|
||||
|
||||
// Pass in externally generated blinding values, for generating or testing against test vectors.
|
||||
func proveWithFixedRandomness(blindings: [Group.Scalar]) throws -> Proof<H2G> {
|
||||
// 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..<self.points.count).contains(constraintPoint.index) {
|
||||
throw ZKPErrors.invalidVariableAllocation
|
||||
}
|
||||
for (scalarVar, pointVar) in linearCombination {
|
||||
if !(0..<self.scalars.count).contains(scalarVar.index) || !(0..<self.points.count).contains(pointVar.index) {
|
||||
throw ZKPErrors.invalidVariableAllocation
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: expose the identity point from ECToolbox, and use `.reduce(0, +)` instead.
|
||||
// Compute the first multiplication in the constraint.
|
||||
let scalarIndex = linearCombination[0].0.index
|
||||
let pointIndex = linearCombination[0].1.index
|
||||
let firstBlindedPoint = blindings[scalarIndex] * self.points[pointIndex]
|
||||
|
||||
// Compute the rest of the multiplications in the constraint.
|
||||
let blindedPoint = (linearCombination[1...]).map { (scalar, point) in
|
||||
blindings[scalar.index] * self.points[point.index]
|
||||
}.reduce(firstBlindedPoint, +)
|
||||
|
||||
blindedPoints.append(blindedPoint)
|
||||
blindedPointsLabels.append(self.pointLabels[constraintPoint.index] + "-blind")
|
||||
}
|
||||
|
||||
// Obtain a scalar challenge.
|
||||
let challenge = try Proof<H2G>.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)
|
||||
}
|
||||
}
|
||||
@@ -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<H2G: HashToGroup>: 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<H2G>) 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..<self.points.count).contains(constraintPoint.index) {
|
||||
throw ZKPErrors.invalidVariableAllocation
|
||||
}
|
||||
for (_, pointVar) in linearCombination {
|
||||
if !(0..<self.points.count).contains(pointVar.index) {
|
||||
throw ZKPErrors.invalidVariableAllocation
|
||||
}
|
||||
}
|
||||
|
||||
// challenge * constraintPoint
|
||||
let challengePoint = proof.challenge * self.points[constraintPoint.index]
|
||||
let blindedPoint = (linearCombination).map { (scalar, point) in
|
||||
proof.responses[scalar.index] * self.points[point.index]
|
||||
}.reduce(challengePoint, +)
|
||||
|
||||
blindedPoints.append(blindedPoint)
|
||||
blindedPointsLabels.append(self.pointLabels[constraintPoint.index] + "-blind")
|
||||
}
|
||||
|
||||
// Obtain a scalar challenge.
|
||||
let challenge = try Proof<H2G>.composeChallenge(label: self.label, points: self.points, pointLabels: self.pointLabels, blindedPoints: blindedPoints, blindedPointsLabels: blindedPointsLabels, scalarLabels: self.scalarLabels)
|
||||
|
||||
return challenge == proof.challenge
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<H2G: HashToGroup> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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<ARCCurve>.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<ARCCurve>.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<ARCCurve>.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<ARCCurve>.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<ARCCurve>.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<Int>] = [:]
|
||||
let smallDictionary: [Data: Set<Int>] = [Data("context1".utf8): [1, 2, 3], Data("context2".utf8): [4, 5, 6]]
|
||||
var largeDictionary: [Data: Set<Int>] = [:]
|
||||
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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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..<presentationLimit {
|
||||
_ = try credential.makePresentation(context: presentationContext)
|
||||
}
|
||||
|
||||
XCTAssertThrowsError(try credential.makePresentation(context: presentationContext)) { error in
|
||||
XCTAssertEqual(String(describing: error), "presentationLimitExceeded")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
|
||||
let ARCEncodedTestVector = """
|
||||
[
|
||||
{
|
||||
"Credential": {
|
||||
"U": "02be890d43908e52ed43ae7bc7098f3a7694617fe44a88c33c6fa4eb9e942c0b2bb9d2fd56a44e1d6094fc7b9e8b949055",
|
||||
"U_prime": "02bec70edf38a3f5c77d5c6f39afd5f94cd266f958c804a954f6104b57a2c8310862a790cbc6b519f8db989d59aebaf081",
|
||||
"X1": "03ef0f59c9b0cc51c9e603dfcaa9a3e3719e186252b64f9ce1ebec352c5b605b805af308a9bd697df7c97b0f1147108c3a",
|
||||
"m1": "5a32aaf031be0555089356d299ce24b0eedfe7939e2382934ab5b0f76aae44124955d2c5ebf9b41d88786259c34692d2"
|
||||
},
|
||||
"CredentialRequest": {
|
||||
"m1": "5a32aaf031be0555089356d299ce24b0eedfe7939e2382934ab5b0f76aae44124955d2c5ebf9b41d88786259c34692d2",
|
||||
"m1_enc": "030a5167977e0c038a98fce96e127fc228aa58526f71a920044b74b2f22dd5839f0e1cf871e6419a1f522e94510ccf2d92",
|
||||
"m2": "ae93d3ea7e5856d5d951a0ae87f8845d767df2e97dd669c8025715e604cb1c43569792b6864f592fed3abe29b9ebc950",
|
||||
"m2_enc": "03a0fea0d3e83ee67b36cb86d8380d4b8420a75e23eb5dcb560a79e74d136cf3c382bff7576f7e50c2cd3d247b56dbf56d",
|
||||
"proof": "ec5a68b4b89b7c411d0073ec384c698016ecfeee8903b7c4cc6e63651a8544b4e06f2d61634a84304b4367bbca558609be6382768d7d070ea047831753b0c9add8db1e3bd9476d2661ac6109218cdccbe5b4250d3785b431114d9b53d66ff7cbc44a7ebbdf90dd5366187d7fbbb5d89f1e450ce8c87c75b94b726e931c81c963ba415eb0334a73b73379abdf34284410e079f18c8200b035b11ade92e8d5e381c1cd5d4db9bba5aff1fe97ce1cebf29dc9389aea13dd64fd8fb1779b6bb549af335d4b9c4603dce2a6bc5ca7b6d9c40287bf265f28c7b1d0b0e2300e5854361670617562aa405d861d9170b08bc09e90",
|
||||
"r1": "df2c61be3c0b37bc73dc89fc386c96b3008035081690bfde3b1e68b91443c22cc791d244340fe957d5aa44d7313740df",
|
||||
"r2": "10fcb00134739cc403f27a79588ca05ad59c5e6ff560cc597c2b8ca25256c720bceca2ab03921492c5e9e4ad3b558002",
|
||||
"request_context": "74657374207265717565737420636f6e74657874"
|
||||
},
|
||||
"CredentialResponse": {
|
||||
"H_aux": "03c7714830e1d72604e52fec595c7a399fe0f3276766f84425fd1f98764ac76dab631c6dfd05e0200c4ffe6d6967304882",
|
||||
"U": "02be890d43908e52ed43ae7bc7098f3a7694617fe44a88c33c6fa4eb9e942c0b2bb9d2fd56a44e1d6094fc7b9e8b949055",
|
||||
"X0_aux": "02890d3f4287e7878ce88b2bc1cc818b2c40fee0f93187af43acb479259979cef1c39d609ea69cc7d6ba1e2a55d107653f",
|
||||
"X1_aux": "0345f2be0dd21d49437a82b221f7a9f074b352e8698fe6ffa08aecad480e96e93a25b6dacd4531fc961e78cfb5503f0e69",
|
||||
"X2_aux": "020f31991b9a40be69bc06ef30c250d9353a824f4da88cc43e63bf92bc8ac8bca7e26bffed33a32cc124fd1fb6c73f8b77",
|
||||
"b": "b8b2e8c2103ad6f1970e873420d82a21e699140babbe599f7dd8f6e3e8f615e5f201d1c2b0bc2f821f19e80a0a0e1e7b",
|
||||
"enc_U_prime": "027f43377c69a2ad931cc21a9cc4d6ea85f84d517d197db721c931276a9ed543a78055ddeb9cac6be3af34c212bca5f403",
|
||||
"proof": "1d5ea5448d22de8e4cb2193693a7c50874d37af3e2879cbf4484d26dd23362e6f3765bbf894599e9551deb31e6f362693a5d799f07fbaf2376976608d73c401a20db7385c89e4cd3b805c3ea9bdf03925b04bf24021246a778282adb1d740e82163fb5037c3ad3221f55dd3ed5e3b3c6a0492827c410efde6d315e3b0b7835459292e81805bea764e372fcd77776863c630b1f1509ef52e50a1fea5dc85b48523936408852d19461a2a8410e7aa49182905a444e089f0ad6b116f065debd09798121793487d7c84d680331bacb1e8730928b897ac839b0b748cfd806833d79a3b50d736349b7bc674672de02e375ee20348f5e349e30ab03ccb0f3a530935f4fada0e63ccb52b58785ecd9483ea37cf3faf0ced66cc36ad33a80a94fa9b0041ff5be03e5fd1f74a748bd5986676390427c27696d6591ec0443fac2415e9c0a4d6197d81a242dd71c739a5f9989a51d8b245ecddb94ebb13c3da2bfc91d42ff992d4f0f1b567138ce1d1012053c4b70b10ed756e102faeb9a1d982227ab16c353"
|
||||
},
|
||||
"Presentation1": {
|
||||
"U": "03383b2ad2831739bc86c0c98119f256e54c9d89a762a9fc91b3904eb3aee7260350a19085ea093a8059369219f03da2c3",
|
||||
"U_prime_commit": "034af7c09ee5150fc914a3bb0adf17f7e90af3c4d9246ec8c511f938467174113513b7577329cecd2a7bff0b97e43a9808",
|
||||
"a": "ad00ec0f71b7a8fb7c0aef35c7243e17b78e57df8f0a95d102ff12bbb97e15ed35c23e54f9b4483d30b76772ee60d886",
|
||||
"m1_commit": "02fb95e1d8010da0c63d38ca212c1f76d768cecc8aa26ab07e77557070c8343e1da571230f071a15a03973cd57dc33ebf4",
|
||||
"nonce": "0x0",
|
||||
"presentation_context": "746573742070726573656e746174696f6e20636f6e74657874",
|
||||
"proof": "91a355f96a4917bc81aa7e5573da2a79bc9e026508e8d161cdbba91f7c3f3f4a1a313adfe78c9e0025640720b1cd973b36fce60a4f82aaedc5cefc4c32760fcec573a2609dafaddf4283949445451b614331172be50abc83c32aaf5cb10b4aee06d2d1240cc7c4fb10491a96d125571dc4317c7583ad54c0971e22cb13b2c040e1d4791dba0a25dd3d1b785e484e8a1e8f24ca91f0f6d0cddf8456a21fa42a06748fa865cd008f3fe91e40a47126a47e54a321bec5c7b73700fbcb335c8a0988000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004",
|
||||
"r": "e5cab8c896187b61abe017e57022528742252210dd60ddbbf1a57e3b144e26dd693b7644a9626a8c36896ede53d12930",
|
||||
"tag": "0247e3fd325bc774c27329a78a62f616f5e409d3a4857609cecde3251140f2bb101905c4cbe66fe06a779e44f5d9e97f08",
|
||||
"z": "f61f4c924d3ef04b31e9196935ff27c5f5a4bbcf14e55e357df9f5ccb5ded37b2b14bc2e1a68e31f86416f0606ee75d1"
|
||||
},
|
||||
"Presentation2": {
|
||||
"U": "020c627c7ced92dd621860017ed29361bb78c4a17c8f7deb79f0c49a4772389899a7e3b7b21e6a6c73abfca1332dc7df6e",
|
||||
"U_prime_commit": "023d7eb948df3f49abe39e8ef32f4bb1bcca0f13f04836efd8b7bc9bd0a73f915531ce845dc8c334d03c13647e5e4cc908",
|
||||
"a": "a8e630484ba024bf9363805bc7a45f1695bcf45150a61f5c44a6cfbf343cd9e0f593f127b6f49bec0f9b20f0550504a2",
|
||||
"m1_commit": "036eea98df5b8248262fc5b511eef49bef1c2ec2a724df3e3a811296fcf7891298d99a22f05ef0b08a2d00857117d88ac7",
|
||||
"nonce": "0x1",
|
||||
"presentation_context": "746573742070726573656e746174696f6e20636f6e74657874",
|
||||
"proof": "5547662ff1c63f14292cc998b24f0c74c20149cd89accde1c7a02485ebac2c7888fd2ffbbafd539f79c8c4677dfcf79acf12a70bd0032c89c70e0966204301699a3c50d1a778d55d812f7d4ef71d29c8b8377607d6d8d5884a31ec8386c909145ee7aa6bc17558be1e2dece1329a9473782d97a7ea5819a60d03990563dd2efccd1fd1a6d4376b2f900a4092a73266e3fec867feae45e645e368178df894c3e1353acd57f3757faabf651b2ef04b87b426c1a695bed9002a0657b3752fdeaee4aab899d00e39c0ebd6d336674db0f38b3dfeb6327653321dffc328fc088b0166cf1cddb68db353db732355034ec831dd",
|
||||
"r": "df6d39c3c0716d7cf8093073168bf967d7ed72750b6d366ed0febdc539b52d89434f468a578c59d7ca9015b7da240ad6",
|
||||
"tag": "03f9ceb1690ef6cd9c1b7d4c29dc86cf25565e4045ae431f8d28029e0405f9ac251ef5a9e873f4a038ecd5a1e43d56bf5d",
|
||||
"z": "1b8e374ed4390e5a9023b309ecb94c0791eedfb168c556ff5ca3b89d047f482c9279b47f584aab6c7f895f7674251771"
|
||||
},
|
||||
"ServerKey": {
|
||||
"X0": "02caa111a43a5909de4af5cb836897334e5a34857ffc3565223cad95a20f1f32303eb8f7594b286238f243eca1a79c60b8",
|
||||
"X1": "03ef0f59c9b0cc51c9e603dfcaa9a3e3719e186252b64f9ce1ebec352c5b605b805af308a9bd697df7c97b0f1147108c3a",
|
||||
"X2": "028a9547a39d925bdd054706aa5ff7616c28aca94c92041c678970c52ee65722f2c54d4f6cecba66abd721ecbcdb2b8a04",
|
||||
"x0": "504650f53df8f16f6861633388936ea23338fa65ec36e0290022b48eb562889d89dbfa691d1cde91517fa222ed7ad364",
|
||||
"x1": "803d955f0e073a04aa5d92b3fb739f56f9db001266677f62c095021db018cd8cbb55941d4073698ce45c405d1348b7b1",
|
||||
"x2": "a097e722ed2427de86966910acba9f5c350e8040f828bf6ceca27405420cdf3d63cb3aef005f40ba51943c8026877963",
|
||||
"xb": "3a349db178a923aa7dff7d2d15d89756fd293126bb49a6d793cd77d7db960f5692fec3b7ec07602c60cd32aee595dffd"
|
||||
},
|
||||
"suite": "ARCV1-P384",
|
||||
}
|
||||
]
|
||||
"""
|
||||
|
||||
struct ARCCredentialTestVector: Codable {
|
||||
let U: String
|
||||
let U_prime: String
|
||||
let X1: String
|
||||
let m1: String
|
||||
}
|
||||
|
||||
struct ARCCredentialRequestTestVector: Codable {
|
||||
let m1: String
|
||||
let m1_enc: String
|
||||
let m2: String
|
||||
let m2_enc: String
|
||||
let proof: String
|
||||
let r1: String
|
||||
let r2: String
|
||||
let request_context: String
|
||||
}
|
||||
|
||||
struct ARCCredentialResponseTestVector: Codable {
|
||||
let H_aux: String
|
||||
let U: String
|
||||
let X0_aux: String
|
||||
let X1_aux: String
|
||||
let X2_aux: String
|
||||
let b: String
|
||||
let enc_U_prime: String
|
||||
let proof: String
|
||||
}
|
||||
|
||||
struct ARCPresentationTestVector: Codable {
|
||||
let U: String
|
||||
let U_prime_commit: String
|
||||
let a: String
|
||||
let m1_commit: String
|
||||
let nonce: String
|
||||
let presentation_context: String
|
||||
let proof: String
|
||||
let r: String
|
||||
let tag: String
|
||||
let z: String
|
||||
}
|
||||
|
||||
struct ARCServerTestVector: Codable {
|
||||
let x0: String
|
||||
let x1: String
|
||||
let x2: String
|
||||
let xb: String
|
||||
let X0: String
|
||||
let X1: String
|
||||
let X2: String
|
||||
}
|
||||
|
||||
struct ARCTestVector: Codable {
|
||||
let suite: String
|
||||
let ServerKey: ARCServerTestVector
|
||||
let CredentialRequest: ARCCredentialRequestTestVector
|
||||
let CredentialResponse: ARCCredentialResponseTestVector
|
||||
let Credential: ARCCredentialTestVector
|
||||
let Presentation1: ARCPresentationTestVector
|
||||
let Presentation2: ARCPresentationTestVector
|
||||
}
|
||||
|
||||
class ARCTestVectors: XCTestCase {
|
||||
func testVectors() throws {
|
||||
let data = ARCEncodedTestVector.data(using: .utf8)!
|
||||
let decoder = JSONDecoder()
|
||||
let testVectors = try decoder.decode([ARCTestVector].self, from: data)
|
||||
testVectors.forEach { validateTestVector($0) }
|
||||
}
|
||||
|
||||
func validate<Curve: SupportedCurveDetailsImpl>(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<Curve>.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<Curve: SupportedCurveDetailsImpl>(CurveType _: Curve.Type, value: String) throws -> GroupImpl<Curve>.Element.Scalar {
|
||||
return try GroupImpl<Curve>.Scalar(bytes: Data(hexString: value))
|
||||
}
|
||||
|
||||
private func elementFromString<Curve: SupportedCurveDetailsImpl>(CurveType _: Curve.Type, value: String) throws -> GroupImpl<Curve>.Element {
|
||||
return try GroupImpl<Curve>.Element(oprfRepresentation: Data(hexString: value))
|
||||
}
|
||||
|
||||
private func proofFromString<Curve: SupportedCurveDetailsImpl>(CurveType _: Curve.Type, value: String, scalarCount: Int) throws -> Proof<HashToCurveImpl<Curve>> {
|
||||
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..<endIndex]))
|
||||
let challenge = try GroupImpl<Curve>.Scalar(bytes: challengeEnc)
|
||||
|
||||
// Deserialize responses
|
||||
var responses: [GroupImpl<Curve>.Scalar] = []
|
||||
for _ in (0..<scalarCount-1) {
|
||||
startIndex = endIndex
|
||||
endIndex = value.index(startIndex, offsetBy: scalarHexCharacterCount)
|
||||
|
||||
let responseEnc = try Data(hexString: String(value[startIndex..<endIndex]))
|
||||
let response = try GroupImpl<Curve>.Scalar(bytes: responseEnc)
|
||||
responses.append(response)
|
||||
}
|
||||
|
||||
return Proof(challenge: challenge, responses: responses)
|
||||
}
|
||||
@@ -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<Curve: SupportedCurveDetailsImpl>(CurveType _: Curve.Type) throws {
|
||||
let ciphersuite = ARC.Ciphersuite(HashToCurveImpl<Curve>.self)
|
||||
let (generatorG, generatorH) = ARC.getGenerators(suite: ciphersuite)
|
||||
|
||||
// Create a server, passing in the server keys and key blinding.
|
||||
let x0 = GroupImpl<Curve>.Scalar.random
|
||||
let x1 = GroupImpl<Curve>.Scalar.random
|
||||
let x2 = GroupImpl<Curve>.Scalar.random
|
||||
let x0Blinding = GroupImpl<Curve>.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<Curve>.Scalar.random
|
||||
let r1 = GroupImpl<Curve>.Scalar.random
|
||||
let r2 = GroupImpl<Curve>.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)
|
||||
}
|
||||
}
|
||||
@@ -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<P384>
|
||||
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<Curve: SupportedCurveDetailsImpl>(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<H2G>(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<H2G>(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<H2G>(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<P: ProofParticipant>(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<Curve: SupportedCurveDetailsImpl>(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<H2G>(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<H2G>(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<H2G>(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<Curve: SupportedCurveDetailsImpl>(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<H2G>(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<H2G>(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<Curve: SupportedCurveDetailsImpl>(CurveType _: Curve.Type) throws {
|
||||
// Prover's scope
|
||||
let proof = try {
|
||||
let prover = Prover<H2G>(label: "EmptyTest")
|
||||
let proof = try prover.prove()
|
||||
return proof
|
||||
}()
|
||||
|
||||
// Verifier's scope
|
||||
let verifier = Verifier<H2G>(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)
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ function update_cmakelists_source() {
|
||||
|
||||
src_exts=("*.c" "*.swift" "*.cc")
|
||||
num_exts=${#src_exts[@]}
|
||||
echo "Finding source files (" "${src_exts[@]}" ") platform independent assembly files under $src_root"
|
||||
echo "Finding source files (" "${src_exts[@]}" ") and platform independent assembly files under $src_root"
|
||||
|
||||
# Build file extensions argument for `find`
|
||||
declare -a exts_arg
|
||||
@@ -56,7 +56,10 @@ function update_cmakelists_source() {
|
||||
fi
|
||||
|
||||
# Wrap quotes around each filename since it might contain spaces
|
||||
srcs=$($find -L "${src_root}" -type f \( \( "${exts_arg[@]}" \) -o \( -name "*.S" -a ! -name "*x86_64*" -a ! -name "*arm*" -a ! -name "*apple*" -a ! -name "*linux*" \) \) -printf ' "%P"\n' | LC_ALL=POSIX sort)
|
||||
srcs=$($find -L "${src_root}" -type f \( "${exts_arg[@]}" \) -printf ' "%P"\n' | LC_ALL=POSIX sort)
|
||||
asm_srcs=$($find -L "${src_root}" -type f \( \( -name "*.S" -a ! -name "*x86_64*" -a ! -name "*arm*" -a ! -name "*apple*" -a ! -name "*linux*" \) \) -printf ' "$<$<NOT:$<PLATFORM_ID:Windows>>:%P>"\n' | LC_ALL=POSIX sort)
|
||||
|
||||
srcs="$srcs"$'\n'"$asm_srcs"
|
||||
echo "$srcs"
|
||||
|
||||
# Update list of source files in CMakeLists.txt
|
||||
|
||||
Reference in new issue
Block a user