RSA Utils - Rust Implementation
A Rust implementation of RSA file encryption utilities, converted from Java. This library provides RSA key generation, encryption/decryption, and hybrid file encryption using RSA + AES.
Features
- RSA Key Generation: Generate 2048-bit RSA key pairs
- Key Encoding/Decoding: Base64 encoding for public (X.509/SPKI) and private (PKCS#8) keys
- Data Encryption: Encrypt data with RSA public key (supports chunking for large data)
- Hybrid File Encryption: Encrypt files using AES-128-CBC for content and RSA for key wrapping
- Compatible Format: Uses the same hybrid approach as the Java implementation
Requirements
- Rust 1.90.0 or later
Usage
Generate RSA Key Pair
use ;
let key_pair = init_key?;
let public_key_str = encode_public_key?;
let private_key_str = encode_private_key?;
println!;
println!;
Encrypt Small Data
use encrypt;
let plain_text = b"Hello, World!";
let encrypted = encrypt?;
Encrypt/Decrypt Files
use ;
// Encrypt a file
encrypt_file?;
// Decrypt a file
decrypt_file?;
How It Works
File Encryption Process
- Generate a random AES-128 key and IV
- Encrypt the AES key + IV with RSA public key (key wrapping)
- Write the wrapped key length and wrapped key to output file
- Encrypt the file content with AES-128-CBC
- Write encrypted content to output file
File Decryption Process
- Read wrapped key length and wrapped key from input file
- Decrypt (unwrap) the AES key + IV with RSA private key
- Decrypt the file content with AES-128-CBC
- Write decrypted content to output file
Running Tests
Differences from Java Implementation
- Error Handling: Uses Rust's
Resulttype with custom error enum instead of exceptions - Memory Safety: Rust's ownership system ensures memory safety without garbage collection
- Cipher Mode: Uses AES-128-CBC with PKCS7 padding (similar to Java's default AES behavior)
- Key Format:
- Public keys: X.509/SPKI format (same as Java's X509EncodedKeySpec)
- Private keys: PKCS#8 format (same as Java's PKCS8EncodedKeySpec)
Dependencies
rsa: RSA encryption/decryptionaes: AES encryptioncipher: Cipher traits and block modesbase64: Base64 encoding/decodingrand: Random number generationpkcs8&pkcs1: Key encoding/decodingthiserror: Error handling
License
This is a conversion of Java RSA utilities to Rust.