1 // ring has a garbage API so its use is avoided, but rust-crypto doesn't have RFC-variant poly1305
2 // Instead, we steal rust-crypto's implementation and tweak it to match the RFC.
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 // This is a port of Andrew Moons poly1305-donna
11 // https://github.com/floodyberry/poly1305-donna
13 use crate::ln::msgs::DecodeError;
14 use crate::util::ser::{FixedLengthReader, LengthRead, LengthReadableArgs, Readable, Writeable, Writer};
15 use crate::io::{self, Read, Write};
19 use crate::util::chacha20::ChaCha20;
20 use crate::util::poly1305::Poly1305;
21 use bitcoin::hashes::cmp::fixed_time_eq;
23 #[derive(Clone, Copy)]
24 pub struct ChaCha20Poly1305RFC {
32 impl ChaCha20Poly1305RFC {
34 fn pad_mac_16(mac: &mut Poly1305, len: usize) {
36 mac.input(&[0; 16][0..16 - (len % 16)]);
39 pub fn new(key: &[u8], nonce: &[u8], aad: &[u8]) -> ChaCha20Poly1305RFC {
40 assert!(key.len() == 16 || key.len() == 32);
41 assert!(nonce.len() == 12);
43 // Ehh, I'm too lazy to *also* tweak ChaCha20 to make it RFC-compliant
44 assert!(nonce[0] == 0 && nonce[1] == 0 && nonce[2] == 0 && nonce[3] == 0);
46 let mut cipher = ChaCha20::new(key, &nonce[4..]);
47 let mut mac_key = [0u8; 64];
48 let zero_key = [0u8; 64];
49 cipher.process(&zero_key, &mut mac_key);
51 let mut mac = Poly1305::new(&mac_key[..32]);
53 ChaCha20Poly1305RFC::pad_mac_16(&mut mac, aad.len());
60 aad_len: aad.len() as u64,
64 pub fn encrypt(&mut self, input: &[u8], output: &mut [u8], out_tag: &mut [u8]) {
65 assert!(input.len() == output.len());
66 assert!(self.finished == false);
67 self.cipher.process(input, output);
68 self.data_len += input.len();
69 self.mac.input(output);
70 ChaCha20Poly1305RFC::pad_mac_16(&mut self.mac, self.data_len);
72 self.mac.input(&self.aad_len.to_le_bytes());
73 self.mac.input(&(self.data_len as u64).to_le_bytes());
74 self.mac.raw_result(out_tag);
77 pub fn encrypt_full_message_in_place(&mut self, input_output: &mut [u8], out_tag: &mut [u8]) {
78 self.encrypt_in_place(input_output);
79 self.finish_and_get_tag(out_tag);
82 // Encrypt `input_output` in-place. To finish and calculate the tag, use `finish_and_get_tag`
84 pub(super) fn encrypt_in_place(&mut self, input_output: &mut [u8]) {
85 debug_assert!(self.finished == false);
86 self.cipher.process_in_place(input_output);
87 self.data_len += input_output.len();
88 self.mac.input(input_output);
91 // If we were previously encrypting with `encrypt_in_place`, this method can be used to finish
92 // encrypting and calculate the tag.
93 pub(super) fn finish_and_get_tag(&mut self, out_tag: &mut [u8]) {
94 debug_assert!(self.finished == false);
95 ChaCha20Poly1305RFC::pad_mac_16(&mut self.mac, self.data_len);
97 self.mac.input(&self.aad_len.to_le_bytes());
98 self.mac.input(&(self.data_len as u64).to_le_bytes());
99 self.mac.raw_result(out_tag);
102 pub fn decrypt(&mut self, input: &[u8], output: &mut [u8], tag: &[u8]) -> bool {
103 assert!(input.len() == output.len());
104 assert!(self.finished == false);
106 self.finished = true;
108 self.mac.input(input);
110 self.data_len += input.len();
111 ChaCha20Poly1305RFC::pad_mac_16(&mut self.mac, self.data_len);
112 self.mac.input(&self.aad_len.to_le_bytes());
113 self.mac.input(&(self.data_len as u64).to_le_bytes());
115 let mut calc_tag = [0u8; 16];
116 self.mac.raw_result(&mut calc_tag);
117 if fixed_time_eq(&calc_tag, tag) {
118 self.cipher.process(input, output);
125 // Decrypt in place, without checking the tag. Use `finish_and_check_tag` to check it
126 // later when decryption finishes.
128 // Should never be `pub` because the public API should always enforce tag checking.
129 pub(super) fn decrypt_in_place(&mut self, input_output: &mut [u8]) {
130 debug_assert!(self.finished == false);
131 self.mac.input(input_output);
132 self.data_len += input_output.len();
133 self.cipher.process_in_place(input_output);
136 // If we were previously decrypting with `decrypt_in_place`, this method must be used to finish
137 // decrypting and check the tag. Returns whether or not the tag is valid.
138 pub(super) fn finish_and_check_tag(&mut self, tag: &[u8]) -> bool {
139 debug_assert!(self.finished == false);
140 self.finished = true;
141 ChaCha20Poly1305RFC::pad_mac_16(&mut self.mac, self.data_len);
142 self.mac.input(&self.aad_len.to_le_bytes());
143 self.mac.input(&(self.data_len as u64).to_le_bytes());
145 let mut calc_tag = [0u8; 16];
146 self.mac.raw_result(&mut calc_tag);
147 if fixed_time_eq(&calc_tag, tag) {
156 pub use self::real_chachapoly::ChaCha20Poly1305RFC;
158 /// Enables simultaneously reading and decrypting a ChaCha20Poly1305RFC stream from a std::io::Read.
159 struct ChaChaPolyReader<'a, R: Read> {
160 pub chacha: &'a mut ChaCha20Poly1305RFC,
164 impl<'a, R: Read> Read for ChaChaPolyReader<'a, R> {
165 // Decrypt bytes from Self::read into `dest`.
166 // `ChaCha20Poly1305RFC::finish_and_check_tag` must be called to check the tag after all reads
168 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
169 let res = self.read.read(dest)?;
171 self.chacha.decrypt_in_place(&mut dest[0..res]);
177 /// Enables simultaneously writing and encrypting a byte stream into a Writer.
178 struct ChaChaPolyWriter<'a, W: Writer> {
179 pub chacha: &'a mut ChaCha20Poly1305RFC,
180 pub write: &'a mut W,
183 impl<'a, W: Writer> Writer for ChaChaPolyWriter<'a, W> {
184 // Encrypt then write bytes from `src` into Self::write.
185 // `ChaCha20Poly1305RFC::finish_and_get_tag` can be called to retrieve the tag after all writes
187 fn write_all(&mut self, src: &[u8]) -> Result<(), io::Error> {
189 while src_idx < src.len() {
190 let mut write_buffer = [0; 8192];
191 let bytes_written = (&mut write_buffer[..]).write(&src[src_idx..]).expect("In-memory writes can't fail");
192 self.chacha.encrypt_in_place(&mut write_buffer[..bytes_written]);
193 self.write.write_all(&write_buffer[..bytes_written])?;
194 src_idx += bytes_written;
200 /// Enables the use of the serialization macros for objects that need to be simultaneously encrypted and
201 /// serialized. This allows us to avoid an intermediate Vec allocation.
202 pub(crate) struct ChaChaPolyWriteAdapter<'a, W: Writeable> {
204 pub writeable: &'a W,
207 impl<'a, W: Writeable> ChaChaPolyWriteAdapter<'a, W> {
208 #[allow(unused)] // This will be used for onion messages soon
209 pub fn new(rho: [u8; 32], writeable: &'a W) -> ChaChaPolyWriteAdapter<'a, W> {
210 Self { rho, writeable }
214 impl<'a, T: Writeable> Writeable for ChaChaPolyWriteAdapter<'a, T> {
215 // Simultaneously write and encrypt Self::writeable.
216 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
217 let mut chacha = ChaCha20Poly1305RFC::new(&self.rho, &[0; 12], &[]);
218 let mut chacha_stream = ChaChaPolyWriter { chacha: &mut chacha, write: w };
219 self.writeable.write(&mut chacha_stream)?;
220 let mut tag = [0 as u8; 16];
221 chacha.finish_and_get_tag(&mut tag);
228 /// Enables the use of the serialization macros for objects that need to be simultaneously decrypted and
229 /// deserialized. This allows us to avoid an intermediate Vec allocation.
230 pub(crate) struct ChaChaPolyReadAdapter<R: Readable> {
234 impl<T: Readable> LengthReadableArgs<[u8; 32]> for ChaChaPolyReadAdapter<T> {
235 // Simultaneously read and decrypt an object from a LengthRead, storing it in Self::readable.
236 // LengthRead must be used instead of std::io::Read because we need the total length to separate
237 // out the tag at the end.
238 fn read<R: LengthRead>(mut r: &mut R, secret: [u8; 32]) -> Result<Self, DecodeError> {
239 if r.total_bytes() < 16 { return Err(DecodeError::InvalidValue) }
241 let mut chacha = ChaCha20Poly1305RFC::new(&secret, &[0; 12], &[]);
242 let decrypted_len = r.total_bytes() - 16;
243 let s = FixedLengthReader::new(&mut r, decrypted_len);
244 let mut chacha_stream = ChaChaPolyReader { chacha: &mut chacha, read: s };
245 let readable: T = Readable::read(&mut chacha_stream)?;
246 chacha_stream.read.eat_remaining()?;
248 let mut tag = [0 as u8; 16];
249 r.read_exact(&mut tag)?;
250 if !chacha.finish_and_check_tag(&tag) {
251 return Err(DecodeError::InvalidValue)
254 Ok(Self { readable })
259 mod fuzzy_chachapoly {
260 #[derive(Clone, Copy)]
261 pub struct ChaCha20Poly1305RFC {
265 impl ChaCha20Poly1305RFC {
266 pub fn new(key: &[u8], nonce: &[u8], _aad: &[u8]) -> ChaCha20Poly1305RFC {
267 assert!(key.len() == 16 || key.len() == 32);
268 assert!(nonce.len() == 12);
270 // Ehh, I'm too lazy to *also* tweak ChaCha20 to make it RFC-compliant
271 assert!(nonce[0] == 0 && nonce[1] == 0 && nonce[2] == 0 && nonce[3] == 0);
273 let mut tag = [0; 16];
274 tag.copy_from_slice(&key[0..16]);
276 ChaCha20Poly1305RFC {
282 pub fn encrypt(&mut self, input: &[u8], output: &mut [u8], out_tag: &mut [u8]) {
283 assert!(input.len() == output.len());
284 assert!(self.finished == false);
286 output.copy_from_slice(&input);
287 out_tag.copy_from_slice(&self.tag);
288 self.finished = true;
291 pub fn encrypt_full_message_in_place(&mut self, input_output: &mut [u8], out_tag: &mut [u8]) {
292 self.encrypt_in_place(input_output);
293 self.finish_and_get_tag(out_tag);
296 pub(super) fn encrypt_in_place(&mut self, _input_output: &mut [u8]) {
297 assert!(self.finished == false);
300 pub(super) fn finish_and_get_tag(&mut self, out_tag: &mut [u8]) {
301 assert!(self.finished == false);
302 out_tag.copy_from_slice(&self.tag);
303 self.finished = true;
306 pub fn decrypt(&mut self, input: &[u8], output: &mut [u8], tag: &[u8]) -> bool {
307 assert!(input.len() == output.len());
308 assert!(self.finished == false);
310 if tag[..] != self.tag[..] { return false; }
311 output.copy_from_slice(input);
312 self.finished = true;
316 pub(super) fn decrypt_in_place(&mut self, _input: &mut [u8]) {
317 assert!(self.finished == false);
320 pub(super) fn finish_and_check_tag(&mut self, tag: &[u8]) -> bool {
321 if tag[..] != self.tag[..] { return false; }
322 self.finished = true;
328 pub use self::fuzzy_chachapoly::ChaCha20Poly1305RFC;
332 use crate::ln::msgs::DecodeError;
333 use super::{ChaChaPolyReadAdapter, ChaChaPolyWriteAdapter};
334 use crate::util::ser::{self, FixedLengthReader, LengthReadableArgs, Writeable};
336 // Used for for testing various lengths of serialization.
337 #[derive(Debug, PartialEq, Eq)]
338 struct TestWriteable {
343 impl_writeable_tlv_based!(TestWriteable, {
344 (1, field1, vec_type),
345 (2, field2, vec_type),
346 (3, field3, vec_type),
350 fn test_chacha_stream_adapters() {
351 // Check that ChaChaPolyReadAdapter and ChaChaPolyWriteAdapter correctly encode and decode an
353 macro_rules! check_object_read_write {
355 // First, serialize the object, encrypted with ChaCha20Poly1305.
357 let writeable_len = $obj.serialized_length() as u64 + 16;
358 let write_adapter = ChaChaPolyWriteAdapter::new(rho, &$obj);
359 let encrypted_writeable_bytes = write_adapter.encode();
360 let encrypted_writeable = &encrypted_writeable_bytes[..];
362 // Now deserialize the object back and make sure it matches the original.
363 let mut rd = FixedLengthReader::new(encrypted_writeable, writeable_len);
364 let read_adapter = <ChaChaPolyReadAdapter<TestWriteable>>::read(&mut rd, rho).unwrap();
365 assert_eq!($obj, read_adapter.readable);
369 // Try a big object that will require multiple write buffers.
370 let big_writeable = TestWriteable {
372 field2: vec![44; 4192],
373 field3: vec![45; 4192 + 1],
375 check_object_read_write!(big_writeable);
377 // Try a small object that fits into one write buffer.
378 let small_writeable = TestWriteable {
383 check_object_read_write!(small_writeable);
386 fn do_chacha_stream_adapters_ser_macros() -> Result<(), DecodeError> {
387 let writeable = TestWriteable {
389 field2: vec![44; 4192],
390 field3: vec![45; 4192 + 1],
393 // First, serialize the object into a TLV stream, encrypted with ChaCha20Poly1305.
395 let write_adapter = ChaChaPolyWriteAdapter::new(rho, &writeable);
396 let mut writer = ser::VecWriter(Vec::new());
397 encode_tlv_stream!(&mut writer, {
398 (1, write_adapter, required),
401 // Now deserialize the object back and make sure it matches the original.
402 let mut read_adapter: Option<ChaChaPolyReadAdapter<TestWriteable>> = None;
403 decode_tlv_stream!(&writer.0[..], {
404 (1, read_adapter, (option: LengthReadableArgs, rho)),
406 assert_eq!(writeable, read_adapter.unwrap().readable);
412 fn chacha_stream_adapters_ser_macros() {
413 // Test that our stream adapters work as expected with the TLV macros.
414 // This also serves to test the `option: $trait` variant of the `decode_tlv` ser macro.
415 do_chacha_stream_adapters_ser_macros().unwrap()