bitcoin_hashes/
sha1.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! SHA1 implementation.
4//!
5
6use core::ops::Index;
7use core::slice::SliceIndex;
8use core::{cmp, str};
9
10use crate::{FromSliceError, HashEngine as _};
11
12crate::internal_macros::hash_type! {
13    160,
14    false,
15    "Output of the SHA1 hash function."
16}
17
18fn from_engine(mut e: HashEngine) -> Hash {
19    // pad buffer with a single 1-bit then all 0s, until there are exactly 8 bytes remaining
20    let data_len = e.length as u64;
21
22    let zeroes = [0; BLOCK_SIZE - 8];
23    e.input(&[0x80]);
24    if e.length % BLOCK_SIZE > zeroes.len() {
25        e.input(&zeroes);
26    }
27    let pad_length = zeroes.len() - (e.length % BLOCK_SIZE);
28    e.input(&zeroes[..pad_length]);
29    debug_assert_eq!(e.length % BLOCK_SIZE, zeroes.len());
30
31    e.input(&(8 * data_len).to_be_bytes());
32    debug_assert_eq!(e.length % BLOCK_SIZE, 0);
33
34    Hash(e.midstate())
35}
36
37const BLOCK_SIZE: usize = 64;
38
39/// Engine to compute SHA1 hash function.
40#[derive(Clone)]
41pub struct HashEngine {
42    buffer: [u8; BLOCK_SIZE],
43    h: [u32; 5],
44    length: usize,
45}
46
47impl Default for HashEngine {
48    fn default() -> Self {
49        HashEngine {
50            h: [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0],
51            length: 0,
52            buffer: [0; BLOCK_SIZE],
53        }
54    }
55}
56
57impl crate::HashEngine for HashEngine {
58    type MidState = [u8; 20];
59
60    #[cfg(not(hashes_fuzz))]
61    fn midstate(&self) -> [u8; 20] {
62        let mut ret = [0; 20];
63        for (val, ret_bytes) in self.h.iter().zip(ret.chunks_exact_mut(4)) {
64            ret_bytes.copy_from_slice(&val.to_be_bytes())
65        }
66        ret
67    }
68
69    #[cfg(hashes_fuzz)]
70    fn midstate(&self) -> [u8; 20] {
71        let mut ret = [0; 20];
72        ret.copy_from_slice(&self.buffer[..20]);
73        ret
74    }
75
76    const BLOCK_SIZE: usize = 64;
77
78    fn n_bytes_hashed(&self) -> usize { self.length }
79
80    engine_input_impl!();
81}
82
83impl HashEngine {
84    // Basic unoptimized algorithm from Wikipedia
85    fn process_block(&mut self) {
86        debug_assert_eq!(self.buffer.len(), BLOCK_SIZE);
87
88        let mut w = [0u32; 80];
89        for (w_val, buff_bytes) in w.iter_mut().zip(self.buffer.chunks_exact(4)) {
90            *w_val = u32::from_be_bytes(buff_bytes.try_into().expect("4 bytes slice"))
91        }
92        for i in 16..80 {
93            w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
94        }
95
96        let mut a = self.h[0];
97        let mut b = self.h[1];
98        let mut c = self.h[2];
99        let mut d = self.h[3];
100        let mut e = self.h[4];
101
102        for (i, &wi) in w.iter().enumerate() {
103            let (f, k) = match i {
104                0..=19 => ((b & c) | (!b & d), 0x5a827999),
105                20..=39 => (b ^ c ^ d, 0x6ed9eba1),
106                40..=59 => ((b & c) | (b & d) | (c & d), 0x8f1bbcdc),
107                60..=79 => (b ^ c ^ d, 0xca62c1d6),
108                _ => unreachable!(),
109            };
110
111            let new_a =
112                a.rotate_left(5).wrapping_add(f).wrapping_add(e).wrapping_add(k).wrapping_add(wi);
113            e = d;
114            d = c;
115            c = b.rotate_left(30);
116            b = a;
117            a = new_a;
118        }
119
120        self.h[0] = self.h[0].wrapping_add(a);
121        self.h[1] = self.h[1].wrapping_add(b);
122        self.h[2] = self.h[2].wrapping_add(c);
123        self.h[3] = self.h[3].wrapping_add(d);
124        self.h[4] = self.h[4].wrapping_add(e);
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    #[test]
131    #[cfg(feature = "alloc")]
132    fn test() {
133        use crate::{sha1, Hash, HashEngine};
134
135        #[derive(Clone)]
136        struct Test {
137            input: &'static str,
138            output: Vec<u8>,
139            output_str: &'static str,
140        }
141
142        #[rustfmt::skip]
143        let tests = vec![
144            // Examples from wikipedia
145            Test {
146                input: "",
147                output: vec![
148                    0xda, 0x39, 0xa3, 0xee,
149                    0x5e, 0x6b, 0x4b, 0x0d,
150                    0x32, 0x55, 0xbf, 0xef,
151                    0x95, 0x60, 0x18, 0x90,
152                    0xaf, 0xd8, 0x07, 0x09,
153                ],
154                output_str: "da39a3ee5e6b4b0d3255bfef95601890afd80709"
155            },
156            Test {
157                input: "The quick brown fox jumps over the lazy dog",
158                output: vec![
159                    0x2f, 0xd4, 0xe1, 0xc6,
160                    0x7a, 0x2d, 0x28, 0xfc,
161                    0xed, 0x84, 0x9e, 0xe1,
162                    0xbb, 0x76, 0xe7, 0x39,
163                    0x1b, 0x93, 0xeb, 0x12,
164                ],
165                output_str: "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12",
166            },
167            Test {
168                input: "The quick brown fox jumps over the lazy cog",
169                output: vec![
170                    0xde, 0x9f, 0x2c, 0x7f,
171                    0xd2, 0x5e, 0x1b, 0x3a,
172                    0xfa, 0xd3, 0xe8, 0x5a,
173                    0x0b, 0xd1, 0x7d, 0x9b,
174                    0x10, 0x0d, 0xb4, 0xb3,
175                ],
176                output_str: "de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3",
177            },
178        ];
179
180        for test in tests {
181            // Hash through high-level API, check hex encoding/decoding
182            let hash = sha1::Hash::hash(test.input.as_bytes());
183            assert_eq!(hash, test.output_str.parse::<sha1::Hash>().expect("parse hex"));
184            assert_eq!(&hash[..], &test.output[..]);
185            assert_eq!(&hash.to_string(), &test.output_str);
186
187            // Hash through engine, checking that we can input byte by byte
188            let mut engine = sha1::Hash::engine();
189            for ch in test.input.as_bytes() {
190                engine.input(&[*ch]);
191            }
192            let manual_hash = sha1::Hash::from_engine(engine);
193            assert_eq!(hash, manual_hash);
194            assert_eq!(hash.as_byte_array(), test.output.as_slice());
195        }
196    }
197
198    #[cfg(feature = "serde")]
199    #[test]
200    fn sha1_serde() {
201        use serde_test::{assert_tokens, Configure, Token};
202
203        use crate::{sha1, Hash};
204
205        #[rustfmt::skip]
206        static HASH_BYTES: [u8; 20] = [
207            0x13, 0x20, 0x72, 0xdf,
208            0x69, 0x09, 0x33, 0x83,
209            0x5e, 0xb8, 0xb6, 0xad,
210            0x0b, 0x77, 0xe7, 0xb6,
211            0xf1, 0x4a, 0xca, 0xd7,
212        ];
213
214        let hash = sha1::Hash::from_slice(&HASH_BYTES).expect("right number of bytes");
215        assert_tokens(&hash.compact(), &[Token::BorrowedBytes(&HASH_BYTES[..])]);
216        assert_tokens(&hash.readable(), &[Token::Str("132072df690933835eb8b6ad0b77e7b6f14acad7")]);
217    }
218}
219
220#[cfg(bench)]
221mod benches {
222    use test::Bencher;
223
224    use crate::{sha1, Hash, HashEngine};
225
226    #[bench]
227    pub fn sha1_10(bh: &mut Bencher) {
228        let mut engine = sha1::Hash::engine();
229        let bytes = [1u8; 10];
230        bh.iter(|| {
231            engine.input(&bytes);
232        });
233        bh.bytes = bytes.len() as u64;
234    }
235
236    #[bench]
237    pub fn sha1_1k(bh: &mut Bencher) {
238        let mut engine = sha1::Hash::engine();
239        let bytes = [1u8; 1024];
240        bh.iter(|| {
241            engine.input(&bytes);
242        });
243        bh.bytes = bytes.len() as u64;
244    }
245
246    #[bench]
247    pub fn sha1_64k(bh: &mut Bencher) {
248        let mut engine = sha1::Hash::engine();
249        let bytes = [1u8; 65536];
250        bh.iter(|| {
251            engine.input(&bytes);
252        });
253        bh.bytes = bytes.len() as u64;
254    }
255}