ft_sdk/
crypto.rs

1pub use ft_sys::DecryptionError;
2
3#[derive(Clone, diesel::expression::AsExpression)]
4#[diesel(sql_type = diesel::sql_types::Text)]
5pub struct EncryptedString(String);
6
7impl EncryptedString {
8    /// construct EncryptedString from an already encrypted string.
9    /// useful for wrapping say string from a cookie.
10    pub fn from_already_encrypted_string(input: String) -> Self {
11        EncryptedString(input)
12    }
13}
14
15impl std::fmt::Display for EncryptedString {
16    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17        f.write_str(self.0.as_str())
18    }
19}
20
21impl From<PlainText> for EncryptedString {
22    fn from(input: PlainText) -> Self {
23        EncryptedString(ft_sys::encrypt(input.0.as_str()))
24    }
25}
26
27#[cfg(feature = "postgres")]
28impl diesel::serialize::ToSql<diesel::sql_types::Text, diesel::pg::Pg> for EncryptedString {
29    fn to_sql<'a>(
30        &'a self,
31        out: &mut diesel::serialize::Output<'a, '_, diesel::pg::Pg>,
32    ) -> diesel::serialize::Result {
33        diesel::serialize::ToSql::<diesel::sql_types::Text, diesel::pg::Pg>::to_sql(&self.0, out)
34    }
35}
36
37impl TryInto<PlainText> for EncryptedString {
38    type Error = ft_sdk::DecryptionError;
39
40    fn try_into(self) -> Result<PlainText, Self::Error> {
41        Ok(PlainText(ft_sys::decrypt(self.0.as_str())?))
42    }
43}
44
45impl std::fmt::Debug for EncryptedString {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        f.debug_tuple("EncryptedString")
48            .field(&"[REDACTED]")
49            .finish()
50    }
51}
52
53pub struct PlainText(String);
54
55impl From<&str> for PlainText {
56    fn from(input: &str) -> Self {
57        PlainText(input.to_owned())
58    }
59}
60
61impl From<PlainText> for String {
62    fn from(val: PlainText) -> String {
63        val.0
64    }
65}
66
67impl std::fmt::Display for PlainText {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        f.write_str(self.0.as_str())
70    }
71}