ate_crypto/crypto/
encrypted_secure_data.rs1use crate::spec::SerializationFormat;
2use crate::utils::vec_deserialize;
3use crate::utils::vec_serialize;
4use serde::{Deserialize, Serialize};
5use std::result::Result;
6use std::{io::ErrorKind, marker::PhantomData};
7#[allow(unused_imports)]
8use tracing::{debug, error, info, instrument, span, trace, warn, Level};
9
10use super::*;
11
12#[derive(Serialize, Deserialize, Debug, Clone)]
13pub struct EncryptedSecureData<T>
14where
15 T: serde::Serialize + serde::de::DeserializeOwned,
16{
17 format: SerializationFormat,
18 ek_hash: AteHash,
19 sd_iv: InitializationVector,
20 #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")]
21 sd_encrypted: Vec<u8>,
22 #[serde(skip)]
23 _marker: std::marker::PhantomData<T>,
24}
25
26impl<T> EncryptedSecureData<T>
27where
28 T: serde::Serialize + serde::de::DeserializeOwned,
29{
30 pub fn new(
31 encrypt_key: &EncryptKey,
32 data: T,
33 ) -> Result<EncryptedSecureData<T>, std::io::Error> {
34 let format = SerializationFormat::Bincode;
35 let data = match format.serialize(data) {
36 Ok(a) => a,
37 Err(err) => {
38 return Err(std::io::Error::new(ErrorKind::Other, err.to_string()));
39 }
40 };
41 let result = encrypt_key.encrypt(&data[..]);
42
43 Ok(EncryptedSecureData {
44 format,
45 ek_hash: encrypt_key.hash(),
46 sd_iv: result.iv,
47 sd_encrypted: result.data,
48 _marker: PhantomData,
49 })
50 }
51
52 pub fn unwrap(&self, key: &EncryptKey) -> Result<T, std::io::Error> {
53 let data = key.decrypt(&self.sd_iv, &self.sd_encrypted[..]);
54 Ok(match self.format.deserialize_ref(&data[..]) {
55 Ok(a) => a,
56 Err(err) => {
57 return Err(std::io::Error::new(ErrorKind::Other, err.to_string()));
58 }
59 })
60 }
61
62 pub fn ek_hash(&self) -> AteHash {
63 self.ek_hash
64 }
65}