Skip to main content

hyde_core/
protected.rs

1use std::marker::PhantomData;
2
3use serde::{de::DeserializeOwned, Deserialize, Serialize};
4
5use crate::{
6    context::{HydeContext, ProtectedData},
7    error::{HydeError, Result},
8};
9
10/// A type-safe wrapper around TEE-protected data.
11///
12/// `Protected<T>` ensures the inner value `T` cannot be accessed without
13/// going through the TEE. The encrypted data is serializable for persistence.
14///
15/// Created by `Protected::new()` or by the `#[hyde::protect]` macro.
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct Protected<T> {
18    data: ProtectedData,
19    #[serde(skip)]
20    _phantom: PhantomData<T>,
21}
22
23impl<T: Serialize + DeserializeOwned> Protected<T> {
24    /// Protect a value by serializing it and encrypting with the TEE.
25    pub fn new(ctx: &mut HydeContext, value: &T) -> Result<Self> {
26        let bytes = serde_json::to_vec(value)
27            .map_err(|e| HydeError::Serialization(e.to_string()))?;
28        let data = ctx.protect(&bytes)?;
29        Ok(Self {
30            data,
31            _phantom: PhantomData,
32        })
33    }
34
35    /// Decrypt and deserialize the protected value. Requires the same TEE.
36    pub fn unprotect(&self, ctx: &mut HydeContext) -> Result<T> {
37        let bytes = ctx.unprotect(&self.data)?;
38        serde_json::from_slice(&bytes)
39            .map_err(|e| HydeError::Serialization(e.to_string()))
40    }
41
42    /// Access the underlying `ProtectedData` for backup/restore operations.
43    pub fn protected_data(&self) -> &ProtectedData {
44        &self.data
45    }
46
47    /// Construct from raw `ProtectedData` (e.g., after restore).
48    pub fn from_protected_data(data: ProtectedData) -> Self {
49        Self {
50            data,
51            _phantom: PhantomData,
52        }
53    }
54}