Modern Apps git

← Modern-Apps.git

securemail: standard PGP/MIME so Proton and other clients can decrypt

Commit
90aa2c81b3a8e4c6976287e4e4561f6f23595170
Author
Vayun Mathur <[email protected]>
When
2026-11-02 01:38 UTC (1 month ago)
Parents
a4d0753
Encrypted mail to other providers was unreadable. RFC 3156 requires the
second part of multipart/encrypted to be an ASCII-armored PGP MESSAGE;
buildEncryptedBody instead put bare base64 of the binary ciphertext
there with no Content-Transfer-Encoding, which Proton, GnuPG and
Thunderbird do not treat as an OpenPGP message (it shows up as an opaque
encrypted.asc attachment). Key discovery to Proton already worked (WKD
at openpgpkey.proton.me) - only the envelope format was wrong.

Sending
- The data part is now PgpCrypto.armorMessage(...) (rPGP-tested armor:
  BEGIN/END lines, 64-col body, CRC24), CRLF line endings. The control
  part gains the conventional Content-Description.
- The encrypted inner text/plain part is marked protected-headers="v1"
  so Proton/Thunderbird show the real (encrypted) Subject instead of the
  outer "(encrypted message)" placeholder the server puts on the wire.

Receiving
- MimeCodec.extractPgpPayloadB64 now reads armored PGP MESSAGE parts
  (with or without armor headers such as "Version: ProtonMail"), which is
  what Proton and every standard client send, and what SecureMail now
  sends itself. Older SecureMail bare-base64 blobs still parse, and the
  legacy path ends at any MIME boundary rather than only "--maemail-",
  so a foreign boundary no longer swallows the closing delimiter.

Verified: new MimeCodecTest (Proton-style armored part, header-less
armor, legacy bare base64, non-PGP rejection) plus the existing
securemail unit tests; :securemail:lint clean; detekt unchanged at 40.
Not yet sent to a real Proton mailbox.

Diff

securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.kt b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.ktindex 79df56af3f..1d76aa4b87 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.kt@@ -9,34 +9,55 @@ object MimeCodec {      /**      * Extracts the raw PGP bytes from an RFC 3156 multipart/encrypted envelope-     * (second part, base64 `application/octet-stream`). Returns the base64-     * payload string, or null when the input is not such an envelope (legacy-     * bare blobs pass through undecrypted at a higher layer).+     * as base64. The data part is normally an ASCII-armored `PGP MESSAGE`+     * (what Proton/GnuPG/Thunderbird send, and what SecureMail sends since it+     * federates); older SecureMail blobs carried bare base64 instead, which is+     * still accepted. Returns null when the input is not such an envelope.      */     fun extractPgpPayloadB64(envelope: ByteArray): String? {         return try {             val text = envelope.toString(Charsets.UTF_8)             if (!text.contains("application/pgp-encrypted")) return null-            // Split on boundary markers; the data part follows the octet-stream header.+            val armorStart = text.indexOf(ARMOR_BEGIN)+            if (armorStart >= 0) return dearmorBody(text.substring(armorStart))+            // Legacy bare-base64 part: body follows the octet-stream headers and+            // runs to the next MIME boundary line (any boundary, not just ours).             val octetIdx = text.indexOf("application/octet-stream")             if (octetIdx < 0) return null             val bodyStart = text.indexOf("\r\n\r\n", octetIdx).takeIf { it >= 0 }                 ?: text.indexOf("\n\n", octetIdx).takeIf { it >= 0 }                 ?: return null-            val afterHeaders = if (text.startsWith("\r\n\r\n", bodyStart)) {-                text.substring(bodyStart + 4)-            } else {-                text.substring(bodyStart + 2)-            }-            // Cut at the closing boundary; de-whitespace the base64.-            val end = afterHeaders.indexOf("--maemail-").takeIf { it >= 0 } ?: afterHeaders.length-            val b64 = afterHeaders.substring(0, end).filterNot { it.isWhitespace() }-            if (b64.isEmpty()) null else b64+            val b64 = text.substring(bodyStart).lineSequence()+                .map { it.trim() }+                .dropWhile { it.isEmpty() }+                .takeWhile { !it.startsWith("--") }+                .joinToString("")+            b64.ifEmpty { null }         } catch (_: Exception) {             null         }     } +    /**+     * Base64 body of an armored block starting at `-----BEGIN PGP MESSAGE-----`+     * (RFC 9580 §6.2): skips armor headers (`Key: value` up to the blank line),+     * stops at the CRC24 line (`=xxxx`) or the END line.+     */+    private fun dearmorBody(armored: String): String? {+        val lines = armored.lineSequence().map { it.trim() }.drop(1).toList()+        val bodyStart = if (lines.firstOrNull()?.contains(": ") == true) {+            lines.indexOfFirst { it.isEmpty() }.takeIf { it >= 0 }?.plus(1) ?: return null+        } else {+            lines.indexOfFirst { it.isNotEmpty() }.takeIf { it >= 0 } ?: return null+        }+        val b64 = lines.drop(bodyStart)+            .takeWhile { !it.startsWith("=") && !it.startsWith("-----") }+            .joinToString("")+        return b64.ifEmpty { null }+    }++    private const val ARMOR_BEGIN = "-----BEGIN PGP MESSAGE-----"+     /**      * Minimal parser for the MIME skeleton the composer emits (headers +      * trailing `--boundary--`). Returns (subject, body, from). The payload is
securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.ktindex 9663e3d24d..2535d47d0c 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt@@ -755,7 +755,7 @@ class MailViewModel(app: Application) : AndroidViewModel(app) {                 "Subject: $safeSubject\r\n" +                 "Message-ID: <${newMessageId()}>\r\n" +                 "MIME-Version: 1.0\r\n" +-                "Content-Type: text/plain; charset=utf-8\r\n" ++                "Content-Type: text/plain; charset=utf-8; protected-headers=\"v1\"\r\n" +                 "Content-Transfer-Encoding: 8bit\r\n" +                 "\r\n" +                 "$body\r\n"@@ -769,15 +769,16 @@ class MailViewModel(app: Application) : AndroidViewModel(app) {      */     private fun buildEncryptedBody(encrypted: ByteArray): ByteArray {         val boundary = "maemail-${UUID.randomUUID().toString().take(8)}"-        val armor = android.util.Base64.encodeToString(encrypted, android.util.Base64.NO_WRAP)-        // Fold armor at 64 cols per RFC 3156 line-length limits.-        val folded = armor.chunked(64).joinToString("\r\n")+        // RFC 3156 §4: the second part is an ASCII-armored PGP MESSAGE. Proton,+        // GnuPG and Thunderbird reject a bare base64 body here.+        val armored = PgpCrypto.armorMessage(encrypted).trimEnd().lines().joinToString("\r\n")         return (             "MIME-Version: 1.0\r\n" +                 "Content-Type: multipart/encrypted; boundary=\"$boundary\"; protocol=\"application/pgp-encrypted\"\r\n" +                 "\r\n" +                 "--$boundary\r\n" +                 "Content-Type: application/pgp-encrypted\r\n" ++                "Content-Description: PGP/MIME version identification\r\n" +                 "\r\n" +                 "Version: 1\r\n" +                 "\r\n" +@@ -786,7 +787,7 @@ class MailViewModel(app: Application) : AndroidViewModel(app) {                 "Content-Description: OpenPGP encrypted message\r\n" +                 "Content-Disposition: inline; filename=\"encrypted.asc\"\r\n" +                 "\r\n" +-                "$folded\r\n" ++                "$armored\r\n" +                 "--$boundary--\r\n"             ).toByteArray(Charsets.UTF_8)     }
securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.ktnew file mode 100644index 0000000000..8b64a43f97--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.kt@@ -0,0 +1,58 @@+package com.vayunmathur.securemail.domain.mail++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++class MimeCodecTest {++    private fun envelope(boundary: String, dataPart: String) = (+        "Content-Type: multipart/encrypted; boundary=\"$boundary\"; protocol=\"application/pgp-encrypted\"\r\n" ++            "\r\n" ++            "--$boundary\r\n" ++            "Content-Type: application/pgp-encrypted\r\n" ++            "\r\n" ++            "Version: 1\r\n" ++            "\r\n" ++            "--$boundary\r\n" ++            "Content-Type: application/octet-stream; name=\"encrypted.asc\"\r\n" ++            "\r\n" ++            dataPart ++            "--$boundary--\r\n"+        ).toByteArray()++    @Test+    fun armoredPartFromAnotherClient() {+        val proton = envelope(+            "------------ProtonBoundary0123",+            "-----BEGIN PGP MESSAGE-----\r\n" ++                "Version: ProtonMail\r\n" ++                "\r\n" ++                "wV4DAAEC\r\n" ++                "AwQF\r\n" ++                "=ABCD\r\n" ++                "-----END PGP MESSAGE-----\r\n",+        )+        assertEquals("wV4DAAECAwQF", MimeCodec.extractPgpPayloadB64(proton))+    }++    @Test+    fun armoredPartWithoutHeaders() {+        val ours = envelope(+            "maemail-1234abcd",+            "-----BEGIN PGP MESSAGE-----\r\n\r\nwV4DAAEC\r\n=ABCD\r\n-----END PGP MESSAGE-----\r\n",+        )+        assertEquals("wV4DAAEC", MimeCodec.extractPgpPayloadB64(ours))+    }++    @Test+    fun legacyBareBase64StillParses() {+        val legacy = envelope("maemail-1234abcd", "wV4DAAEC\r\nAwQF\r\n")+        assertEquals("wV4DAAECAwQF", MimeCodec.extractPgpPayloadB64(legacy))+    }++    @Test+    fun nonPgpMimeIsRejected() {+        assertNull(MimeCodec.extractPgpPayloadB64("Content-Type: text/plain\r\n\r\nhello\r\n".toByteArray()))+    }+}