Skip to content

LanguageIdiomaภาษา

Cryptography with Rust on Android: ring and RustCrypto Instead of Rolling Your Own

Cryptography with Rust on Android: ring and RustCrypto Instead of Rolling Your OwnCriptografía con Rust en Android: ring y RustCrypto en lugar de escribir la tuyaการเข้ารหัสด้วย Rust บน Android: ring และ RustCrypto แทนการเขียนเอง

Rust & NativeRust y nativoRust และเนทีฟ

ByPorโดย David Cruz Anaya, Mobile & Applied AI EngineerIngeniero sénior de móvil e IA aplicada (Android, Kotlin Multiplatform, IA de producto)วิศวกรมือถือและ AI ประยุกต์ระดับอาวุโส (Android, Kotlin Multiplatform, AI ของผลิตภัณฑ์)

Updated 9 October 2026Actualizado el 9 de octubre de 2026อัปเดตเมื่อ 9 ตุลาคม 20269 min read9 min de lecturaอ่าน 9 นาที
AndroidRustNDKCryptographySecurityKeystore
Share:Compartir:แชร์:

Rust + NDK on Android, Part 12 of 15.This series teaches Android developers how to ship Rust in production apps, no prior Rust required. Hub: Rust on Android: How to Use It, How to Debug It, and Why It's Worth It. Previous: Heavy Parsing with Serde: Offloading JSON and CSV Crunching to Rust. Next: Binary Size and the 16KB Page Requirement: Optimizing Rust .so Files for Release.

The right amount of cryptographic algorithm code to write yourself for an Android app is zero, and Rust does not change that rule. The case for Rust crypto is calling audited implementations, ring or the RustCrypto crates, from a language that cannot corrupt the memory around them, while Android Keystore keeps ownership of the keys. This part builds the rust/cryptobox module: streamed BLAKE3 hashing, XChaCha20-Poly1305 file encryption, and constant-time comparison for the secrets that need it.

The scope is the three jobs apps actually have: prove a file is intact, keep a file confidential, and never leak a secret while checking one. It assumes the toolchain from Part 1, the byte-crossing cost model from Part 6, and the exception mapping from Part 8.

Key Takeaways

  • Crypto code is the worst place for a memory bug: Google measured 0.2 memory safety vulnerabilities per million lines of Rust in Android against roughly 1,000 for its C and C++ (Google, 2025).
  • ring wraps BoringSSL-derived primitives in C and assembly behind a small Rust API; RustCrypto is a family of pure-Rust crates, one primitive each, and its AEAD crates carry an NCC Group audit with no significant findings (docs.rs).
  • Hardware-backed Android Keystore keys never enter your app’s process, so Rust can never use them directly. The division of labor is envelope encryption: the Keystore key wraps a data key, and only the data key crosses into Rust.
  • Never compare secrets with ==. The AEAD crates verify their tags in constant time internally, and the subtle crate covers every comparison you still write yourself.

Why crypto is where memory safety pays the most

Heartbleed was not a cryptographic flaw. It was a missing bounds check in OpenSSL’s heartbeat handler, a memory safety bug that let anyone read the memory next to the crypto code, private keys included (The Heartbleed Bug, 2014). Crypto code processes attacker input beside the most valuable bytes in the process; an over-read there is a disclosure, not a crash.

The numbers in the series’ anchor post: 0.2 memory safety vulnerabilities per million lines of Rust in Android, against roughly 1,000 for Google’s C and C++ history (Google, Rust in Android: move fast and fix things, 2025). The production table there has a theme, Signal, Wire, 1Password, Bitwarden: when cryptographic correctness is the product, the crypto core moved to Rust first.

Memory safety removes a whole class of implementation bugs and does nothing for design bugs. A memory-safe program that reuses an AES-GCM nonce has still lost its authentication key, because unique IVs are a hard requirement of the mode itself (NIST SP 800-38D). So this post sticks to audited crates, boring constructions, and Keystore-owned keys.

Choosing Rust crypto crates for Android: ring or RustCrypto

Two names dominate the Rust crypto search results. ring describes itself as safe, fast, small crypto using Rust with BoringSSL’s cryptography primitives: a deliberately small API over a core inherited from Google’s TLS stack, much of it C and hand-written assembly. That pedigree is its strength; the cost on Android is that every ABI you ship now compiles C and assembly too. cargo-ndk wires the C compiler to the NDK toolchain for you, as Part 1 set up, but it is one more thing to diagnose when a single ABI misbehaves.

RustCrypto is the other model: an organization publishing one small pure-Rust crate per primitive, sha2, aes-gcm, chacha20poly1305. Pure Rust cross-compiles like any other crate in this series, and your dependency tree contains exactly the algorithms you use. The audit status is public: aes-gcm and chacha20poly1305 received a security audit by NCC Group with no significant findings (docs.rs), and the aes crate uses the ARMv8 AES instructions on 64-bit Android hardware.

For hashing, the blake3 crate is the official implementation from the BLAKE3 team, with NEON acceleration on 64-bit ARM. My rule for this module and most app work: RustCrypto plus blake3, which keeps the build pure Rust and the size accounting honest. Reach for ring when you are already in its ecosystem, typically for TLS or its signature and key-agreement primitives.

Hashing files with BLAKE3, streamed from Rust

The module’s manifest pulls five small dependencies. This is rust/cryptobox/Cargo.toml in full:

[package]
name = "cryptobox"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
jni = "0.21"
blake3 = "1"
chacha20poly1305 = "0.10"
subtle = "2"
zeroize = "1"

The hashing API takes a file path, not the file’s bytes: the chunky-call principle from Part 6 applied to crypto. Crossing JNI once with a short string beats marshalling a hundred megabytes, and streaming in Rust keeps memory flat whatever the file size. Here are the imports and the hashing half of rust/cryptobox/src/lib.rs:

use std::fs::File;
use std::io::{BufReader, Read};

use chacha20poly1305::aead::{Aead, AeadCore, KeyInit, OsRng};
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use jni::objects::{JByteArray, JClass, JString};
use jni::sys::{jbyteArray, jstring};
use jni::JNIEnv;
use zeroize::Zeroize;

const NONCE_LEN: usize = 24;

