Testing iOS X25519 Key Agreement on a Cloud Mac
The project already builds on a cloud Mac, but once end-to-end encryption is added, “both sides generated keys” is no longer enough to pass acceptance testing. First, confirm that the shared secrets produce matching derived keys. Then check that protocol versions, purposes, and message directions are kept separate. This article uses CryptoKit to build an executable Swift fixture that makes no network connections and reads no production credentials, then moves the assertions into an iOS test target.
Define the acceptance boundary for key agreement first
The cloud Mac must have a macOS SDK that includes CryptoKit, and running xcrun --find swift in the terminal must return the compiler path. The tests use temporarily generated X25519 keys and require no certificates, signing configuration, or remote services.
Acceptance covers three checks: both sides derive the same key using the other party’s public key; changing the purpose produces a different key; and an invalid length is rejected when constructing a public key. These checks validate the API contract, not re-prove the cryptographic algorithm.
X25519 does not authenticate the peer. If an attacker can replace the public keys the two parties exchange, the attacker may still establish a separate connection with each side. Identity binding must be handled by an authenticated protocol.
Boundary: a successful command-line run only confirms that the checks pass in the current macOS environment. It does not replace testing on the iOS target or justify designing a custom production encryption protocol.
Fix the byte format for public keys and derivation context
An X25519 public key has a 32-byte raw representation. The transport layer can apply an additional encoding, but the receiver must first recover the bytes and pass them to the rawRepresentation initializer. Encoded text must not be used directly as a public key.
HKDF uses sharedInfo to bind the protocol and purpose. The example below encodes each UTF-8 field as “two-byte big-endian length followed by field contents.” This avoids the ambiguity of simple concatenation, where ab plus c produces the same result as a plus bc. The example defines four fields: protocol name, version, message direction, and purpose. Both sides must use exactly the same values.
Direction refers to fixed roles in the protocol, not “sending” from each party’s local perspective. The client’s sending key and the server’s receiving key both use client-to-server.
Boundary: field order, case, and encoding are part of the protocol and must not depend on the interface language. A public salt need not be secret, but its value must match on both sides.
Run a minimal Swift acceptance fixture
Save the following as AgreementCheck.swift. The code generates both parties’ private keys in memory, reconstructs their public keys from bytes, performs key agreement, and then derives a 32-byte key using HKDF-SHA256. Errors stop execution by being thrown.
import Foundation
import CryptoKit
enum CheckError: Error {
case contextTooLong
case agreementMismatch
case contextCollision
case invalidKeyAccepted
}
func context(_ fields: [String]) throws -> Data {
var output = Data()
for field in fields {
let bytes = Data(field.utf8)
guard bytes.count <= Int(UInt16.max) else {
throw CheckError.contextTooLong
}
let count = UInt16(bytes.count)
output.append(UInt8(count >> 8))
output.append(UInt8(count & 0xff))
output.append(bytes)
}
return output
}
func derive(
_ secret: SharedSecret,
purpose: String
) throws -> SymmetricKey {
let info = try context([
"agreement-check",
"v1",
"client-to-server",
purpose
])
return secret.hkdfDerivedSymmetricKey(
using: SHA256.self,
salt: Data("fixture-salt-v1".utf8),
sharedInfo: info,
outputByteCount: 32
)
}
func testBytes(_ key: SymmetricKey) -> Data {
key.withUnsafeBytes { Data($0) }
}
let alice = Curve25519.KeyAgreement.PrivateKey()
let bob = Curve25519.KeyAgreement.PrivateKey()
let alicePublic = try Curve25519.KeyAgreement.PublicKey(
rawRepresentation: alice.publicKey.rawRepresentation
)
let bobPublic = try Curve25519.KeyAgreement.PublicKey(
rawRepresentation: bob.publicKey.rawRepresentation
)
let aliceSecret = try alice.sharedSecretFromKeyAgreement(
with: bobPublic
)
let bobSecret = try bob.sharedSecretFromKeyAgreement(
with: alicePublic
)
let aliceKey = try derive(aliceSecret, purpose: "payload")
let bobKey = try derive(bobSecret, purpose: "payload")
guard testBytes(aliceKey) == testBytes(bobKey) else {
throw CheckError.agreementMismatch
}
let otherKey = try derive(aliceSecret, purpose: "receipt")
guard testBytes(aliceKey) != testBytes(otherKey) else {
throw CheckError.contextCollision
}
let malformed = Data(repeating: 0, count: 31)
do {
_ = try Curve25519.KeyAgreement.PublicKey(
rawRepresentation: malformed
)
throw CheckError.invalidKeyAccepted
} catch CheckError.invalidKeyAccepted {
throw CheckError.invalidKeyAccepted
} catch {
}
Run it in the terminal:
xcrun swift AgreementCheck.swift
The expected result is an exit code of zero with no output. Do not print private keys, shared secrets, or derived keys to determine whether the test succeeded.
Boundary: testBytes copies key material and is intended only for comparisons in temporary tests. Those copies must not enter production logs or telemetry. The example also makes no guarantee that the copies are immediately zeroed.
Add negative cases, not just a check that both sides match
The first group of negative cases changes the protocol version, direction, and purpose in turn. Change only one field at a time and check that the derived result no longer matches. Then change one byte of the salt and confirm that the original result is no longer produced. These checks catch integration mistakes in application logic; they do not statistically measure the algorithm’s collision probability.
The second group tests public-key inputs with lengths of zero, 31, and 33 bytes. All must be rejected. A length of exactly 32 bytes only satisfies the format prerequisite. It does not establish trust, nor does it make every arbitrary byte sequence a valid input for key agreement. Errors from both initialization and agreement must propagate to the caller.
The third group adds publicly available standard test vectors to complete the interoperability checks. The randomized two-party test above can allow errors within the same implementation to cancel each other out. The raw public keys, shared secret, and derived output therefore also need independent verification.
Boundary: on failure, record only the stage and error category. Do not retain key material from real sessions to create regression fixtures.
Move the checks into iOS tests and set merge criteria
Extract the context encoding and derivation functions into a shared module, then repeat the same assertions in the iOS unit test target. Add a round-trip check for the public-key transport encoding to ensure that the 32 bytes remain unchanged after encoding and decoding.
Check four things before merging: both sides derive matching keys; changing each context field provides separation; malformed inputs fail explicitly; and standard test vectors match byte for byte. The test report should retain the source commit, toolchain version, and failure stage, but no secret values.
Finally, review identity binding, the public-key lifecycle, and nonce management in the encryption protocol that follows. The agreement fixture demonstrates that these interfaces are wired together as specified; it cannot replace a full protocol review. State that boundary in the test documentation so that one green run is not mistaken for a security verdict on the entire system.
Frequently asked questions
Do matching derived keys prove the peer is trustworthy?
No. X25519 establishes a shared secret but does not authenticate the peer. Bind public keys to identities through an authenticated protocol or trusted channel.
Are iOS tests still necessary after the macOS fixture passes?
Yes. The command-line fixture checks algorithm calls and input contracts. Run the same assertions in supported iOS test targets to cover SDK availability, serialization, and app integration.
Get a cloud Mac ready for your next build
Prepare your project on Windows or Linux, then rent a dedicated physical machine and use Xcode in your browser to build and archive your app.
You’ll need to provide the developer account, certificates, and provisioning profiles required for code signing. We don’t submit apps for you.