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
115
116
117
118
119
use hmac::{Hmac, Mac};
use serde::{Deserialize, Serialize};
use sha2::{digest::CtOutput, Sha256};
use zeroize::Zeroize;
use super::{
message_key::{MessageKey, RemoteMessageKey},
ratchet::RatchetPublicKey,
};
const MESSAGE_KEY_SEED: &[u8; 1] = b"\x01";
const ADVANCEMENT_SEED: &[u8; 1] = b"\x02";
fn expand_chain_key(key: &[u8; 32]) -> Box<[u8; 32]> {
let mut mac =
Hmac::<Sha256>::new_from_slice(key).expect("Can't create HmacSha256 from the key");
mac.update(MESSAGE_KEY_SEED);
let mut output = mac.finalize().into_bytes();
let mut key = Box::new([0u8; 32]);
key.copy_from_slice(output.as_slice());
output.zeroize();
key
}
fn advance(key: &[u8; 32]) -> CtOutput<Hmac<Sha256>> {
let mut mac = Hmac::<Sha256>::new_from_slice(key)
.expect("Coulnd't create a valid Hmac object to advance the ratchet");
mac.update(ADVANCEMENT_SEED);
mac.finalize()
}
#[derive(Clone, Zeroize, Serialize, Deserialize)]
#[zeroize(drop)]
pub(super) struct ChainKey {
key: Box<[u8; 32]>,
index: u64,
}
#[derive(Clone, Zeroize, Serialize, Deserialize)]
#[zeroize(drop)]
pub(super) struct RemoteChainKey {
key: Box<[u8; 32]>,
index: u64,
}
impl RemoteChainKey {
pub fn new(bytes: Box<[u8; 32]>) -> Self {
Self { key: bytes, index: 0 }
}
pub fn chain_index(&self) -> u64 {
self.index
}
#[cfg(feature = "libolm-compat")]
pub fn from_bytes_and_index(bytes: Box<[u8; 32]>, index: u32) -> Self {
Self { key: bytes, index: index.into() }
}
pub fn advance(&mut self) {
let output = advance(&self.key).into_bytes();
self.key.copy_from_slice(output.as_slice());
self.index += 1;
}
pub fn create_message_key(&mut self) -> RemoteMessageKey {
let key = expand_chain_key(&self.key);
let message_key = RemoteMessageKey::new(key, self.index);
self.advance();
message_key
}
}
impl ChainKey {
pub fn new(bytes: Box<[u8; 32]>) -> Self {
Self { key: bytes, index: 0 }
}
#[cfg(feature = "libolm-compat")]
pub fn from_bytes_and_index(bytes: Box<[u8; 32]>, index: u32) -> Self {
Self { key: bytes, index: index.into() }
}
pub fn advance(&mut self) {
let output = advance(&self.key).into_bytes();
self.key.copy_from_slice(output.as_slice());
self.index += 1;
}
pub fn create_message_key(&mut self, ratchet_key: RatchetPublicKey) -> MessageKey {
let key = expand_chain_key(&self.key);
let message_key = MessageKey::new(key, ratchet_key, self.index);
self.advance();
message_key
}
}