// A `c1:` chat box opened with CryptoKit, for the notification extension // alone: it rewrites an alert to the sender's name and words, and lands // nothing. Every message the app keeps is opened, checked and landed by the // core (`chat.incoming`); this is the same construction read on the lock // screen, where the core is not open (`cotton_core::chat::seal`): // // c1: + base64url(ephemeral pub ‖ sender pub ‖ nonce(12) ‖ ciphertext ‖ tag(16)) // key = HKDF-SHA256(ikm: X25519(me, ephemeral) ‖ X25519(me, sender), // salt: ephemeral ‖ sender ‖ me, info: "cotton-chat-v1") // AES-256-GCM, aad = "cotton-chat-v1" ‖ sender ‖ me // // Held to the core's `vectors.json` by `ChatBoxTests`. import CryptoKit import Foundation public enum ChatBox { static let prefix = "c1:" static let info = Data("cotton-chat-v1".utf8) /// The sender's public key and the payload's bytes, or nil for a box /// that is not one, not for this key, or tampered with. public static func open(_ sealed: String, privateKey: String) -> (sender: Data, payload: Data)? { guard sealed.hasPrefix(prefix), let secret = base64url(privateKey), secret.count == 32, let body = base64url(String(sealed.dropFirst(prefix.count))), body.count >= 64 + 12 + 16, let me = try? Curve25519.KeyAgreement.PrivateKey(rawRepresentation: secret) else { return nil } let ephemeral = body.subdata(in: 0..<32) let sender = body.subdata(in: 32..<64) let nonce = body.subdata(in: 64..<76) let sealedBytes = body.subdata(in: 76..