solana_zk_token_sdk/zk_token_elgamal/pod/
auth_encryption.rs1#[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
12const AE_CIPHERTEXT_LEN: usize = 36;
14
15const AE_CIPHERTEXT_MAX_BASE64_LEN: usize = 48;
17
18#[derive(Clone, Copy, PartialEq, Eq)]
20#[repr(transparent)]
21pub struct AeCiphertext(pub [u8; AE_CIPHERTEXT_LEN]);
22
23unsafe 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}