reth_ecies/mac.rs
1//! # Ethereum MAC Module
2//!
3//! This module provides the implementation of the Ethereum MAC (Message Authentication Code)
4//! construction, as specified in the Ethereum `RLPx` protocol.
5//!
6//! The Ethereum MAC is a nonstandard MAC construction that utilizes AES-256 (as a block cipher)
7//! and Keccak-256. It is specifically designed for messages of 128 bits in length and is not
8//! intended for general MAC use.
9//!
10//! For more information, refer to the [Ethereum MAC specification](https://github.com/ethereum/devp2p/blob/master/rlpx.md#mac).
11
12use aes::Aes256Enc;
13use alloy_primitives::{Keccak256, B128, B256};
14use block_padding::NoPadding;
15use cipher::BlockEncrypt;
16use digest::KeyInit;
17
18/// [`Ethereum MAC`](https://github.com/ethereum/devp2p/blob/master/rlpx.md#mac) state.
19///
20/// The ethereum MAC is a cursed MAC construction.
21///
22/// The ethereum MAC is a nonstandard MAC construction that uses AES-256 (without a mode, as a
23/// block cipher) and Keccak-256. However, it only ever encrypts messages that are 128 bits long,
24/// and is not defined as a general MAC.
25#[derive(Debug)]
26pub struct MAC {
27 secret: B256,
28 hasher: Keccak256,
29}
30
31impl MAC {
32 /// Initialize the MAC with the given secret
33 pub fn new(secret: B256) -> Self {
34 Self { secret, hasher: Keccak256::new() }
35 }
36
37 /// Update the internal keccak256 hasher with the given data
38 pub fn update(&mut self, data: &[u8]) {
39 self.hasher.update(data)
40 }
41
42 /// Accumulate the given header bytes into the MAC's internal state.
43 pub fn update_header(&mut self, data: &[u8; 16]) {
44 let aes = Aes256Enc::new_from_slice(self.secret.as_ref()).unwrap();
45 let mut encrypted = self.digest().0;
46
47 aes.encrypt_padded::<NoPadding>(&mut encrypted, B128::len_bytes()).unwrap();
48 for i in 0..data.len() {
49 encrypted[i] ^= data[i];
50 }
51 self.hasher.update(encrypted);
52 }
53
54 /// Accumulate the given message body into the MAC's internal state.
55 pub fn update_body(&mut self, data: &[u8]) {
56 self.hasher.update(data);
57 let prev = self.digest();
58 let aes = Aes256Enc::new_from_slice(self.secret.as_ref()).unwrap();
59 let mut encrypted = prev.0;
60
61 aes.encrypt_padded::<NoPadding>(&mut encrypted, B128::len_bytes()).unwrap();
62 for i in 0..16 {
63 encrypted[i] ^= prev[i];
64 }
65 self.hasher.update(encrypted);
66 }
67
68 /// Produce a digest by finalizing the internal keccak256 hasher and returning the first 128
69 /// bits.
70 pub fn digest(&self) -> B128 {
71 B128::from_slice(&self.hasher.clone().finalize()[..16])
72 }
73}