fn hash_file(path: &str) -> std::io::Result<String> {
    let file = File::open(path)?;
    let mut reader = BufReader::new(file);
    let mut hasher = blake3::Hasher::new();
    let mut buf = vec![0u8; 64 * 1024];
    loop {
        let read = reader.read(&mut buf)?;
        if read == 0 {
            break;
        }
        hasher.update(&buf[..read]);
    }
    Ok(hasher.finalize().to_hex().to_string())
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_CryptoBox_nativeHashFile(
    mut env: JNIEnv,
    _class: JClass,
    path: JString,
) -> jstring {
    let path: String = match env.get_string(&path) {
        Ok(s) => s.into(),
        Err(_) => return std::ptr::null_mut(),
    };
    match hash_file(&path) {
        Ok(hex) => env
            .new_string(hex)
            .expect("hex output is valid UTF-8")
            .into_raw(),
        Err(err) => {
            let _ = env.throw_new("java/io/IOException", err.to_string());
            std::ptr::null_mut()
        }
    }
}

A BufReader and 64 kilobytes at a time are plenty for a demo, and an I/O failure surfaces in Kotlin as an ordinary IOException, the mapping pattern from Part 8. For more throughput, Hasher::update_mmap_rayon behind the mmap and rayon features memory-maps the file and hashes it on all cores (docs.rs/blake3); I left it out to keep the dependency list short.

Sealing files with XChaCha20-Poly1305

The module encrypts with an AEAD, authenticated encryption with associated data: one operation that encrypts and authenticates, so tampered ciphertext fails to decrypt instead of decrypting into garbage. The mainstream choices are AES-256-GCM and ChaCha20-Poly1305 (RFC 8439). I picked the extended-nonce XChaCha20-Poly1305 for one reason: its 24-byte nonce is safe to generate randomly for every message, and that is exactly how the crate documents it should be used (docs.rs/chacha20poly1305). That deletes nonce bookkeeping, the classic AEAD footgun, from the design.

The core is two functions. The sealed format is the random nonce, then the ciphertext, which ends with the 16-byte tag. This continues rust/cryptobox/src/lib.rs:

fn seal(key: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, String> {
    let cipher = XChaCha20Poly1305::new_from_slice(key)
        .map_err(|_| "key must be exactly 32 bytes".to_string())?;
    let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng);
    let ciphertext = cipher
        .encrypt(&nonce, plaintext)
        .map_err(|_| "encryption failed".to_string())?;
    let mut out = Vec::with_capacity(NONCE_LEN + ciphertext.len());
    out.extend_from_slice(nonce.as_slice());
    out.extend_from_slice(&ciphertext);
    Ok(out)
}

fn open(key: &[u8], sealed: &[u8]) -> Result<Vec<u8>, String> {
    if sealed.len() < NONCE_LEN {
        return Err("input shorter than the nonce".to_string());
    }
    let cipher = XChaCha20Poly1305::new_from_slice(key)
        .map_err(|_| "key must be exactly 32 bytes".to_string())?;
    let (nonce, ciphertext) = sealed.split_at(NONCE_LEN);
    cipher
        .decrypt(XNonce::from_slice(nonce), ciphertext)
        .map_err(|_| "decryption failed: wrong key or modified data".to_string())
}

open never touches the tag. The crate verifies it internally, in constant time, and returns one deliberately opaque error for every failure mode. Decrypt APIs that explained exactly why they failed are how padding oracle attacks were born.

The JNI boundary is one shared wrapper, because sealing and opening have the same shape: two byte arrays in, one out, exception on failure. The key bytes are wiped with zeroize the moment the operation finishes. These functions complete rust/cryptobox/src/lib.rs:

fn run_aead(
    env: &mut JNIEnv,
    key: JByteArray,
    input: JByteArray,
    op: fn(&[u8], &[u8]) -> Result<Vec<u8>, String>,
) -> jbyteArray {
    let mut key_bytes = match env.convert_byte_array(&key) {
        Ok(bytes) => bytes,
        Err(_) => return std::ptr::null_mut(),
    };
    let input_bytes = match env.convert_byte_array(&input) {
        Ok(bytes) => bytes,
        Err(_) => {
            key_bytes.zeroize();
            return std::ptr::null_mut();
        }
    };
    let result = op(&key_bytes, &input_bytes);
    key_bytes.zeroize();
    match result {
        Ok(out) => match env.byte_array_from_slice(&out) {
            Ok(arr) => arr.into_raw(),
            Err(_) => std::ptr::null_mut(),
        },
        Err(message) => {
            let _ = env.throw_new("java/security/GeneralSecurityException", message);
            std::ptr::null_mut()
        }
    }
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_CryptoBox_nativeSeal(
    mut env: JNIEnv,
    _class: JClass,
    key: JByteArray,
    plaintext: JByteArray,
) -> jbyteArray {
    run_aead(&mut env, key, plaintext, seal)
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_CryptoBox_nativeOpen(
    mut env: JNIEnv,
    _class: JClass,
    key: JByteArray,
    sealed: JByteArray,
) -> jbyteArray {
    run_aead(&mut env, key, sealed, open)
}

One more constant-time note, because audits keep catching it. The AEAD handled its own tag, but any secret you compare yourself, a stored MAC, an API token, a derived key, must not go through ==. Slice equality returns at the first differing byte, and that timing is measurable. The subtle crate exists for this, also in rust/cryptobox/src/lib.rs:

use subtle::ConstantTimeEq;

/// Constant-time equality for secrets: MACs, tokens, derived keys.
pub fn secrets_equal(a: &[u8], b: &[u8]) -> bool {
    a.ct_eq(b).into()
}

Android Keystore still owns the keys

Android Keystore’s security model is that key material for hardware-backed keys never enters the application process; the key lives in the TEE or StrongBox and only operation requests cross over (Android Developers, Android Keystore system).

The resolution is envelope encryption. Kotlin generates a random data encryption key, the DEK, which does the file work in Rust. The Keystore holds a key encryption key, the KEK, with exactly one job: wrapping and unwrapping those 32 DEK bytes with AES-GCM. Bulk megabytes go through Rust; the secret that must survive device compromise stays behind hardware. Here is the complete app/src/main/java/dev/davthecoder/rustseries/KeyWrapper.kt:

package dev.davthecoder.rustseries

import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import java.security.KeyStore
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec

/** The Keystore KEK wraps a random DEK; only the DEK crosses into Rust. */
object KeyWrapper {

    private const val KEY_ALIAS = "cryptobox-kek"
    private const val GCM_TAG_BITS = 128
    private const val IV_LEN = 12

    fun generateDek(): ByteArray =
        ByteArray(32).also { SecureRandom().nextBytes(it) }

    fun wrapDek(dek: ByteArray): ByteArray {
        val cipher = Cipher.getInstance("AES/GCM/NoPadding")
        cipher.init(Cipher.ENCRYPT_MODE, kek())
        return cipher.iv + cipher.doFinal(dek)
    }

    fun unwrapDek(wrapped: ByteArray): ByteArray {
        val iv = wrapped.copyOfRange(0, IV_LEN)
        val ciphertext = wrapped.copyOfRange(IV_LEN, wrapped.size)
        val cipher = Cipher.getInstance("AES/GCM/NoPadding")
        cipher.init(Cipher.DECRYPT_MODE, kek(), GCMParameterSpec(GCM_TAG_BITS, iv))
        return cipher.doFinal(ciphertext)
    }

    private fun kek(): SecretKey {
        val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
        keyStore.getKey(KEY_ALIAS, null)?.let { return it as SecretKey }

        val generator = KeyGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"
        )
        generator.init(
            KeyGenParameterSpec.Builder(
                KEY_ALIAS,
                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
            )
                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                .setKeySize(256)
                .build()
        )
        return generator.generateKey()
    }
}

The bridge itself is three externals in app/src/main/java/dev/davthecoder/rustseries/CryptoBox.kt:

package dev.davthecoder.rustseries

object CryptoBox {
    init {
        System.loadLibrary("cryptobox")
    }

    external fun nativeHashFile(path: String): String
    external fun nativeSeal(key: ByteArray, plaintext: ByteArray): ByteArray
    external fun nativeOpen(key: ByteArray, sealed: ByteArray): ByteArray
}

The whole flow is four lines at the call site:

val dek = KeyWrapper.generateDek()
val wrapped = KeyWrapper.wrapDek(dek) // persist next to the sealed file
val sealed = CryptoBox.nativeSeal(dek, plaintextBytes)
dek.fill(0) // wipe Kotlin's copy

Be honest about that last line. fill(0) wipes the array you hold, but the garbage collector may have copied it earlier, so wiping on the managed side is best effort. The real mitigations are a short DEK lifetime, unwrapping only for the duration of an operation, and letting the KEK stay where no memcpy can reach it.

Do not invent protocols

Everything above assembles other people’s constructions, and that is the guidance: crates for primitives, published constructions for everything else. The failure mode for app crypto in 2026 is sound primitives composed into an unsound protocol: AES-CTR with a hash glued on, a key derived by hashing a password once, a chunked format where chunks can be reordered or truncated undetected.

Each of those has a boring, published answer. Authenticated encryption is the AEAD you already have. Password-based keys go through a real password hash like Argon2, which RustCrypto also packages (docs.rs/argon2). Files too large for one AEAD call use STREAM, implemented in the aead crate’s stream module (docs.rs/aead): chunked encryption is a dependency. If your requirement does not map to hash this, seal this, or wrap this key, involve someone who reviews protocols for a living. I write Rust crypto plumbing; I do not design protocols, and neither should your app team.

Frequently Asked Questions

Why not do all of this in Kotlin with the Keystore?

The Keystore is the right tool for small operations like wrapping a 32-byte key, and javax.crypto is fine for modest payloads. Rust earns its place for bulk work over large files and for cores shared across platforms. It also fills a gap Google left: Jetpack’s security-crypto library, the one behind EncryptedFile, is deprecated (AndroidX release notes).

Where this leaves you

The AEAD checks its own tag, the oversized nonce removes the bookkeeping that breaks GCM deployments, and the KEK never leaves the hardware. If a future diff makes this module more interesting, treat that as a review flag.

Part 13 covers what these crates weigh. Binary Size and the 16KB Page Requirement: Optimizing Rust .so Files for Release walks the size playbook over the series’ own crates. The full series map lives at the hub.

Sources

Rust + NDK on Android, Part 12 of 15.This series teaches Android developers how to ship Rust in production apps, no prior Rust required. Hub: Rust on Android: How to Use It, How to Debug It, and Why It's Worth It. Previous: Heavy Parsing with Serde: Offloading JSON and CSV Crunching to Rust. Next: Binary Size and the 16KB Page Requirement: Optimizing Rust .so Files for Release.

La cantidad correcta de código de algoritmos criptográficos que debes escribir tú mismo para una app de Android es cero, y Rust no cambia esa regla. El argumento a favor de la cripto en Rust es llamar a implementaciones auditadas, ring o los crates de RustCrypto, desde un lenguaje que no puede corromper la memoria que las rodea, mientras Android Keystore conserva la propiedad de las claves. Esta parte construye el módulo rust/cryptobox: hash BLAKE3 en flujo, cifrado de archivos con XChaCha20-Poly1305 y comparación en tiempo constante para los secretos que la necesitan.

El alcance son los tres trabajos que las apps tienen de verdad: demostrar que un archivo está intacto, mantener un archivo confidencial y no filtrar un secreto mientras lo compruebas. Asume la cadena de herramientas de la parte 1, el modelo de coste de cruzar bytes de la parte 6 y el mapeo de excepciones de la parte 8.

Puntos clave

  • El código cripto es el peor sitio para un bug de memoria: Google midió 0,2 vulnerabilidades de seguridad de memoria por millón de líneas de Rust en Android, frente a unas 1.000 en su C y C++ (Google, 2025).
  • ring envuelve primitivas derivadas de BoringSSL, en C y ensamblador, detrás de una API pequeña de Rust; RustCrypto es una familia de crates en Rust puro, una primitiva cada uno, y sus crates AEAD llevan una auditoría de NCC Group sin hallazgos significativos (docs.rs).
  • Las claves de Android Keystore respaldadas por hardware nunca entran en el proceso de tu app, así que Rust no puede usarlas directamente. El reparto del trabajo es el cifrado de sobre: la clave del Keystore envuelve una clave de datos, y solo la clave de datos cruza hacia Rust.
  • No compares nunca secretos con ==. Los crates AEAD verifican sus tags en tiempo constante por dentro, y el crate subtle cubre cada comparación que aún escribes tú.

Por qué la cripto es donde la seguridad de memoria más se nota

Heartbleed no fue un fallo criptográfico. Fue una comprobación de límites que faltaba en el manejador de heartbeat de OpenSSL, un bug de seguridad de memoria que permitía a cualquiera leer la memoria de al lado del código cripto, claves privadas incluidas (The Heartbleed Bug, 2014). El código cripto procesa entrada del atacante junto a los bytes más valiosos del proceso; una lectura de más ahí es una filtración, no un crash.

Las cifras del artículo ancla de la serie: 0,2 vulnerabilidades de seguridad de memoria por millón de líneas de Rust en Android, frente a unas 1.000 en la historia de C y C++ de Google (Google, Rust in Android: move fast and fix things, 2025). La tabla de producción de allí tiene un tema, Signal, Wire, 1Password, Bitwarden: cuando la corrección criptográfica es el producto, el núcleo cripto se mudó a Rust primero.

La seguridad de memoria elimina toda una clase de bugs de implementación y no hace nada contra los bugs de diseño. Un programa con memoria segura que reutiliza un nonce de AES-GCM ha perdido igual su clave de autenticación, porque los IV únicos son un requisito duro del propio modo (NIST SP 800-38D). Así que este artículo se ciñe a crates auditados, construcciones aburridas y claves que pertenecen al Keystore.

Elegir crates cripto de Rust para Android: ring o RustCrypto

Dos nombres dominan los resultados de búsqueda de cripto en Rust. ring se describe como cripto segura, rápida y pequeña usando Rust con las primitivas criptográficas de BoringSSL: una API deliberadamente pequeña sobre un núcleo heredado de la pila TLS de Google, gran parte en C y ensamblador escrito a mano. Esa procedencia es su fuerza; el coste en Android es que cada ABI que publicas compila ahora también C y ensamblador. cargo-ndk conecta el compilador de C a la cadena de herramientas del NDK por ti, como dejó preparado la parte 1, pero es una cosa más que diagnosticar cuando una sola ABI se porta mal.

RustCrypto es el otro modelo: una organización que publica un crate pequeño en Rust puro por primitiva, sha2, aes-gcm, chacha20poly1305. El Rust puro se compila de forma cruzada como cualquier otro crate de esta serie, y tu árbol de dependencias contiene exactamente los algoritmos que usas. El estado de la auditoría es público: aes-gcm y chacha20poly1305 recibieron una auditoría de seguridad de NCC Group sin hallazgos significativos (docs.rs), y el crate aes usa las instrucciones AES de ARMv8 en hardware Android de 64 bits.

Para el hash, el crate blake3 es la implementación oficial del equipo de BLAKE3, con aceleración NEON en ARM de 64 bits. Mi regla para este módulo y para la mayoría del trabajo de app: RustCrypto más blake3, que mantiene la compilación en Rust puro y la contabilidad del tamaño honesta. Tira de ring cuando ya estés en su ecosistema, normalmente para TLS o para sus primitivas de firma y acuerdo de claves.

Hashear archivos con BLAKE3, en flujo desde Rust

El manifiesto del módulo tira de cinco dependencias pequeñas. Este es rust/cryptobox/Cargo.toml entero:

[package]
name = "cryptobox"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
jni = "0.21"
blake3 = "1"
chacha20poly1305 = "0.10"
subtle = "2"
zeroize = "1"

La API de hash toma una ruta de archivo, no los bytes del archivo: el principio de la llamada gruesa de la parte 6 aplicado a la cripto. Cruzar JNI una vez con una cadena corta gana a acarrear cien megabytes, y el flujo en Rust mantiene la memoria plana sea cual sea el tamaño del archivo. Aquí van los imports y la mitad de hash de rust/cryptobox/src/lib.rs:

use std::fs::File;
use std::io::{BufReader, Read};

use chacha20poly1305::aead::{Aead, AeadCore, KeyInit, OsRng};
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use jni::objects::{JByteArray, JClass, JString};
use jni::sys::{jbyteArray, jstring};
use jni::JNIEnv;
use zeroize::Zeroize;

const NONCE_LEN: usize = 24;

fn hash_file(path: &str) -> std::io::Result<String> {
    let file = File::open(path)?;
    let mut reader = BufReader::new(file);
    let mut hasher = blake3::Hasher::new();
    let mut buf = vec![0u8; 64 * 1024];
    loop {
        let read = reader.read(&mut buf)?;
        if read == 0 {
            break;
        }
        hasher.update(&buf[..read]);
    }
    Ok(hasher.finalize().to_hex().to_string())
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_CryptoBox_nativeHashFile(
    mut env: JNIEnv,
    _class: JClass,
    path: JString,
) -> jstring {
    let path: String = match env.get_string(&path) {
        Ok(s) => s.into(),
        Err(_) => return std::ptr::null_mut(),
    };
    match hash_file(&path) {
        Ok(hex) => env
            .new_string(hex)
            .expect("hex output is valid UTF-8")
            .into_raw(),
        Err(err) => {
            let _ = env.throw_new("java/io/IOException", err.to_string());
            std::ptr::null_mut()
        }
    }
}

Un BufReader y 64 kilobytes cada vez sobran para una demo, y un fallo de E/S aparece en Kotlin como una IOException normal, el patrón de mapeo de la parte 8. Para más rendimiento, Hasher::update_mmap_rayon detrás de las features mmap y rayon mapea el archivo en memoria y lo hashea en todos los núcleos (docs.rs/blake3); lo dejé fuera para mantener corta la lista de dependencias.

Sellar archivos con XChaCha20-Poly1305

El módulo cifra con un AEAD, cifrado autenticado con datos asociados: una operación que cifra y autentica, así que un texto cifrado manipulado falla al descifrar en lugar de descifrar en basura. Las opciones mayoritarias son AES-256-GCM y ChaCha20-Poly1305 (RFC 8439). Elegí XChaCha20-Poly1305, de nonce extendido, por una razón: su nonce de 24 bytes se puede generar al azar para cada mensaje, y así es exactamente como el crate documenta que debe usarse (docs.rs/chacha20poly1305). Eso elimina la contabilidad del nonce, la trampa clásica de los AEAD, del diseño.

El núcleo son dos funciones. El formato sellado es el nonce aleatorio y después el texto cifrado, que termina con el tag de 16 bytes. Esto continúa rust/cryptobox/src/lib.rs:

fn seal(key: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, String> {
    let cipher = XChaCha20Poly1305::new_from_slice(key)
        .map_err(|_| "key must be exactly 32 bytes".to_string())?;
    let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng);
    let ciphertext = cipher
        .encrypt(&nonce, plaintext)
        .map_err(|_| "encryption failed".to_string())?;
    let mut out = Vec::with_capacity(NONCE_LEN + ciphertext.len());
    out.extend_from_slice(nonce.as_slice());
    out.extend_from_slice(&ciphertext);
    Ok(out)
}

fn open(key: &[u8], sealed: &[u8]) -> Result<Vec<u8>, String> {
    if sealed.len() < NONCE_LEN {
        return Err("input shorter than the nonce".to_string());
    }
    let cipher = XChaCha20Poly1305::new_from_slice(key)
        .map_err(|_| "key must be exactly 32 bytes".to_string())?;
    let (nonce, ciphertext) = sealed.split_at(NONCE_LEN);
    cipher
        .decrypt(XNonce::from_slice(nonce), ciphertext)
        .map_err(|_| "decryption failed: wrong key or modified data".to_string())
}

open no toca el tag. El crate lo verifica por dentro, en tiempo constante, y devuelve un único error deliberadamente opaco para cada modo de fallo. Las API de descifrado que explicaban con exactitud por qué fallaban son el origen de los ataques de padding oracle.

La frontera JNI es un wrapper compartido, porque sellar y abrir tienen la misma forma: dos arrays de bytes de entrada, uno de salida, excepción si falla. Los bytes de la clave se borran con zeroize en el momento en que termina la operación. Estas funciones completan rust/cryptobox/src/lib.rs:

fn run_aead(
    env: &mut JNIEnv,
    key: JByteArray,
    input: JByteArray,
    op: fn(&[u8], &[u8]) -> Result<Vec<u8>, String>,
) -> jbyteArray {
    let mut key_bytes = match env.convert_byte_array(&key) {
        Ok(bytes) => bytes,
        Err(_) => return std::ptr::null_mut(),
    };
    let input_bytes = match env.convert_byte_array(&input) {
        Ok(bytes) => bytes,
        Err(_) => {
            key_bytes.zeroize();
            return std::ptr::null_mut();
        }
    };
    let result = op(&key_bytes, &input_bytes);
    key_bytes.zeroize();
    match result {
        Ok(out) => match env.byte_array_from_slice(&out) {
            Ok(arr) => arr.into_raw(),
            Err(_) => std::ptr::null_mut(),
        },
        Err(message) => {
            let _ = env.throw_new("java/security/GeneralSecurityException", message);
            std::ptr::null_mut()
        }
    }
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_CryptoBox_nativeSeal(
    mut env: JNIEnv,
    _class: JClass,
    key: JByteArray,
    plaintext: JByteArray,
) -> jbyteArray {
    run_aead(&mut env, key, plaintext, seal)
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_CryptoBox_nativeOpen(
    mut env: JNIEnv,
    _class: JClass,
    key: JByteArray,
    sealed: JByteArray,
) -> jbyteArray {
    run_aead(&mut env, key, sealed, open)
}

Una nota más sobre el tiempo constante, porque las auditorías siguen pillándolo. El AEAD se ocupó de su propio tag, pero cualquier secreto que compares tú, un MAC guardado, un token de API, una clave derivada, no debe pasar por ==. La igualdad de slices vuelve en el primer byte que difiere, y ese tiempo se puede medir. El crate subtle existe para esto, también en rust/cryptobox/src/lib.rs:

use subtle::ConstantTimeEq;

/// Constant-time equality for secrets: MACs, tokens, derived keys.
pub fn secrets_equal(a: &[u8], b: &[u8]) -> bool {
    a.ct_eq(b).into()
}

Android Keystore sigue custodiando las claves

El modelo de seguridad de Android Keystore es que el material de las claves respaldadas por hardware nunca entra en el proceso de la aplicación; la clave vive en el TEE o en StrongBox y solo cruzan las peticiones de operación (Android Developers, Android Keystore system).

La resolución es el cifrado de sobre. Kotlin genera una clave de cifrado de datos aleatoria, la DEK, que hace el trabajo sobre el archivo en Rust. El Keystore guarda una clave de cifrado de claves, la KEK, con un único trabajo: envolver y desenvolver esos 32 bytes de la DEK con AES-GCM. Los megabytes en bruto pasan por Rust; el secreto que tiene que sobrevivir a un dispositivo comprometido se queda tras el hardware. Aquí está el app/src/main/java/dev/davthecoder/rustseries/KeyWrapper.kt completo:

package dev.davthecoder.rustseries

import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import java.security.KeyStore
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec

/** The Keystore KEK wraps a random DEK; only the DEK crosses into Rust. */
object KeyWrapper {

    private const val KEY_ALIAS = "cryptobox-kek"
    private const val GCM_TAG_BITS = 128
    private const val IV_LEN = 12

    fun generateDek(): ByteArray =
        ByteArray(32).also { SecureRandom().nextBytes(it) }

    fun wrapDek(dek: ByteArray): ByteArray {
        val cipher = Cipher.getInstance("AES/GCM/NoPadding")
        cipher.init(Cipher.ENCRYPT_MODE, kek())
        return cipher.iv + cipher.doFinal(dek)
    }

    fun unwrapDek(wrapped: ByteArray): ByteArray {
        val iv = wrapped.copyOfRange(0, IV_LEN)
        val ciphertext = wrapped.copyOfRange(IV_LEN, wrapped.size)
        val cipher = Cipher.getInstance("AES/GCM/NoPadding")
        cipher.init(Cipher.DECRYPT_MODE, kek(), GCMParameterSpec(GCM_TAG_BITS, iv))
        return cipher.doFinal(ciphertext)
    }

    private fun kek(): SecretKey {
        val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
        keyStore.getKey(KEY_ALIAS, null)?.let { return it as SecretKey }

        val generator = KeyGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"
        )
        generator.init(
            KeyGenParameterSpec.Builder(
                KEY_ALIAS,
                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
            )
                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                .setKeySize(256)
                .build()
        )
        return generator.generateKey()
    }
}

El puente en sí son tres externals en app/src/main/java/dev/davthecoder/rustseries/CryptoBox.kt:

package dev.davthecoder.rustseries

object CryptoBox {
    init {
        System.loadLibrary("cryptobox")
    }

    external fun nativeHashFile(path: String): String
    external fun nativeSeal(key: ByteArray, plaintext: ByteArray): ByteArray
    external fun nativeOpen(key: ByteArray, sealed: ByteArray): ByteArray
}

Todo el flujo son cuatro líneas en el punto de llamada:

val dek = KeyWrapper.generateDek()
val wrapped = KeyWrapper.wrapDek(dek) // persist next to the sealed file
val sealed = CryptoBox.nativeSeal(dek, plaintextBytes)
dek.fill(0) // wipe Kotlin's copy

Sé honesto con esa última línea. fill(0) borra el array que tienes, pero el recolector de basura puede haberlo copiado antes, así que borrar en el lado gestionado es un intento, no una garantía. Las mitigaciones reales son una vida corta de la DEK, desenvolverla solo durante una operación y dejar que la KEK se quede donde ningún memcpy puede alcanzarla.

No inventes protocolos

Todo lo de arriba ensambla construcciones de otras personas, y esa es la guía: crates para las primitivas, construcciones publicadas para todo lo demás. El modo de fallo de la cripto de app en 2026 son primitivas sólidas compuestas en un protocolo que no se sostiene: AES-CTR con un hash pegado, una clave derivada hasheando una contraseña una sola vez, un formato por trozos en el que los trozos se pueden reordenar o truncar sin que se note.

Cada uno de esos tiene una respuesta aburrida y publicada. El cifrado autenticado es el AEAD que ya tienes. Las claves basadas en contraseña pasan por un hash de contraseñas de verdad como Argon2, que RustCrypto también empaqueta (docs.rs/argon2). Los archivos demasiado grandes para una sola llamada AEAD usan STREAM, implementado en el módulo stream del crate aead (docs.rs/aead): el cifrado por trozos es una dependencia. Si tu requisito no se mapea a hashear esto, sellar esto o envolver esta clave, cuenta con alguien que revise protocolos por oficio. Yo escribo el pegamento cripto en Rust; no diseño protocolos, y tu equipo de app tampoco debería.

Preguntas frecuentes

¿Por qué no hacer todo esto en Kotlin con el Keystore?

El Keystore es la herramienta correcta para operaciones pequeñas, como envolver una clave de 32 bytes, y javax.crypto vale para cargas modestas. Rust se gana su sitio en el trabajo en bruto sobre archivos grandes y en núcleos compartidos entre plataformas. También llena un hueco que dejó Google: la biblioteca security-crypto de Jetpack, la que hay detrás de EncryptedFile, está obsoleta (AndroidX release notes).

Dónde te deja esto

El AEAD comprueba su propio tag, el nonce sobredimensionado elimina la contabilidad que rompe los despliegues de GCM, y la KEK nunca sale del hardware. Si un diff futuro hace este módulo más interesante, trátalo como una señal de alarma en la revisión.

La parte 13 cubre lo que pesan estos crates. Tamaño del binario y el requisito de páginas de 16 KB: optimizar los .so de Rust para release recorre el manual de tamaño sobre los propios crates de la serie. El mapa completo de la serie vive en el hub.

Fuentes

Rust + NDK on Android, Part 12 of 15.This series teaches Android developers how to ship Rust in production apps, no prior Rust required. Hub: Rust on Android: How to Use It, How to Debug It, and Why It's Worth It. Previous: Heavy Parsing with Serde: Offloading JSON and CSV Crunching to Rust. Next: Binary Size and the 16KB Page Requirement: Optimizing Rust .so Files for Release.

ปริมาณโค้ดอัลกอริทึมการเข้ารหัสที่ควรเขียนเองสำหรับแอป Android คือศูนย์ และ Rust ไม่ได้เปลี่ยนกฎนั้น เหตุผลของคริปโตฝั่ง Rust คือการเรียกอิมพลีเมนต์ที่ผ่านการตรวจสอบ ไม่ว่าจะเป็น ring หรือ crate ของ RustCrypto จากภาษาที่ทำให้หน่วยความจำรอบๆ พังไม่ได้ ขณะที่ Android Keystore ยังถือกรรมสิทธิ์ของคีย์ ตอนนี้สร้างโมดูล rust/cryptobox: การแฮช BLAKE3 แบบสตรีม การเข้ารหัสไฟล์ด้วย XChaCha20-Poly1305 และการเปรียบเทียบแบบเวลาคงที่สำหรับความลับที่ต้องใช้มัน

ขอบเขตคืองานสามอย่างที่แอปมีจริง: พิสูจน์ว่าไฟล์ยังครบ รักษาความลับของไฟล์ และไม่ให้ความลับรั่วตอนตรวจความลับอีกชิ้น สิ่งนี้สมมติทูลเชนจาก ตอนที่ 1 โมเดลต้นทุนการข้ามไบต์จาก ตอนที่ 6 และการแมป exception จาก ตอนที่ 8

ประเด็นสำคัญ

  • โค้ดคริปโตคือที่ที่แย่ที่สุดสำหรับบั๊กหน่วยความจำ: Google วัดได้ 0.2 ช่องโหว่ด้านความปลอดภัยของหน่วยความจำต่อหนึ่งล้านบรรทัดของ Rust ใน Android เทียบกับราว 1,000 สำหรับ C และ C++ ของตน (Google, 2025)
  • ring ห่อ primitive ที่สืบจาก BoringSSL ใน C และแอสเซมบลีไว้หลัง API Rust ขนาดเล็ก RustCrypto คือตระกูล crate ที่เป็น Rust ล้วน หนึ่ง primitive ต่อ crate และ crate AEAD ของมันมีการตรวจสอบโดย NCC Group โดยไม่พบประเด็นสำคัญ (docs.rs)
  • คีย์ Android Keystore ที่หนุนด้วยฮาร์ดแวร์ไม่เคยเข้าโปรเซสของแอป ดังนั้น Rust ใช้มันตรงๆ ไม่ได้ การแบ่งงานคือการเข้ารหัสแบบ envelope: คีย์ Keystore ห่อคีย์ข้อมูล และมีแค่คีย์ข้อมูลที่ข้ามเข้า Rust
  • อย่าเปรียบเทียบความลับด้วย == crate AEAD ตรวจแท็กของตัวเองแบบเวลาคงที่อยู่ภายใน และ crate subtle ครอบคลุมทุกการเปรียบเทียบที่คุณยังเขียนเอง

ทำไมคริปโตคือจุดที่ความปลอดภัยของหน่วยความจำคุ้มที่สุด

Heartbleed ไม่ใช่ข้อบกพร่องของอัลกอริทึมการเข้ารหัส มันคือการตรวจขอบเขตที่หายไปในตัวจัดการ heartbeat ของ OpenSSL บั๊กความปลอดภัยของหน่วยความจำที่เปิดให้ใครก็ได้อ่านหน่วยความจำข้างโค้ดคริปโต รวมถึงคีย์ส่วนตัว (The Heartbleed Bug, 2014) โค้ดคริปโตประมวลผลอินพุตของผู้โจมตีข้างไบต์ที่มีค่าที่สุดในโปรเซส การอ่านเลยขอบตรงนั้นคือการเปิดเผย ไม่ใช่แครช

ตัวเลขใน บทความหลักของชุด: 0.2 ช่องโหว่ด้านความปลอดภัยของหน่วยความจำต่อหนึ่งล้านบรรทัดของ Rust ใน Android เทียบกับราว 1,000 สำหรับประวัติ C และ C++ ของ Google (Google, Rust in Android: move fast and fix things, 2025) ตารางโปรดักชันตรงนั้นมีธีมเดียวกัน Signal, Wire, 1Password, Bitwarden: เมื่อความถูกต้องของการเข้ารหัสคือผลิตภัณฑ์ คอร์คริปโตย้ายไป Rust ก่อน

ความปลอดภัยของหน่วยความจำตัดบั๊กอิมพลีเมนต์ทั้งคลาส และไม่ช่วยอะไรกับบั๊กการออกแบบ โปรแกรมที่ปลอดภัยด้านหน่วยความจำแต่ใช้ nonce ของ AES-GCM ซ้ำก็ยังเสียคีย์การยืนยันตัวตน เพราะ IV ที่ไม่ซ้ำเป็นข้อกำหนดแข็งของโหมดนั้นเอง (NIST SP 800-38D) ดังนั้นบทความนี้ยึด crate ที่ผ่านการตรวจสอบ โครงสร้างที่เรียบง่าย และคีย์ที่ Keystore เป็นเจ้าของ

การเลือก crate คริปโตของ Rust สำหรับ Android: ring หรือ RustCrypto

สองชื่อครองผลการค้นหาคริปโตของ Rust ring อธิบายตัวเองว่าเป็นคริปโตที่ปลอดภัย เร็ว และเล็ก โดยใช้ Rust กับ primitive การเข้ารหัสของ BoringSSL: API ขนาดเล็กโดยตั้งใจ ทับคอร์ที่สืบทอดจากสแตก TLS ของ Google ซึ่งส่วนใหญ่เป็น C และแอสเซมบลีที่เขียนด้วยมือ เชื้อสายนั้นคือจุดแข็ง ต้นทุนบน Android คือทุก ABI ที่คุณชิปตอนนี้ต้องคอมไพล์ C และแอสเซมบลีด้วย cargo-ndk ต่อคอมไพเลอร์ C เข้าทูลเชน NDK ให้ ตามที่ ตอนที่ 1 ตั้งไว้ แต่มันเป็นอีกอย่างที่ต้องวินิจฉัยเมื่อ ABI เดียวทำงานผิด

RustCrypto เป็นอีกโมเดล: องค์กรที่เผยแพร่ crate Rust ล้วนขนาดเล็กหนึ่งตัวต่อ primitive sha2, aes-gcm, chacha20poly1305 Rust ล้วนคอมไพล์ข้ามแพลตฟอร์มเหมือน crate อื่นในชุดนี้ และต้นไม้ดีเพนเดนซีมีเฉพาะอัลกอริทึมที่คุณใช้ สถานะการตรวจสอบเป็นสาธารณะ: aes-gcm และ chacha20poly1305 ได้รับการตรวจสอบความปลอดภัยโดย NCC Group โดยไม่พบประเด็นสำคัญ (docs.rs) และ crate aes ใช้คำสั่ง AES ของ ARMv8 บนฮาร์ดแวร์ Android 64 บิต

สำหรับการแฮช crate blake3 คืออิมพลีเมนต์ทางการจากทีม BLAKE3 พร้อมการเร่งด้วย NEON บน ARM 64 บิต กฎของผมสำหรับโมดูลนี้และงานแอปส่วนใหญ่: RustCrypto บวก blake3 ซึ่งทำให้บิลด์เป็น Rust ล้วน และการคิดขนาดซื่อสัตย์ หยิบ ring เมื่อคุณอยู่ในระบบนิเวศของมันอยู่แล้ว โดยทั่วไปเพื่อ TLS หรือ primitive ลายเซ็นและข้อตกลงคีย์ของมัน

การแฮชไฟล์ด้วย BLAKE3 สตรีมจาก Rust

มานิเฟสต์ของโมดูลดึงดีเพนเดนซีเล็กๆ ห้าตัว นี่คือ rust/cryptobox/Cargo.toml ทั้งไฟล์:

[package]
name = "cryptobox"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
jni = "0.21"
blake3 = "1"
chacha20poly1305 = "0.10"
subtle = "2"
zeroize = "1"

API การแฮชรับพาธของไฟล์ ไม่ใช่ไบต์ของไฟล์: หลักการเรียกเป็นก้อนจาก ตอนที่ 6 ที่ใช้กับคริปโต การข้าม JNI ครั้งเดียวด้วยสตริงสั้นดีกว่าการจัดเรียงร้อยเมกะไบต์ และการสตรีมใน Rust ทำให้หน่วยความจำราบไม่ว่าไฟล์จะใหญ่แค่ไหน นี่คือ import และครึ่งการแฮชของ rust/cryptobox/src/lib.rs:

use std::fs::File;
use std::io::{BufReader, Read};

use chacha20poly1305::aead::{Aead, AeadCore, KeyInit, OsRng};
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use jni::objects::{JByteArray, JClass, JString};
use jni::sys::{jbyteArray, jstring};
use jni::JNIEnv;
use zeroize::Zeroize;

const NONCE_LEN: usize = 24;

fn hash_file(path: &str) -> std::io::Result<String> {
    let file = File::open(path)?;
    let mut reader = BufReader::new(file);
    let mut hasher = blake3::Hasher::new();
    let mut buf = vec![0u8; 64 * 1024];
    loop {
        let read = reader.read(&mut buf)?;
        if read == 0 {
            break;
        }
        hasher.update(&buf[..read]);
    }
    Ok(hasher.finalize().to_hex().to_string())
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_CryptoBox_nativeHashFile(
    mut env: JNIEnv,
    _class: JClass,
    path: JString,
) -> jstring {
    let path: String = match env.get_string(&path) {
        Ok(s) => s.into(),
        Err(_) => return std::ptr::null_mut(),
    };
    match hash_file(&path) {
        Ok(hex) => env
            .new_string(hex)
            .expect("hex output is valid UTF-8")
            .into_raw(),
        Err(err) => {
            let _ = env.throw_new("java/io/IOException", err.to_string());
            std::ptr::null_mut()
        }
    }
}

BufReader กับครั้งละ 64 กิโลไบต์พอสำหรับเดโม และความล้มเหลวของ I/O โผล่ใน Kotlin เป็น IOException ธรรมดา ตามแพตเทิร์นการแมปจาก ตอนที่ 8 ถ้าอยากได้ทรูพุตมากขึ้น Hasher::update_mmap_rayon หลังฟีเจอร์ mmap และ rayon จะแมปไฟล์เข้าหน่วยความจำแล้วแฮชบนทุกคอร์ (docs.rs/blake3) ผมเว้นมันไว้เพื่อให้รายการดีเพนเดนซีสั้น

การปิดผนึกไฟล์ด้วย XChaCha20-Poly1305

โมดูลเข้ารหัสด้วย AEAD คือ authenticated encryption with associated data: การทำงานครั้งเดียวที่ทั้งเข้ารหัสและยืนยันตัวตน ดังนั้นไซเฟอร์เท็กซ์ที่ถูกแก้ไขจะถอดรหัสไม่ผ่าน แทนที่จะถอดออกมาเป็นขยะ ตัวเลือกกระแสหลักคือ AES-256-GCM และ ChaCha20-Poly1305 (RFC 8439) ผมเลือก XChaCha20-Poly1305 ที่ nonce ยาวขึ้นด้วยเหตุผลเดียว: nonce 24 ไบต์ของมันปลอดภัยที่จะสุ่มสำหรับทุกข้อความ และนั่นคือวิธีที่ crate เอกสารไว้ว่าควรใช้ (docs.rs/chacha20poly1305) นั่นลบบัญชี nonce ซึ่งเป็นกับดักคลาสสิกของ AEAD ออกจากการออกแบบ

แกนคือสองฟังก์ชัน รูปแบบที่ปิดผนึกคือ nonce สุ่ม แล้วตามด้วยไซเฟอร์เท็กซ์ ซึ่งลงท้ายด้วยแท็ก 16 ไบต์ ส่วนนี้ต่อใน rust/cryptobox/src/lib.rs:

fn seal(key: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, String> {
    let cipher = XChaCha20Poly1305::new_from_slice(key)
        .map_err(|_| "key must be exactly 32 bytes".to_string())?;
    let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng);
    let ciphertext = cipher
        .encrypt(&nonce, plaintext)
        .map_err(|_| "encryption failed".to_string())?;
    let mut out = Vec::with_capacity(NONCE_LEN + ciphertext.len());
    out.extend_from_slice(nonce.as_slice());
    out.extend_from_slice(&ciphertext);
    Ok(out)
}

fn open(key: &[u8], sealed: &[u8]) -> Result<Vec<u8>, String> {
    if sealed.len() < NONCE_LEN {
        return Err("input shorter than the nonce".to_string());
    }
    let cipher = XChaCha20Poly1305::new_from_slice(key)
        .map_err(|_| "key must be exactly 32 bytes".to_string())?;
    let (nonce, ciphertext) = sealed.split_at(NONCE_LEN);
    cipher
        .decrypt(XNonce::from_slice(nonce), ciphertext)
        .map_err(|_| "decryption failed: wrong key or modified data".to_string())
}

open ไม่แตะแท็ก crate ตรวจมันภายในแบบเวลาคงที่ และคืนข้อผิดพลาดทึบหนึ่งแบบโดยตั้งใจสำหรับทุกโหมดความล้มเหลว API ถอดรหัสที่อธิบายตรงๆ ว่าทำไมล้มเหลวคือที่มาของการโจมตีแบบ padding oracle

ขอบเขต JNI คือตัวห่อที่ใช้ร่วมหนึ่งตัว เพราะการปิดผนึกและการเปิดมีรูปเดียวกัน: อาร์เรย์ไบต์เข้าสองตัว ออกหนึ่งตัว exception เมื่อล้มเหลว ไบต์ของคีย์ถูกลบด้วย zeroize ทันทีที่การทำงานจบ ฟังก์ชันเหล่านี้ปิด rust/cryptobox/src/lib.rs:

fn run_aead(
    env: &mut JNIEnv,
    key: JByteArray,
    input: JByteArray,
    op: fn(&[u8], &[u8]) -> Result<Vec<u8>, String>,
) -> jbyteArray {
    let mut key_bytes = match env.convert_byte_array(&key) {
        Ok(bytes) => bytes,
        Err(_) => return std::ptr::null_mut(),
    };
    let input_bytes = match env.convert_byte_array(&input) {
        Ok(bytes) => bytes,
        Err(_) => {
            key_bytes.zeroize();
            return std::ptr::null_mut();
        }
    };
    let result = op(&key_bytes, &input_bytes);
    key_bytes.zeroize();
    match result {
        Ok(out) => match env.byte_array_from_slice(&out) {
            Ok(arr) => arr.into_raw(),
            Err(_) => std::ptr::null_mut(),
        },
        Err(message) => {
            let _ = env.throw_new("java/security/GeneralSecurityException", message);
            std::ptr::null_mut()
        }
    }
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_CryptoBox_nativeSeal(
    mut env: JNIEnv,
    _class: JClass,
    key: JByteArray,
    plaintext: JByteArray,
) -> jbyteArray {
    run_aead(&mut env, key, plaintext, seal)
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_CryptoBox_nativeOpen(
    mut env: JNIEnv,
    _class: JClass,
    key: JByteArray,
    sealed: JByteArray,
) -> jbyteArray {
    run_aead(&mut env, key, sealed, open)
}

อีกหนึ่งหมายเหตุเรื่องเวลาคงที่ เพราะการตรวจสอบยังจับเรื่องนี้ได้เรื่อยๆ AEAD จัดการแท็กของตัวเองแล้ว แต่ความลับใดที่คุณเปรียบเทียบเอง ไม่ว่าจะเป็น MAC ที่เก็บไว้ โทเค็น API หรือคีย์ที่อนุมานมา ต้องไม่ผ่าน == ความเท่ากันของสไลซ์กลับที่ไบต์แรกที่ต่าง และเวลานั้นวัดได้ crate subtle มีไว้เพื่อสิ่งนี้ ก็อยู่ใน rust/cryptobox/src/lib.rs:

use subtle::ConstantTimeEq;

/// Constant-time equality for secrets: MACs, tokens, derived keys.
pub fn secrets_equal(a: &[u8], b: &[u8]) -> bool {
    a.ct_eq(b).into()
}

Android Keystore ยังเป็นเจ้าของคีย์

โมเดลความปลอดภัยของ Android Keystore คือวัสดุคีย์ของคีย์ที่หนุนด้วยฮาร์ดแวร์ไม่เคยเข้าโปรเซสของแอปพลิเคชัน คีย์อยู่ใน TEE หรือ StrongBox และมีแค่คำขอการทำงานที่ข้ามไป (Android Developers, Android Keystore system)

ทางออกคือการเข้ารหัสแบบ envelope Kotlin สุ่มคีย์เข้ารหัสข้อมูล คือ DEK ซึ่งทำงานกับไฟล์ใน Rust Keystore ถือคีย์เข้ารหัสคีย์ คือ KEK ที่มีงานเดียว: ห่อและแกะไบต์ DEK 32 ไบต์นั้นด้วย AES-GCM เมกะไบต์ก้อนใหญ่ผ่าน Rust ความลับที่ต้องรอดจากการถูกเจาะอุปกรณ์อยู่หลังฮาร์ดแวร์ นี่คือ app/src/main/java/dev/davthecoder/rustseries/KeyWrapper.kt ทั้งไฟล์:

package dev.davthecoder.rustseries

import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import java.security.KeyStore
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec

/** The Keystore KEK wraps a random DEK; only the DEK crosses into Rust. */
object KeyWrapper {

    private const val KEY_ALIAS = "cryptobox-kek"
    private const val GCM_TAG_BITS = 128
    private const val IV_LEN = 12

    fun generateDek(): ByteArray =
        ByteArray(32).also { SecureRandom().nextBytes(it) }

    fun wrapDek(dek: ByteArray): ByteArray {
        val cipher = Cipher.getInstance("AES/GCM/NoPadding")
        cipher.init(Cipher.ENCRYPT_MODE, kek())
        return cipher.iv + cipher.doFinal(dek)
    }

    fun unwrapDek(wrapped: ByteArray): ByteArray {
        val iv = wrapped.copyOfRange(0, IV_LEN)
        val ciphertext = wrapped.copyOfRange(IV_LEN, wrapped.size)
        val cipher = Cipher.getInstance("AES/GCM/NoPadding")
        cipher.init(Cipher.DECRYPT_MODE, kek(), GCMParameterSpec(GCM_TAG_BITS, iv))
        return cipher.doFinal(ciphertext)
    }

    private fun kek(): SecretKey {
        val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
        keyStore.getKey(KEY_ALIAS, null)?.let { return it as SecretKey }

        val generator = KeyGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"
        )
        generator.init(
            KeyGenParameterSpec.Builder(
                KEY_ALIAS,
                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
            )
                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                .setKeySize(256)
                .build()
        )
        return generator.generateKey()
    }
}

ตัวบริดจ์เองคือ external สามตัวใน app/src/main/java/dev/davthecoder/rustseries/CryptoBox.kt:

package dev.davthecoder.rustseries

object CryptoBox {
    init {
        System.loadLibrary("cryptobox")
    }

    external fun nativeHashFile(path: String): String
    external fun nativeSeal(key: ByteArray, plaintext: ByteArray): ByteArray
    external fun nativeOpen(key: ByteArray, sealed: ByteArray): ByteArray
}

ทั้งโฟลว์คือสี่บรรทัดที่จุดเรียก:

val dek = KeyWrapper.generateDek()
val wrapped = KeyWrapper.wrapDek(dek) // persist next to the sealed file
val sealed = CryptoBox.nativeSeal(dek, plaintextBytes)
dek.fill(0) // wipe Kotlin's copy

พูดตรงๆ เกี่ยวกับบรรทัดสุดท้ายนั้น fill(0) ลบอาร์เรย์ที่คุณถือ แต่ตัวเก็บกวาดขยะอาจคัดลอกมันไปก่อนแล้ว ดังนั้นการลบฝั่งที่จัดการให้คือความพยายามที่ดีที่สุด ตัวบรรเทาจริงคืออายุของ DEK ที่สั้น การแกะเฉพาะช่วงเวลาของการทำงาน และการปล่อยให้ KEK อยู่ที่ที่ memcpy ใดไปไม่ถึง

อย่าคิดค้นโปรโตคอล

ทุกอย่างด้านบนประกอบโครงสร้างของคนอื่น และนั่นคือแนวทาง: crate สำหรับ primitive โครงสร้างที่เผยแพร่แล้วสำหรับอย่างอื่น โหมดความล้มเหลวของคริปโตในแอปในปี 2026 คือ primitive ที่ถูกต้องถูกประกอบเป็นโปรโตคอลที่ไม่ถูกต้อง: AES-CTR ที่แปะแฮชไว้ คีย์ที่อนุมานโดยแฮชรหัสผ่านครั้งเดียว รูปแบบเป็นชิ้นที่ชิ้นถูกสลับหรือตัดทิ้งโดยไม่ถูกตรวจพบ

แต่ละอย่างมีคำตอบที่เรียบและเผยแพร่แล้ว การเข้ารหัสแบบยืนยันตัวตนคือ AEAD ที่คุณมีอยู่แล้ว คีย์จากรหัสผ่านผ่านแฮชรหัสผ่านจริงอย่าง Argon2 ซึ่ง RustCrypto ก็แพ็กไว้ (docs.rs/argon2) ไฟล์ที่ใหญ่เกินกว่าการเรียก AEAD ครั้งเดียวใช้ STREAM ซึ่งอิมพลีเมนต์ในโมดูล stream ของ crate aead (docs.rs/aead): การเข้ารหัสเป็นชิ้นคือดีเพนเดนซี ถ้าความต้องการของคุณไม่ตรงกับแฮชสิ่งนี้ ปิดผนึกสิ่งนี้ หรือห่อคีย์นี้ ให้คนที่รีวิวโปรโตคอลเป็นอาชีพเข้ามา ผมเขียนท่อคริปโตของ Rust ผมไม่ได้ออกแบบโปรโตคอล และทีมแอปของคุณก็ไม่ควรทำ

คำถามที่พบบ่อย

ทำไมไม่ทำทั้งหมดนี้ใน Kotlin ด้วย Keystore?

Keystore เป็นเครื่องมือที่ถูกสำหรับงานเล็กอย่างการห่อคีย์ 32 ไบต์ และ javax.crypto ใช้ได้กับเพย์โหลดขนาดพอประมาณ Rust ได้ที่ของมันสำหรับงานก้อนใหญ่บนไฟล์ใหญ่ และสำหรับคอร์ที่แชร์ข้ามแพลตฟอร์ม มันยังอุดช่องที่ Google ทิ้งไว้: ไลบรารี security-crypto ของ Jetpack ซึ่งอยู่หลัง EncryptedFile ถูกเลิกใช้แล้ว (AndroidX release notes)

จุดที่บทความนี้พาคุณมา

AEAD ตรวจแท็กของตัวเอง nonce ที่ยาวเกินเอาบัญชีที่ทำให้การใช้งาน GCM พังออกไป และ KEK ไม่เคยออกจากฮาร์ดแวร์ ถ้า diff ในอนาคตทำให้โมดูลนี้น่าสนใจขึ้น ให้ถือว่าเป็นธงในการรีวิว

ตอนที่ 13 ครอบคลุมว่า crate เหล่านี้หนักเท่าไร ขนาดไบนารีและข้อกำหนดเพจ 16KB: การปรับไฟล์ .so ของ Rust สำหรับ release เดินคู่มือขนาดทับ crate ของชุดนี้เอง แผนที่ทั้งชุดอยู่ที่ บทความฮับ

แหล่งที่มา

Share:Compartir:แชร์:

CommentsComentariosความคิดเห็น

Loading comments…Cargando comentarios…กำลังโหลดความคิดเห็น…