auth_encryption.rs 2.8 KB

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