Modern Apps git

← Modern-Apps.git

pdf: cryptographic PKCS#7 digital signing

Commit
bbbd59079872f12aa57a461ce7d4a381dc7bd82e
Author
Vayun Mathur <[email protected]>
When
2026-07-09 16:44 UTC (5 months ago)
Parents
f611d77

Diff

gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex e63aa8eade..27efcc1bdd 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -208,6 +208,7 @@ protobuf-java = { module = "com.google.protobuf:protobuf-java", version.ref = "p zxing-core = { module = "com.google.zxing:core", version.ref = "zxing" } keepassjava2-dom = { module = "org.linguafranca.pwdb:KeePassJava2-dom", version.ref = "keepassJava2" } bouncycastle = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" }+bouncycastle-pkix = { module = "org.bouncycastle:bcpkix-jdk18on", version.ref = "bouncycastle" }  [plugins] android-application = { id = "com.android.application", version.ref = "agp" }
pdf/build.gradle.kts
diff --git a/pdf/build.gradle.kts b/pdf/build.gradle.ktsindex 9cbec21456..a803cc269b 100644--- a/pdf/build.gradle.kts+++ b/pdf/build.gradle.kts@@ -116,5 +116,7 @@ dependencies {     implementation(libs.coil.compose)     implementation(libs.reorderable)     implementation(libs.material)+    implementation(libs.bouncycastle)+    implementation(libs.bouncycastle.pkix)     implementation(project(":library:ocr")) }
pdf/rust/src/lib.rs
diff --git a/pdf/rust/src/lib.rs b/pdf/rust/src/lib.rsindex 0c859b3d33..5d466c36c2 100644--- a/pdf/rust/src/lib.rs+++ b/pdf/rust/src/lib.rs@@ -3328,6 +3328,80 @@ fn save_document(handle: i64) -> Option<Vec<u8>> {     Some(buf) } +/// Build a signature-ready PDF: an invisible signature field + `/Sig` dict with a+/// fixed-width `/ByteRange` placeholder and a `contents_bytes`-long zero+/// `/Contents`. Kotlin patches the ByteRange and fills the detached PKCS#7+/// signature. Returns the serialized bytes.+fn prepare_signature(handle: i64, name: &str, contents_bytes: usize) -> Option<Vec<u8>> {+    let bytes = save_document(handle)?;+    let mut doc = Document::load_mem(&bytes).ok()?;+    let page0 = doc.get_pages().values().next().copied()?;+    let catalog_id = doc.trailer.get(b"Root").ok().and_then(|o| o.as_reference().ok())?;++    let mut sig = Dictionary::new();+    sig.set("Type", name_obj("Sig"));+    sig.set("Filter", name_obj("Adobe.PPKLite"));+    sig.set("SubFilter", name_obj("adbe.pkcs7.detached"));+    sig.set(+        "ByteRange",+        Object::Array(vec![+            Object::Integer(0),+            Object::Integer(2_000_000_000),+            Object::Integer(2_000_000_000),+            Object::Integer(2_000_000_000),+        ]),+    );+    sig.set(+        "Contents",+        Object::String(vec![0u8; contents_bytes], lopdf::StringFormat::Hexadecimal),+    );+    sig.set("Name", Object::string_literal(name));+    let sig_id = doc.add_object(sig);++    let mut widget = Dictionary::new();+    widget.set("Type", name_obj("Annot"));+    widget.set("Subtype", name_obj("Widget"));+    widget.set("FT", name_obj("Sig"));+    widget.set("T", Object::string_literal("Signature1"));+    widget.set("V", Object::Reference(sig_id));+    widget.set("P", Object::Reference(page0));+    widget.set("Rect", Object::Array(vec![0.into(), 0.into(), 0.into(), 0.into()]));+    widget.set("F", Object::Integer(132));+    let widget_id = doc.add_object(widget);+    append_annot(&mut doc, page0, widget_id);++    // Attach the field to the AcroForm (reuse/extend existing, else create one).+    let af_ref = doc+        .get_dictionary(catalog_id)+        .ok()+        .and_then(|c| c.get(b"AcroForm").ok())+        .and_then(|o| o.as_reference().ok());+    if let Some(af_id) = af_ref {+        if let Ok(af) = doc.get_dictionary_mut(af_id) {+            let has_fields = matches!(af.get(b"Fields"), Ok(Object::Array(_)));+            if !has_fields {+                af.set("Fields", Object::Array(vec![]));+            }+            if let Ok(Object::Array(a)) = af.get_mut(b"Fields") {+                a.push(Object::Reference(widget_id));+            }+            af.set("SigFlags", Object::Integer(3));+        }+    } else {+        let mut af = Dictionary::new();+        af.set("Fields", Object::Array(vec![Object::Reference(widget_id)]));+        af.set("SigFlags", Object::Integer(3));+        let af_id = doc.add_object(af);+        if let Ok(cat) = doc.get_dictionary_mut(catalog_id) {+            cat.set("AcroForm", Object::Reference(af_id));+        }+    }++    let mut out = Vec::new();+    doc.save_to(&mut out).ok()?;+    Some(out)+}+ /// Extract the document's visible text (from rendered text primitives), one /// blank line between pages. fn document_text(handle: i64) -> Option<String> {@@ -5722,6 +5796,19 @@ mod jni_bindings {         bytes_or_null(&env, save_document(handle as i64))     } +    /// `PdfNative.prepareSignature(long, String, int) -> byte[]`.+    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_prepareSignature<'local>(+        mut env: JNIEnv<'local>,+        _class: JClass<'local>,+        handle: jlong,+        name: JString<'local>,+        contents_bytes: jint,+    ) -> jbyteArray {+        let n = jstr(&mut env, &name);+        bytes_or_null(&env, prepare_signature(handle as i64, &n, contents_bytes.max(0) as usize))+    }+     /// `PdfNative.saveCompressed(long) -> byte[]`.     #[no_mangle]     pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_saveCompressed<'local>(
pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.ktindex 6531c431f5..b8e063ab38 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt@@ -625,6 +625,25 @@ fun SafePdfViewerScreen(uri: Uri, onBack: () -> Unit) {      var showEncrypt by remember { mutableStateOf(false) }     var pendingEncryptPw by remember { mutableStateOf<String?>(null) }+    val signLauncher = rememberLauncherForActivityResult(+        ActivityResultContracts.CreateDocument("application/pdf")+    ) { outUri ->+        val doc = document+        if (outUri != null && doc != null) scope.launch {+            val signerName = android.os.Build.MODEL ?: "PDF Signer"+            val bytes = doc.sign(signerName)+            withContext(Dispatchers.IO) {+                if (bytes != null) {+                    runCatching { context.contentResolver.openOutputStream(outUri)?.use { it.write(bytes) } }+                }+            }+            android.widget.Toast.makeText(+                context,+                if (bytes != null) "Signed & saved" else "Signing failed",+                android.widget.Toast.LENGTH_SHORT,+            ).show()+        }+    }     val encryptLauncher = rememberLauncherForActivityResult(         ActivityResultContracts.CreateDocument("application/pdf")     ) { outUri ->@@ -779,6 +798,9 @@ fun SafePdfViewerScreen(uri: Uri, onBack: () -> Unit) {                             IconButton({ showEncrypt = true }) {                                 Icon(painterResource(R.drawable.ic_lock), contentDescription = "Encrypt with password")                             }+                            IconButton({ signLauncher.launch((uri.lastPathSegment ?: "document") + "-signed.pdf") }) {+                                Icon(painterResource(R.drawable.ic_signature), contentDescription = "Sign document")+                            }                         }                         if (editMode) {                             IconButton({ undo() }, enabled = undoStack.isNotEmpty()) {
pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.ktindex b9f0e065db..6c06da01de 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt@@ -164,6 +164,9 @@ object PdfNative {     /** Serialize the modified document to PDF bytes, or null on failure. */     external fun saveDocument(handle: Long): ByteArray? +    /** Build a signature-ready PDF (placeholder /ByteRange + /Contents) for signing. */+    external fun prepareSignature(handle: Long, name: String, contentsBytes: Int): ByteArray?+     /** Serialize with streams compressed + unused objects pruned, or null. */     external fun saveCompressed(handle: Long): ByteArray? 
pdf/src/main/java/com/vayunmathur/pdf/util/PdfSigner.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfSigner.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfSigner.ktnew file mode 100644index 0000000000..c5a4971fe5--- /dev/null+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfSigner.kt@@ -0,0 +1,139 @@+package com.vayunmathur.pdf.util++import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter+import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder+import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder+import org.bouncycastle.cms.CMSProcessableByteArray+import org.bouncycastle.cms.CMSSignedDataGenerator+import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder+import org.bouncycastle.jce.provider.BouncyCastleProvider+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder+import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder+import org.bouncycastle.asn1.x500.X500Name+import java.io.ByteArrayOutputStream+import java.math.BigInteger+import java.security.KeyPairGenerator+import java.security.PrivateKey+import java.security.cert.X509Certificate+import java.util.Date++/**+ * Produces a cryptographically signed PDF (detached PKCS#7 / adbe.pkcs7.detached)+ * from a signature-ready PDF built by [PdfNative.prepareSignature]. Uses a+ * freshly generated self-signed RSA certificate. The signed PDF validates its+ * own byte-range digest; trust must be established out of band (self-signed).+ */+object PdfSigner {+    /** Size (bytes) of the /Contents placeholder; must fit the CMS signature. */+    const val CONTENTS_BYTES = 8192++    private val bc = BouncyCastleProvider()++    /** Patch [prepared] (from prepareSignature) with a real detached signature. */+    fun sign(prepared: ByteArray, name: String): ByteArray? {+        val buf = prepared.copyOf()++        val brKey = indexOf(buf, "/ByteRange".toByteArray(), 0)+        if (brKey < 0) return null+        val brOpen = indexOfByte(buf, '['.code.toByte(), brKey)+        val brClose = indexOfByte(buf, ']'.code.toByte(), brOpen)+        if (brOpen < 0 || brClose < 0) return null++        val cKey = indexOf(buf, "/Contents".toByteArray(), brKey)+        if (cKey < 0) return null+        val cOpen = indexOfByte(buf, '<'.code.toByte(), cKey)+        val cClose = indexOfByte(buf, '>'.code.toByte(), cOpen)+        if (cOpen < 0 || cClose < 0) return null++        // Signature covers everything except the Contents value (incl. < and >).+        val a = cOpen+        val b = cClose + 1+        val c = buf.size - b++        // Patch /ByteRange in place (fixed-width slot, so offsets don't shift).+        val slot = brClose - (brOpen + 1)+        val br = "0 $a $b $c"+        if (br.length > slot) return null+        val padded = br.padEnd(slot, ' ').toByteArray(Charsets.US_ASCII)+        System.arraycopy(padded, 0, buf, brOpen + 1, slot)++        // Build the detached CMS over the two byte ranges.+        val content = ByteArrayOutputStream(a + c).apply {+            write(buf, 0, a)+            write(buf, b, c)+        }.toByteArray()++        val (key, cert) = generateKeyAndCert(name)+        val cms = buildDetachedCms(content, key, cert) ?: return null++        val hex = toHex(cms)+        val hexSlot = cClose - (cOpen + 1)+        if (hex.length > hexSlot) return null // signature too large for placeholder+        val hexPadded = hex.padEnd(hexSlot, '0').toByteArray(Charsets.US_ASCII)+        System.arraycopy(hexPadded, 0, buf, cOpen + 1, hexSlot)+        return buf+    }++    private fun buildDetachedCms(+        content: ByteArray,+        key: PrivateKey,+        cert: X509Certificate,+    ): ByteArray? = runCatching {+        val signer = JcaContentSignerBuilder("SHA256withRSA").setProvider(bc).build(key)+        val digestProvider = JcaDigestCalculatorProviderBuilder().setProvider(bc).build()+        val gen = CMSSignedDataGenerator()+        gen.addSignerInfoGenerator(+            JcaSignerInfoGeneratorBuilder(digestProvider).build(signer, cert)+        )+        gen.addCertificate(JcaX509CertificateHolder(cert))+        val processable = CMSProcessableByteArray(content)+        gen.generate(processable, false).encoded // detached+    }.getOrNull()++    private fun generateKeyAndCert(name: String): Pair<PrivateKey, X509Certificate> {+        val kpg = KeyPairGenerator.getInstance("RSA")+        kpg.initialize(2048)+        val kp = kpg.generateKeyPair()+        val now = Date()+        val end = Date(now.time + 3650L * 24 * 60 * 60 * 1000)+        val subject = X500Name("CN=${name.ifBlank { "PDF Signer" }}")+        val serial = BigInteger.valueOf(System.currentTimeMillis())+        val builder = JcaX509v3CertificateBuilder(subject, serial, now, end, subject, kp.public)+        val certSigner = JcaContentSignerBuilder("SHA256withRSA").setProvider(bc).build(kp.private)+        val holder = builder.build(certSigner)+        val cert = JcaX509CertificateConverter().setProvider(bc).getCertificate(holder)+        return kp.private to cert+    }++    private fun toHex(bytes: ByteArray): String {+        val sb = StringBuilder(bytes.size * 2)+        val hex = "0123456789abcdef"+        for (x in bytes) {+            val v = x.toInt() and 0xFF+            sb.append(hex[v ushr 4]).append(hex[v and 0x0F])+        }+        return sb.toString()+    }++    private fun indexOf(haystack: ByteArray, needle: ByteArray, from: Int): Int {+        var i = from.coerceAtLeast(0)+        val last = haystack.size - needle.size+        while (i <= last) {+            var j = 0+            while (j < needle.size && haystack[i + j] == needle[j]) j+++            if (j == needle.size) return i+            i+++        }+        return -1+    }++    private fun indexOfByte(haystack: ByteArray, b: Byte, from: Int): Int {+        if (from < 0) return -1+        var i = from+        while (i < haystack.size) {+            if (haystack[i] == b) return i+            i+++        }+        return -1+    }+}
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.ktindex ed6f7925f6..aa0ecb2cb3 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt@@ -169,6 +169,12 @@ class SafePdfDocument private constructor(     /** Serialize the (possibly edited) document to PDF bytes. */     suspend fun save(): ByteArray? = withContext(Dispatchers.IO) { PdfNative.saveDocument(handle) } +    /** Digitally sign the document (self-signed cert) and return the signed bytes. */+    suspend fun sign(name: String): ByteArray? = withContext(Dispatchers.IO) {+        val prepared = PdfNative.prepareSignature(handle, name, PdfSigner.CONTENTS_BYTES) ?: return@withContext null+        PdfSigner.sign(prepared, name)+    }+     /** Add a redaction annotation over the rect; returns id (0 on failure). */     suspend fun addRedaction(         index: Int, x0: Float, y0: Float, x1: Float, y1: Float,
pdf/src/main/res/drawable/ic_signature.xml
diff --git a/pdf/src/main/res/drawable/ic_signature.xml b/pdf/src/main/res/drawable/ic_signature.xmlnew file mode 100644index 0000000000..988fa4dc81--- /dev/null+++ b/pdf/src/main/res/drawable/ic_signature.xml@@ -0,0 +1,8 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+    android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">+    <path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="2"+        android:strokeLineCap="round" android:strokeLineJoin="round"+        android:pathData="M3,17 C6,17 6,8 8,8 C10,8 8,16 11,16 C13,16 13,11 15,11 C16.5,11 16,14 18,13" />+    <path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="2"+        android:strokeLineCap="round" android:pathData="M4,21 L20,21" />+</vector>