1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
use std::io::{self, Read, Write};
use super::{
crypto::{CryptoError, CryptoStore},
SecureHeader, SECURE_HEADER_SIZE,
};
#[derive(Debug)]
pub enum SecureLayerError {
Bincode(bincode::Error),
Io(io::Error),
Crypto(CryptoError),
}
impl From<bincode::Error> for SecureLayerError {
fn from(err: bincode::Error) -> Self {
Self::Bincode(err)
}
}
impl From<io::Error> for SecureLayerError {
fn from(err: io::Error) -> Self {
Self::Io(err)
}
}
impl From<CryptoError> for SecureLayerError {
fn from(err: CryptoError) -> Self {
Self::Crypto(err)
}
}
pub struct SecureLayer<S> {
crypto: CryptoStore,
stream: S,
current_header: Option<SecureHeader>,
}
impl<S> SecureLayer<S> {
pub fn new(crypto: CryptoStore, stream: S) -> Self {
Self { crypto, stream, current_header: None }
}
pub fn stream(&self) -> &S {
&self.stream
}
pub fn stream_mut(&mut self) -> &mut S {
&mut self.stream
}
pub fn crypto(&self) -> &CryptoStore {
&self.crypto
}
pub fn unwrap(self) -> (CryptoStore, S) {
(self.crypto, self.stream)
}
}
impl<S: Read> SecureLayer<S> {
pub fn read(&mut self) -> Result<Vec<u8>, SecureLayerError> {
let header = match self.current_header.take() {
Some(header) => header,
None => {
let mut header_buf = [0_u8; SECURE_HEADER_SIZE];
self.stream.read_exact(&mut header_buf)?;
bincode::deserialize::<SecureHeader>(&header_buf)?
},
};
let mut encrypted_buf = vec![0_u8; (header.data_size - 16) as usize];
if let Err(err) = self.stream.read_exact(&mut encrypted_buf) {
self.current_header = Some(header);
return Err(SecureLayerError::from(err));
}
let data = self.crypto.decrypt_aes(&encrypted_buf, &header.iv)?;
Ok(data)
}
}
impl<S: Write> SecureLayer<S> {
pub fn write(&mut self, buf: &[u8]) -> Result<usize, SecureLayerError> {
let mut iv = [0_u8; 16];
CryptoStore::gen_random(&mut iv);
let data_buf = self.crypto.encrypt_aes(&buf, &iv)?;
let secure_header = SecureHeader {
data_size: (data_buf.len() + iv.len()) as u32,
iv,
};
self.stream
.write_all(&bincode::serialize(&secure_header)?)
.and(self.stream.write_all(&data_buf))?;
Ok(buf.len())
}
}