Skip to main content

kevy_lua/
sha1.rs

1//! Hand-rolled SHA-1 (RFC 3174 / FIPS 180-1).
2//!
3//! Used by the SCRIPT LOAD / EVALSHA cache key and the
4//! `redis.sha1hex` host fn. Kevy's L2 lockdown forbids crates.io
5//! third-party deps; SHA-1 is short enough to write once and lint
6//! against well-known test vectors.
7//!
8//! ## NOT a security primitive
9//!
10//! SHA-1 is broken for collision resistance (SHAttered, 2017+).
11//! That doesn't matter here — kevy uses it as a content-addressed
12//! cache key the same way Redis does, where collisions would only
13//! cause cross-script cache hits (which never produces a security
14//! issue) and Redis itself uses SHA-1 for the same reason.
15//!
16//! If kevy ever needs SHA-1 / SHA-256 for an actual security-bearing
17//! purpose, that's a separate `kevy-crypto` stone, not here.
18
19/// Compute the SHA-1 of `data`. Returns the 20-byte digest.
20pub fn sha1(data: &[u8]) -> [u8; 20] {
21    let mut h: [u32; 5] = [
22        0x6745_2301,
23        0xEFCD_AB89,
24        0x98BA_DCFE,
25        0x1032_5476,
26        0xC3D2_E1F0,
27    ];
28
29    // Pre-processing: append `1` bit, then `0` bits until length ≡ 448 (mod 512),
30    // then 64-bit big-endian original-length-in-bits.
31    let bit_len: u64 = (data.len() as u64) * 8;
32    let mut buf: Vec<u8> = Vec::with_capacity(data.len() + 72);
33    buf.extend_from_slice(data);
34    buf.push(0x80);
35    while buf.len() % 64 != 56 {
36        buf.push(0);
37    }
38    buf.extend_from_slice(&bit_len.to_be_bytes());
39    debug_assert_eq!(buf.len() % 64, 0);
40
41    for chunk in buf.chunks_exact(64) {
42        let mut w = [0u32; 80];
43        for (i, word) in chunk.chunks_exact(4).enumerate() {
44            w[i] = u32::from_be_bytes([word[0], word[1], word[2], word[3]]);
45        }
46        for i in 16..80 {
47            w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
48        }
49        let mut a = h[0];
50        let mut b = h[1];
51        let mut c = h[2];
52        let mut d = h[3];
53        let mut e = h[4];
54        for (i, &wi) in w.iter().enumerate() {
55            let (f, k) = match i {
56                0..=19 => ((b & c) | ((!b) & d), 0x5A82_7999),
57                20..=39 => (b ^ c ^ d, 0x6ED9_EBA1),
58                40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1B_BCDC),
59                _ => (b ^ c ^ d, 0xCA62_C1D6),
60            };
61            let t = a
62                .rotate_left(5)
63                .wrapping_add(f)
64                .wrapping_add(e)
65                .wrapping_add(k)
66                .wrapping_add(wi);
67            e = d;
68            d = c;
69            c = b.rotate_left(30);
70            b = a;
71            a = t;
72        }
73        h[0] = h[0].wrapping_add(a);
74        h[1] = h[1].wrapping_add(b);
75        h[2] = h[2].wrapping_add(c);
76        h[3] = h[3].wrapping_add(d);
77        h[4] = h[4].wrapping_add(e);
78    }
79
80    let mut out = [0u8; 20];
81    for (i, &word) in h.iter().enumerate() {
82        out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
83    }
84    out
85}
86
87/// Format a 20-byte SHA-1 digest as 40 lowercase ASCII hex chars.
88pub fn hex(digest: &[u8; 20]) -> [u8; 40] {
89    const HEX: &[u8; 16] = b"0123456789abcdef";
90    let mut out = [0u8; 40];
91    for (i, &byte) in digest.iter().enumerate() {
92        out[i * 2] = HEX[(byte >> 4) as usize];
93        out[i * 2 + 1] = HEX[(byte & 0x0f) as usize];
94    }
95    out
96}
97
98/// Parse a 40-character ASCII hex string into a SHA-1 digest.
99/// Returns `None` on malformed input (wrong length or non-hex chars).
100pub fn parse_hex(hex_str: &[u8]) -> Option<[u8; 20]> {
101    if hex_str.len() != 40 {
102        return None;
103    }
104    let mut out = [0u8; 20];
105    for (i, pair) in hex_str.chunks_exact(2).enumerate() {
106        let hi = hex_nibble(pair[0])?;
107        let lo = hex_nibble(pair[1])?;
108        out[i] = (hi << 4) | lo;
109    }
110    Some(out)
111}
112
113fn hex_nibble(b: u8) -> Option<u8> {
114    match b {
115        b'0'..=b'9' => Some(b - b'0'),
116        b'a'..=b'f' => Some(b - b'a' + 10),
117        b'A'..=b'F' => Some(b - b'A' + 10),
118        _ => None,
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    /// RFC 3174 / FIPS 180-1 — standard SHA-1 test vectors.
127    #[test]
128    fn empty_string() {
129        // SHA1("") = da39a3ee5e6b4b0d3255bfef95601890afd80709
130        let d = sha1(b"");
131        assert_eq!(
132            hex(&d),
133            *b"da39a3ee5e6b4b0d3255bfef95601890afd80709"
134        );
135    }
136
137    #[test]
138    fn abc() {
139        // SHA1("abc") = a9993e364706816aba3e25717850c26c9cd0d89d
140        let d = sha1(b"abc");
141        assert_eq!(
142            hex(&d),
143            *b"a9993e364706816aba3e25717850c26c9cd0d89d"
144        );
145    }
146
147    #[test]
148    fn quick_brown_fox() {
149        // SHA1("The quick brown fox jumps over the lazy dog")
150        //   = 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12
151        let d = sha1(b"The quick brown fox jumps over the lazy dog");
152        assert_eq!(
153            hex(&d),
154            *b"2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"
155        );
156    }
157
158    #[test]
159    fn quick_brown_fox_dot() {
160        // SHA1("The quick brown fox jumps over the lazy cog")
161        //   = de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3
162        let d = sha1(b"The quick brown fox jumps over the lazy cog");
163        assert_eq!(
164            hex(&d),
165            *b"de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3"
166        );
167    }
168
169    #[test]
170    fn fips180_56_byte_msg() {
171        // SHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")
172        //   = 84983e441c3bd26ebaae4aa1f95129e5e54670f1
173        let d = sha1(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq");
174        assert_eq!(
175            hex(&d),
176            *b"84983e441c3bd26ebaae4aa1f95129e5e54670f1"
177        );
178    }
179
180    #[test]
181    fn eight_byte_return_1() {
182        // openssl says SHA1("return 1") = e0e1f9fabfc9d4800c877a703b823ac0578ff8db
183        let d = sha1(b"return 1");
184        assert_eq!(
185            hex(&d),
186            *b"e0e1f9fabfc9d4800c877a703b823ac0578ff8db"
187        );
188    }
189
190    #[test]
191    fn four_byte_input() {
192        // openssl: SHA1("1234") = 7110eda4d09e062aa5e4a390b0a572ac0d2c0220
193        let d = sha1(b"1234");
194        assert_eq!(
195            hex(&d),
196            *b"7110eda4d09e062aa5e4a390b0a572ac0d2c0220"
197        );
198    }
199
200    #[test]
201    fn fips180_one_million_a() {
202        // SHA1("a" × 1_000_000) = 34aa973cd4c4daa4f61eeb2bdbad27316534016f
203        let data = vec![b'a'; 1_000_000];
204        let d = sha1(&data);
205        assert_eq!(
206            hex(&d),
207            *b"34aa973cd4c4daa4f61eeb2bdbad27316534016f"
208        );
209    }
210
211    #[test]
212    fn hex_round_trips_through_parse_hex() {
213        let d1 = sha1(b"kevy");
214        let h = hex(&d1);
215        let d2 = parse_hex(&h).expect("valid hex");
216        assert_eq!(d1, d2);
217    }
218
219    #[test]
220    fn parse_hex_rejects_wrong_length() {
221        assert!(parse_hex(b"too short").is_none());
222        assert!(parse_hex(&[b'a'; 41]).is_none());
223    }
224
225    #[test]
226    fn parse_hex_rejects_non_hex_chars() {
227        assert!(parse_hex(b"zzz3e364706816aba3e25717850c26c9cd0d89d").is_none());
228    }
229
230    #[test]
231    fn parse_hex_accepts_uppercase() {
232        let d1 = sha1(b"abc");
233        let lower = hex(&d1);
234        let upper: Vec<u8> = lower
235            .iter()
236            .map(|&b| b.to_ascii_uppercase())
237            .collect();
238        let d2 = parse_hex(&upper).expect("upper-hex valid");
239        assert_eq!(d1, d2);
240    }
241}