use crate::{Keypair, Signature};
use base64::{engine::general_purpose, Engine as _};
use rand::{distr::Alphanumeric, RngExt};
use serde::{Deserialize, Serialize};
pub const NCRYPTF_CONTENT_TYPE: &str = "application/vnd.ncryptf+json";
pub const NCRYPTF_DRIFT_ALLOWANCE: i32 = 90;
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ExportableEncryptionKeyData {
pub public: String,
pub signature: String,
pub hash_id: String,
pub expires_at: i64,
pub ephemeral: bool,
}
impl ExportableEncryptionKeyData {
pub fn is_expired(&self) -> bool {
return chrono::Utc::now().timestamp() >= self.expires_at;
}
pub fn get_public_key(&self) -> Option<Vec<u8>> {
if self.public.is_empty() {
return None;
}
return Some(general_purpose::STANDARD.decode(self.public.clone()).unwrap());
}
pub fn get_signature_key(&self) -> Option<Vec<u8>> {
if self.public.is_empty() {
return None;
}
return Some(general_purpose::STANDARD.decode(self.signature.clone()).unwrap());
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EncryptionKey {
bkp: Keypair,
skp: Keypair,
ephemeral: bool,
pub expires_at: i64,
hash_id: String,
}
impl EncryptionKey {
pub fn get_box_kp(&self) -> Keypair {
return self.bkp.clone();
}
pub fn get_sign_kp(&self) -> Keypair {
return self.skp.clone();
}
pub fn is_ephemeral(&self) -> bool {
return self.ephemeral;
}
pub fn get_hash_id(&self) -> String {
return self.hash_id.clone();
}
pub fn is_expired(&self) -> bool {
if chrono::Utc::now().timestamp() >= self.expires_at {
return true;
}
return false;
}
pub fn new(ephemeral: bool) -> Self {
let s: String = rand::rng()
.sample_iter(&Alphanumeric)
.take(24)
.map(char::from)
.collect();
let expiration = chrono::Utc::now() + chrono::Duration::hours(1);
return Self {
bkp: Keypair::new(),
skp: Signature::new(),
ephemeral: ephemeral,
expires_at: expiration.timestamp(),
hash_id: s,
};
}
}