Cotton code
60 lines · 3.2 KB · SwiftRaw
// 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 CryptoKitimport Foundationpublic 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..<body.count)        let mine = me.publicKey.rawRepresentation        guard let ephemeralKey = try? Curve25519.KeyAgreement.PublicKey(rawRepresentation: ephemeral),            let senderKey = try? Curve25519.KeyAgreement.PublicKey(rawRepresentation: sender),            let dh1 = try? me.sharedSecretFromKeyAgreement(with: ephemeralKey),            let dh2 = try? me.sharedSecretFromKeyAgreement(with: senderKey)        else { return nil }        let first = dh1.withUnsafeBytes { Data($0) }        let second = dh2.withUnsafeBytes { Data($0) }        // A low-order point agrees on zeros: the core refuses it, and so does this.        let zero = Data(count: 32)        guard first != zero, second != zero else { return nil }        let key = HKDF<SHA256>.deriveKey(            inputKeyMaterial: SymmetricKey(data: first + second),            salt: ephemeral + sender + mine, info: info, outputByteCount: 32)        guard let box = try? AES.GCM.SealedBox(            nonce: AES.GCM.Nonce(data: nonce),            ciphertext: sealedBytes.dropLast(16), tag: sealedBytes.suffix(16)),            let payload = try? AES.GCM.open(box, using: key, authenticating: info + sender + mine)        else { return nil }        return (sender, payload)    }    /// Base64url without padding, as the core writes keys and boxes.    static func base64url(_ text: String) -> Data? {        var standard = text.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")        while standard.count % 4 != 0 { standard.append("=") }        return Data(base64Encoded: standard)    }}