solana_zk_token_sdk/zk_token_elgamal/pod/
auth_encryption.rs

1//! Plain Old Data types for the AES128-GCM-SIV authenticated encryption scheme.
2
3#[cfg(not(target_os = "solana"))]
4use crate::{encryption::auth_encryption as decoded, errors::AuthenticatedEncryptionError};
5use {
6    crate::zk_token_elgamal::pod::impl_from_str,
7    base64::{prelude::BASE64_STANDARD, Engine},
8    bytemuck::{Pod, Zeroable},
9    std::fmt,
10};
11
12/// Byte length of an authenticated encryption ciphertext
13const AE_CIPHERTEXT_LEN: usize = 36;
14
15/// Maximum length of a base64 encoded authenticated encryption ciphertext
16const AE_CIPHERTEXT_MAX_BASE64_LEN: usize = 48;
17
18/// The `AeCiphertext` type as a `Pod`.
19#[derive(Clone, Copy, PartialEq, Eq)]
20#[repr(transparent)]
21pub struct AeCiphertext(pub [u8; AE_CIPHERTEXT_LEN]);
22
23// `AeCiphertext` is a wrapper type for a byte array, which is both `Pod` and `Zeroable`. However,
24// the marker traits `bytemuck::Pod` and `bytemuck::Zeroable` can only be derived for power-of-two
25// length byte arrays. Directly implement these traits for `AeCiphertext`.
26unsafe impl Zeroable for AeCiphertext {}
27unsafe impl Pod for AeCiphertext {}
28
29impl fmt::Debug for AeCiphertext {
30    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
31        write!(f, "{:?}", self.0)
32    }
33}
34
35impl fmt::Display for AeCiphertext {
36    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37        write!(f, "{}", BASE64_STANDARD.encode(self.0))
38    }
39}
40
41impl_from_str!(
42    TYPE = AeCiphertext,
43    BYTES_LEN = AE_CIPHERTEXT_LEN,
44    BASE64_LEN = AE_CIPHERTEXT_MAX_BASE64_LEN
45);
46
47impl Default for AeCiphertext {
48    fn default() -> Self {
49        Self::zeroed()
50    }
51}
52
53#[cfg(not(target_os = "solana"))]
54impl From<decoded::AeCiphertext> for AeCiphertext {
55    fn from(decoded_ciphertext: decoded::AeCiphertext) -> Self {
56        Self(decoded_ciphertext.to_bytes())
57    }
58}
59
60#[cfg(not(target_os = "solana"))]
61impl TryFrom<AeCiphertext> for decoded::AeCiphertext {
62    type Error = AuthenticatedEncryptionError;
63
64    fn try_from(pod_ciphertext: AeCiphertext) -> Result<Self, Self::Error> {
65        Self::from_bytes(&pod_ciphertext.0).ok_or(AuthenticatedEncryptionError::Deserialization)
66    }
67}
68
69#[cfg(test)]
70mod tests {
71    use {super::*, crate::encryption::auth_encryption::AeKey, std::str::FromStr};
72
73    #[test]
74    fn ae_ciphertext_fromstr() {
75        let ae_key = AeKey::new_rand();
76        let expected_ae_ciphertext: AeCiphertext = ae_key.encrypt(0_u64).into();
77
78        let ae_ciphertext_base64_str = format!("{}", expected_ae_ciphertext);
79        let computed_ae_ciphertext = AeCiphertext::from_str(&ae_ciphertext_base64_str).unwrap();
80
81        assert_eq!(expected_ae_ciphertext, computed_ae_ciphertext);
82    }
83}