expo-hybrid-crypto
v1.1.0
Published
Native hybrid encryption (AES-256-GCM + RSA-OAEP) for Expo and React Native
Maintainers
Readme
expo-hybrid-crypto
Native hybrid encryption for Expo and React Native apps: AES-256-GCM for the payload and RSA-OAEP (SHA-256) for the key, implemented in Swift (CryptoKit + Security) on iOS and Kotlin (javax.crypto) on Android.
Use it when the app needs to send data that only your backend can read (documents, images, sensitive form data) and the payload is too large for RSA alone.
Why hybrid encryption?
RSA can only encrypt a few hundred bytes and is slow. AES is fast and handles any size, but both sides need the same secret key. Hybrid encryption combines the two:
- The device generates a random, single-use AES-256 key and a 12-byte IV.
- The payload is encrypted with AES-256-GCM, which also produces an authentication tag (tampering is detected on decryption).
- The AES key is encrypted with your backend's RSA public key using OAEP with SHA-256.
- Only the holder of the RSA private key can recover the AES key and decrypt the payload.
Everything runs in native code, using the platforms' secure random generators. No key material is ever handled in JavaScript.
Installation
npx expo install expo-hybrid-cryptoThe module uses the Expo Modules API, so it needs a development build (it does not run in Expo Go):
npx expo prebuild
npx expo run:ios # or run:androidBare React Native projects must have expo installed and configured, then run npx pod-install.
Usage
import { encryptHybrid } from 'expo-hybrid-crypto';
const PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...
-----END PUBLIC KEY-----`;
// The payload must be base64. For a JSON object:
const payloadBase64 = Buffer.from(JSON.stringify(data)).toString('base64');
// For a file, read it as base64 (e.g. with expo-file-system).
const encrypted = await encryptHybrid(payloadBase64, PUBLIC_KEY_PEM);
await fetch('https://api.example.com/secure-upload', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(encrypted),
});API
encryptHybrid(largeDataBase64: string, publicKeyPem: string): Promise<HybridEncryptedPayload>
| Parameter | Description |
|---|---|
| largeDataBase64 | The data to encrypt, base64-encoded. |
| publicKeyPem | RSA public key in PEM format (-----BEGIN PUBLIC KEY-----, X.509 SubjectPublicKeyInfo). 2048 bits or more recommended. |
Returns:
type HybridEncryptedPayload = {
data: string; // AES-256-GCM ciphertext (base64), without the tag
key: string; // AES key encrypted with RSA-OAEP SHA-256 (base64)
iv: string; // 12-byte GCM nonce (base64)
tag: string; // 16-byte GCM authentication tag (base64)
};The promise rejects if the payload is not valid base64 or the public key cannot be parsed.
Decrypting on the server (Node.js)
Platform difference: both platforms use RSA-OAEP with SHA-256 as the main hash, but the MGF1 hash differs: SHA-256 on iOS and SHA-1 on Android (the default of
OAEPWithSHA-256AndMGF1Paddingin Java). Node's built-incrypto.privateDecryptuses the same hash for both, so it only decrypts iOS payloads. The example below uses node-forge, which lets you set the MGF1 hash, and tries both.
import forge from 'node-forge';
import crypto from 'node:crypto';
function unwrapKey(encryptedKeyB64, privateKeyPem) {
const privateKey = forge.pki.privateKeyFromPem(privateKeyPem);
const encrypted = forge.util.decode64(encryptedKeyB64);
for (const mgf1 of [forge.md.sha256, forge.md.sha1]) { // iOS, then Android
try {
const key = privateKey.decrypt(encrypted, 'RSA-OAEP', {
md: forge.md.sha256.create(),
mgf1: { md: mgf1.create() },
});
return Buffer.from(key, 'binary');
} catch {}
}
throw new Error('Unable to decrypt AES key');
}
export function decryptHybrid({ data, key, iv, tag }, privateKeyPem) {
const aesKey = unwrapKey(key, privateKeyPem);
const decipher = crypto.createDecipheriv('aes-256-gcm', aesKey, Buffer.from(iv, 'base64'));
decipher.setAuthTag(Buffer.from(tag, 'base64'));
return Buffer.concat([
decipher.update(Buffer.from(data, 'base64')),
decipher.final(), // throws if the data was tampered with
]);
}Algorithms
| | iOS | Android |
|---|---|---|
| Symmetric | AES-256-GCM (CryptoKit) | AES/GCM/NoPadding, 128-bit tag |
| Key wrap | RSA-OAEP, SHA-256, MGF1-SHA-256 (rsaEncryptionOAEPSHA256) | RSA-OAEP, SHA-256, MGF1-SHA-1 (OAEPWithSHA-256AndMGF1Padding) |
| Randomness | SecRandomCopyBytes | SecureRandom / KeyGenerator |
A new AES key and IV are generated on every call, so encrypting the same payload twice produces different outputs.
Security notes
- This library encrypts on the device. Keep the RSA private key only on the server and never ship it in the app.
- Hybrid encryption protects the payload in transit and at rest on your servers. It does not replace TLS or certificate pinning.
- The public key is not secret, but make sure the app cannot be tricked into using a key you don't control (ship it with the app or fetch it over a pinned channel).
Contributing
Issues and pull requests are welcome.
License
MIT © Vanderlei Oliveira Jr.
