cipherstash-client 0.34.1-alpha.3

The official CipherStash SDK
Documentation
use super::{DataKeyWithTag, EncryptPayload};
use aes_gcm_siv::{aead::Payload, Nonce};
use recipher::key::{Iv, Key};
use uuid::Uuid;

/// An encryption target is a payload that is ready to be encrypted.
pub struct EncryptionTarget<'e> {
    payload: EncryptPayload<'e>,
    key_with_tag: DataKeyWithTag,
    aad: Vec<u8>,
    keyset_id: Option<Uuid>,
}

impl<'e> EncryptionTarget<'e> {
    pub(crate) fn new(
        payload: EncryptPayload<'e>,
        key: DataKeyWithTag,
        keyset_id: Option<Uuid>,
    ) -> Self {
        let descriptor_bytes = payload.descriptor.as_bytes();
        // The AAD is the descriptor and the tag generated by ZeroKMS
        // This ensures we have key committment
        // TODO: Split this out into an AAD type
        // TODO: We should include the keyset_id in the AAD (if there is one)
        let mut aad = Vec::with_capacity(descriptor_bytes.len() + key.tag.len());
        aad.extend_from_slice(descriptor_bytes);
        aad.extend_from_slice(&key.tag);

        Self {
            payload,
            key_with_tag: key,
            aad,
            keyset_id,
        }
    }

    /// We're using the first 12 bytes of the IV as the nonce for AES-GCM-SIV.
    pub(super) fn nonce(&self) -> &Nonce {
        Nonce::from_slice(&self.key_with_tag.iv[..12])
    }

    pub(super) fn key(&self) -> &Key {
        self.key_with_tag.key()
    }

    /// Consumes self and returns the metadata that should be stored with the encrypted record.
    /// This is the IV, tag, and descriptor.
    pub(super) fn into_meta(self) -> (Iv, Vec<u8>, String, Option<Uuid>) {
        (
            self.key_with_tag.iv,
            self.key_with_tag.tag,
            self.payload.descriptor.to_string(),
            self.keyset_id,
        )
    }
}

impl<'e> From<&'e EncryptionTarget<'e>> for Payload<'e, 'e> {
    fn from(target: &'e EncryptionTarget<'e>) -> Self {
        Payload {
            msg: target.payload.msg,
            aad: &target.aad,
        }
    }
}