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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
use prost::Message as ProstMessage;
use serde::{Deserialize, Serialize};
use crate::{
cipher::Mac,
utilities::{base64_decode, base64_encode, VarInt},
Curve25519PublicKey, DecodeError,
};
const VERSION: u8 = 3;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Message {
pub(crate) ratchet_key: Curve25519PublicKey,
pub(crate) chain_index: u64,
pub(crate) ciphertext: Vec<u8>,
pub(crate) mac: [u8; Mac::TRUNCATED_LEN],
}
impl Message {
pub fn ratchet_key(&self) -> Curve25519PublicKey {
self.ratchet_key
}
pub fn chain_index(&self) -> u64 {
self.chain_index
}
pub fn ciphertext(&self) -> &[u8] {
&self.ciphertext
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
Self::try_from(bytes)
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut message = self.encode();
message.extend(self.mac);
message
}
pub fn from_base64(message: &str) -> Result<Self, DecodeError> {
Self::try_from(message)
}
pub fn to_base64(&self) -> String {
base64_encode(self.to_bytes())
}
pub(crate) fn new(
ratchet_key: Curve25519PublicKey,
chain_index: u64,
ciphertext: Vec<u8>,
) -> Self {
Self { ratchet_key, chain_index, ciphertext, mac: [0u8; Mac::TRUNCATED_LEN] }
}
fn encode(&self) -> Vec<u8> {
ProtoBufMessage {
ratchet_key: self.ratchet_key.to_bytes().to_vec(),
chain_index: self.chain_index,
ciphertext: self.ciphertext.clone(),
}
.encode_manual()
}
pub(crate) fn to_mac_bytes(&self) -> Vec<u8> {
self.encode()
}
}
impl Serialize for Message {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let message = self.to_base64();
serializer.serialize_str(&message)
}
}
impl<'de> Deserialize<'de> for Message {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let ciphertext = String::deserialize(d)?;
Message::from_base64(&ciphertext).map_err(serde::de::Error::custom)
}
}
impl TryFrom<&str> for Message {
type Error = DecodeError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let decoded = base64_decode(value)?;
Self::try_from(decoded)
}
}
impl TryFrom<Vec<u8>> for Message {
type Error = DecodeError;
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
Self::try_from(value.as_slice())
}
}
impl TryFrom<&[u8]> for Message {
type Error = DecodeError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
let version = *value.get(0).ok_or(DecodeError::MissingVersion)?;
if version != VERSION {
Err(DecodeError::InvalidVersion(VERSION, version))
} else if value.len() < Mac::TRUNCATED_LEN + 2 {
Err(DecodeError::MessageTooShort(value.len()))
} else {
let inner = ProtoBufMessage::decode(&value[1..value.len() - Mac::TRUNCATED_LEN])?;
let mac_slice = &value[value.len() - Mac::TRUNCATED_LEN..];
if mac_slice.len() != Mac::TRUNCATED_LEN {
Err(DecodeError::InvalidMacLength(Mac::TRUNCATED_LEN, mac_slice.len()))
} else {
let mut mac = [0u8; Mac::TRUNCATED_LEN];
mac.copy_from_slice(mac_slice);
let chain_index = inner.chain_index;
let ciphertext = inner.ciphertext;
let ratchet_key = Curve25519PublicKey::from_slice(&inner.ratchet_key)?;
let message = Message { ratchet_key, chain_index, ciphertext, mac };
Ok(message)
}
}
}
}
#[derive(ProstMessage, PartialEq, Eq)]
struct ProtoBufMessage {
#[prost(bytes, tag = "1")]
ratchet_key: Vec<u8>,
#[prost(uint64, tag = "2")]
chain_index: u64,
#[prost(bytes, tag = "4")]
ciphertext: Vec<u8>,
}
impl ProtoBufMessage {
const RATCHET_TAG: &'static [u8; 1] = b"\x0A";
const INDEX_TAG: &'static [u8; 1] = b"\x10";
const CIPHER_TAG: &'static [u8; 1] = b"\x22";
fn encode_manual(&self) -> Vec<u8> {
let index = self.chain_index.to_var_int();
let ratchet_len = self.ratchet_key.len().to_var_int();
let ciphertext_len = self.ciphertext.len().to_var_int();
[
[VERSION].as_ref(),
Self::RATCHET_TAG.as_ref(),
&ratchet_len,
&self.ratchet_key,
Self::INDEX_TAG.as_ref(),
&index,
Self::CIPHER_TAG.as_ref(),
&ciphertext_len,
&self.ciphertext,
]
.concat()
}
}
#[cfg(test)]
mod test {
use super::Message;
use crate::Curve25519PublicKey;
#[test]
fn encode() {
let message = b"\x03\n\x20ratchetkeyhereprettyplease123456\x10\x01\"\nciphertext";
let message_mac =
b"\x03\n\x20ratchetkeyhereprettyplease123456\x10\x01\"\nciphertextMACHEREE";
let ratchet_key = Curve25519PublicKey::from(*b"ratchetkeyhereprettyplease123456");
let ciphertext = b"ciphertext";
let mut encoded = Message::new(ratchet_key, 1, ciphertext.to_vec());
encoded.mac = *b"MACHEREE";
assert_eq!(encoded.to_mac_bytes(), message.as_ref());
assert_eq!(encoded.to_bytes(), message_mac.as_ref());
}
}