use crate::error::{Error, Result};
use crate::pager::PageId;
use chacha20poly1305::aead::{Aead, Payload};
use chacha20poly1305::{ChaCha20Poly1305, Key, KeyInit, Nonce, XChaCha20Poly1305, XNonce};
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
use zeroize::Zeroize;
pub const TAG_SIZE: usize = 16;
pub const XNONCE_SIZE: usize = 24;
pub const CRYPTO_TRAILER_SIZE: usize = XNONCE_SIZE + TAG_SIZE;
pub const KEY_SIZE: usize = 32;
pub const SALT_SIZE: usize = 16;
pub const KCV_MAGIC: &[u8] = b"TAPIRUS_CIPHER_KCV_V1";
pub const ENCRYPTED_PAGE_USABLE_SIZE: usize = 4096 - CRYPTO_TRAILER_SIZE;
pub const PBKDF2_RECOMMENDED_ITERATIONS: u32 = 600_000;
pub const PBKDF2_FAST_ITERATIONS: u32 = 10_000;
pub fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
let mut k_block = [0u8; 64];
if key.len() > 64 {
let hashed = Sha256::digest(key);
k_block[0..32].copy_from_slice(&hashed);
} else {
k_block[0..key.len()].copy_from_slice(key);
}
let mut ipad = [0u8; 64];
let mut opad = [0u8; 64];
for i in 0..64 {
ipad[i] = k_block[i] ^ 0x36;
opad[i] = k_block[i] ^ 0x5c;
}
let mut inner_hasher = Sha256::new();
inner_hasher.update(ipad);
inner_hasher.update(data);
let inner_hash = inner_hasher.finalize();
let mut outer_hasher = Sha256::new();
outer_hasher.update(opad);
outer_hasher.update(inner_hash);
let outer_hash = outer_hasher.finalize();
let mut out = [0u8; 32];
out.copy_from_slice(&outer_hash);
k_block.zeroize();
ipad.zeroize();
opad.zeroize();
out
}
pub fn pbkdf2_hmac_sha256(passphrase: &[u8], salt: &[u8], iterations: u32) -> [u8; 32] {
assert!(iterations >= 1);
let mut salt_and_int = Vec::with_capacity(salt.len() + 4);
salt_and_int.extend_from_slice(salt);
salt_and_int.extend_from_slice(&1u32.to_be_bytes());
let mut u_prev = hmac_sha256(passphrase, &salt_and_int);
let mut result = u_prev;
for _ in 1..iterations {
u_prev = hmac_sha256(passphrase, &u_prev);
for j in 0..32 {
result[j] ^= u_prev[j];
}
}
u_prev.zeroize();
salt_and_int.zeroize();
result
}
pub fn derive_key(passphrase: &str, salt: &[u8; 16]) -> [u8; 32] {
pbkdf2_hmac_sha256(passphrase.as_bytes(), salt, PBKDF2_RECOMMENDED_ITERATIONS)
}
pub fn derive_key_with_iterations(passphrase: &str, salt: &[u8; 16], iterations: u32) -> [u8; 32] {
pbkdf2_hmac_sha256(passphrase.as_bytes(), salt, iterations)
}
pub fn generate_random_salt() -> [u8; 16] {
let mut salt = [0u8; 16];
getrandom::fill(&mut salt).expect("OS CSPRNG unavailable — cannot generate secure salt");
salt
}
pub struct DatabaseCipher {
key: [u8; 32],
salt: [u8; 16],
epoch: u32,
}
impl Zeroize for DatabaseCipher {
fn zeroize(&mut self) {
self.key.zeroize();
self.salt.zeroize();
self.epoch = 0;
}
}
impl Drop for DatabaseCipher {
fn drop(&mut self) {
self.zeroize();
}
}
fn build_page_aad(page_id: PageId, page_bytes: &[u8]) -> ([u8; 49], usize) {
let mut aad = [0u8; 49];
aad[0..4].copy_from_slice(&page_id.to_le_bytes());
if page_id == 1 && page_bytes.len() >= 81 {
aad[4..16].copy_from_slice(&page_bytes[0..12]);
aad[16..49].copy_from_slice(&page_bytes[48..81]);
(aad, 49)
} else {
(aad, 4)
}
}
impl DatabaseCipher {
pub fn new(key: [u8; 32], salt: [u8; 16]) -> Self {
Self {
key,
salt,
epoch: 1,
}
}
pub fn from_passphrase(passphrase: &str, salt: [u8; 16]) -> Self {
let key = derive_key(passphrase, &salt);
Self {
key,
salt,
epoch: 1,
}
}
pub fn from_passphrase_with_iterations(
passphrase: &str,
salt: [u8; 16],
iterations: u32,
) -> Self {
let key = derive_key_with_iterations(passphrase, &salt, iterations);
Self {
key,
salt,
epoch: 1,
}
}
pub fn salt(&self) -> &[u8; 16] {
&self.salt
}
pub fn key(&self) -> &[u8; 32] {
&self.key
}
pub fn epoch(&self) -> u32 {
self.epoch
}
pub fn set_epoch(&mut self, epoch: u32) {
self.epoch = epoch;
}
pub fn derive_nonce_with_seq(&self, page_id: PageId, sequence: u32, epoch: u32) -> [u8; 12] {
let mut nonce = [0u8; 12];
nonce[0..4].copy_from_slice(&epoch.to_le_bytes());
nonce[4..8].copy_from_slice(&page_id.to_le_bytes());
nonce[8..12].copy_from_slice(&sequence.to_le_bytes());
nonce
}
pub fn derive_nonce(&self, page_id: PageId) -> [u8; 12] {
self.derive_nonce_with_seq(page_id, 0, self.epoch)
}
pub fn generate_kcv(&self) -> Result<[u8; 16]> {
let mut key = Key::from(self.key);
let cipher = ChaCha20Poly1305::new(&key);
key.as_mut_slice().zeroize();
let nonce = Nonce::try_from(&self.salt[0..12])
.map_err(|_| Error::Corrupted("Invalid salt slice for KCV nonce".into()))?;
let ciphertext = cipher.encrypt(&nonce, KCV_MAGIC).map_err(|_| {
Error::Corrupted("KCV generation failed: ChaCha20-Poly1305 encryption error".into())
})?;
if ciphertext.len() < 16 {
return Err(Error::Corrupted("KCV ciphertext too short".into()));
}
let mut tag = [0u8; 16];
tag.copy_from_slice(&ciphertext[ciphertext.len() - 16..]);
Ok(tag)
}
pub fn verify_kcv(&self, stored_kcv: &[u8; 16]) -> bool {
let expected = match self.generate_kcv() {
Ok(v) => v,
Err(_) => return false,
};
expected.ct_eq(stored_kcv).into()
}
pub fn encrypt_page(&self, page_id: PageId, plaintext: &[u8]) -> Result<Vec<u8>> {
let mut nonce_bytes = [0u8; XNONCE_SIZE];
getrandom::fill(&mut nonce_bytes)
.expect("OS CSPRNG unavailable — cannot generate secure nonce");
self.encrypt_page_with_nonce(page_id, &nonce_bytes, plaintext)
}
pub fn encrypt_page_with_nonce(
&self,
page_id: PageId,
nonce_bytes: &[u8; XNONCE_SIZE],
plaintext: &[u8],
) -> Result<Vec<u8>> {
if plaintext.len() != 4096 {
return Err(Error::Corrupted(format!(
"Expected 4096 byte page, got {}",
plaintext.len()
)));
}
let mut key = Key::from(self.key);
let cipher = XChaCha20Poly1305::new(&key);
key.as_mut_slice().zeroize();
let nonce = XNonce::from(*nonce_bytes);
let (pt_start, pt_end) = if page_id == 1 {
(100, ENCRYPTED_PAGE_USABLE_SIZE)
} else {
(0, ENCRYPTED_PAGE_USABLE_SIZE)
};
let pt_slice = &plaintext[pt_start..pt_end];
let (aad_buf, aad_len) = build_page_aad(page_id, plaintext);
let payload = Payload {
msg: pt_slice,
aad: &aad_buf[..aad_len],
};
let ct = cipher
.encrypt(&nonce, payload)
.map_err(|e| Error::Corrupted(format!("Encryption error: {e}")))?;
let tag_offset = ct.len() - TAG_SIZE;
let actual_ct = &ct[..tag_offset];
let tag = &ct[tag_offset..];
let mut out_page = vec![0u8; 4096];
if page_id == 1 {
out_page[0..100].copy_from_slice(&plaintext[0..100]);
}
out_page[pt_start..pt_end].copy_from_slice(actual_ct);
out_page[ENCRYPTED_PAGE_USABLE_SIZE..ENCRYPTED_PAGE_USABLE_SIZE + XNONCE_SIZE]
.copy_from_slice(nonce_bytes);
out_page[ENCRYPTED_PAGE_USABLE_SIZE + XNONCE_SIZE..4096].copy_from_slice(tag);
Ok(out_page)
}
pub fn encrypt_page_with_seq(
&self,
page_id: PageId,
sequence: u32,
epoch: u32,
plaintext: &[u8],
) -> Result<Vec<u8>> {
let mut nonce = [0u8; XNONCE_SIZE];
nonce[0..4].copy_from_slice(&epoch.to_le_bytes());
nonce[4..8].copy_from_slice(&page_id.to_le_bytes());
nonce[8..12].copy_from_slice(&sequence.to_le_bytes());
self.encrypt_page_with_nonce(page_id, &nonce, plaintext)
}
pub fn decrypt_page(&self, page_id: PageId, disk_page: &[u8]) -> Result<Vec<u8>> {
if disk_page.len() != 4096 {
return Err(Error::Corrupted(format!(
"Expected 4096 byte page, got {}",
disk_page.len()
)));
}
let mut key = Key::from(self.key);
let cipher = XChaCha20Poly1305::new(&key);
key.as_mut_slice().zeroize();
let (pt_start, pt_end) = if page_id == 1 {
(100, ENCRYPTED_PAGE_USABLE_SIZE)
} else {
(0, ENCRYPTED_PAGE_USABLE_SIZE)
};
let ct_slice = &disk_page[pt_start..pt_end];
let nonce_slice =
&disk_page[ENCRYPTED_PAGE_USABLE_SIZE..ENCRYPTED_PAGE_USABLE_SIZE + XNONCE_SIZE];
let tag_slice = &disk_page[ENCRYPTED_PAGE_USABLE_SIZE + XNONCE_SIZE..4096];
let nonce = XNonce::try_from(nonce_slice).map_err(|_| Error::DecryptionFailed(page_id))?;
let mut combined = Vec::with_capacity(ct_slice.len() + tag_slice.len());
combined.extend_from_slice(ct_slice);
combined.extend_from_slice(tag_slice);
let (aad_buf, aad_len) = build_page_aad(page_id, disk_page);
let payload = Payload {
msg: &combined,
aad: &aad_buf[..aad_len],
};
let pt = cipher
.decrypt(&nonce, payload)
.map_err(|_| Error::DecryptionFailed(page_id))?;
let mut out_page = vec![0u8; 4096];
if page_id == 1 {
out_page[0..100].copy_from_slice(&disk_page[0..100]);
}
out_page[pt_start..pt_end].copy_from_slice(&pt);
Ok(out_page)
}
pub fn decrypt_page_with_seq(
&self,
page_id: PageId,
_sequence: u32,
_epoch: u32,
disk_page: &[u8],
) -> Result<Vec<u8>> {
self.decrypt_page(page_id, disk_page)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cipher_roundtrip_page() {
let salt = [7u8; 16];
let cipher = DatabaseCipher::from_passphrase_with_iterations(
"super-secret-robot-key",
salt,
PBKDF2_FAST_ITERATIONS,
);
let kcv = cipher.generate_kcv().unwrap();
assert!(cipher.verify_kcv(&kcv));
let wrong_cipher = DatabaseCipher::from_passphrase_with_iterations(
"wrong-password",
salt,
PBKDF2_FAST_ITERATIONS,
);
assert!(!wrong_cipher.verify_kcv(&kcv));
let mut original_page = vec![0u8; 4096];
original_page[10] = 42;
original_page[500] = 99;
original_page[4000] = 123;
let encrypted = cipher.encrypt_page(2, &original_page).unwrap();
assert_ne!(encrypted, original_page);
assert_eq!(encrypted.len(), 4096);
let decrypted = cipher.decrypt_page(2, &encrypted).unwrap();
assert_eq!(decrypted[10], 42);
assert_eq!(decrypted[500], 99);
assert_eq!(decrypted[4000], 123);
let fail = wrong_cipher.decrypt_page(2, &encrypted);
assert!(fail.is_err());
}
#[test]
fn test_cipher_roundtrip_page1() {
let salt = [3u8; 16];
let cipher = DatabaseCipher::from_passphrase_with_iterations(
"mars-rover-mission",
salt,
PBKDF2_FAST_ITERATIONS,
);
let mut page1 = vec![0u8; 4096];
page1[0..8].copy_from_slice(b"TAPIRUS\0"); page1[200] = 88;
let encrypted = cipher.encrypt_page(1, &page1).unwrap();
assert_eq!(&encrypted[0..8], b"TAPIRUS\0"); assert_ne!(encrypted[200], 88);
let decrypted = cipher.decrypt_page(1, &encrypted).unwrap();
assert_eq!(&decrypted[0..8], b"TAPIRUS\0");
assert_eq!(decrypted[200], 88);
}
#[test]
fn test_pbkdf2_rfc6070_vectors() {
let p = b"password";
let s = b"salt";
let key_c1 = pbkdf2_hmac_sha256(p, s, 1);
let expected_c1 = [
0x12, 0x0f, 0xb6, 0xcf, 0xfc, 0xf8, 0xb3, 0x2c, 0x43, 0xe7, 0x22, 0x52, 0x56, 0xc4,
0xf8, 0x37, 0xa8, 0x65, 0x48, 0xc9, 0x2c, 0xcc, 0x35, 0x48, 0x08, 0x05, 0x98, 0x7c,
0xb7, 0x0b, 0xe1, 0x7b,
];
assert_eq!(key_c1, expected_c1);
let key_c2 = pbkdf2_hmac_sha256(p, s, 2);
let expected_c2 = [
0xae, 0x4d, 0x0c, 0x95, 0xaf, 0x6b, 0x46, 0xd3, 0x2d, 0x0a, 0xdf, 0xf9, 0x28, 0xf0,
0x6d, 0xd0, 0x2a, 0x30, 0x3f, 0x8e, 0xf3, 0xc2, 0x51, 0xdf, 0xd6, 0xe2, 0xd8, 0x5a,
0x95, 0x47, 0x4c, 0x43,
];
assert_eq!(key_c2, expected_c2);
}
#[test]
fn test_random_nonce_uniqueness() {
let salt = [11u8; 16];
let cipher = DatabaseCipher::from_passphrase_with_iterations(
"quantum_encryption_2026",
salt,
PBKDF2_FAST_ITERATIONS,
);
let page_data = vec![0xaau8; 4096];
let ct1 = cipher.encrypt_page(4, &page_data).unwrap();
let ct2 = cipher.encrypt_page(4, &page_data).unwrap();
assert_ne!(ct1, ct2);
assert_ne!(
&ct1[ENCRYPTED_PAGE_USABLE_SIZE..ENCRYPTED_PAGE_USABLE_SIZE + XNONCE_SIZE],
&ct2[ENCRYPTED_PAGE_USABLE_SIZE..ENCRYPTED_PAGE_USABLE_SIZE + XNONCE_SIZE]
);
let pt1 = cipher.decrypt_page(4, &ct1).unwrap();
let pt2 = cipher.decrypt_page(4, &ct2).unwrap();
assert_eq!(
&pt1[0..ENCRYPTED_PAGE_USABLE_SIZE],
&page_data[0..ENCRYPTED_PAGE_USABLE_SIZE]
);
assert_eq!(
&pt2[0..ENCRYPTED_PAGE_USABLE_SIZE],
&page_data[0..ENCRYPTED_PAGE_USABLE_SIZE]
);
let swap_fail = cipher.decrypt_page(5, &ct1);
assert!(swap_fail.is_err());
let mut tampered_ct = ct1.clone();
tampered_ct[50] ^= 0x01;
assert!(cipher.decrypt_page(4, &tampered_ct).is_err());
let mut tampered_nonce = ct1.clone();
tampered_nonce[ENCRYPTED_PAGE_USABLE_SIZE + 2] ^= 0x01;
assert!(cipher.decrypt_page(4, &tampered_nonce).is_err());
let mut tampered_tag = ct1.clone();
tampered_tag[4090] ^= 0x01;
assert!(cipher.decrypt_page(4, &tampered_tag).is_err());
}
#[test]
fn test_database_cipher_zeroize_scrubs_key_and_salt() {
let mut cipher = DatabaseCipher::new([0xA5u8; 32], [0x5Au8; 16]);
cipher.set_epoch(9);
assert_eq!(cipher.key(), &[0xA5u8; 32]);
assert_eq!(cipher.salt(), &[0x5Au8; 16]);
assert_eq!(cipher.epoch(), 9);
cipher.zeroize();
assert_eq!(cipher.key(), &[0u8; 32]);
assert_eq!(cipher.salt(), &[0u8; 16]);
assert_eq!(cipher.epoch(), 0);
assert!(core::mem::needs_drop::<DatabaseCipher>());
}
#[test]
fn test_page1_immutable_header_authenticated_by_aead() {
let salt = [9u8; 16];
let cipher = DatabaseCipher::from_passphrase_with_iterations(
"header-auth-secret",
salt,
PBKDF2_FAST_ITERATIONS,
);
let mut page1 = vec![0u8; 4096];
page1[0..8].copy_from_slice(b"TAPIRUS\0");
page1[8..10].copy_from_slice(&4096u16.to_le_bytes());
page1[10..12].copy_from_slice(&1u16.to_le_bytes());
page1[48] = 1;
page1[49..65].copy_from_slice(&salt);
page1[65..81].copy_from_slice(&cipher.generate_kcv().unwrap());
page1[200] = 0x7E;
let encrypted = cipher.encrypt_page(1, &page1).unwrap();
assert!(cipher.decrypt_page(1, &encrypted).is_ok());
for offset in [0usize, 8, 10, 48, 50, 70] {
let mut tampered = encrypted.clone();
tampered[offset] ^= 0x01;
assert!(
cipher.decrypt_page(1, &tampered).is_err(),
"Page 1 header tampering at byte {offset} must fail AEAD"
);
}
}
}