use aes_gcm::{
aead::{Aead, KeyInit},
Aes256Gcm, Key, Nonce,
};
use anyhow::{Context, Result};
use std::path::Path;
pub const ENC_PREFIX: &str = "enc:v1:";
pub fn load_or_create_key(path: &Path) -> Result<[u8; 32]> {
if path.exists() {
let bytes = std::fs::read(path).context("Failed to read secret key file")?;
anyhow::ensure!(
bytes.len() == 32,
"Secret key file '{}' is corrupted ({} bytes, expected 32). \
Delete it manually to regenerate, but note that existing encrypted values will be lost.",
path.display(),
bytes.len()
);
let mut key = [0u8; 32];
key.copy_from_slice(&bytes);
return Ok(key);
}
let mut key = [0u8; 32];
use rand::RngCore;
rand::thread_rng().fill_bytes(&mut key);
std::fs::write(path, key).context("Failed to write secret key file")?;
set_owner_readonly(path);
Ok(key)
}
#[cfg(unix)]
fn set_owner_readonly(path: &Path) {
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}
#[cfg(not(unix))]
fn set_owner_readonly(_path: &Path) {}
pub fn encrypt(key: &[u8; 32], plaintext: &str) -> Result<String> {
let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key));
let mut nonce_bytes = [0u8; 12];
use rand::RngCore;
rand::thread_rng().fill_bytes(&mut nonce_bytes);
let nonce = Nonce::from_slice(&nonce_bytes);
let ciphertext = cipher
.encrypt(nonce, plaintext.as_bytes())
.map_err(|_| anyhow::anyhow!("Encryption failed"))?;
let mut combined = nonce_bytes.to_vec();
combined.extend_from_slice(&ciphertext);
Ok(format!("{}{}", ENC_PREFIX, hex::encode(&combined)))
}
pub fn decrypt(key: &[u8; 32], value: &str) -> Result<String> {
let hex_str = value
.strip_prefix(ENC_PREFIX)
.ok_or_else(|| anyhow::anyhow!("Value is not an encrypted blob"))?;
let combined = hex::decode(hex_str).context("Invalid hex in encrypted value")?;
if combined.len() < 12 {
anyhow::bail!("Encrypted value is too short to contain a nonce");
}
let (nonce_bytes, ciphertext) = combined.split_at(12);
let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key));
let nonce = Nonce::from_slice(nonce_bytes);
let plaintext = cipher
.decrypt(nonce, ciphertext)
.map_err(|_| anyhow::anyhow!("Decryption failed — key mismatch or data corrupted"))?;
String::from_utf8(plaintext).context("Decrypted bytes are not valid UTF-8")
}
pub fn is_encrypted(value: &str) -> bool {
value.starts_with(ENC_PREFIX)
}
#[cfg(test)]
mod tests;