office: split OpenPGP into :library:e2ee-openpgp to shrink office .so (#873)
- Commit
9ec7d53508366ad00485e033432f9cf4860e928c- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-05 18:59 UTC (1 month ago)
- Parents
954631f
Symptom: office grew in v2.6.11 with no office-side code change; the issue points at the OpenPGP addition in :library:e2ee-p2p. Root cause: v2.6.10 -> v2.6.11b added native OpenPGP (rPGP 0.21, Ed25519 + X25519, RFC 9580) directly into :library:e2ee-p2p's e2ee_pqc cdylib, compiled unconditionally with no cargo feature gate. rPGP pulls a large transitive cipher suite, and every e2ee-p2p consumer (office, cast, findfamily, everysync, backup, voxels, ...) links the whole libe2ee_pqc.so — but only :securemail uses the PGP surface (office uses E2ee/E2eeKeyStore/Pqc/PqcIdentity only). DEX was never the problem: Pgp.kt/PgpNative.kt are ~170 lines and R8 strips unreferenced Kotlin in release builds; the growth is native .so size. No too-broad keep rule exists (apps use the default optimize file, no app-level proguard-rules.pro), so there was nothing to tighten. Fix: move the OpenPGP surface into a new :library:e2ee-openpgp module with its own e2ee_pgp cdylib (Pgp.kt, PgpNative.kt, pgp.rs, pgp_jni.rs, pgp_tests.rs, PgpTest.kt unchanged apart from the .so name in loadLibrary). Same com.vayunmathur.e2ee package so the JNI entry points and the securemail import stay stable. :securemail now depends on :library:e2ee-openpgp instead of :library:e2ee-p2p; everyone else keeps PQC-only libe2ee_pqc.so. New module is arm64-only (no :cast:tv 32-bit need); e2ee-p2p keeps its armeabi-v7a build. Workspace lints/deps (pgp, rand08, base64, smallvec) stay in the root Cargo.toml; Cargo.lock gains the e2ee_pgp entry and drops those edges from e2ee_pqc. User-visible effect: office (and the other non-mail e2ee-p2p apps) stop shipping the rPGP cipher suite. Measured dev-profile arm64: libe2ee_pqc.so 3.61MB -> 0.60MB; libe2ee_pgp.so 3.72MB goes only to securemail. Release numbers need a release build to confirm. Verification: cargo check -p e2ee_pgp / e2ee_pqc clean; cargo test -p e2ee_pgp 12/12 pass; :library:e2ee-openpgp + :library:e2ee-p2p compileDebugKotlin/detekt/lint green; :securemail + :office compileDevKotlin green; releaseRuntimeClasspath shows office -> e2ee-p2p only and securemail -> e2ee-openpgp only.
Diff
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex f0c2db5f65..af96780b62 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1567,21 +1567,28 @@ dependencies = [ ] [[package]]-name = "e2ee_pqc"+name = "e2ee_pgp" version = "0.1.0" dependencies = [ "base64 0.23.1",+ "jni",+ "pgp",+ "rand 0.8.6",+ "smallvec",+]++[[package]]+name = "e2ee_pqc"+version = "0.1.0"+dependencies = [ "fips203", "fips204", "jni",- "pgp", "rand 0.10.3",- "rand 0.8.6", "rand_core 0.10.1", "sha2 0.11.1", "sha3 0.12.0", "shake",- "smallvec", ] [[package]]
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex a5ee29ba56..9be06d5c85 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -13,6 +13,7 @@ members = [ "appstore/src/main/rust", "vpn/src/main/rust", "library/e2ee-p2p/src/main/rust",+ "library/e2ee-openpgp/src/main/rust", "library/jni-http/src/main/rust", "library/map/src/main/rust", "library/ml/src/main/rust",
library/e2ee-openpgp/AGENTS.md
diff --git a/library/e2ee-openpgp/AGENTS.md b/library/e2ee-openpgp/AGENTS.mdnew file mode 100644index 0000000000..46053ca553--- /dev/null+++ b/library/e2ee-openpgp/AGENTS.md@@ -0,0 +1,27 @@+# AGENTS.md — library/e2ee-openpgp/ (':library:e2ee-openpgp')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside `library/e2ee-openpgp/` + allowed shared modules. Do not root-scan.++<!-- last-reviewed: 2026-11-05 -->+- Gradle: :library:e2ee-openpgp / dir: library/e2ee-openpgp/+- Package roots present: (OpenPGP primitives — `com.vayunmathur.e2ee` package, shared with `:library:e2ee-p2p` by design so the JNI entry points stay stable)+- Entry files: Pgp.kt (no MainActivity/Route — library)+- Deps: (none — Rust rPGP core via JNI)+- Metadata: metadata_data/library-e2ee-openpgp.md (absent — libraries have none by design)+- Rust: yes / screenshotTest: no++## Overview+**Purpose:** OpenPGP (RFC 9580, Ed25519 primary + X25519 subkey) for SecureMail, backed by native Rust (rPGP) instead of BouncyCastle. Split out of `:library:e2ee-p2p`'s `e2ee_pqc` crate (#873): rPGP's cipher suite materially grows the `.so`, and only `:securemail` uses the PGP surface — every other e2ee-p2p consumer (office, cast, findfamily, everysync, backup, voxels, ...) links PQC only.+**How to use:** `Pgp.generateIdentity` / `encrypt` / `decrypt` / `decryptVerify` / `signDetached` (`Pgp.kt`); JNI via `PgpNative` (`libe2ee_pgp.so`). Keys cross as ASCII armor; the relay wire carries raw PGP bytes.+**Entry points:** `Pgp.kt` → `PgpNative.kt` (Rust bridge, `pgp_jni.rs`).+**Gotchas:** Crypto changes need adversarial review. Same `com.vayunmathur.e2ee` package as `:library:e2ee-p2p` is intentional (JNI names); keep it so. Phone-app only: arm64-v8a alone, no armeabi-v7a (unlike e2ee-p2p, which `:cast:tv` needs on 32-bit Google TV hardware).++## Key files+- com/vayunmathur/e2ee/Pgp.kt+- com/vayunmathur/e2ee/PgpNative.kt — Rust bridge (`// PACKAGE STRUCTURE EXCEPTION (JNI)`)++## Verify (this module only)+```+./gradlew :library:e2ee-openpgp:compileDevKotlin+./gradlew :library:e2ee-openpgp:lint+```
library/e2ee-openpgp/build.gradle.kts
diff --git a/library/e2ee-openpgp/build.gradle.kts b/library/e2ee-openpgp/build.gradle.ktsnew file mode 100644index 0000000000..aa7802e960--- /dev/null+++ b/library/e2ee-openpgp/build.gradle.kts@@ -0,0 +1,27 @@+plugins {+ id("common-conventions-library")+}++android {+ // The convention plugin derives the namespace from the module name, which contains a hyphen+ // ("e2ee-openpgp") and is not a valid package segment — so set it explicitly.+ // Same package as :library:e2ee-p2p's PQC surface on purpose: the JNI entry+ // points below (`Java_com_vayunmathur_e2ee_PgpNative_*`) are bound to this+ // package, and consumers keep importing `com.vayunmathur.e2ee.Pgp`.+ namespace = "com.vayunmathur.e2ee"+}++androidComponents {+ onVariants { variant ->+ variant.sources.jniLibs?.addStaticSourceDirectory(+ layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath+ )+ }+}++// Native OpenPGP (Rust: rPGP, RFC 9580 Ed25519 + X25519). Split out of+// :library:e2ee-p2p's `e2ee_pqc` crate (#873): only :securemail uses OpenPGP,+// and rPGP's cipher suite materially grows the .so for every other e2ee-p2p+// consumer (office, cast, findfamily, everysync, backup, voxels, ...).+// Phone-app only, so arm64-v8a alone (no :cast:tv 32-bit requirement here).+rustNativeLib("e2ee_pgp", "e2ee-pgp")
library/e2ee-openpgp/src/main/java/com/vayunmathur/e2ee/Pgp.kt
diff --git a/library/e2ee-openpgp/src/main/java/com/vayunmathur/e2ee/Pgp.kt b/library/e2ee-openpgp/src/main/java/com/vayunmathur/e2ee/Pgp.ktnew file mode 100644index 0000000000..fc8240bffc--- /dev/null+++ b/library/e2ee-openpgp/src/main/java/com/vayunmathur/e2ee/Pgp.kt@@ -0,0 +1,128 @@+package com.vayunmathur.e2ee++/**+ * OpenPGP (RFC 9580) primitives for SecureMail, backed by native Rust (rPGP)+ * instead of BouncyCastle.+ *+ * Suite: Ed25519 signing primary + X25519 encryption subkey, AES-256 session+ * keys, SHA-512 digests — interoperable with ProtonMail and any OpenPGP+ * client. All key handling speaks ASCII armor; the relay wire carries raw+ * bytes and converts at the boundary only, mirroring the FindFamily relay+ * contract.+ */+object Pgp {++ /** A generated identity: armored secret ring (passphrase-wrapped) + armored public ring. */+ data class Identity(+ val armoredSecret: String,+ val armoredPublic: String,+ val fingerprintHex: String,+ )++ /** `nativePgpGenerate` returns exactly (secret, public, fingerprint). */+ private const val GENERATED_PART_COUNT = 3++ private fun String.toUtf8(): ByteArray = toByteArray(Charsets.UTF_8)+ private fun ByteArray.toUtf8String(): String = toString(Charsets.UTF_8)++ /**+ * Generates an Ed25519 primary + X25519 encryption subkey for [userId]+ * (e.g. "alice <[email protected]>"). The secret key material is wrapped+ * with [passphrase] via S2K so the stored blob alone is useless.+ */+ fun generateIdentity(userId: String, passphrase: String): Identity {+ val parts = PgpNative.nativePgpGenerate(userId.toUtf8(), passphrase.toUtf8())+ ?: error("OpenPGP key generation failed")+ require(parts.size == GENERATED_PART_COUNT) { "OpenPGP key generation returned ${parts.size} parts" }+ return Identity(+ armoredSecret = parts[0].toUtf8String(),+ armoredPublic = parts[1].toUtf8String(),+ fingerprintHex = parts[2].toUtf8String(),+ )+ }++ /** Fingerprint hex (uppercase, no spaces) of an armored public key. */+ fun fingerprintHex(armoredPublic: String): String =+ PgpNative.nativePgpFingerprint(armoredPublic.toUtf8())?.toUtf8String()+ ?: error("Invalid OpenPGP public key")++ /**+ * Normalizes a WKD record (binary key or armor) to canonical armor text.+ * Throws when the input is not a parseable OpenPGP public key.+ */+ fun normalizeKey(record: ByteArray): String =+ PgpNative.nativePgpNormalizeKey(record)?.toUtf8String()+ ?: error("Invalid OpenPGP public key")++ /**+ * Encrypts [plaintext] (raw message bytes, e.g. a PGP/MIME body) to the+ * holder of [armoredPublic]. Returns raw (unarmored) PGP bytes for the+ * relay wire; armor via [armorMessage] for SMTP federation.+ */+ fun encrypt(armoredPublic: String, plaintext: ByteArray): ByteArray =+ PgpNative.nativePgpEncrypt(armoredPublic.toUtf8(), plaintext)+ ?: error("OpenPGP encryption failed")++ /**+ * Encrypts + signs: as [encrypt], additionally signing with the sender's+ * secret key. Empty [senderSecret] disables signing (same as [encrypt]).+ */+ fun encryptSigned(+ armoredPublic: String,+ senderSecret: String,+ senderPassphrase: String,+ plaintext: ByteArray,+ ): ByteArray =+ PgpNative.nativePgpEncryptSigned(+ armoredPublic.toUtf8(),+ senderSecret.toUtf8(),+ senderPassphrase.toUtf8(),+ plaintext,+ ) ?: error("OpenPGP signed encryption failed")++ /**+ * Decrypts raw PGP bytes with [armoredSecret] + [passphrase]. Returns the+ * literal payload.+ */+ fun decrypt(armoredSecret: String, passphrase: String, ciphertext: ByteArray): ByteArray =+ PgpNative.nativePgpDecrypt(armoredSecret.toUtf8(), passphrase.toUtf8(), ciphertext)+ ?: error("OpenPGP decryption failed")++ /** Result of [decryptVerify]: payload plus signer fingerprint (empty when unsigned). */+ data class Verified(val payload: ByteArray, val signerFingerprintHex: String)++ /**+ * Decrypts + verifies: as [decrypt], additionally verifying an embedded+ * signature against [verifierPublic] (empty = skip verification).+ * Unsigned messages verify cleanly with an empty fingerprint (accepted);+ * tampered signatures throw.+ */+ fun decryptVerify(+ armoredSecret: String,+ passphrase: String,+ ciphertext: ByteArray,+ verifierPublic: String,+ ): Verified {+ val parts = PgpNative.nativePgpDecryptVerify(+ armoredSecret.toUtf8(),+ passphrase.toUtf8(),+ ciphertext,+ verifierPublic.toUtf8(),+ ) ?: error("OpenPGP decrypt/verify failed")+ require(parts.size == 2) { "decryptVerify returned ${parts.size} parts" }+ return Verified(+ payload = parts[0],+ signerFingerprintHex = parts[1].toUtf8String(),+ )+ }++ /** Armors raw PGP bytes as a `PGP MESSAGE` block (for SMTP federation). */+ fun armorMessage(raw: ByteArray): String =+ PgpNative.nativePgpArmorMessage(raw)?.toUtf8String()+ ?: error("OpenPGP armor failed")++ /** Raw binary detached signature over [data] with the Ed25519 primary. */+ fun signDetached(armoredSecret: String, passphrase: String, data: ByteArray): ByteArray =+ PgpNative.nativePgpSignDetached(armoredSecret.toUtf8(), passphrase.toUtf8(), data)+ ?: error("OpenPGP detached signing failed")+}
library/e2ee-openpgp/src/main/java/com/vayunmathur/e2ee/PgpNative.kt
diff --git a/library/e2ee-openpgp/src/main/java/com/vayunmathur/e2ee/PgpNative.kt b/library/e2ee-openpgp/src/main/java/com/vayunmathur/e2ee/PgpNative.ktnew file mode 100644index 0000000000..3d2ee1513a--- /dev/null+++ b/library/e2ee-openpgp/src/main/java/com/vayunmathur/e2ee/PgpNative.kt@@ -0,0 +1,45 @@+package com.vayunmathur.e2ee++// PACKAGE STRUCTURE EXCEPTION (JNI)++/**+ * JNI surface for the native Rust OpenPGP module (libe2ee_pgp.so, `pgp.rs` via+ * rPGP): Ed25519 primary + X25519 subkey generation, armor, encrypt, decrypt.+ *+ * Keys cross as ASCII armor (UTF-8 bytes); ciphertext crosses as raw PGP bytes+ * (armored only for SMTP federation via [nativePgpArmorMessage]). Null on any+ * failure — callers in [Pgp] map null to errors.+ */+internal object PgpNative {+ external fun nativePgpGenerate(userId: ByteArray, passphrase: ByteArray): Array<ByteArray>?+ external fun nativePgpFingerprint(armoredPublic: ByteArray): ByteArray?+ external fun nativePgpNormalizeKey(input: ByteArray): ByteArray?+ external fun nativePgpEncrypt(armoredPublic: ByteArray, plaintext: ByteArray): ByteArray?+ external fun nativePgpEncryptSigned(+ armoredPublic: ByteArray,+ armoredSecret: ByteArray,+ passphrase: ByteArray,+ plaintext: ByteArray,+ ): ByteArray?+ external fun nativePgpDecrypt(+ armoredSecret: ByteArray,+ passphrase: ByteArray,+ ciphertext: ByteArray,+ ): ByteArray?+ external fun nativePgpDecryptVerify(+ armoredSecret: ByteArray,+ passphrase: ByteArray,+ ciphertext: ByteArray,+ verifierPublic: ByteArray,+ ): Array<ByteArray>?+ external fun nativePgpArmorMessage(raw: ByteArray): ByteArray?+ external fun nativePgpSignDetached(+ armoredSecret: ByteArray,+ passphrase: ByteArray,+ data: ByteArray,+ ): ByteArray?++ init {+ System.loadLibrary("e2ee_pgp")+ }+}
library/e2ee-openpgp/src/main/rust/Cargo.toml
diff --git a/library/e2ee-openpgp/src/main/rust/Cargo.toml b/library/e2ee-openpgp/src/main/rust/Cargo.tomlnew file mode 100644index 0000000000..6c94081745--- /dev/null+++ b/library/e2ee-openpgp/src/main/rust/Cargo.toml@@ -0,0 +1,23 @@+[package]+name = "e2ee_pgp"+version = "0.1.0"+edition = "2021"+description = "OpenPGP (RFC 9580) for SecureMail via :library:e2ee-openpgp (rPGP, Ed25519 + X25519), exposed to Kotlin via JNI. Split out of the e2ee_pqc crate so non-mail apps don't pay for the rPGP cipher suite (#873)."+license = "GPL-2.0-only"++[lib]+name = "e2ee_pgp"+crate-type = ["cdylib", "rlib"]++[dependencies]+jni.workspace = true+# OpenPGP packet engine for SecureMail (generate/armor/encrypt/decrypt).+# Same crate as the relay server would use; the JNI surface below exposes only+# what the app needs (no WKD/SMTP — those stay in Kotlin via library:network).+pgp.workspace = true+# rand 0.8 for rPGP keygen/encrypt RNG (workspace default is 0.10; see root).+rand08.workspace = true+# Base64 framing for PGP/MIME armor output (workspace pin, betocore line).+base64.workspace = true+# smallvec! for rPGP key-preference lists (workspace pin, betocore line).+smallvec.workspace = true
library/e2ee-openpgp/src/main/rust/src/lib.rs
diff --git a/library/e2ee-openpgp/src/main/rust/src/lib.rs b/library/e2ee-openpgp/src/main/rust/src/lib.rsnew file mode 100644index 0000000000..98084e8e1a--- /dev/null+++ b/library/e2ee-openpgp/src/main/rust/src/lib.rs@@ -0,0 +1,19 @@+//! OpenPGP (RFC 9580) for SecureMail, via rPGP.+//!+//! Suite: Ed25519 signing primary + X25519 encryption subkey, AES-256 session+//! keys, SHA-512 digests. Keys cross the JNI boundary as ASCII armor; ciphertext+//! crosses as raw PGP/MIME bytes (armored only for SMTP federation, which the+//! app does with [`pgp::to_armored_message`]).+//!+//! The relay server never sees plaintext or private keys — it routes opaque+//! blobs by recipient address, exactly like the FindFamily relay routes opaque+//! ciphertext by userid.+//!+//! Lives in its own `e2ee_pgp` cdylib (see :library:e2ee-openpgp) so apps that+//! don't do mail never link the rPGP cipher suite (#873).++pub mod pgp;+mod pgp_jni;++#[cfg(test)]+mod pgp_tests;
library/e2ee-openpgp/src/main/rust/src/pgp.rs
diff --git a/library/e2ee-openpgp/src/main/rust/src/pgp.rs b/library/e2ee-openpgp/src/main/rust/src/pgp.rsnew file mode 100644index 0000000000..0f9ef5dedb--- /dev/null+++ b/library/e2ee-openpgp/src/main/rust/src/pgp.rs@@ -0,0 +1,248 @@+//! OpenPGP (RFC 9580) for SecureMail, via rPGP.+//!+//! Suite: Ed25519 signing primary + X25519 encryption subkey (the same suite+//! the app previously generated with BouncyCastle), AES-256 session keys,+//! SHA-512 digests. Keys cross the JNI boundary as ASCII armor; ciphertext+//! crosses as raw PGP/MIME bytes (armored only for SMTP federation, which the+//! app does with [`to_armored_message`]).+//!+//! The relay server never sees plaintext or private keys — it routes opaque+//! blobs by recipient address, exactly like the FindFamily relay routes opaque+//! ciphertext by userid.++use pgp::armor::Dearmor;+use pgp::composed::{+ ArmorOptions, Deserializable, EncryptionCaps, KeyType, Message, MessageBuilder,+ SecretKeyParamsBuilder, SignedPublicKey, SignedSecretKey, SubkeyParamsBuilder,+};+use pgp::crypto::hash::HashAlgorithm;+use pgp::crypto::sym::SymmetricKeyAlgorithm;+use pgp::types::{KeyDetails, Password};+use rand08::rngs::OsRng;++/// Generate an Ed25519 primary + X25519 encryption subkey for `user_id`.+/// Returns (armoredSecret, armoredPublic, fingerprintHex).+pub fn pgp_generate(user_id: &str, passphrase: &str) -> Option<(String, String, String)> {+ let mut rng = OsRng;+ let mut params = SecretKeyParamsBuilder::default();+ params+ .key_type(KeyType::Ed25519)+ .can_certify(false)+ .can_sign(true)+ .primary_user_id(user_id.to_string())+ .passphrase(Some(passphrase.to_string()))+ .preferred_symmetric_algorithms(smallvec::smallvec![+ SymmetricKeyAlgorithm::AES256,+ ])+ .preferred_hash_algorithms(smallvec::smallvec![HashAlgorithm::Sha512])+ .preferred_compression_algorithms(smallvec::smallvec![])+ .subkeys(vec![SubkeyParamsBuilder::default()+ .key_type(KeyType::X25519)+ .can_encrypt(EncryptionCaps::All)+ .passphrase(Some(passphrase.to_string()))+ .build()+ .ok()?]);+ let secret = params.build().ok()?.generate(&mut rng).ok()?;+ let public = secret.to_public_key();+ let fingerprint = hex_upper(&secret.fingerprint().as_bytes());+ Some((+ secret.to_armored_string(ArmorOptions::default()).ok()?,+ public.to_armored_string(ArmorOptions::default()).ok()?,+ fingerprint,+ ))+}++/// Fingerprint (uppercase hex, no spaces) of an armored public key.+pub fn pgp_fingerprint(armored_public: &str) -> Option<String> {+ let (key, _) = SignedPublicKey::from_string(armored_public).ok()?;+ Some(hex_upper(&key.fingerprint().as_bytes()))+}++/// Normalize a public key (binary WKD record or armor) to canonical armor.+/// Returns None when the input is not a parseable OpenPGP public key.+pub fn pgp_normalize_key(input: &[u8]) -> Option<String> {+ use pgp::composed::Deserializable as _;+ let key = if is_probably_armor(input) {+ let text = std::str::from_utf8(input).ok()?;+ let (key, _) = SignedPublicKey::from_string(text).ok()?;+ key+ } else {+ SignedPublicKey::from_bytes(input).ok()?+ };+ key.to_armored_string(ArmorOptions::default()).ok()+}++fn is_probably_armor(input: &[u8]) -> bool {+ input.starts_with(b"-----BEGIN PGP")+}++/// Encrypt `plaintext` to one recipient's armored public key. Returns raw+/// (unarmored) PGP bytes for the relay wire.+pub fn pgp_encrypt(armored_public: &str, plaintext: &[u8]) -> Option<Vec<u8>> {+ pgp_encrypt_signed(armored_public, None, plaintext)+}++/// Encrypt + sign: as [`pgp_encrypt`], additionally signing with the sender's+/// secret key (`(armored_secret, passphrase)`). Returns raw PGP bytes.+pub fn pgp_encrypt_signed(+ armored_public: &str,+ signer: Option<(&str, &str)>,+ plaintext: &[u8],+) -> Option<Vec<u8>> {+ let mut rng = OsRng;+ let (public, _) = SignedPublicKey::from_string(armored_public).ok()?;+ // Encrypt to the first subkey (our keys always carry the X25519+ // encryption subkey; a foreign key without one cannot be encrypted to).+ // Matches the documented `encrypt_to_key(&rng, &public_subkeys[0])` shape.+ let subkey = public.public_subkeys.first()?;+ let mut builder = MessageBuilder::from_bytes("message.txt", plaintext.to_vec())+ .seipd_v1(&mut rng, SymmetricKeyAlgorithm::AES256);+ // Parse the signer first: builder.sign() borrows the secret key for the+ // builder's lifetime, so it must outlive the if-let scope.+ let signer_key: Option<SignedSecretKey> = match signer {+ Some((armored_secret, _)) => {+ Some(SignedSecretKey::from_string(armored_secret).ok()?.0)+ }+ None => None,+ };+ if let (Some(key), Some((_, passphrase))) = (&signer_key, signer) {+ // packet::SecretKey implements SigningKey; the primary is Ed25519.+ builder.sign(+ &key.primary_key,+ Password::from(passphrase),+ HashAlgorithm::Sha512,+ );+ }+ builder.encrypt_to_key(&mut rng, subkey).ok()?;+ builder.to_vec(&mut rng).ok()+}++/// Decrypt raw PGP bytes with an armored secret key + passphrase. Returns the+/// literal payload. Signature verification is a separate pass (see below).+pub fn pgp_decrypt(+ armored_secret: &str,+ passphrase: &str,+ ciphertext: &[u8],+) -> Option<Vec<u8>> {+ pgp_decrypt_verify(armored_secret, passphrase, ciphertext, None).map(|(p, _)| p)+}++/// Decrypt + verify: as [`pgp_decrypt`], additionally verifying an embedded+/// signature against `verifier` (armored sender public key). Returns+/// (payload, signer_fingerprint_hex_or_empty). Unsigned messages verify+/// cleanly with an empty fingerprint (accepted, not rejected); tampered+/// signatures fail the whole call (None).+pub fn pgp_decrypt_verify(+ armored_secret: &str,+ passphrase: &str,+ ciphertext: &[u8],+ verifier: Option<&str>,+) -> Option<(Vec<u8>, String)> {+ let (secret, _) = SignedSecretKey::from_string(armored_secret).ok()?;+ let msg = Message::from_bytes(ciphertext).ok()?;+ let mut decrypted = msg+ .decrypt(&Password::from(passphrase), &secret)+ .ok()?;+ // Signedness is structural: an unsigned message decrypts to Literal and+ // must NOT attempt verify() (it bails "message was not signed"). Only+ // Signed messages go through verification; a failed check there means+ // tamper and fails the whole call.+ let is_signed = matches!(decrypted, Message::Signed { .. });+ // Drain the literal first: verify() requires the message read to the end.+ let payload = decrypted.as_data_vec().ok()?;+ if !is_signed {+ return Some((payload, String::new()));+ }+ let fingerprint = match verifier {+ Some(armored_public) => {+ let (public, _) = SignedPublicKey::from_string(armored_public).ok()?;+ // Try the primary first, then each subkey (sender may sign with+ // either; ours always signs with the Ed25519 primary).+ let mut candidates: Vec<&dyn pgp::types::VerifyingKey> = vec![&public.primary_key];+ for sub in &public.public_subkeys {+ candidates.push(&sub.key);+ }+ let mut matched: Option<String> = None;+ for key in candidates {+ if decrypted.verify(key).is_ok() {+ matched = Some(hex_upper(&key.fingerprint().as_bytes()));+ break;+ }+ }+ matched?+ }+ // No verifier key supplied: is the message signed at all? A signed+ // message without a key to check against stays unverified (empty),+ // which callers render as "signature not verified" — accepted.+ None => String::new(),+ };+ Some((payload, fingerprint))+}++/// Binary detached signature over `data` with the Ed25519 primary (SHA-512).+/// Returns the raw signature packet (used for relay SUB authentication).+pub fn pgp_sign_detached(armored_secret: &str, passphrase: &str, data: &[u8]) -> Option<Vec<u8>> {+ use pgp::composed::DetachedSignature;+ use pgp::ser::Serialize;+ let (secret, _) = SignedSecretKey::from_string(armored_secret).ok()?;+ DetachedSignature::sign_binary_data(+ OsRng,+ &secret.primary_key,+ &Password::from(passphrase),+ HashAlgorithm::Sha512,+ data,+ )+ .ok()?+ .to_bytes()+ .ok()+}++/// Armor raw PGP bytes as a `PGP MESSAGE` block (for SMTP federation).+pub fn to_armored_message(raw: &[u8]) -> Option<String> {+ use base64::Engine;+ // RFC 9580 §6 armor framing: header, base64 body at 64-col, CRC24 footer.+ let mut out = String::from("-----BEGIN PGP MESSAGE-----\n\n");+ let b64 = base64::engine::general_purpose::STANDARD.encode(raw);+ for chunk in b64.as_bytes().chunks(64) {+ out.push_str(std::str::from_utf8(chunk).ok()?);+ out.push('\n');+ }+ out.push('=');+ out.push_str(&base64::engine::general_purpose::STANDARD.encode(crc24(raw)));+ out.push_str("\n-----END PGP MESSAGE-----\n");+ Some(out)+}++/// OpenPGP CRC24 (RFC 9580 §6.1): polynomial 0x1864CFB, init 0xB704CE.+fn crc24(data: &[u8]) -> [u8; 3] {+ let mut crc: u32 = 0xB704CE;+ for &b in data {+ crc ^= (b as u32) << 16;+ for _ in 0..8 {+ crc <<= 1;+ if crc & 0x1000000 != 0 {+ crc ^= 0x1864CFB;+ }+ }+ }+ [(crc >> 16) as u8, (crc >> 8) as u8, crc as u8]+}++/// Dearmor any ASCII-armored input to raw bytes (key or message).+pub fn dearmor_any(armored: &str) -> Option<Vec<u8>> {+ use std::io::Read;+ let mut dearmor = Dearmor::new(armored.as_bytes());+ let mut bytes = Vec::new();+ dearmor.read_to_end(&mut bytes).ok()?;+ Some(bytes)+}++fn hex_upper(bytes: &[u8]) -> String {+ const HEX: &[u8; 16] = b"0123456789ABCDEF";+ let mut out = String::with_capacity(bytes.len() * 2);+ for b in bytes {+ out.push(HEX[(b >> 4) as usize] as char);+ out.push(HEX[(b & 0x0f) as usize] as char);+ }+ out+}
library/e2ee-openpgp/src/main/rust/src/pgp_jni.rs
diff --git a/library/e2ee-openpgp/src/main/rust/src/pgp_jni.rs b/library/e2ee-openpgp/src/main/rust/src/pgp_jni.rsnew file mode 100644index 0000000000..0bed120df3--- /dev/null+++ b/library/e2ee-openpgp/src/main/rust/src/pgp_jni.rs@@ -0,0 +1,284 @@+//! JNI surface for `com.vayunmathur.e2ee.PgpNative`.+//! Armor crosses as UTF-8 bytes; ciphertext crosses as raw bytes.++use crate::pgp::*;++use jni::objects::{JByteArray, JClass};+use jni::sys::{jbyteArray, jobjectArray};+use jni::{Env, EnvUnowned};++fn jbytes_in(env: &Env, arr: &JByteArray) -> Option<Vec<u8>> {+ env.convert_byte_array(arr).ok()+}++fn jbytes_out(env: &mut Env, data: &[u8]) -> jbyteArray {+ match env.byte_array_from_slice(data) {+ Ok(a) => a.into_raw(),+ Err(_) => std::ptr::null_mut(),+ }+}++fn jstring_in(env: &mut Env, arr: &JByteArray) -> Option<String> {+ let bytes = jbytes_in(env, arr)?;+ String::from_utf8(bytes).ok()+}++fn jstring_out(env: &mut Env, s: &str) -> jbyteArray {+ jbytes_out(env, s.as_bytes())+}++/// Return a Java `byte[][]` of exactly three elements (secret, public,+/// fingerprint), or null.+fn triple_out(env: &mut Env, a: &str, b: &str, c: &str) -> jobjectArray {+ let arr = match env.new_object_type_array::<JByteArray>(3, JByteArray::null()) {+ Ok(a) => a,+ Err(_) => return std::ptr::null_mut(),+ };+ let items = [a.as_bytes(), b.as_bytes(), c.as_bytes()];+ for (i, data) in items.iter().enumerate() {+ let element = match env.byte_array_from_slice(data) {+ Ok(x) => x,+ Err(_) => return std::ptr::null_mut(),+ };+ if arr.set_element(env, i, &element).is_err() {+ return std::ptr::null_mut();+ }+ }+ arr.into_raw()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpGenerate<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ user_id: JByteArray<'l>,+ passphrase: JByteArray<'l>,+) -> jobjectArray {+ env.with_env(|env| -> jni::errors::Result<jobjectArray> {+ let (uid, pw) = match (jstring_in(env, &user_id), jstring_in(env, &passphrase)) {+ (Some(a), Some(b)) => (a, b),+ _ => return Ok(std::ptr::null_mut()),+ };+ match pgp_generate(&uid, &pw) {+ Some((secret, public, fp)) => Ok(triple_out(env, &secret, &public, &fp)),+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpFingerprint<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ armored_public: JByteArray<'l>,+) -> jbyteArray {+ env.with_env(|env| -> jni::errors::Result<jbyteArray> {+ let armor = match jstring_in(env, &armored_public) {+ Some(a) => a,+ None => return Ok(std::ptr::null_mut()),+ };+ match pgp_fingerprint(&armor) {+ Some(fp) => Ok(jstring_out(env, &fp)),+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpNormalizeKey<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ input: JByteArray<'l>,+) -> jbyteArray {+ env.with_env(|env| -> jni::errors::Result<jbyteArray> {+ let bytes = match jbytes_in(env, &input) {+ Some(b) => b,+ None => return Ok(std::ptr::null_mut()),+ };+ match pgp_normalize_key(&bytes) {+ Some(armor) => Ok(jstring_out(env, &armor)),+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpEncrypt<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ armored_public: JByteArray<'l>,+ plaintext: JByteArray<'l>,+) -> jbyteArray {+ env.with_env(|env| -> jni::errors::Result<jbyteArray> {+ let (armor, plain) = match (+ jstring_in(env, &armored_public),+ jbytes_in(env, &plaintext),+ ) {+ (Some(a), Some(b)) => (a, b),+ _ => return Ok(std::ptr::null_mut()),+ };+ match pgp_encrypt(&armor, &plain) {+ Some(raw) => Ok(jbytes_out(env, &raw)),+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpDecrypt<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ armored_secret: JByteArray<'l>,+ passphrase: JByteArray<'l>,+ ciphertext: JByteArray<'l>,+) -> jbyteArray {+ env.with_env(|env| -> jni::errors::Result<jbyteArray> {+ let (armor, pw, ct) = match (+ jstring_in(env, &armored_secret),+ jstring_in(env, &passphrase),+ jbytes_in(env, &ciphertext),+ ) {+ (Some(a), Some(b), Some(c)) => (a, b, c),+ _ => return Ok(std::ptr::null_mut()),+ };+ match pgp_decrypt(&armor, &pw, &ct) {+ Some(plain) => Ok(jbytes_out(env, &plain)),+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpArmorMessage<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ raw: JByteArray<'l>,+) -> jbyteArray {+ env.with_env(|env| -> jni::errors::Result<jbyteArray> {+ let bytes = match jbytes_in(env, &raw) {+ Some(b) => b,+ None => return Ok(std::ptr::null_mut()),+ };+ match to_armored_message(&bytes) {+ Some(armor) => Ok(jstring_out(env, &armor)),+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++/// Encrypt + sign: recipient armor, sender secret armor (empty string = no+/// signing), sender passphrase, plaintext → raw PGP bytes or null.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpEncryptSigned<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ armored_public: JByteArray<'l>,+ armored_secret: JByteArray<'l>,+ passphrase: JByteArray<'l>,+ plaintext: JByteArray<'l>,+) -> jbyteArray {+ env.with_env(|env| -> jni::errors::Result<jbyteArray> {+ let (armor, secret, pw, plain) = match (+ jstring_in(env, &armored_public),+ jstring_in(env, &armored_secret),+ jstring_in(env, &passphrase),+ jbytes_in(env, &plaintext),+ ) {+ (Some(a), Some(b), Some(c), Some(d)) => (a, b, c, d),+ _ => return Ok(std::ptr::null_mut()),+ };+ // Empty secret = encrypt-only (same as nativePgpEncrypt).+ let signer = if secret.is_empty() {+ None+ } else {+ Some((secret.as_str(), pw.as_str()))+ };+ match pgp_encrypt_signed(&armor, signer, &plain) {+ Some(raw) => Ok(jbytes_out(env, &raw)),+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++/// Detached sign: secret armor, passphrase, data → raw signature packet or null.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpSignDetached<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ armored_secret: JByteArray<'l>,+ passphrase: JByteArray<'l>,+ data: JByteArray<'l>,+) -> jbyteArray {+ env.with_env(|env| -> jni::errors::Result<jbyteArray> {+ let (secret, pw, bytes) = match (+ jstring_in(env, &armored_secret),+ jstring_in(env, &passphrase),+ jbytes_in(env, &data),+ ) {+ (Some(a), Some(b), Some(c)) => (a, b, c),+ _ => return Ok(std::ptr::null_mut()),+ };+ match pgp_sign_detached(&secret, &pw, &bytes) {+ Some(sig) => Ok(jbytes_out(env, &sig)),+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++/// Decrypt + verify: secret armor, passphrase, ciphertext, verifier public+/// armor (empty string = no verification) → `byte[][]` [payload, fingerprint]+/// (fingerprint empty when unsigned/unverified) or null on failure/tamper.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpDecryptVerify<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ armored_secret: JByteArray<'l>,+ passphrase: JByteArray<'l>,+ ciphertext: JByteArray<'l>,+ verifier_public: JByteArray<'l>,+) -> jobjectArray {+ env.with_env(|env| -> jni::errors::Result<jobjectArray> {+ let (secret, pw, ct, verifier) = match (+ jstring_in(env, &armored_secret),+ jstring_in(env, &passphrase),+ jbytes_in(env, &ciphertext),+ jstring_in(env, &verifier_public),+ ) {+ (Some(a), Some(b), Some(c), Some(d)) => (a, b, c, d),+ _ => return Ok(std::ptr::null_mut()),+ };+ let verifier_opt = if verifier.is_empty() { None } else { Some(verifier.as_str()) };+ match pgp_decrypt_verify(&secret, &pw, &ct, verifier_opt) {+ Some((payload, fp)) => {+ let arr = match env.new_object_type_array::<JByteArray>(2, JByteArray::null()) {+ Ok(a) => a,+ Err(_) => return Ok(std::ptr::null_mut()),+ };+ let payload_arr = match env.byte_array_from_slice(&payload) {+ Ok(x) => x,+ Err(_) => return Ok(std::ptr::null_mut()),+ };+ let fp_arr = match env.byte_array_from_slice(fp.as_bytes()) {+ Ok(x) => x,+ Err(_) => return Ok(std::ptr::null_mut()),+ };+ if arr.set_element(env, 0, &payload_arr).is_err()+ || arr.set_element(env, 1, &fp_arr).is_err()+ {+ return Ok(std::ptr::null_mut());+ }+ Ok(arr.into_raw())+ }+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}
library/e2ee-openpgp/src/main/rust/src/pgp_tests.rs
diff --git a/library/e2ee-openpgp/src/main/rust/src/pgp_tests.rs b/library/e2ee-openpgp/src/main/rust/src/pgp_tests.rsnew file mode 100644index 0000000000..117cf44d59--- /dev/null+++ b/library/e2ee-openpgp/src/main/rust/src/pgp_tests.rs@@ -0,0 +1,199 @@+//! OpenPGP round-trip tests: generate → armor → encrypt → decrypt.+//! No external vectors: keys are randomized per run (keygen uses OS entropy),+//! so these prove self-consistency of the rPGP pipeline the app ships.++use super::pgp::*;++#[test]+fn generate_emits_armor_and_fingerprint() {+ let (secret, public, fp) = pgp_generate("alice <[email protected]>", "correct horse")+ .expect("keygen");+ assert!(secret.contains("-----BEGIN PGP PRIVATE KEY BLOCK-----"), "secret armor");+ assert!(public.contains("-----BEGIN PGP PUBLIC KEY BLOCK-----"), "public armor");+ assert_eq!(fp.len(), 40, "v4 fingerprint is 20 bytes hex");+ assert!(fp.bytes().all(|b| b.is_ascii_hexdigit()), "fingerprint hex");+ assert_eq!(fp, fp.to_uppercase(), "fingerprint uppercase");+}++#[test]+fn fingerprint_is_stable_and_address_independent() {+ let (_, public_a, fp_a) = pgp_generate("alice <[email protected]>", "pw12345678")+ .expect("keygen a");+ assert_eq!(Some(fp_a.clone()), pgp_fingerprint(&public_a));+ let (_, public_b, fp_b) = pgp_generate("bob <[email protected]>", "pw12345678")+ .expect("keygen b");+ assert_ne!(fp_a, fp_b, "distinct keys have distinct fingerprints");+ assert!(pgp_fingerprint(&public_b).is_some());+}++#[test]+fn encrypt_decrypt_roundtrip() {+ let (secret, public, _) = pgp_generate("alice <[email protected]>", "pw12345678")+ .expect("keygen");+ let plaintext = b"Hello from SecureMail";+ let raw = pgp_encrypt(&public, plaintext).expect("encrypt");+ assert!(!raw.is_empty(), "ciphertext non-empty");+ assert_ne!(raw.as_slice(), plaintext.as_slice(), "ciphertext differs");+ let back = pgp_decrypt(&secret, "pw12345678", &raw).expect("decrypt");+ assert_eq!(back, plaintext, "round-trip plaintext");+}++#[test]+fn wrong_passphrase_fails_decrypt() {+ let (secret, public, _) = pgp_generate("alice <[email protected]>", "pw12345678")+ .expect("keygen");+ let raw = pgp_encrypt(&public, b"secret").expect("encrypt");+ assert!(+ pgp_decrypt(&secret, "wrong passphrase", &raw).is_none(),+ "wrong passphrase must fail"+ );+}++#[test]+fn signed_encrypt_verify_roundtrip() {+ let (alice_secret, alice_public, alice_fp) =+ pgp_generate("alice <[email protected]>", "pw12345678").expect("alice keygen");+ let (bob_secret, bob_public, _) =+ pgp_generate("bob <[email protected]>", "pw87654321").expect("bob keygen");+ let plaintext = b"signed hello from alice";+ // Alice signs + encrypts to Bob.+ let raw = pgp_encrypt_signed(+ &bob_public,+ Some((alice_secret.as_str(), "pw12345678")),+ plaintext,+ )+ .expect("signed encrypt");+ // Bob decrypts and verifies against Alice's public key.+ let (back, signer_fp) =+ pgp_decrypt_verify(&bob_secret, "pw87654321", &raw, Some(&alice_public))+ .expect("decrypt+verify");+ assert_eq!(back, plaintext, "round-trip plaintext");+ assert_eq!(signer_fp, alice_fp, "signer fingerprint matches Alice");+}++#[test]+fn detached_signature_verifies_and_rejects_tamper() {+ use pgp::composed::{Deserializable, DetachedSignature, SignedPublicKey};+ let (secret, public, _) =+ pgp_generate("alias <[email protected]>", "pw12345678").expect("keygen");+ let data = b"maemail-sub-v1\[email protected]";+ let sig_bytes = pgp_sign_detached(&secret, "pw12345678", data).expect("sign");+ let sig = DetachedSignature::from_bytes(&sig_bytes[..]).expect("parse sig");+ let (key, _) = SignedPublicKey::from_string(&public).expect("parse key");+ assert!(sig.verify(&key.primary_key, data).is_ok(), "verifies over exact bytes");+ assert!(sig.verify(&key.primary_key, b"other bytes").is_err(), "tamper rejected");+ assert!(pgp_sign_detached(&secret, "wrong", data).is_none(), "wrong passphrase");+}++#[test]+fn unsigned_message_verifies_empty_but_decrypts() {+ let (alice_secret, alice_public, _) =+ pgp_generate("alice <[email protected]>", "pw12345678").expect("alice keygen");+ let (bob_secret, bob_public, _) =+ pgp_generate("bob <[email protected]>", "pw87654321").expect("bob keygen");+ // Encrypt-only (no signer): accepted, empty fingerprint.+ let raw = pgp_encrypt_signed(&bob_public, None, b"unsigned hello").expect("encrypt");+ let (back, signer_fp) =+ pgp_decrypt_verify(&bob_secret, "pw87654321", &raw, Some(&alice_public))+ .expect("unsigned must still decrypt");+ assert_eq!(back, b"unsigned hello");+ assert!(signer_fp.is_empty(), "no signer fingerprint for unsigned");+ let _ = (alice_secret, alice_public);+}++#[test]+fn tampered_signature_fails_verify() {+ let (alice_secret, _, _) =+ pgp_generate("alice <[email protected]>", "pw12345678").expect("alice keygen");+ let (bob_secret, bob_public, _) =+ pgp_generate("bob <[email protected]>", "pw87654321").expect("bob keygen");+ let (_, carol_public, _) =+ pgp_generate("carol <[email protected]>", "pw00000000").expect("carol keygen");+ let raw = pgp_encrypt_signed(+ &bob_public,+ Some((alice_secret.as_str(), "pw12345678")),+ b"signed hello",+ )+ .expect("signed encrypt");+ // Verifying against the WRONG key (Carol, not Alice) must fail closed.+ assert!(+ pgp_decrypt_verify(&bob_secret, "pw87654321", &raw, Some(&carol_public)).is_none(),+ "wrong verifier key must fail"+ );+}++#[test]+fn tampered_ciphertext_fails_decrypt() {+ let (alice_secret, _, _) =+ pgp_generate("alice <[email protected]>", "pw12345678").expect("alice keygen");+ let (bob_secret, bob_public, _) =+ pgp_generate("bob <[email protected]>", "pw87654321").expect("bob keygen");+ let mut raw = pgp_encrypt_signed(+ &bob_public,+ Some((alice_secret.as_str(), "pw12345678")),+ b"signed hello",+ )+ .expect("signed encrypt");+ // Flip a byte late in the ciphertext (inside the encrypted session data).+ let last = raw.len() - 1;+ raw[last] ^= 0x01;+ assert!(+ pgp_decrypt_verify(&bob_secret, "pw87654321", &raw, None).is_none(),+ "tampered ciphertext must fail"+ );+}++#[test]+fn malformed_inputs_fail_cleanly() {+ assert!(pgp_fingerprint("not armor at all").is_none());+ assert!(pgp_encrypt("not armor at all", b"x").is_none());+ assert!(pgp_decrypt("not armor at all", "pw", b"x").is_none());+}++#[test]+fn armor_message_roundtrip() {+ let (_, public, _) = pgp_generate("alice <[email protected]>", "pw12345678")+ .expect("keygen");+ let raw = pgp_encrypt(&public, b"federation body").expect("encrypt");+ let armored = to_armored_message(&raw).expect("armor");+ assert!(+ armored.starts_with("-----BEGIN PGP MESSAGE-----"),+ "message armor header"+ );+ assert!(armored.contains("-----END PGP MESSAGE-----"), "message armor footer");+ let back = dearmor_any(&armored).expect("dearmor");+ assert_eq!(back, raw, "armor round-trips raw bytes");+}++#[test]+fn normalize_accepts_binary_and_armor() {+ use pgp::composed::{Deserializable, SignedPublicKey};+ let (_, public, fp) = pgp_generate("alice <[email protected]>", "pw12345678")+ .expect("keygen");+ // Armor in → canonical armor out with the same fingerprint.+ let normalized = pgp_normalize_key(public.as_bytes()).expect("normalize armor");+ assert!(normalized.contains("-----BEGIN PGP PUBLIC KEY BLOCK-----"));+ let (reparsed, _) = SignedPublicKey::from_string(&normalized).expect("reparse");+ assert_eq!(fingerprint_of(&reparsed), fp);+ // Binary (WKD-style record) in → armor out.+ let binary = dearmor_any(&public).expect("dearmor for binary form");+ assert!(!binary.starts_with(b"-----BEGIN"));+ let normalized_bin = pgp_normalize_key(&binary).expect("normalize binary");+ assert!(normalized_bin.contains("-----BEGIN PGP PUBLIC KEY BLOCK-----"));+ // Garbage fails cleanly.+ assert!(pgp_normalize_key(b"not a key").is_none());+ assert!(pgp_normalize_key(b"-----BEGIN PGP MESSAGE-----\n\nAAAA\n=ABCD\n-----END PGP MESSAGE-----\n").is_none());+}++fn fingerprint_of(_key: &pgp::composed::SignedPublicKey) -> String {+ use pgp::types::KeyDetails;+ let fp = _key.fingerprint();+ let bytes = fp.as_bytes();+ const HEX: &[u8; 16] = b"0123456789ABCDEF";+ let mut out = String::with_capacity(bytes.len() * 2);+ for b in bytes {+ out.push(HEX[(b >> 4) as usize] as char);+ out.push(HEX[(b & 0x0f) as usize] as char);+ }+ out+}
library/e2ee-openpgp/test/java/com/vayunmathur/e2ee/PgpTest.kt
diff --git a/library/e2ee-openpgp/test/java/com/vayunmathur/e2ee/PgpTest.kt b/library/e2ee-openpgp/test/java/com/vayunmathur/e2ee/PgpTest.ktnew file mode 100644index 0000000000..ed20055ed6--- /dev/null+++ b/library/e2ee-openpgp/test/java/com/vayunmathur/e2ee/PgpTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.e2ee++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlin.test.assertFailsWith++class PgpTest {++ @Test+ fun generateEncryptDecryptRoundtrip() {+ val identity = Pgp.generateIdentity("alice <[email protected]>", "correct horse battery")+ assertTrue(identity.armoredSecret.contains("PGP PRIVATE KEY BLOCK"))+ assertTrue(identity.armoredPublic.contains("PGP PUBLIC KEY BLOCK"))+ assertEquals(40, identity.fingerprintHex.length)++ val plaintext = "Hello from SecureMail".toByteArray(Charsets.UTF_8)+ val raw = Pgp.encrypt(identity.armoredPublic, plaintext)+ assertTrue(raw.isNotEmpty())++ val back = Pgp.decrypt(identity.armoredSecret, "correct horse battery", raw)+ assertEquals(plaintext.toList(), back.toList())+ }++ @Test+ fun wrongPassphraseFails() {+ val identity = Pgp.generateIdentity("alice <[email protected]>", "correct horse battery")+ val raw = Pgp.encrypt(identity.armoredPublic, "secret".toByteArray(Charsets.UTF_8))+ assertFailsWith<IllegalStateException> {+ Pgp.decrypt(identity.armoredSecret, "wrong passphrase", raw)+ }+ }++ @Test+ fun fingerprintStable() {+ val identity = Pgp.generateIdentity("alice <[email protected]>", "correct horse battery")+ assertEquals(identity.fingerprintHex, Pgp.fingerprintHex(identity.armoredPublic))+ }++ @Test+ fun armorMessageRoundtrip() {+ val identity = Pgp.generateIdentity("alice <[email protected]>", "correct horse battery")+ val raw = Pgp.encrypt(identity.armoredPublic, "federation".toByteArray(Charsets.UTF_8))+ val armored = Pgp.armorMessage(raw)+ assertTrue(armored.startsWith("-----BEGIN PGP MESSAGE-----"))+ assertTrue(armored.contains("-----END PGP MESSAGE-----"))+ }++ @Test+ fun signedEncryptVerifyRoundtrip() {+ val alice = Pgp.generateIdentity("alice <[email protected]>", "alice-pw-123")+ val bob = Pgp.generateIdentity("bob <[email protected]>", "bob-pw-456")+ val plaintext = "signed hello".toByteArray(Charsets.UTF_8)+ val raw = Pgp.encryptSigned(+ bob.armoredPublic, alice.armoredSecret, "alice-pw-123", plaintext,+ )+ assertTrue(raw.isNotEmpty())+ val verified = Pgp.decryptVerify(+ bob.armoredSecret, "bob-pw-456", raw, alice.armoredPublic,+ )+ assertEquals(plaintext.toList(), verified.payload.toList())+ assertEquals(alice.fingerprintHex, verified.signerFingerprintHex)+ }++ @Test+ fun unsignedMessageVerifiesEmpty() {+ val alice = Pgp.generateIdentity("alice <[email protected]>", "alice-pw-123")+ val bob = Pgp.generateIdentity("bob <[email protected]>", "bob-pw-456")+ // Empty sender secret = encrypt-only, same as encrypt().+ val raw = Pgp.encryptSigned(+ bob.armoredPublic, "", "alice-pw-123",+ "unsigned hello".toByteArray(Charsets.UTF_8),+ )+ val verified = Pgp.decryptVerify(+ bob.armoredSecret, "bob-pw-456", raw, alice.armoredPublic,+ )+ assertEquals("unsigned hello".toByteArray(Charsets.UTF_8).toList(), verified.payload.toList())+ assertTrue(verified.signerFingerprintHex.isEmpty())+ }++ @Test+ fun wrongVerifierKeyFails() {+ val alice = Pgp.generateIdentity("alice <[email protected]>", "alice-pw-123")+ val bob = Pgp.generateIdentity("bob <[email protected]>", "bob-pw-456")+ val carol = Pgp.generateIdentity("carol <[email protected]>", "carol-pw-789")+ val raw = Pgp.encryptSigned(+ bob.armoredPublic, alice.armoredSecret, "alice-pw-123",+ "signed hello".toByteArray(Charsets.UTF_8),+ )+ assertFailsWith<IllegalStateException> {+ Pgp.decryptVerify(bob.armoredSecret, "bob-pw-456", raw, carol.armoredPublic)+ }+ }+}
library/e2ee-p2p/build.gradle.kts
diff --git a/library/e2ee-p2p/build.gradle.kts b/library/e2ee-p2p/build.gradle.ktsindex 9752118d88..51332b319f 100644--- a/library/e2ee-p2p/build.gradle.kts+++ b/library/e2ee-p2p/build.gradle.kts@@ -19,6 +19,8 @@ androidComponents { // Native post-quantum crypto (Rust: fips203 ML-KEM-768 + fips204 ML-DSA-65). // See library/e2ee-p2p/src/main/rust/. Replaces Bouncy Castle; keys cross as DER, // byte-compatible with the previously-deployed BC encoding.+// OpenPGP (rPGP) used to live in this crate too; it moved to :library:e2ee-openpgp's+// `e2ee_pgp` crate so non-mail apps don't link the PGP cipher suite (#873). // armeabi-v7a as well as arm64: :cast:tv runs on 32-bit-userspace Google TV hardware // and links this .so. Phone apps filter it back out via their arm64-only abiFilters. rustNativeLib("e2ee_pqc", "e2ee-pqc", extraAbis = listOf(ABI_ARMV7))
library/e2ee-p2p/src/main/rust/Cargo.toml
diff --git a/library/e2ee-p2p/src/main/rust/Cargo.toml b/library/e2ee-p2p/src/main/rust/Cargo.tomlindex 5e1ecffc92..ac8582573c 100644--- a/library/e2ee-p2p/src/main/rust/Cargo.toml+++ b/library/e2ee-p2p/src/main/rust/Cargo.toml@@ -18,13 +18,3 @@ shake.workspace = true jni.workspace = true rand.workspace = true rand_core.workspace = true-# rand 0.8 for rPGP keygen/encrypt RNG (workspace default is 0.10; see root).-rand08.workspace = true-# OpenPGP packet engine for SecureMail (generate/armor/encrypt/decrypt).-# Same crate as the relay server would use; the JNI surface below exposes only-# what the app needs (no WKD/SMTP — those stay in Kotlin via library:network).-pgp.workspace = true-# Base64 framing for PGP/MIME armor output (workspace pin, betocore line).-base64.workspace = true-# smallvec! for rPGP key-preference lists (workspace pin, betocore line).-smallvec.workspace = true
library/e2ee-p2p/src/main/rust/src/lib.rs
diff --git a/library/e2ee-p2p/src/main/rust/src/lib.rs b/library/e2ee-p2p/src/main/rust/src/lib.rsindex 8e197aebed..07424141b1 100644--- a/library/e2ee-p2p/src/main/rust/src/lib.rs+++ b/library/e2ee-p2p/src/main/rust/src/lib.rs@@ -239,11 +239,6 @@ pub fn mldsa_verify_der(pub_der: &[u8], msg: &[u8], sig: &[u8]) -> bool { mod jni_bridge; mod c_bridge;-pub mod pgp;-mod pgp_jni; #[cfg(test)] mod tests;--#[cfg(test)]-mod pgp_tests;
securemail/build.gradle.kts
diff --git a/securemail/build.gradle.kts b/securemail/build.gradle.ktsindex fcae4ac396..44336c3e8e 100644--- a/securemail/build.gradle.kts+++ b/securemail/build.gradle.kts@@ -37,6 +37,8 @@ dependencies { implementRoom(libs) // Address token + onboarded flag. implementation(libs.androidx.datastore.preferences)- // OpenPGP via the native Rust core (rPGP in libe2ee_pqc.so). No BouncyCastle.- implementation(project(":library:e2ee-p2p"))+ // OpenPGP via the native Rust core (rPGP in libe2ee_pgp.so). No BouncyCastle.+ // Split out of :library:e2ee-p2p so non-mail apps don't link rPGP (#873);+ // securemail is the only consumer of the PGP surface.+ implementation(project(":library:e2ee-openpgp")) }
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 907d06dd01..78a005f250 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -37,6 +37,7 @@ include(":library:ui") include(":library:room") include(":library:ink") include(":library:e2ee-p2p")+include(":library:e2ee-openpgp") include(":library:everysync-core") include(":library:widgets") include(":library:work")