Debian Codegraph @

lib/sha1.c

raw
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * SHA-1 message digest algorithm
4 *
5 * Copyright 2025 Google LLC
6 */
7
8 #include <arpa/inet.h>
9 #include <string.h>
10
11 #include "sha1.h"
12 #include "utils.h"
13
14 static const __u32 sha1_K[4] = { 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC,
15 0xCA62C1D6 };
16
17 static inline __u32 rol32(__u32 v, int bits)
18 {
19 return (v << bits) | (v >> (32 - bits));
20 }
21
22 #define round_up(a, b) (((a) + (b) - 1) & ~((b) - 1))
23
24 #define SHA1_ROUND(i, a, b, c, d, e) \
25 do { \
26 if ((i) >= 16) \
27 w[i] = rol32(w[(i) - 16] ^ w[(i) - 14] ^ w[(i) - 8] ^ \
28 w[(i) - 3], \
29 1); \
30 e += w[i] + rol32(a, 5) + sha1_K[(i) / 20]; \
31 if ((i) < 20) \
32 e += (b & (c ^ d)) ^ d; \
33 else if ((i) < 40 || (i) >= 60) \
34 e += b ^ c ^ d; \
35 else \
36 e += (c & d) ^ (b & (c ^ d)); \
37 b = rol32(b, 30); \
38 /* The new (a, b, c, d, e) is the old (e, a, b, c, d). */ \
39 } while (0)
40
41 #define SHA1_5ROUNDS(i) \
42 do { \
43 SHA1_ROUND((i) + 0, a, b, c, d, e); \
44 SHA1_ROUND((i) + 1, e, a, b, c, d); \
45 SHA1_ROUND((i) + 2, d, e, a, b, c); \
46 SHA1_ROUND((i) + 3, c, d, e, a, b); \
47 SHA1_ROUND((i) + 4, b, c, d, e, a); \
48 } while (0)
49
50 #define SHA1_20ROUNDS(i) \
51 do { \
52 SHA1_5ROUNDS((i) + 0); \
53 SHA1_5ROUNDS((i) + 5); \
54 SHA1_5ROUNDS((i) + 10); \
55 SHA1_5ROUNDS((i) + 15); \
56 } while (0)
57
58 static void sha1_blocks(__u32 h[5], const __u8 *data, size_t nblocks)
59 {
60 while (nblocks--) {
61 __u32 a = h[0];
62 __u32 b = h[1];
63 __u32 c = h[2];
64 __u32 d = h[3];
65 __u32 e = h[4];
66 __u32 w[80];
67 int i;
68
69 memcpy(w, data, SHA1_BLOCK_SIZE);
70 for (i = 0; i < 16; i++)
71 w[i] = ntohl(w[i]);
72 SHA1_20ROUNDS(0);
73 SHA1_20ROUNDS(20);
74 SHA1_20ROUNDS(40);
75 SHA1_20ROUNDS(60);
76
77 h[0] += a;
78 h[1] += b;
79 h[2] += c;
80 h[3] += d;
81 h[4] += e;
82 data += SHA1_BLOCK_SIZE;
83 }
84 }
85
86 /* Calculate the SHA-1 message digest of the given data. */
87 void sha1(const __u8 *data, size_t len, __u8 out[SHA1_DIGEST_SIZE])
88 {
89 __u32 h[5] = { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476,
90 0xC3D2E1F0 };
91 const __be64 bitcount = htonll((__u64)len * 8);
92 __u8 final_data[2 * SHA1_BLOCK_SIZE] = { 0 };
93 size_t final_len = len % SHA1_BLOCK_SIZE;
94 int i;
95
96 sha1_blocks(h, data, len / SHA1_BLOCK_SIZE);
97
98 memcpy(final_data, data + len - final_len, final_len);
99 final_data[final_len] = 0x80;
100 final_len = round_up(final_len + 9, SHA1_BLOCK_SIZE);
101 memcpy(&final_data[final_len - 8], &bitcount, 8);
102
103 sha1_blocks(h, final_data, final_len / SHA1_BLOCK_SIZE);
104
105 for (i = 0; i < ARRAY_SIZE(h); i++)
106 h[i] = htonl(h[i]);
107 memcpy(out, h, SHA1_DIGEST_SIZE);
108 }