Skip to main content

pg_ntex_session/
encryption.rs

1//! Utilities for session encryption.
2//! 
3//! ## Package feature
4//! 
5//! * `StateEncryption`. A trait interfacing encryption-decryption on states/data saved in the DB
6//! * `Simple`. A struct that implements ```StateEncryption```, based on [*simple_crypt*](https://docs.rs/simple_crypt/0.2.3/simple_crypt/index.html) crate.
7
8use std::fmt::Display;
9
10use simple_crypt::{decrypt, encrypt};
11
12/// StateEncryption trait. An encryption/decryption struct must implement this trait.
13/// 
14/// Only has 2: ```encrypt``` and ```decrypt```
15pub trait StateEncryption {
16    fn encrypt(&self,plain_text:impl Display)->anyhow::Result<Vec<u8>>;
17    fn decrypt(&self,encoded_text:impl AsRef<[u8]>)->anyhow::Result<String>;
18}
19
20/// Simple encryption and decryption, implements [*StateEncryption*](./trait.StateEncryption.html) trait
21/// 
22/// Based on [*simple_crypt*](https://docs.rs/simple_crypt/0.2.3/simple_crypt/index.html) crate.
23#[derive(Debug,Clone)]
24pub struct Simple(String);
25
26impl Simple
27{
28/// Creates a new ```Simple``` instance, with 32 chars of password
29/// 
30    pub fn new(password:impl Display)->Self
31    {
32        Self(password.to_string())
33    }
34}
35
36impl StateEncryption for Simple
37{
38/// Implements a decryption. Takes an encoded text (binary) as input.
39/// Discouraged to use this manually, as [*PgNtexSession*](../struct.PgNtexSession.html) calls this internally
40    fn decrypt(&self,encoded_text:impl AsRef<[u8]>)->anyhow::Result<String> {
41        let plain=decrypt(encoded_text.as_ref(), self.0.as_bytes())?;
42        Ok(String::from_utf8(plain)?)
43    }
44
45/// Implements an encryption. Takes an plain text as input.
46/// Discouraged to use this manually, as [*PgNtexSession*](../struct.PgNtexSession.html) calls this internally
47    fn encrypt(&self,plain_text:impl Display)->anyhow::Result<Vec<u8>> {
48        let plain_text=plain_text.to_string();
49        Ok(encrypt(plain_text.as_bytes(), self.0.as_bytes())?)
50    }
51}