solana_zk_sdk/encryption/pod/
auth_encryption.rs1#[cfg(not(target_os = "solana"))]
4use crate::{encryption::auth_encryption::AeCiphertext, errors::AuthenticatedEncryptionError};
5use {
6 crate::{
7 encryption::AE_CIPHERTEXT_LEN,
8 pod::{impl_from_bytes, impl_from_str},
9 },
10 base64::{prelude::BASE64_STANDARD, Engine},
11 bytemuck::{Pod, Zeroable},
12 std::fmt,
13};
14
15const AE_CIPHERTEXT_MAX_BASE64_LEN: usize = 48;
17
18#[derive(Clone, Copy, PartialEq, Eq)]
20#[repr(transparent)]
21pub struct PodAeCiphertext(pub(crate) [u8; AE_CIPHERTEXT_LEN]);
22
23unsafe impl Zeroable for PodAeCiphertext {}
27unsafe impl Pod for PodAeCiphertext {}
28
29impl fmt::Debug for PodAeCiphertext {
30 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
31 write!(f, "{:?}", self.0)
32 }
33}
34
35impl fmt::Display for PodAeCiphertext {
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 = PodAeCiphertext,
43 BYTES_LEN = AE_CIPHERTEXT_LEN,
44 BASE64_LEN = AE_CIPHERTEXT_MAX_BASE64_LEN
45);
46
47impl_from_bytes!(TYPE = PodAeCiphertext, BYTES_LEN = AE_CIPHERTEXT_LEN);
48
49impl Default for PodAeCiphertext {
50 fn default() -> Self {
51 Self::zeroed()
52 }
53}
54
55#[cfg(not(target_os = "solana"))]
56impl From<AeCiphertext> for PodAeCiphertext {
57 fn from(decoded_ciphertext: AeCiphertext) -> Self {
58 Self(decoded_ciphertext.to_bytes())
59 }
60}
61
62#[cfg(not(target_os = "solana"))]
63impl TryFrom<PodAeCiphertext> for AeCiphertext {
64 type Error = AuthenticatedEncryptionError;
65
66 fn try_from(pod_ciphertext: PodAeCiphertext) -> Result<Self, Self::Error> {
67 Self::from_bytes(&pod_ciphertext.0).ok_or(AuthenticatedEncryptionError::Deserialization)
68 }
69}
70
71#[cfg(test)]
72mod tests {
73 use {super::*, crate::encryption::auth_encryption::AeKey, std::str::FromStr};
74
75 #[test]
76 fn ae_ciphertext_fromstr() {
77 let ae_key = AeKey::new_rand();
78 let expected_ae_ciphertext: PodAeCiphertext = ae_key.encrypt(0_u64).into();
79
80 let ae_ciphertext_base64_str = format!("{}", expected_ae_ciphertext);
81 let computed_ae_ciphertext = PodAeCiphertext::from_str(&ae_ciphertext_base64_str).unwrap();
82
83 assert_eq!(expected_ae_ciphertext, computed_ae_ciphertext);
84 }
85}