Compare commits

...
3 Commits
Author SHA1 Message Date
Si Beaumont a8a02ac79a Use more efficient serialization and deserialization for ARC types (#336)
### Motivation

The use of `Data.subdata(in:)` results in needless copies when decoding
fields from bytes. Additionally, the use of a long chain of
`Data.append(_:)` without a call to `Data.init(capacity:)` or
`Data.reserveCapacity(_:)` can result in needless reallocations.

### Modifications

- Remove unused `EncodeInt` and `DecodeInt` functions. They were unused
before this PR but are there from when ARC credential serialization
included the presentation limit. `DecodeInt` also happened to be
incorrect and would crash when called with a slice.
- Add some useful utility methods for popping bytes from a view without
copying.
- Add some generic functions for encoding and decoding
`FixedWidthInteger` types along with tests for concrete types over
`Data` and slices.
- In ARC decoding, replace the use of `Data.subdata(in:)` with code that
uses the `Data.Subsequence` slice (which happens to be `Data` since the
type is self-slicing).
- In ARC encoding, reserve enough capacity in the resulting `Data` when
the sizes are known to reduce allocations.

## Results

More performant serialization and deserialization for ARC types.
2025-03-12 13:03:42 +00:00
Si Beaumont fca04734d7 Add Sendable conformance to ARC API types (#335)
### Motivation

The ARC API surface had no Sendable conformance.

### Modifications

Add Sendable conformance to ARC API types, which are all value types.

### Result

Easier to use ARC API types in concurrent contexts.
2025-03-10 14:35:31 +00:00
Si Beaumont 4ac764398d Update ARC API to reflect latest draft (#334)
### Motivation

The latest draft of the ARC spec[0] includes moving where the
presentation limit is used. Before it was baked in when a client
constructed a credential request, but now it has moved to when a client
makes a presentation from a finalized credential. This PR updates the
internals and API surface to reflect this change.

### Modifications

- Defer passing the presentation limit until a presentation is made.

### Result

Align more closely with the published draft.

### API breakage

It's expected that this will result in the following _breaking_ API
changes:

```diff
- P384._ARCV1.PublicKey.prepareCredentialRequest(requestContext:presentationLimit:)
+ P384._ARCV1.PublicKey.prepareCredentialRequest(requestContext:)
```

```diff
- P384._ARCV1.Credential.makePresentation(context:)
+ P384._ARCV1.Credential.makePresentation(context:presentationLimit:)
```

As this is behind an underscored namespace, we deem this an acceptable
break.

[0]: https://datatracker.ietf.org/doc/draft-yun-cfrg-arc/
2025-03-10 14:22:27 +00:00
13 changed files with 509 additions and 241 deletions

No files matched your search

+2
View File
@@ -99,6 +99,7 @@ Sources/_CryptoExtras/Util/BoringSSLHelpers.swift
Sources/_CryptoExtras/Util/DigestType.swift
Sources/_CryptoExtras/Util/Error.swift
Sources/_CryptoExtras/Util/I2OSP.swift
Sources/_CryptoExtras/Util/IntegerEncoding.swift
Sources/_CryptoExtras/Util/PEMDocument.swift
Sources/_CryptoExtras/Util/PrettyBytes.swift
Sources/_CryptoExtras/Util/SubjectPublicKeyInfo.swift
@@ -151,6 +152,7 @@ Tests/_CryptoExtrasTests/TestRSABlindSigning.swift
Tests/_CryptoExtrasTests/TestRSABlindSigningAPI.swift
Tests/_CryptoExtrasTests/TestRSAEncryption.swift
Tests/_CryptoExtrasTests/TestRSASigning.swift
Tests/_CryptoExtrasTests/Util/IntegerEncodingTests.swift
Tests/_CryptoExtrasTests/Utils/BytesUtil.swift
Tests/_CryptoExtrasTests/Utils/RFCVector.swift
Tests/_CryptoExtrasTests/Utils/SplitData.swift
+29 -32
View File
@@ -24,7 +24,6 @@ extension P384 {
/// - 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>
@@ -35,7 +34,7 @@ extension P384 {
@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 {
public struct PrivateKey: Sendable {
fileprivate var backing: ARC.Server<H2G>
/// Creates a random private key for ARC(P-384).
@@ -55,7 +54,6 @@ extension P384._ARCV1 {
// 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
@@ -87,7 +85,6 @@ extension P384._ARCV1 {
// 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)
@@ -107,7 +104,7 @@ extension P384._ARCV1 {
}
/// The server public key, used by clients to create anonymous credentials in conjunction with the server.
public struct PublicKey {
public struct PublicKey: Sendable {
fileprivate var backing: ARC.ServerPublicKey<H2G>
fileprivate init(backing: ARC.ServerPublicKey<H2G>) {
@@ -124,7 +121,6 @@ extension P384._ARCV1 {
// 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 }
@@ -148,7 +144,6 @@ extension P384._ARCV1 {
// 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)
@@ -166,7 +161,7 @@ extension P384._ARCV1 {
/// 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 {
public struct CredentialRequest: Sendable {
var backing: ARC.CredentialRequest<H2G>
fileprivate init(backing: ARC.CredentialRequest<H2G>) {
@@ -185,10 +180,10 @@ extension P384._ARCV1 {
/// 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 {
public struct Precredential: Sendable {
/// This backing type binds many things together, including the server commitments, client secrets, credential
/// request, and presentation limit.
fileprivate var backing: ARC.Precredential<H2G>
internal var backing: ARC.Precredential<H2G>
/// The credential request to be sent to the server.
public var credentialRequest: CredentialRequest {
@@ -201,7 +196,7 @@ extension P384._ARCV1 {
/// 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 {
public struct CredentialResponse: Sendable {
var backing: ARC.CredentialResponse<H2G>
fileprivate init(backing: ARC.CredentialResponse<H2G>) {
@@ -221,21 +216,18 @@ extension P384._ARCV1 {
/// 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 {
public struct Credential: Sendable {
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 {
public struct Presentation: Sendable {
internal var backing: ARC.Presentation<H2G>
fileprivate init(backing: ARC.Presentation<H2G>) {
@@ -250,10 +242,6 @@ extension P384._ARCV1 {
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
}
@@ -264,7 +252,6 @@ extension P384._ARCV1 {
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
@@ -275,8 +262,7 @@ extension P384._ARCV1.PublicKey {
requestContext: Data(requestContext),
r1: r1,
r2: r2,
serverPublicKey: self.backing,
presentationLimit: presentationLimit
serverPublicKey: self.backing
)
return P384._ARCV1.Precredential(backing: precedential)
}
@@ -285,16 +271,13 @@ extension P384._ARCV1.PublicKey {
///
/// - 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
requestContext: D
) throws -> P384._ARCV1.Precredential {
try self.prepareCredentialRequest(
requestContext: requestContext,
presentationLimit: presentationLimit,
m1: .random,
r1: .random,
r2: .random
@@ -334,6 +317,7 @@ extension P384._ARCV1.PublicKey {
extension P384._ARCV1.Credential {
internal mutating func makePresentation<D: DataProtocol>(
context: D,
presentationLimit: Int,
fixedNonce: Int?,
a: P384._ARCV1.H2G.G.Scalar,
r: P384._ARCV1.H2G.G.Scalar,
@@ -341,23 +325,36 @@ extension P384._ARCV1.Credential {
) 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
presentationLimit: presentationLimit,
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.
/// - Parameters:
/// - context: The presentation context agreed with the verifier.
/// - presentationLimit: The presentation limit to enforce.
///
/// - 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
context: D,
presentationLimit: Int
) throws -> (presentation: P384._ARCV1.Presentation, nonce: Int) {
try self.makePresentation(context: context, fixedNonce: nil, a: .random, r: .random, z: .random)
try self.makePresentation(
context: context,
presentationLimit: presentationLimit,
fixedNonce: nil,
a: .random,
r: .random,
z: .random
)
}
}
+45 -20
View File
@@ -25,10 +25,9 @@ extension ARC {
let ciphersuite: Ciphersuite<H2G>
let generatorG: Group.Element
let generatorH: Group.Element
let presentationLimit: Int
var presentationNonces: [Data: Set<Int>]
var presentationState: PresentationState
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 {
init(credentialResponse: CredentialResponse<H2G>, credentialRequest: CredentialRequest<H2G>, clientSecrets: ClientSecrets<Group.Scalar>, serverPublicKey: ServerPublicKey<H2G>, ciphersuite: Ciphersuite<H2G>, generatorG: Group.Element, generatorH: Group.Element) throws {
// Verify credential response proof
guard
try credentialResponse.verify(request: credentialRequest, serverPublicKey: serverPublicKey, generatorG: generatorG, generatorH: generatorH)
@@ -39,48 +38,74 @@ extension ARC {
// 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)
self = Self(m1: clientSecrets.m1, U: credentialResponse.U, UPrime: UPrime, X1: serverPublicKey.X1, ciphersuite: ciphersuite, generatorG: generatorG, generatorH: generatorH, presentationState: ARC.PresentationState())
}
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) {
internal init(m1: Group.Scalar, U: Group.Element, UPrime: Group.Element, X1: Group.Element, ciphersuite: Ciphersuite<H2G>, generatorG: Group.Element, generatorH: Group.Element, presentationState: PresentationState) {
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
self.presentationState = presentationState
}
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) {
mutating func makePresentation(presentationContext: Data, presentationLimit: Int, 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) {
let nonce = try self.presentationState.update(presentationContext: presentationContext, presentationLimit: presentationLimit, optionalNonce: optionalNonce)
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)
}
}
struct PresentationState {
typealias PresentationContext = Data
typealias PresentationLimit = Int
typealias NonceSet = Set<Int>
var state: [PresentationContext: (PresentationLimit, NonceSet)]
init() {
self.state = [PresentationContext: (PresentationLimit, NonceSet)]()
}
internal init(state: [PresentationContext: (PresentationLimit, NonceSet)]) {
self.state = state
}
mutating func update(presentationContext: Data, presentationLimit: Int, optionalNonce: Int? = nil) throws -> Int {
if presentationLimit <= 0 {
throw ARC.Errors.invalidPresentationLimit
}
// 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)
var nonce = optionalNonce != nil ? optionalNonce! : Int.random(in: 0..<presentationLimit)
// Store the nonce in presentationNonces for that presentationContext.
if self.presentationNonces[presentationContext] != nil {
if self.presentationNonces[presentationContext]!.count >= self.presentationLimit {
if self.state[presentationContext] != nil {
let presentationContextState = self.state[presentationContext]!
if presentationLimit != presentationContextState.0 {
throw ARC.Errors.invalidPresentationLimit
}
if presentationContextState.1.count >= presentationLimit {
throw ARC.Errors.presentationLimitExceeded
}
while self.presentationNonces[presentationContext]!.contains(nonce) {
while presentationContextState.1.contains(nonce) {
if optionalNonce == nil {
// Randomly generated nonce collides with existing nonce for presentationContext
nonce = Int.random(in: 0..<self.presentationLimit)
nonce = Int.random(in: 0..<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)
self.state[presentationContext]!.1.insert(nonce)
} else {
self.state[presentationContext] = (presentationLimit, [nonce])
}
return nonce
}
}
}
+106 -138
View File
@@ -19,50 +19,30 @@ typealias ARCCurve = P384
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, *)
typealias ARCH2G = HashToCurveImpl<ARCCurve>
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal func DecodeInt(value: Data) -> Int {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
var result = Int(0)
for i in 0..<value.count {
result = result << 8
result += Int(value[i])
}
return result
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal func EncodeInt(value: Int) -> Data {
return I2OSP(value: value, outputByteCount: 4)
}
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, *)
extension ARC.CredentialRequest where H2G == ARCH2G {
static let scalarCount = 5
static let pointCount = 2
static let serializedByteCount = pointCount * ARCCurve.compressedx962PointByteCount + scalarCount * ARCCurve.orderByteCount
static let serializedByteCount = 2 * ARCCurve.compressedx962PointByteCount + Self.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
var result = Data(capacity: Self.serializedByteCount)
result.append(self.m1Enc.compressedRepresentation)
result.append(self.m2Enc.compressedRepresentation)
result.append(self.proof.serialize())
return result
}
static func deserialize<D: DataProtocol>(requestData: D) throws -> ARC.CredentialRequest<ARCH2G> {
guard requestData.count == self.serializedByteCount else {
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
var bytes = Data(requestData)
let m1Enc = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let m2Enc = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let proof = try Proof.deserialize(proofData: bytes, scalarCount: Self.scalarCount)
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)
}
}
@@ -70,43 +50,38 @@ extension ARC.CredentialRequest where H2G == ARCH2G {
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, *)
extension ARC.CredentialResponse where H2G == ARCH2G {
static let scalarCount = 8
static let pointCount = 6
static let serializedByteCount = pointCount * ARCCurve.compressedx962PointByteCount + scalarCount * ARCCurve.orderByteCount
static let serializedByteCount = 6 * ARCCurve.compressedx962PointByteCount + Self.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
var result = Data(capacity: Self.serializedByteCount)
let proofData = self.proof.serialize()
return responsePoints + proofData
result.append(self.U.compressedRepresentation)
result.append(self.encUPrime.compressedRepresentation)
result.append(self.X0Aux.compressedRepresentation)
result.append(self.X1Aux.compressedRepresentation)
result.append(self.X2Aux.compressedRepresentation)
result.append(self.HAux.compressedRepresentation)
result.append(self.proof.serialize())
return result
}
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
var bytes = Data(responseData)
let U = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let encUPrime = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X0Aux = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X1Aux = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X2Aux = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let HAux = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let proof = try Proof.deserialize(proofData: bytes, scalarCount: self.scalarCount)
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)
}
}
@@ -118,65 +93,59 @@ extension ARC.Presentation where H2G == ARCH2G {
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
var result = Data(capacity: Self.serializedByteCount)
let presentationProofData = self.proof.serialize()
return U + UPrimeCommit + m1Commit + tag + presentationProofData
result.append(self.U.compressedRepresentation)
result.append(self.UPrimeCommit.compressedRepresentation)
result.append(self.m1Commit.compressedRepresentation)
result.append(self.tag.compressedRepresentation)
result.append(self.proof.serialize())
return result
}
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
var bytes = Data(presentationData)
let U = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let UPrimeCommit = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let m1Commit = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let tag = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let presentationProof = try Proof.deserialize(proofData: bytes, scalarCount: Self.scalarCount)
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)
}
}
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, *)
extension ARC.ServerPublicKey where H2G == ARCH2G {
static let pointCount = 3
static let serializedByteCount = 3 * ARCCurve.compressedx962PointByteCount
static let pointCount = 3 // TODO: delete
func serialize() -> Data {
// Serialize server commitment elements
let X0 = self.X0.compressedRepresentation
let X1 = self.X1.compressedRepresentation
let X2 = self.X2.compressedRepresentation
var result = Data(capacity: Self.serializedByteCount)
return X0 + X1 + X2
result.append(self.X0.compressedRepresentation)
result.append(self.X1.compressedRepresentation)
result.append(self.X2.compressedRepresentation)
return result
}
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
var bytes = Data(serverPublicKeyData)
let X0 = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X1 = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X2 = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
return ARC.ServerPublicKey(X0: X0, X1: X1, X2: X2)
}
@@ -201,19 +170,18 @@ extension Proof where H2G == ARCH2G {
guard proofData.count == scalarCount * ARCCurve.orderByteCount else {
throw ARC.Errors.incorrectProofDataSize
}
let proofData = Data(proofData)
var startPointer = 0
var bytes = Data(proofData)
// Deserialize challenge
let challenge = try GroupImpl<ARCCurve>.Scalar(bytes: proofData.subdata(in: startPointer..<startPointer+ARCCurve.orderByteCount))
startPointer += ARCCurve.orderByteCount
let challenge = try ARCH2G.G.Scalar(bytes: bytes.popFirst(ARCCurve.orderByteCount))
// Deserialize responses
var responses: [GroupImpl<ARCCurve>.Scalar] = []
responses.reserveCapacity(scalarCount - 1)
for _ in (0..<scalarCount-1) {
let response = try GroupImpl<ARCCurve>.Scalar(bytes: proofData.subdata(in: startPointer..<startPointer+ARCCurve.orderByteCount))
let response = try ARCH2G.G.Scalar(bytes: bytes.popFirst(ARCCurve.orderByteCount))
responses.append(response)
startPointer += ARCCurve.orderByteCount
}
return Proof(challenge: challenge, responses: responses)
@@ -226,68 +194,68 @@ extension Proof where H2G == ARCH2G {
extension ARC.Credential where H2G == ARCH2G {
static let scalarCount = 1
static let pointCount = 5
static let integerByteCount = 4
static let serializedByteCountExcludingPresentationState = 1 * ARCCurve.orderByteCount + 5 * ARCCurve.compressedx962PointByteCount
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)
let presentationStateBytes = try self.presentationState.serialize()
return m1 + U + UPrime + X1 + genG + genH + presentationLimit + noncesData
var result = Data(capacity: Self.serializedByteCountExcludingPresentationState + presentationStateBytes.count)
result.append(self.m1.rawRepresentation)
result.append(self.U.compressedRepresentation)
result.append(self.UPrime.compressedRepresentation)
result.append(self.X1.compressedRepresentation)
result.append(self.generatorG.compressedRepresentation)
result.append(self.generatorH.compressedRepresentation)
result.append(presentationStateBytes)
return result
}
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 {
guard credentialData.count - Self.serializedByteCountExcludingPresentationState >= 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
var bytes = Data(credentialData)
// Deserialize presentationNonces dictionary
let noncesData = credentialData.subdata(in: startPointer..<startPointer+noncesByteCount)
let presentationNonces = try ARCNonces.deserialize(noncesData: noncesData)
let m1 = try ARCH2G.G.Scalar(bytes: bytes.popFirst(ARCCurve.orderByteCount))
let U = try ARCH2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let UPrime = try ARCH2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X1 = try ARCH2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let genG = try ARCH2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let genH = try ARCH2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
// Deserialize presentationState from remaining bytes.
let presentationState = try ARC.PresentationState.deserialize(presentationStateData: bytes)
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)
return ARC.Credential(m1: m1, U: U, UPrime: UPrime, X1: X1, ciphersuite: ciphersuite, generatorG: genG, generatorH: genH, presentationState: presentationState)
}
}
// A helper for serializing a ARC credential. This will only be called client-side, and never be sent over the wire.
// Serialize a ARC PresentationState, to help save and restore a credential.
// This will only be called client-side, and never be sent over the wire.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
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) }
extension ARC.PresentationState {
func serialize() throws -> Data {
let encoder = PropertyListEncoder()
encoder.outputFormat = .binary
// Convert (Int, Set<Int>) to Array<Int> for encoding
let dictForEncoding = self.state.mapValues { [$0.0] + Array($0.1) }
return try encoder.encode(dictForEncoding)
}
static func deserialize<D: DataProtocol>(noncesData: D) throws -> [Data: Set<Int>] {
static func deserialize<D: DataProtocol>(presentationStateData: D) throws -> ARC.PresentationState {
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) }
let stateIntList = try decoder.decode([Data: [Int]].self, from: Data(presentationStateData))
// Convert [Int] to (Int, Set<Int>) for decoding
let state = stateIntList.mapValues { value in (value[0], Set(value[1...])) }
return ARC.PresentationState(state: state)
}
}
@@ -38,23 +38,18 @@ extension ARC {
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
}
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>) throws {
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)
return try Credential<H2G>(credentialResponse: credentialResponse, credentialRequest: self.credentialRequest, clientSecrets: self.clientSecrets, serverPublicKey: self.serverPublicKey, ciphersuite: self.ciphersuite, generatorG: self.generatorG, generatorH: self.generatorH)
}
}
}
+1
View File
@@ -56,6 +56,7 @@ add_library(_CryptoExtras
"Util/DigestType.swift"
"Util/Error.swift"
"Util/I2OSP.swift"
"Util/IntegerEncoding.swift"
"Util/PEMDocument.swift"
"Util/PrettyBytes.swift"
"Util/SubjectPublicKeyInfo.swift"
@@ -0,0 +1,88 @@
//===----------------------------------------------------------------------===//
//
// 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
enum IntegerDecodingError: Error, Equatable {
case incorrectNumberOfBytes(expected: Int, actual: Int)
}
extension FixedWidthInteger {
/// Create an new value from a collection of its big endian bytes.
///
/// - Parameter bytes: Big endian bytes.
///
/// - Throws: A decoding error if the collection did not contain the exact number of bytes.
init(bigEndianBytes bytes: some Collection<UInt8>) throws {
guard bytes.count == Self.bitWidth / 8 else {
throw IntegerDecodingError.incorrectNumberOfBytes(expected: Self.bitWidth / 8, actual: bytes.count)
}
self = 0
var index = bytes.startIndex
for _ in 0..<(Self.bitWidth / 8) {
self <<= 8
self |= Self(bytes[index])
bytes.formIndex(after: &index)
}
}
fileprivate init(bigEndianContiguousBytes bytes: some ContiguousBytes) throws {
self = try bytes.withUnsafeBytes { try Self(bigEndianBytes: $0 ) }
}
/// Create an new value from its big endian bytes representation.
///
/// - Parameter bytes: Big endian bytes.
///
/// - Throws: A decoding error if the collection did not contain the exact number of bytes.
init(bigEndianBytes bytes: Data) throws {
self = try Self(bigEndianContiguousBytes: bytes)
}
/// The big endian bytes that represent this value.
var bigEndianBytes: Data { Data(bigEndianBytesOf: self) }
}
extension Data {
/// Creates a new instance initialized with the big endian bytes representation of the given integer.
init(bigEndianBytesOf integer: some FixedWidthInteger) {
self.init()
self.append(bigEndianBytesOf: integer)
}
/// Appends the big endian bytes of the given integer.
mutating func append<T: FixedWidthInteger>(bigEndianBytesOf integer: T) {
let previousCount = self.count
let newCount = previousCount + T.bitWidth / 8
self.reserveCapacity(newCount)
self.count = newCount
self.withUnsafeMutableBytes {
$0.storeBytes(of: integer.bigEndian, toByteOffset: previousCount, as: T.self)
}
}
/// Removes and returns the first k bytes.
mutating func popFirst(_ k: Int) -> Self {
let prefix = self.prefix(k)
self.removeFirst(k)
return prefix
}
/// Removes and returns the first k bytes, decoded as a value of the given type from its big endian bytes.
mutating func popFirst<T: FixedWidthInteger>(bigEndian: T.Type) throws -> T {
let value = try T(bigEndianBytes: self.prefix(T.bitWidth / 8))
self.removeFirst(T.bitWidth / 8)
return value
}
}
@@ -57,7 +57,6 @@ final class ARCAPITests: XCTestCase {
// [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))
@@ -110,6 +109,7 @@ final class ARCAPITests: XCTestCase {
// [Client] Make a presentation from the credential for a presentation prefix.
let (presentation, _) = try credential.makePresentation(
context: presentationContext,
presentationLimit: presentationLimit,
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)),
@@ -36,7 +36,7 @@ class ARCEncodingTests: XCTestCase {
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 precredential = try ARC.Precredential(ciphersuite: ciphersuite, requestContext: requestContext, serverPublicKey: server.serverPublicKey)
let request = precredential.credentialRequest
let requestData = request.serialize()
@@ -56,7 +56,7 @@ class ARCEncodingTests: XCTestCase {
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 precredential = try ARC.Precredential(ciphersuite: ciphersuite, requestContext: requestContext, serverPublicKey: server.serverPublicKey)
let request = precredential.credentialRequest
let response = try server.respond(credentialRequest: request)
@@ -81,7 +81,7 @@ class ARCEncodingTests: XCTestCase {
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 precredential = try ARC.Precredential(ciphersuite: ciphersuite, requestContext: requestContext, serverPublicKey: server.serverPublicKey)
let request = precredential.credentialRequest
let response = try server.respond(credentialRequest: request)
let credential = try precredential.makeCredential(credentialResponse: response)
@@ -94,8 +94,10 @@ class ARCEncodingTests: XCTestCase {
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)
for (key, value) in credential.presentationState.state {
XCTAssertEqual(value.0, credential2.presentationState.state[key]?.0)
XCTAssertEqual(value.1, credential2.presentationState.state[key]?.1)
}
let credentialData2 = try credential2.serialize()
XCTAssertEqual(credentialData, credentialData2)
@@ -105,11 +107,11 @@ class ARCEncodingTests: XCTestCase {
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 precredential = try ARC.Precredential(ciphersuite: ciphersuite, requestContext: requestContext, serverPublicKey: server.serverPublicKey)
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 (presentation, _) = try credential.makePresentation(presentationContext: Data("test presentation context".utf8), presentationLimit: 1)
let presentationData = presentation.serialize()
let presentation2 = try ARC.Presentation.deserialize(presentationData: presentationData)
@@ -126,21 +128,27 @@ class ARCEncodingTests: XCTestCase {
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
func testPresentationStateEncoding() throws {
let emptyPresentationState = ARC.PresentationState()
let smallPresentationState = ARC.PresentationState(state: [Data("context1".utf8): (4, [1, 2, 3]), Data("context2".utf8): (10, [4, 5, 6])])
var largePresentationState = ARC.PresentationState()
for presentationLimit in 1..<100 {
let presentationContext = Data("presentationContext\(presentationLimit)".utf8)
for nonce in 0..<presentationLimit {
let selectedNonce = try largePresentationState.update(presentationContext:presentationContext, presentationLimit: presentationLimit, optionalNonce: nonce)
XCTAssertEqual(selectedNonce, nonce)
}
}
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")
for state in [emptyPresentationState, smallPresentationState, largePresentationState] {
let serializedState = try state.serialize()
XCTAssertNotNil(serializedState, "Serialized state should not be nil")
let deserializedState = try ARC.PresentationState.deserialize(presentationStateData: serializedState)
for (key, value) in state.state {
XCTAssertEqual(value.0, deserializedState.state[key]?.0)
XCTAssertEqual(value.1, deserializedState.state[key]?.1)
}
}
}
}
@@ -38,10 +38,7 @@ final class ARCPublicAPITests: XCTestCase {
let publicKey = try P384._ARCV1.PublicKey(rawRepresentation: publicKeyBytes)
// [Client] Prepare a credential request.
let precredential = try publicKey.prepareCredentialRequest(
requestContext: requestContext,
presentationLimit: presentationLimit
)
let precredential = try publicKey.prepareCredentialRequest(requestContext: requestContext)
// [Client -> Issuer] Send the credential request.
let credentialRequestBytes = precredential.credentialRequest.rawRepresentation
@@ -59,14 +56,15 @@ final class ARCPublicAPITests: XCTestCase {
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.
// NOTE: This is a var because it enforces the presentation limits 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
// NOTE: On first presentation, the presentation limit provided is now set, and enforced going forward.
let (presentation, nonce) = try credential.makePresentation(
context: presentationContext,
presentationLimit: presentationLimit
)
// [Client -> Verifier] Send the presentation.
let presentationBytes = presentation.rawRepresentation
@@ -95,18 +93,17 @@ final class ARCPublicAPITests: XCTestCase {
let presentationContext = Data("shared presentation context".utf8)
let presentationLimit = 2
let precredential = try publicKey.prepareCredentialRequest(
requestContext: requestContext,
presentationLimit: presentationLimit
)
let precredential = try publicKey.prepareCredentialRequest(requestContext: requestContext)
let credentialResponse = try privateKey.issue(precredential.credentialRequest)
var credential = try publicKey.finalize(credentialResponse, for: precredential)
for _ in 0..<presentationLimit {
_ = try credential.makePresentation(context: presentationContext)
_ = try credential.makePresentation(context: presentationContext, presentationLimit: presentationLimit)
}
XCTAssertThrowsError(try credential.makePresentation(context: presentationContext)) { error in
XCTAssertThrowsError(
try credential.makePresentation(context: presentationContext, presentationLimit: presentationLimit)
) { error in
XCTAssertEqual(String(describing: error), "presentationLimitExceeded")
}
}
@@ -172,7 +172,7 @@ class ARCTestVectors: XCTestCase {
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)
let precredential = try ARC.Precredential(ciphersuite: ciphersuite, m1: m1, requestContext: requestContext, r1: r1, r2: r2, serverPublicKey: server.serverPublicKey)
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)
@@ -212,7 +212,7 @@ class ARCTestVectors: XCTestCase {
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)
let (presentation1, nonce_1_returned) = try credential.makePresentation(presentationContext: presentationContext1, presentationLimit: 2, 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)
@@ -231,7 +231,7 @@ class ARCTestVectors: XCTestCase {
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)
let (presentation2, nonce_2_returned) = try credential.makePresentation(presentationContext: presentationContext1, presentationLimit: 2, 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)
+39 -5
View File
@@ -39,7 +39,7 @@ class ARCTests: XCTestCase {
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)
let precredential = try ARC.Precredential(ciphersuite: ciphersuite, m1: m1, requestContext: requestContext, r1: r1, r2: r2, serverPublicKey: serverPublicKey)
// Client makes an CredentialRequest using its private attributes.
let request = precredential.credentialRequest
@@ -61,16 +61,16 @@ class ARCTests: XCTestCase {
// 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)
let (presentation1, nonce1) = try credential.makePresentation(presentationContext: presentationContext, presentationLimit: presentationLimit)
let (presentation2, nonce2) = try credential.makePresentation(presentationContext: presentationContext, presentationLimit: presentationLimit)
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)
XCTAssertThrowsError(try credential.makePresentation(presentationContext: presentationContext, presentationLimit: presentationLimit), 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)
let (presentation3, nonce3) = try credential.makePresentation(presentationContext: newPresentationContext, presentationLimit: presentationLimit)
XCTAssertNotNil(presentation3)
// Server verifies Presentation1 with its server keys.
@@ -155,4 +155,38 @@ class ARCTests: XCTestCase {
try endToEndWorkflow(CurveType: P384.self)
// try endToEndWorkflow(CurveType: P521.self)
}
func testPresentationState() throws {
let context1 = Data("context1".utf8)
let context2 = Data("context2".utf8)
var smallPresentationState = ARC.PresentationState(state: [context1: (4, [0, 1, 2]), context2: (10, [3, 4, 5, 6])])
// Test that a new nonce is selected correctly
XCTAssertEqual(3, try smallPresentationState.update(presentationContext: context1, presentationLimit: 4))
XCTAssertEqual(0, try smallPresentationState.update(presentationContext: Data("context 3".utf8), presentationLimit: 1))
XCTAssert(try smallPresentationState.update(presentationContext: context2, presentationLimit: 10) < 10)
// Test that exceeding the rate limit for a presentationContext throws an error
XCTAssertThrowsError(try smallPresentationState.update(presentationContext: context1, presentationLimit: 4), error: ARC.Errors.presentationLimitExceeded)
// Test that reusing a nonce for a presentationContext throws an error
XCTAssertThrowsError(try smallPresentationState.update(presentationContext: context2, presentationLimit: 10, optionalNonce: 3), error: ARC.Errors.presentationLimitExceeded)
// Test that using an incorrect presentationLimit throws an error
XCTAssertThrowsError(try smallPresentationState.update(presentationContext: context2, presentationLimit: 9), error: ARC.Errors.invalidPresentationLimit)
XCTAssertThrowsError(try smallPresentationState.update(presentationContext: Data("context 4".utf8), presentationLimit: 0), error: ARC.Errors.invalidPresentationLimit)
var largePresentationState = ARC.PresentationState()
for presentationLimit in 1..<100 {
let presentationContext = Data("presentationContext\(presentationLimit)".utf8)
for _ in 0..<presentationLimit {
let nonce = try largePresentationState.update(presentationContext:presentationContext, presentationLimit: presentationLimit)
XCTAssert(nonce < presentationLimit)
// Test that reusing a nonce for a presentationContext throws an error
XCTAssertThrowsError(try largePresentationState.update(presentationContext: presentationContext, presentationLimit: presentationLimit, optionalNonce: nonce), error: ARC.Errors.presentationLimitExceeded)
}
// Test that exceeding the rate limit for a presentationContext throws an error
XCTAssertThrowsError(try largePresentationState.update(presentationContext: presentationContext, presentationLimit: presentationLimit), error: ARC.Errors.presentationLimitExceeded)
XCTAssertEqual(largePresentationState.state[presentationContext]!.1.count, presentationLimit)
// Test that using an incorrect presentationLimit throws an error
XCTAssertThrowsError(try largePresentationState.update(presentationContext: presentationContext, presentationLimit: presentationLimit-1), error: ARC.Errors.invalidPresentationLimit)
}
}
}
@@ -0,0 +1,153 @@
//===----------------------------------------------------------------------===//
//
// 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
final class IntegerEncodingTests: XCTestCase {
func testIntegerDecoding() throws {
func test<T: FixedWidthInteger>(
decoding bytes: [UInt8],
as: T.Type,
expect expectedResult: Swift.Result<T, IntegerDecodingError>,
file: StaticString = #filePath, line: UInt = #line
) {
let actualResult = Swift.Result { try T(bigEndianBytes: bytes) }
switch (actualResult, expectedResult) {
case (.success(let actual), .success(let expected)):
XCTAssertEqual(actual, expected, file: file, line: line)
case (.success(let actual), .failure(let error)):
XCTFail("Expected error: \(error), got \(actual)", file: file, line: line)
case (.failure(let error), .success(let expected)):
XCTFail("Decode failed; expected: \(expected), got error: \(error)", file: file, line: line)
case (.failure(let actualError), .failure(let expectedError)):
guard let typedError = actualError as? IntegerDecodingError else {
XCTFail("Expected error but not this one: \(actualError)", file: file, line: line)
return
}
XCTAssertEqual(typedError, expectedError, file: file, line: line)
}
}
test(decoding: [0,0], as: UInt16.self, expect: .success(0))
test(decoding: [0,1], as: UInt16.self, expect: .success(1))
test(decoding: [1,0], as: UInt16.self, expect: .success(256))
test(decoding: [1,1], as: UInt16.self, expect: .success(257))
test(decoding: [0xff,0xff], as: UInt16.self, expect: .success(UInt16.max))
test(decoding: [], as: UInt16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 0)))
test(decoding: [0], as: UInt16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 1)))
test(decoding: [0,0,0], as: UInt16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 3)))
test(decoding: [0,0,0,0], as: UInt16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 4)))
test(decoding: [0,0], as: Int16.self, expect: .success(0))
test(decoding: [0,1], as: Int16.self, expect: .success(1))
test(decoding: [1,0], as: Int16.self, expect: .success(256))
test(decoding: [1,1], as: Int16.self, expect: .success(257))
test(decoding: [0xff,0xff], as: Int16.self, expect: .success(-1))
test(decoding: [0x80,0x00], as: Int16.self, expect: .success(Int16.min))
test(decoding: [0x7f,0xff], as: Int16.self, expect: .success(Int16.max))
test(decoding: [], as: Int16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 0)))
test(decoding: [0], as: Int16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 1)))
test(decoding: [0,0,0], as: Int16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 3)))
test(decoding: [0,0,0,0], as: Int16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 4)))
}
func testIntegerEncoding() throws {
func test<T: FixedWidthInteger>(encoding value: T, expect bytes: [UInt8], file: StaticString = #filePath, line: UInt = #line) {
XCTAssertEqual(value.bigEndianBytes, Data(bytes), file: file, line: line)
}
test(encoding: UInt16.zero, expect: [0,0])
test(encoding: UInt16(1), expect: [0,1])
test(encoding: UInt16(256), expect: [1,0])
test(encoding: UInt16(257), expect: [1,1])
test(encoding: UInt16.max, expect: [0xff,0xff])
test(encoding: Int16.zero, expect: [0,0])
test(encoding: Int16(1), expect: [0,1])
test(encoding: Int16(256), expect: [1,0])
test(encoding: Int16(257), expect: [1,1])
test(encoding: Int16(-1), expect: [0xff,0xff])
test(encoding: Int16.min, expect: [0x80,0x00])
test(encoding: Int16.max, expect: [0x7f,0xff])
}
func testIntegerEncodingDataAppend() throws {
var bytes = Data()
bytes.append(bigEndianBytesOf: Int32(1))
bytes.append(bigEndianBytesOf: Int16(2))
bytes.append(bigEndianBytesOf: Int8(3))
bytes.append(bigEndianBytesOf: Int64(4))
XCTAssertEqual(bytes.hexString, Data([0,0,0,1] + [0,2] + [3] + [0,0,0,0,0,0,0,4]).hexString)
}
func testIntegerDecodingFromDataSubsequence() throws {
let data = Data([0,0,0,1] + [0,2] + [3] + [0,0,0,0,0,0,0,4])
var bytes = data[...]
XCTAssertEqual(bytes.count, 15)
XCTAssertEqual(try Int32(bigEndianBytes: bytes[..<bytes.startIndex.advanced(by: 4)]), 1)
bytes.removeFirst(4)
XCTAssertEqual(try Int16(bigEndianBytes: bytes[..<bytes.startIndex.advanced(by: 2)]), 2)
bytes.removeFirst(2)
XCTAssertEqual(try Int8(bigEndianBytes: bytes[..<bytes.startIndex.advanced(by: 1)]), 3)
bytes.removeFirst(1)
XCTAssertEqual(try Int64(bigEndianBytes: bytes[..<bytes.startIndex.advanced(by: 8)]), 4)
bytes.removeFirst(8)
XCTAssert(bytes.isEmpty)
}
func testIntegerDecodingUsingDataPopFirstK() throws {
var bytes = Data([0,0,0,1] + [0,2] + [3] + [0,0,0,0,0,0,0,4])
XCTAssertEqual(bytes.count, 15)
XCTAssertEqual(try Int32(bigEndianBytes: bytes.popFirst(4)), 1)
XCTAssertEqual(try Int16(bigEndianBytes: bytes.popFirst(2)), 2)
XCTAssertEqual(try Int8(bigEndianBytes: bytes.popFirst(1)), 3)
XCTAssertEqual(try Int64(bigEndianBytes: bytes.popFirst(8)), 4)
XCTAssert(bytes.isEmpty)
}
func testIntegerDecodingUsingDataPopFirst() throws {
var bytes = Data([0,0,0,1] + [0,2] + [3] + [0,0,0,0,0,0,0,4])
XCTAssertEqual(bytes.count, 15)
XCTAssertEqual(try bytes.popFirst(bigEndian: Int32.self), 1)
XCTAssertEqual(try bytes.popFirst(bigEndian: Int16.self), 2)
XCTAssertEqual(try bytes.popFirst(bigEndian: Int8.self), 3)
XCTAssertEqual(try bytes.popFirst(bigEndian: Int64.self), 4)
XCTAssert(bytes.isEmpty)
}
func testIntegerDecodingUsingDataPopFirstTooFewBytes() throws {
var bytes = Data([0])
XCTAssertThrowsError(try bytes.popFirst(bigEndian: Int16.self))
XCTAssertThrowsError(try bytes.popFirst(bigEndian: Int32.self))
XCTAssertThrowsError(try bytes.popFirst(bigEndian: Int64.self))
}
}