fire_crypto/cipher/
mac.rs

1use crate::error::TryFromError;
2
3use std::convert::{TryFrom, TryInto};
4use std::fmt;
5
6use poly1305::Tag;
7
8// Tag is an universal_hash::Output which provides a `Eq` implementation with
9// constant time
10/// A message authentication code.
11///
12/// This is used to authenticate a message and it should always be transferred
13/// with the ciphertext. Without it data integrity and authenticity is not guaranteed.
14#[derive(Clone, PartialEq, Eq)]
15pub struct Mac {
16	tag: Tag,
17}
18
19impl Mac {
20	pub const LEN: usize = 16;
21
22	pub(crate) fn new(tag: Tag) -> Self {
23		Self { tag }
24	}
25
26	/// ## Panics
27	/// if the slice is not 16 bytes long.
28	pub fn from_slice(slice: &[u8]) -> Self {
29		slice.try_into().unwrap()
30	}
31
32	pub fn into_bytes(self) -> [u8; 16] {
33		self.tag.into()
34	}
35}
36
37impl fmt::Debug for Mac {
38	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39		f.write_str("Mac")
40	}
41}
42
43impl From<[u8; 16]> for Mac {
44	/// This function should only be used with bytes that
45	/// were received with a message.
46	fn from(bytes: [u8; 16]) -> Self {
47		Self { tag: bytes.into() }
48	}
49}
50
51impl TryFrom<&[u8]> for Mac {
52	type Error = TryFromError;
53
54	fn try_from(s: &[u8]) -> Result<Self, Self::Error> {
55		<[u8; 16]>::try_from(s)
56			.map_err(TryFromError::from_any)
57			.map(Mac::from)
58	}
59}