Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraIdentity/HybridEnvelope.swift8// Module : Qyvora Identity9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import QyvoraMLKEM43import QyvoraMath44import QyvoraStorage45import QyvoraVault4647/// A message from one QYVORA identity to another, protected by a hybrid key exchange:48/// X25519 (CryptoKit) and ML-KEM-1024 (QYVORA engine) together. The payload stays confidential as long as49/// either of the two holds.50///51/// Binary form (integers big-endian):52///53/// "QYEN" (4) ‖ version (u8 = 1)54/// ‖ u8 length ‖ content type (ASCII, 1…64 characters among a-z 0-9 - . /)55/// ‖ u32 length ‖ sender PublicIdentity (binary form)56/// ‖ recipient fingerprint (32)57/// ‖ ephemeral X25519 public key (32)58/// ‖ u16 length ‖ ML-KEM-1024 ciphertext (1 568)59/// ‖ nonce (12)60/// ‖ u32 length ‖ AES-256-GCM ciphertext ‖ tag (16)61/// ‖ u32 length ‖ IdentitySignature (binary form)62///63/// Key schedule:64///65/// ss_x = X25519(ephemeral private key, recipient X25519 public key)66/// (ss_k, ct) = ML-KEM-1024.Encaps(recipient encapsulation key)67/// transcript = "QYVORA-ENVELOPE-v1" ‖ sender fingerprint ‖ recipient fingerprint ‖ recipient X25519 public key68/// ‖ recipient ML-KEM key ‖ ephemeral X25519 public key ‖ ct69/// key = HKDF-SHA256(ikm = ss_x ‖ ss_k ‖ transcript, salt = "QYVORA-ENVELOPE-v1",70/// info = "payload-key/" ‖ content type, 32 bytes) — CryptoKit71///72/// AEAD: AES-256-GCM (CryptoKit), random 96-bit nonce, associated data = every byte before the nonce.73/// Signature: the sender signs every byte before the signature field, purpose "envelope".74///75/// Opening verifies the recipient fingerprint and the signature first, then decapsulates and decrypts.76public struct HybridEnvelope: Sendable, Equatable {77 public static let magic = Bytes("QYEN".utf8)78 public static let version: UInt8 = 179 public static let label = "QYVORA-ENVELOPE-v1"80 /// Largest payload accepted by the parser (64 MiB).81 public static let maximumPayloadSize = 64 << 208283 public let contentType: String84 public let sender: PublicIdentity85 public let recipientFingerprint: Bytes86 public let ephemeralX25519PublicKey: Bytes87 public let mlkemCiphertext: Bytes88 public let nonce: Bytes89 /// Ciphertext followed by the 16-byte tag.90 public let ciphertext: Bytes91 public let signature: IdentitySignature9293 // MARK: Encoding9495 /// The associated data of the payload: magic through the ML-KEM ciphertext.96 static func headerBytes(contentType: String, sender: PublicIdentity, recipientFingerprint: Bytes, ephemeral: Bytes, mlkemCiphertext: Bytes) -> Bytes {97 var w = ByteWriter()98 w.raw(magic)99 w.u8(version)100 w.prefixed8(Bytes(contentType.utf8))101 w.prefixed32(sender.encoded())102 w.raw(recipientFingerprint)103 w.raw(ephemeral)104 w.prefixed16(mlkemCiphertext)105 return w.bytes106 }107108 func header() -> Bytes {109 Self.headerBytes(110 contentType: contentType, sender: sender, recipientFingerprint: recipientFingerprint, ephemeral: ephemeralX25519PublicKey,111 mlkemCiphertext: mlkemCiphertext)112 }113114 /// Everything the sender signs.115 func signedBytes() -> Bytes {116 var w = ByteWriter()117 w.raw(header())118 w.raw(nonce)119 w.prefixed32(ciphertext)120 return w.bytes121 }122123 public func encoded() -> Bytes {124 var w = ByteWriter()125 w.raw(signedBytes())126 w.prefixed32(signature.encoded())127 return w.bytes128 }129130 init(131 contentType: String, sender: PublicIdentity, recipientFingerprint: Bytes, ephemeralX25519PublicKey: Bytes, mlkemCiphertext: Bytes,132 nonce: Bytes, ciphertext: Bytes, signature: IdentitySignature133 ) {134 self.contentType = contentType135 self.sender = sender136 self.recipientFingerprint = recipientFingerprint137 self.ephemeralX25519PublicKey = ephemeralX25519PublicKey138 self.mlkemCiphertext = mlkemCiphertext139 self.nonce = nonce140 self.ciphertext = ciphertext141 self.signature = signature142 }143144 public init(encoded: Bytes) throws(IdentityError) {145 var r = ByteReader(encoded)146 do {147 guard try r.raw(4) == Self.magic else { throw IdentityError.malformed }148 let version = try r.u8()149 guard version == Self.version else { throw IdentityError.unsupportedVersion(version) }150 let type = String(decoding: try r.prefixed8(), as: UTF8.self)151 guard SignaturePurpose(type) != nil else { throw IdentityError.malformed }152 contentType = type153 sender = try PublicIdentity(encoded: try r.prefixed32(max: 1 << 16))154 recipientFingerprint = try r.raw(32)155 ephemeralX25519PublicKey = try r.raw(32)156 mlkemCiphertext = try r.prefixed16()157 nonce = try r.raw(12)158 ciphertext = try r.prefixed32(max: Self.maximumPayloadSize + 16)159 signature = try IdentitySignature(encoded: try r.prefixed32(max: 1 << 17))160 try r.finish()161 guard mlkemCiphertext.count == IdentitySuite.mlkem.ciphertextSize, ciphertext.count >= 16 else { throw IdentityError.malformed }162 } catch let error as IdentityError {163 throw error164 } catch {165 throw .malformed166 }167 }168169 // MARK: Key schedule170171 static func payloadKey(172 x25519Secret: Bytes, mlkemSecret: Bytes, senderFingerprint: Bytes, recipient: PublicIdentity, ephemeral: Bytes,173 mlkemCiphertext: Bytes, contentType: String174 ) -> Bytes {175 var ikm = x25519Secret + mlkemSecret176 defer { SecureMemory.zero(&ikm) }177 ikm += Bytes(label.utf8) + senderFingerprint + recipient.fingerprint + recipient.x25519PublicKey + recipient.mlkemPublicKey178 ikm += ephemeral + mlkemCiphertext179 return SystemCrypto.hkdfSHA256(180 inputKeyMaterial: ikm, salt: Bytes(label.utf8), info: Bytes(("payload-key/" + contentType).utf8), length: 32)181 }182183 // MARK: Sealing and opening184185 /// Encrypts `payload` to `recipient` and signs the envelope as `sender`.186 /// `contentType` tells the receiver what the payload is (for example "qyvora/transfer-v1"); it is authenticated.187 public static func seal(188 _ payload: Bytes, contentType: String, to recipient: PublicIdentity, from sender: Identity, dualSignature: Bool = false189 ) throws(IdentityError) -> HybridEnvelope {190 guard SignaturePurpose(contentType) != nil, payload.count <= maximumPayloadSize else { throw .malformed }191 let ephemeral = X25519.generateKeyPair()192 var ephemeralPrivate = ephemeral.privateKey193 defer { SecureMemory.zero(&ephemeralPrivate) }194 guard var ssX = try? X25519.sharedSecret(privateKey: ephemeralPrivate, publicKey: recipient.x25519PublicKey),195 let encapsulation = try? MLKEM.encapsulate(IdentitySuite.mlkem, encapsulationKey: recipient.mlkemPublicKey)196 else { throw .invalidKey }197 defer { SecureMemory.zero(&ssX) }198 var ssK = encapsulation.sharedSecret199 defer { SecureMemory.zero(&ssK) }200 var key = payloadKey(201 x25519Secret: ssX, mlkemSecret: ssK, senderFingerprint: sender.fingerprint, recipient: recipient,202 ephemeral: ephemeral.publicKey, mlkemCiphertext: encapsulation.ciphertext, contentType: contentType)203 defer { SecureMemory.zero(&key) }204205 let nonce = SystemRandom.bytes(12)206 let header = headerBytes(207 contentType: contentType, sender: sender.publicIdentity, recipientFingerprint: recipient.fingerprint,208 ephemeral: ephemeral.publicKey, mlkemCiphertext: encapsulation.ciphertext)209 guard let sealed = try? SystemCrypto.aes256GCMSeal(key: key, nonce: nonce, plaintext: payload, associatedData: header) else {210 throw .malformed211 }212 var signed = ByteWriter()213 signed.raw(header)214 signed.raw(nonce)215 signed.prefixed32(sealed)216 return HybridEnvelope(217 contentType: contentType, sender: sender.publicIdentity, recipientFingerprint: recipient.fingerprint,218 ephemeralX25519PublicKey: ephemeral.publicKey, mlkemCiphertext: encapsulation.ciphertext, nonce: nonce, ciphertext: sealed,219 signature: try sender.sign(signed.bytes, purpose: .envelope, dual: dualSignature))220 }221222 /// True when the envelope carries a valid signature of its embedded sender.223 public func verifySignature(requireDual: Bool = false) -> Bool {224 signature.verify(message: signedBytes(), signer: sender, purpose: .envelope, requireDual: requireDual)225 }226227 /// Verifies and decrypts. Pass `expectedSender` whenever the sender is known in advance: without it, the result228 /// only proves that the payload comes from the identity embedded in the envelope (returned by `sender`).229 public func open(with recipient: Identity, expectedSender: PublicIdentity? = nil, expectedContentType: String? = nil) throws(IdentityError) -> Bytes {230 guard ConstantTime.equal(recipientFingerprint, recipient.fingerprint) else { throw .wrongRecipient }231 if let expectedSender, expectedSender.fingerprint != sender.fingerprint { throw .unexpectedSender }232 if let expectedContentType, expectedContentType != contentType { throw .malformed }233 guard verifySignature() else { throw .invalidSignature }234 return try decrypt(with: recipient)235 }236237 /// Decapsulation and decryption without the signature check (the signature check always comes first in `open`).238 func decrypt(with recipient: Identity) throws(IdentityError) -> Bytes {239 guard var ssX = try? X25519.sharedSecret(privateKey: recipient.x25519PrivateKey, publicKey: ephemeralX25519PublicKey),240 var ssK = try? MLKEM.decapsulate(IdentitySuite.mlkem, decapsulationKey: recipient.mlkemDecapsulationKey, ciphertext: mlkemCiphertext)241 else { throw .decryptionFailed }242 defer {243 SecureMemory.zero(&ssX)244 SecureMemory.zero(&ssK)245 }246 var key = Self.payloadKey(247 x25519Secret: ssX, mlkemSecret: ssK, senderFingerprint: sender.fingerprint, recipient: recipient.publicIdentity,248 ephemeral: ephemeralX25519PublicKey, mlkemCiphertext: mlkemCiphertext, contentType: contentType)249 defer { SecureMemory.zero(&key) }250 guard let payload = try? SystemCrypto.aes256GCMOpen(key: key, nonce: nonce, sealed: ciphertext, associatedData: header()) else {251 throw .decryptionFailed252 }253 return payload254 }255}256