use rand::RngCore;
use x25519_dalek::{PublicKey, StaticSecret};
use super::encryption;
use super::error::{CryptoError, CryptoResult};
pub fn generate_master_key() -> [u8; 32] {
let mut key = [0u8; 32];
rand::thread_rng().fill_bytes(&mut key);
key
}
pub fn generate_salt() -> [u8; 32] {
let mut salt = [0u8; 32];
rand::thread_rng().fill_bytes(&mut salt);
salt
}
pub fn generate_recovery_key() -> [u8; 32] {
let mut key = [0u8; 32];
rand::thread_rng().fill_bytes(&mut key);
key
}
pub fn format_recovery_key(key: &[u8; 32]) -> String {
let hex: String = key.iter().map(|b| format!("{:02X}", b)).collect();
hex.as_bytes()
.chunks(8)
.map(|chunk| std::str::from_utf8(chunk).unwrap_or(""))
.collect::<Vec<&str>>()
.join("-")
}
pub fn parse_recovery_key(formatted: &str) -> Result<Vec<u8>, String> {
let clean: String = formatted
.chars()
.filter(|c| c.is_ascii_hexdigit())
.collect();
if clean.len() != 64 {
return Err(format!(
"Invalid recovery key: expected 64 hex chars, got {}",
clean.len()
));
}
let bytes: Result<Vec<u8>, _> = (0..32)
.map(|i| u8::from_str_radix(&clean[i * 2..i * 2 + 2], 16))
.collect();
bytes.map_err(|e| format!("Invalid recovery key hex: {}", e))
}
pub fn generate_x25519_keypair() -> ([u8; 32], [u8; 32]) {
let secret = StaticSecret::random_from_rng(rand::thread_rng());
let public = PublicKey::from(&secret);
let private_bytes: [u8; 32] = secret.to_bytes();
let public_bytes: [u8; 32] = public.to_bytes();
(private_bytes, public_bytes)
}
pub fn encrypt_profile_key_for_sharing(
sender_private: &[u8; 32],
recipient_public: &[u8; 32],
profile_key: &[u8; 32],
) -> CryptoResult<Vec<u8>> {
encrypt_blob_for_sharing(sender_private, recipient_public, profile_key)
}
pub fn decrypt_shared_profile_key(
recipient_private: &[u8; 32],
sender_public: &[u8; 32],
encrypted_profile_key: &[u8],
) -> CryptoResult<[u8; 32]> {
let plaintext = decrypt_shared_blob(recipient_private, sender_public, encrypted_profile_key)?;
if plaintext.len() != 32 {
return Err(CryptoError::InvalidKeyLength {
expected: 32,
actual: plaintext.len(),
});
}
let mut key = [0u8; 32];
key.copy_from_slice(&plaintext);
Ok(key)
}
pub fn encrypt_blob_for_sharing(
sender_private: &[u8; 32],
recipient_public: &[u8; 32],
plaintext: &[u8],
) -> CryptoResult<Vec<u8>> {
let shared_secret = x25519_diffie_hellman(sender_private, recipient_public);
let enc_key = derive_sharing_key(&shared_secret)?;
encryption::encrypt(&enc_key, plaintext)
}
pub fn decrypt_shared_blob(
recipient_private: &[u8; 32],
sender_public: &[u8; 32],
ciphertext: &[u8],
) -> CryptoResult<Vec<u8>> {
let shared_secret = x25519_diffie_hellman(recipient_private, sender_public);
let enc_key = derive_sharing_key(&shared_secret)?;
encryption::decrypt(&enc_key, ciphertext)
}
pub fn generate_profile_key() -> [u8; 32] {
let mut key = [0u8; 32];
rand::thread_rng().fill_bytes(&mut key);
key
}
pub fn derive_profile_key(master_key: &[u8; 32], profile_id: i64) -> CryptoResult<[u8; 32]> {
super::namespace::KeyNamespace::Profile.derive_key(master_key, profile_id)
}
pub fn encrypt_private_key(master_key: &[u8; 32], private_key: &[u8; 32]) -> CryptoResult<Vec<u8>> {
encryption::encrypt(master_key, private_key)
}
pub fn decrypt_private_key(master_key: &[u8; 32], encrypted: &[u8]) -> CryptoResult<[u8; 32]> {
let plaintext = encryption::decrypt(master_key, encrypted)?;
if plaintext.len() != 32 {
return Err(CryptoError::InvalidKeyLength {
expected: 32,
actual: plaintext.len(),
});
}
let mut key = [0u8; 32];
key.copy_from_slice(&plaintext);
Ok(key)
}
pub fn wrap_profile_key_with_master(
master_key: &[u8; 32],
profile_key: &[u8; 32],
) -> CryptoResult<Vec<u8>> {
encryption::encrypt(master_key, profile_key)
}
pub fn unwrap_profile_key_with_master(
master_key: &[u8; 32],
wrapped: &[u8],
) -> CryptoResult<[u8; 32]> {
let plaintext = encryption::decrypt(master_key, wrapped)?;
if plaintext.len() != 32 {
return Err(CryptoError::InvalidKeyLength {
expected: 32,
actual: plaintext.len(),
});
}
let mut key = [0u8; 32];
key.copy_from_slice(&plaintext);
Ok(key)
}
fn x25519_diffie_hellman(my_private: &[u8; 32], their_public: &[u8; 32]) -> [u8; 32] {
let secret = StaticSecret::from(*my_private);
let public = PublicKey::from(*their_public);
let shared = secret.diffie_hellman(&public);
shared.to_bytes()
}
fn derive_sharing_key(shared_secret: &[u8; 32]) -> CryptoResult<[u8; 32]> {
use hkdf::Hkdf;
use sha2::Sha256;
let hk = Hkdf::<Sha256>::new(None, shared_secret);
let mut key = [0u8; 32];
hk.expand(b"incokit-profile-sharing-v1", &mut key)
.map_err(|e| CryptoError::Hkdf(e.to_string()))?;
Ok(key)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_generate_master_key() {
let k1 = generate_master_key();
let k2 = generate_master_key();
assert_ne!(k1, k2); assert_eq!(k1.len(), 32);
}
#[test]
fn test_x25519_keypair() {
let (priv_a, pub_a) = generate_x25519_keypair();
let (priv_b, pub_b) = generate_x25519_keypair();
let shared_ab = x25519_diffie_hellman(&priv_a, &pub_b);
let shared_ba = x25519_diffie_hellman(&priv_b, &pub_a);
assert_eq!(shared_ab, shared_ba);
}
#[test]
fn test_profile_key_sharing_roundtrip() {
let (priv_a, pub_a) = generate_x25519_keypair();
let (priv_b, pub_b) = generate_x25519_keypair();
let profile_key = generate_profile_key();
let encrypted = encrypt_profile_key_for_sharing(&priv_a, &pub_b, &profile_key).unwrap();
let decrypted = decrypt_shared_profile_key(&priv_b, &pub_a, &encrypted).unwrap();
assert_eq!(decrypted, profile_key);
}
#[test]
fn test_recovery_key_format() {
let key = generate_recovery_key();
let formatted = format_recovery_key(&key);
assert!(formatted.contains('-'));
assert_eq!(formatted.len(), 71);
let groups: Vec<&str> = formatted.split('-').collect();
assert_eq!(groups.len(), 8);
for g in &groups {
assert_eq!(g.len(), 8);
assert!(g.chars().all(|c| c.is_ascii_hexdigit()));
}
}
#[test]
fn test_recovery_key_roundtrip() {
let key = generate_recovery_key();
let formatted = format_recovery_key(&key);
let parsed = parse_recovery_key(&formatted).unwrap();
assert_eq!(parsed, key.to_vec());
}
#[test]
fn test_parse_recovery_key_tolerant() {
let key = [0xAB_u8; 32];
let formatted = format_recovery_key(&key);
let mangled = format!(" {} ", formatted.to_lowercase());
let parsed = parse_recovery_key(&mangled).unwrap();
assert_eq!(parsed, key.to_vec());
}
#[test]
fn test_encrypt_decrypt_private_key() {
let master = generate_master_key();
let (private_key, _) = generate_x25519_keypair();
let encrypted = encrypt_private_key(&master, &private_key).unwrap();
let decrypted = decrypt_private_key(&master, &encrypted).unwrap();
assert_eq!(decrypted, private_key);
}
#[test]
fn shared_key_not_decryptable_by_third_party() {
let (priv_a, pub_a) = generate_x25519_keypair();
let (_priv_b, pub_b) = generate_x25519_keypair();
let (priv_c, _pub_c) = generate_x25519_keypair();
let profile_key = generate_profile_key();
let sealed = encrypt_profile_key_for_sharing(&priv_a, &pub_b, &profile_key).unwrap();
let result = decrypt_shared_profile_key(&priv_c, &pub_a, &sealed);
assert!(
result.is_err(),
"a non-recipient must not be able to decrypt the share"
);
}
#[test]
fn shared_key_rejects_wrong_sender_public_key() {
let (priv_a, _pub_a) = generate_x25519_keypair();
let (priv_b, pub_b) = generate_x25519_keypair();
let (_priv_x, pub_x) = generate_x25519_keypair(); let profile_key = generate_profile_key();
let sealed = encrypt_profile_key_for_sharing(&priv_a, &pub_b, &profile_key).unwrap();
let result = decrypt_shared_profile_key(&priv_b, &pub_x, &sealed);
assert!(
result.is_err(),
"decrypt must fail when the sender public key doesn't match the sealer"
);
}
#[test]
fn shared_key_tampering_is_detected() {
let (priv_a, pub_a) = generate_x25519_keypair();
let (priv_b, pub_b) = generate_x25519_keypair();
let profile_key = generate_profile_key();
let mut sealed = encrypt_profile_key_for_sharing(&priv_a, &pub_b, &profile_key).unwrap();
let last = sealed.len() - 1;
sealed[last] ^= 0x01;
let result = decrypt_shared_profile_key(&priv_b, &pub_a, &sealed);
assert!(result.is_err(), "tampered ciphertext must be rejected");
}
#[test]
fn blob_sharing_roundtrips_arbitrary_length() {
let (priv_a, pub_a) = generate_x25519_keypair();
let (priv_b, pub_b) = generate_x25519_keypair();
for payload in [
b"".as_slice(),
b"socks5://user:pass@1.2.3.4:1080",
&[0xFFu8; 500],
] {
let sealed = encrypt_blob_for_sharing(&priv_a, &pub_b, payload).unwrap();
let opened = decrypt_shared_blob(&priv_b, &pub_a, &sealed).unwrap();
assert_eq!(
opened,
payload,
"blob of len {} must roundtrip",
payload.len()
);
}
}
#[test]
fn shared_profile_key_rejects_non_32_byte_payload() {
let (priv_a, pub_a) = generate_x25519_keypair();
let (priv_b, pub_b) = generate_x25519_keypair();
let sealed = encrypt_blob_for_sharing(&priv_a, &pub_b, &[7u8; 16]).unwrap();
let result = decrypt_shared_profile_key(&priv_b, &pub_a, &sealed);
match result {
Err(CryptoError::InvalidKeyLength { expected, actual }) => {
assert_eq!(expected, 32);
assert_eq!(actual, 16);
}
other => panic!("expected InvalidKeyLength {{ 32, 16 }}, got {other:?}"),
}
}
#[test]
fn wrap_unwrap_profile_key_with_master_roundtrips() {
let master = generate_master_key();
let profile_key = generate_profile_key();
let wrapped = wrap_profile_key_with_master(&master, &profile_key).unwrap();
assert!(wrapped.len() > 32);
assert_ne!(
&wrapped[..32],
&profile_key[..],
"must not store key in clear"
);
let unwrapped = unwrap_profile_key_with_master(&master, &wrapped).unwrap();
assert_eq!(unwrapped, profile_key);
}
#[test]
fn unwrap_profile_key_with_wrong_master_fails() {
let master = generate_master_key();
let other_master = generate_master_key();
let profile_key = generate_profile_key();
let wrapped = wrap_profile_key_with_master(&master, &profile_key).unwrap();
let result = unwrap_profile_key_with_master(&other_master, &wrapped);
assert!(result.is_err(), "a different master key must not unwrap");
}
#[test]
fn wrap_profile_key_is_non_deterministic() {
let master = generate_master_key();
let profile_key = generate_profile_key();
let a = wrap_profile_key_with_master(&master, &profile_key).unwrap();
let b = wrap_profile_key_with_master(&master, &profile_key).unwrap();
assert_ne!(a, b, "AES-GCM must use a fresh nonce each call");
assert_eq!(
unwrap_profile_key_with_master(&master, &a).unwrap(),
unwrap_profile_key_with_master(&master, &b).unwrap(),
);
}
}