use crate::{error::CgkaError, operation::CgkaOperation, pcs_key::PcsKey};
use alloc::vec::Vec;
use core::marker::PhantomData;
use keyhive_crypto::{
content::reference::ContentRef,
digest::Digest,
share_key::{ShareKey, ShareSecretKey},
signed::Signed,
siv::Siv,
symmetric_key::SymmetricKey,
};
use serde::{Deserialize, Serialize};
use tracing::instrument;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct EncryptedContent<T, Cr: ContentRef> {
pub nonce: Siv,
pub ciphertext: Vec<u8>,
pub pcs_key_hash: Digest<PcsKey>,
pub pcs_update_op_hash: Digest<Signed<CgkaOperation>>,
pub content_ref: Cr,
pub pred_refs: Digest<Vec<Cr>>,
_plaintext_tag: PhantomData<T>,
}
impl<T, Cr: ContentRef> EncryptedContent<T, Cr> {
pub fn new(
nonce: Siv,
ciphertext: Vec<u8>,
pcs_key_hash: Digest<PcsKey>,
pcs_update_op_hash: Digest<Signed<CgkaOperation>>,
content_ref: Cr,
pred_refs: Digest<Vec<Cr>>,
) -> EncryptedContent<T, Cr> {
EncryptedContent {
nonce,
ciphertext,
pcs_key_hash,
pcs_update_op_hash,
content_ref,
pred_refs,
_plaintext_tag: PhantomData,
}
}
pub fn try_decrypt(&self, key: SymmetricKey) -> Result<Vec<u8>, chacha20poly1305::Error> {
let mut buf: Vec<u8> = self.ciphertext.clone();
key.try_decrypt(self.nonce, &mut buf)?;
Ok(buf)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
pub struct EncryptedSecret<T> {
pub nonce: Siv,
pub ciphertext: Vec<u8>,
pub paired_pk: ShareKey,
_plaintext_tag: PhantomData<T>,
}
impl<T> EncryptedSecret<T> {
pub fn new(nonce: Siv, ciphertext: Vec<u8>, paired_pk: ShareKey) -> EncryptedSecret<T> {
EncryptedSecret {
nonce,
ciphertext,
paired_pk,
_plaintext_tag: PhantomData,
}
}
#[instrument(skip(self))]
pub fn try_encrypter_decrypt(
&self,
encrypter_secret_key: &ShareSecretKey,
) -> Result<Vec<u8>, chacha20poly1305::Error> {
let mut buf: Vec<u8> = self.ciphertext.clone();
let key = encrypter_secret_key.derive_symmetric_key(&self.paired_pk);
key.try_decrypt(self.nonce, &mut buf)?;
Ok(buf)
}
}
impl<T: core::hash::Hash, Cr: ContentRef> core::hash::Hash for EncryptedContent<T, Cr> {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
let EncryptedContent {
nonce,
ciphertext,
pcs_key_hash,
pcs_update_op_hash,
content_ref,
pred_refs,
_plaintext_tag,
} = self;
nonce.hash(state);
ciphertext.hash(state);
pcs_key_hash.hash(state);
pcs_update_op_hash.hash(state);
content_ref.hash(state);
pred_refs.hash(state);
}
}
pub fn encrypt_secret(
doc_id: &[u8],
secret: ShareSecretKey,
sk: &ShareSecretKey,
paired_pk: &ShareKey,
) -> Result<EncryptedSecret<ShareSecretKey>, CgkaError> {
let key = sk.derive_symmetric_key(paired_pk);
let mut ciphertext: Vec<u8> = (&secret).into();
let nonce = Siv::new(&key, &ciphertext, doc_id);
key.try_encrypt(nonce, &mut ciphertext)
.map_err(CgkaError::Encryption)?;
Ok(EncryptedSecret::new(nonce, ciphertext, *paired_pk))
}