scripts: mkhash fail on hashing a folder
[openwrt/openwrt.git] / scripts / mkhash.c
1 /*
2 * Copyright (C) 2016 Felix Fietkau <nbd@nbd.name>
3 *
4 * Permission to use, copy, modify, and/or distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 *
16 * -- MD5 code:
17 *
18 * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc.
19 * MD5 Message-Digest Algorithm (RFC 1321).
20 *
21 * Homepage:
22 * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5
23 *
24 * Author:
25 * Alexander Peslyak, better known as Solar Designer <solar at openwall.com>
26 *
27 * This software was written by Alexander Peslyak in 2001. No copyright is
28 * claimed, and the software is hereby placed in the public domain.
29 * In case this attempt to disclaim copyright and place the software in the
30 * public domain is deemed null and void, then the software is
31 * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the
32 * general public under the following terms:
33 *
34 * Redistribution and use in source and binary forms, with or without
35 * modification, are permitted.
36 *
37 * There's ABSOLUTELY NO WARRANTY, express or implied.
38 *
39 * (This is a heavily cut-down "BSD license".)
40 *
41 * This differs from Colin Plumb's older public domain implementation in that
42 * no exactly 32-bit integer data type is required (any 32-bit or wider
43 * unsigned integer data type will do), there's no compile-time endianness
44 * configuration, and the function prototypes match OpenSSL's. No code from
45 * Colin Plumb's implementation has been reused; this comment merely compares
46 * the properties of the two independent implementations.
47 *
48 * The primary goals of this implementation are portability and ease of use.
49 * It is meant to be fast, but not as fast as possible. Some known
50 * optimizations are not included to reduce source code size and avoid
51 * compile-time configuration.
52 *
53 * -- SHA256 Code:
54 *
55 * Copyright 2005 Colin Percival
56 * All rights reserved.
57 *
58 * Redistribution and use in source and binary forms, with or without
59 * modification, are permitted provided that the following conditions
60 * are met:
61 * 1. Redistributions of source code must retain the above copyright
62 * notice, this list of conditions and the following disclaimer.
63 * 2. Redistributions in binary form must reproduce the above copyright
64 * notice, this list of conditions and the following disclaimer in the
65 * documentation and/or other materials provided with the distribution.
66 *
67 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
68 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
69 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
70 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
71 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
72 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
73 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
74 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
75 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
76 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
77 * SUCH DAMAGE.
78 */
79
80
81
82 #include <endian.h>
83 #include <stdio.h>
84 #include <string.h>
85 #include <stdint.h>
86 #include <stdbool.h>
87 #include <unistd.h>
88 #include <sys/stat.h>
89
90 #define ARRAY_SIZE(_n) (sizeof(_n) / sizeof((_n)[0]))
91
92 static void
93 be32enc(void *buf, uint32_t u)
94 {
95 uint8_t *p = buf;
96
97 p[0] = ((uint8_t) ((u >> 24) & 0xff));
98 p[1] = ((uint8_t) ((u >> 16) & 0xff));
99 p[2] = ((uint8_t) ((u >> 8) & 0xff));
100 p[3] = ((uint8_t) (u & 0xff));
101 }
102
103 static void
104 be64enc(void *buf, uint64_t u)
105 {
106 uint8_t *p = buf;
107
108 be32enc(p, ((uint32_t) (u >> 32)));
109 be32enc(p + 4, ((uint32_t) (u & 0xffffffffULL)));
110 }
111
112
113 static uint16_t
114 be16dec(const void *buf)
115 {
116 const uint8_t *p = buf;
117
118 return (((uint16_t) p[0]) << 8) | p[1];
119 }
120
121 static uint32_t
122 be32dec(const void *buf)
123 {
124 const uint8_t *p = buf;
125
126 return (((uint32_t) be16dec(p)) << 16) | be16dec(p + 2);
127 }
128
129 #define MD5_DIGEST_LENGTH 16
130
131 typedef struct MD5_CTX {
132 uint32_t lo, hi;
133 uint32_t a, b, c, d;
134 unsigned char buffer[64];
135 } MD5_CTX;
136
137 /*
138 * The basic MD5 functions.
139 *
140 * F and G are optimized compared to their RFC 1321 definitions for
141 * architectures that lack an AND-NOT instruction, just like in Colin Plumb's
142 * implementation.
143 */
144 #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
145 #define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y))))
146 #define H(x, y, z) (((x) ^ (y)) ^ (z))
147 #define H2(x, y, z) ((x) ^ ((y) ^ (z)))
148 #define I(x, y, z) ((y) ^ ((x) | ~(z)))
149
150 /*
151 * The MD5 transformation for all four rounds.
152 */
153 #define STEP(f, a, b, c, d, x, t, s) \
154 (a) += f((b), (c), (d)) + (x) + (t); \
155 (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \
156 (a) += (b);
157
158 /*
159 * SET reads 4 input bytes in little-endian byte order and stores them
160 * in a properly aligned word in host byte order.
161 */
162 #if __BYTE_ORDER == __LITTLE_ENDIAN
163 #define SET(n) \
164 (*(uint32_t *)&ptr[(n) * 4])
165 #define GET(n) \
166 SET(n)
167 #else
168 #define SET(n) \
169 (block[(n)] = \
170 (uint32_t)ptr[(n) * 4] | \
171 ((uint32_t)ptr[(n) * 4 + 1] << 8) | \
172 ((uint32_t)ptr[(n) * 4 + 2] << 16) | \
173 ((uint32_t)ptr[(n) * 4 + 3] << 24))
174 #define GET(n) \
175 (block[(n)])
176 #endif
177
178 /*
179 * This processes one or more 64-byte data blocks, but does NOT update
180 * the bit counters. There are no alignment requirements.
181 */
182 static const void *MD5_body(MD5_CTX *ctx, const void *data, unsigned long size)
183 {
184 const unsigned char *ptr;
185 uint32_t a, b, c, d;
186 uint32_t saved_a, saved_b, saved_c, saved_d;
187 #if __BYTE_ORDER != __LITTLE_ENDIAN
188 uint32_t block[16];
189 #endif
190
191 ptr = (const unsigned char *)data;
192
193 a = ctx->a;
194 b = ctx->b;
195 c = ctx->c;
196 d = ctx->d;
197
198 do {
199 saved_a = a;
200 saved_b = b;
201 saved_c = c;
202 saved_d = d;
203
204 /* Round 1 */
205 STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7)
206 STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12)
207 STEP(F, c, d, a, b, SET(2), 0x242070db, 17)
208 STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22)
209 STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7)
210 STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12)
211 STEP(F, c, d, a, b, SET(6), 0xa8304613, 17)
212 STEP(F, b, c, d, a, SET(7), 0xfd469501, 22)
213 STEP(F, a, b, c, d, SET(8), 0x698098d8, 7)
214 STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12)
215 STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17)
216 STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22)
217 STEP(F, a, b, c, d, SET(12), 0x6b901122, 7)
218 STEP(F, d, a, b, c, SET(13), 0xfd987193, 12)
219 STEP(F, c, d, a, b, SET(14), 0xa679438e, 17)
220 STEP(F, b, c, d, a, SET(15), 0x49b40821, 22)
221
222 /* Round 2 */
223 STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5)
224 STEP(G, d, a, b, c, GET(6), 0xc040b340, 9)
225 STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14)
226 STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20)
227 STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5)
228 STEP(G, d, a, b, c, GET(10), 0x02441453, 9)
229 STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14)
230 STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20)
231 STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5)
232 STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9)
233 STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14)
234 STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20)
235 STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5)
236 STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9)
237 STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14)
238 STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20)
239
240 /* Round 3 */
241 STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4)
242 STEP(H2, d, a, b, c, GET(8), 0x8771f681, 11)
243 STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16)
244 STEP(H2, b, c, d, a, GET(14), 0xfde5380c, 23)
245 STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4)
246 STEP(H2, d, a, b, c, GET(4), 0x4bdecfa9, 11)
247 STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16)
248 STEP(H2, b, c, d, a, GET(10), 0xbebfbc70, 23)
249 STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4)
250 STEP(H2, d, a, b, c, GET(0), 0xeaa127fa, 11)
251 STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16)
252 STEP(H2, b, c, d, a, GET(6), 0x04881d05, 23)
253 STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4)
254 STEP(H2, d, a, b, c, GET(12), 0xe6db99e5, 11)
255 STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16)
256 STEP(H2, b, c, d, a, GET(2), 0xc4ac5665, 23)
257
258 /* Round 4 */
259 STEP(I, a, b, c, d, GET(0), 0xf4292244, 6)
260 STEP(I, d, a, b, c, GET(7), 0x432aff97, 10)
261 STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15)
262 STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21)
263 STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6)
264 STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10)
265 STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15)
266 STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21)
267 STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6)
268 STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10)
269 STEP(I, c, d, a, b, GET(6), 0xa3014314, 15)
270 STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21)
271 STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6)
272 STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10)
273 STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15)
274 STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21)
275
276 a += saved_a;
277 b += saved_b;
278 c += saved_c;
279 d += saved_d;
280
281 ptr += 64;
282 } while (size -= 64);
283
284 ctx->a = a;
285 ctx->b = b;
286 ctx->c = c;
287 ctx->d = d;
288
289 return ptr;
290 }
291
292 void MD5_begin(MD5_CTX *ctx)
293 {
294 ctx->a = 0x67452301;
295 ctx->b = 0xefcdab89;
296 ctx->c = 0x98badcfe;
297 ctx->d = 0x10325476;
298
299 ctx->lo = 0;
300 ctx->hi = 0;
301 }
302
303 static void
304 MD5_hash(const void *data, size_t size, MD5_CTX *ctx)
305 {
306 uint32_t saved_lo;
307 unsigned long used, available;
308
309 saved_lo = ctx->lo;
310 if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo)
311 ctx->hi++;
312 ctx->hi += size >> 29;
313
314 used = saved_lo & 0x3f;
315
316 if (used) {
317 available = 64 - used;
318
319 if (size < available) {
320 memcpy(&ctx->buffer[used], data, size);
321 return;
322 }
323
324 memcpy(&ctx->buffer[used], data, available);
325 data = (const unsigned char *)data + available;
326 size -= available;
327 MD5_body(ctx, ctx->buffer, 64);
328 }
329
330 if (size >= 64) {
331 data = MD5_body(ctx, data, size & ~((size_t) 0x3f));
332 size &= 0x3f;
333 }
334
335 memcpy(ctx->buffer, data, size);
336 }
337
338 static void
339 MD5_end(void *resbuf, MD5_CTX *ctx)
340 {
341 unsigned char *result = resbuf;
342 unsigned long used, available;
343
344 used = ctx->lo & 0x3f;
345
346 ctx->buffer[used++] = 0x80;
347
348 available = 64 - used;
349
350 if (available < 8) {
351 memset(&ctx->buffer[used], 0, available);
352 MD5_body(ctx, ctx->buffer, 64);
353 used = 0;
354 available = 64;
355 }
356
357 memset(&ctx->buffer[used], 0, available - 8);
358
359 ctx->lo <<= 3;
360 ctx->buffer[56] = ctx->lo;
361 ctx->buffer[57] = ctx->lo >> 8;
362 ctx->buffer[58] = ctx->lo >> 16;
363 ctx->buffer[59] = ctx->lo >> 24;
364 ctx->buffer[60] = ctx->hi;
365 ctx->buffer[61] = ctx->hi >> 8;
366 ctx->buffer[62] = ctx->hi >> 16;
367 ctx->buffer[63] = ctx->hi >> 24;
368
369 MD5_body(ctx, ctx->buffer, 64);
370
371 result[0] = ctx->a;
372 result[1] = ctx->a >> 8;
373 result[2] = ctx->a >> 16;
374 result[3] = ctx->a >> 24;
375 result[4] = ctx->b;
376 result[5] = ctx->b >> 8;
377 result[6] = ctx->b >> 16;
378 result[7] = ctx->b >> 24;
379 result[8] = ctx->c;
380 result[9] = ctx->c >> 8;
381 result[10] = ctx->c >> 16;
382 result[11] = ctx->c >> 24;
383 result[12] = ctx->d;
384 result[13] = ctx->d >> 8;
385 result[14] = ctx->d >> 16;
386 result[15] = ctx->d >> 24;
387
388 memset(ctx, 0, sizeof(*ctx));
389 }
390
391 #define SHA256_BLOCK_LENGTH 64
392 #define SHA256_DIGEST_LENGTH 32
393 #define SHA256_DIGEST_STRING_LENGTH (SHA256_DIGEST_LENGTH * 2 + 1)
394
395 typedef struct SHA256Context {
396 uint32_t state[8];
397 uint64_t count;
398 uint8_t buf[SHA256_BLOCK_LENGTH];
399 } SHA256_CTX;
400
401 #if BYTE_ORDER == BIG_ENDIAN
402
403 /* Copy a vector of big-endian uint32_t into a vector of bytes */
404 #define be32enc_vect(dst, src, len) \
405 memcpy((void *)dst, (const void *)src, (size_t)len)
406
407 /* Copy a vector of bytes into a vector of big-endian uint32_t */
408 #define be32dec_vect(dst, src, len) \
409 memcpy((void *)dst, (const void *)src, (size_t)len)
410
411 #else /* BYTE_ORDER != BIG_ENDIAN */
412
413 /*
414 * Encode a length len/4 vector of (uint32_t) into a length len vector of
415 * (unsigned char) in big-endian form. Assumes len is a multiple of 4.
416 */
417 static void
418 be32enc_vect(unsigned char *dst, const uint32_t *src, size_t len)
419 {
420 size_t i;
421
422 for (i = 0; i < len / 4; i++)
423 be32enc(dst + i * 4, src[i]);
424 }
425
426 /*
427 * Decode a big-endian length len vector of (unsigned char) into a length
428 * len/4 vector of (uint32_t). Assumes len is a multiple of 4.
429 */
430 static void
431 be32dec_vect(uint32_t *dst, const unsigned char *src, size_t len)
432 {
433 size_t i;
434
435 for (i = 0; i < len / 4; i++)
436 dst[i] = be32dec(src + i * 4);
437 }
438
439 #endif /* BYTE_ORDER != BIG_ENDIAN */
440
441
442 /* Elementary functions used by SHA256 */
443 #define Ch(x, y, z) ((x & (y ^ z)) ^ z)
444 #define Maj(x, y, z) ((x & (y | z)) | (y & z))
445 #define ROTR(x, n) ((x >> n) | (x << (32 - n)))
446
447 /*
448 * SHA256 block compression function. The 256-bit state is transformed via
449 * the 512-bit input block to produce a new state.
450 */
451 static void
452 SHA256_Transform(uint32_t * state, const unsigned char block[64])
453 {
454 /* SHA256 round constants. */
455 static const uint32_t K[64] = {
456 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
457 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
458 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
459 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
460 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
461 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
462 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
463 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
464 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
465 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
466 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
467 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
468 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
469 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
470 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
471 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
472 };
473 uint32_t W[64];
474 uint32_t S[8];
475 int i;
476
477 #define S0(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22))
478 #define S1(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25))
479 #define s0(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ (x >> 3))
480 #define s1(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ (x >> 10))
481
482 /* SHA256 round function */
483 #define RND(a, b, c, d, e, f, g, h, k) \
484 h += S1(e) + Ch(e, f, g) + k; \
485 d += h; \
486 h += S0(a) + Maj(a, b, c);
487
488 /* Adjusted round function for rotating state */
489 #define RNDr(S, W, i, ii) \
490 RND(S[(64 - i) % 8], S[(65 - i) % 8], \
491 S[(66 - i) % 8], S[(67 - i) % 8], \
492 S[(68 - i) % 8], S[(69 - i) % 8], \
493 S[(70 - i) % 8], S[(71 - i) % 8], \
494 W[i + ii] + K[i + ii])
495
496 /* Message schedule computation */
497 #define MSCH(W, ii, i) \
498 W[i + ii + 16] = s1(W[i + ii + 14]) + W[i + ii + 9] + s0(W[i + ii + 1]) + W[i + ii]
499
500 /* 1. Prepare the first part of the message schedule W. */
501 be32dec_vect(W, block, 64);
502
503 /* 2. Initialize working variables. */
504 memcpy(S, state, 32);
505
506 /* 3. Mix. */
507 for (i = 0; i < 64; i += 16) {
508 RNDr(S, W, 0, i);
509 RNDr(S, W, 1, i);
510 RNDr(S, W, 2, i);
511 RNDr(S, W, 3, i);
512 RNDr(S, W, 4, i);
513 RNDr(S, W, 5, i);
514 RNDr(S, W, 6, i);
515 RNDr(S, W, 7, i);
516 RNDr(S, W, 8, i);
517 RNDr(S, W, 9, i);
518 RNDr(S, W, 10, i);
519 RNDr(S, W, 11, i);
520 RNDr(S, W, 12, i);
521 RNDr(S, W, 13, i);
522 RNDr(S, W, 14, i);
523 RNDr(S, W, 15, i);
524
525 if (i == 48)
526 break;
527 MSCH(W, 0, i);
528 MSCH(W, 1, i);
529 MSCH(W, 2, i);
530 MSCH(W, 3, i);
531 MSCH(W, 4, i);
532 MSCH(W, 5, i);
533 MSCH(W, 6, i);
534 MSCH(W, 7, i);
535 MSCH(W, 8, i);
536 MSCH(W, 9, i);
537 MSCH(W, 10, i);
538 MSCH(W, 11, i);
539 MSCH(W, 12, i);
540 MSCH(W, 13, i);
541 MSCH(W, 14, i);
542 MSCH(W, 15, i);
543 }
544
545 #undef S0
546 #undef s0
547 #undef S1
548 #undef s1
549 #undef RND
550 #undef RNDr
551 #undef MSCH
552
553 /* 4. Mix local working variables into global state */
554 for (i = 0; i < 8; i++)
555 state[i] += S[i];
556 }
557
558 static unsigned char PAD[64] = {
559 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
560 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
561 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
562 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
563 };
564
565 /* Add padding and terminating bit-count. */
566 static void
567 SHA256_Pad(SHA256_CTX * ctx)
568 {
569 size_t r;
570
571 /* Figure out how many bytes we have buffered. */
572 r = (ctx->count >> 3) & 0x3f;
573
574 /* Pad to 56 mod 64, transforming if we finish a block en route. */
575 if (r < 56) {
576 /* Pad to 56 mod 64. */
577 memcpy(&ctx->buf[r], PAD, 56 - r);
578 } else {
579 /* Finish the current block and mix. */
580 memcpy(&ctx->buf[r], PAD, 64 - r);
581 SHA256_Transform(ctx->state, ctx->buf);
582
583 /* The start of the final block is all zeroes. */
584 memset(&ctx->buf[0], 0, 56);
585 }
586
587 /* Add the terminating bit-count. */
588 be64enc(&ctx->buf[56], ctx->count);
589
590 /* Mix in the final block. */
591 SHA256_Transform(ctx->state, ctx->buf);
592 }
593
594 /* SHA-256 initialization. Begins a SHA-256 operation. */
595 static void
596 SHA256_Init(SHA256_CTX * ctx)
597 {
598
599 /* Zero bits processed so far */
600 ctx->count = 0;
601
602 /* Magic initialization constants */
603 ctx->state[0] = 0x6A09E667;
604 ctx->state[1] = 0xBB67AE85;
605 ctx->state[2] = 0x3C6EF372;
606 ctx->state[3] = 0xA54FF53A;
607 ctx->state[4] = 0x510E527F;
608 ctx->state[5] = 0x9B05688C;
609 ctx->state[6] = 0x1F83D9AB;
610 ctx->state[7] = 0x5BE0CD19;
611 }
612
613 /* Add bytes into the hash */
614 static void
615 SHA256_Update(SHA256_CTX * ctx, const void *in, size_t len)
616 {
617 uint64_t bitlen;
618 uint32_t r;
619 const unsigned char *src = in;
620
621 /* Number of bytes left in the buffer from previous updates */
622 r = (ctx->count >> 3) & 0x3f;
623
624 /* Convert the length into a number of bits */
625 bitlen = len << 3;
626
627 /* Update number of bits */
628 ctx->count += bitlen;
629
630 /* Handle the case where we don't need to perform any transforms */
631 if (len < 64 - r) {
632 memcpy(&ctx->buf[r], src, len);
633 return;
634 }
635
636 /* Finish the current block */
637 memcpy(&ctx->buf[r], src, 64 - r);
638 SHA256_Transform(ctx->state, ctx->buf);
639 src += 64 - r;
640 len -= 64 - r;
641
642 /* Perform complete blocks */
643 while (len >= 64) {
644 SHA256_Transform(ctx->state, src);
645 src += 64;
646 len -= 64;
647 }
648
649 /* Copy left over data into buffer */
650 memcpy(ctx->buf, src, len);
651 }
652
653 /*
654 * SHA-256 finalization. Pads the input data, exports the hash value,
655 * and clears the context state.
656 */
657 static void
658 SHA256_Final(unsigned char digest[static SHA256_DIGEST_LENGTH], SHA256_CTX *ctx)
659 {
660 /* Add padding */
661 SHA256_Pad(ctx);
662
663 /* Write the hash */
664 be32enc_vect(digest, ctx->state, SHA256_DIGEST_LENGTH);
665
666 /* Clear the context state */
667 memset(ctx, 0, sizeof(*ctx));
668 }
669
670 static void *hash_buf(FILE *f, int *len)
671 {
672 static char buf[1024];
673
674 *len = fread(buf, 1, sizeof(buf), f);
675
676 return *len > 0 ? buf : NULL;
677 }
678
679 static char *hash_string(unsigned char *buf, int len)
680 {
681 static char str[SHA256_DIGEST_LENGTH * 2 + 1];
682 int i;
683
684 if (len * 2 + 1 > sizeof(str))
685 return NULL;
686
687 for (i = 0; i < len; i++)
688 sprintf(&str[i * 2], "%02x", buf[i]);
689
690 return str;
691 }
692
693 static const char *md5_hash(FILE *f)
694 {
695 MD5_CTX ctx;
696 unsigned char val[MD5_DIGEST_LENGTH];
697 void *buf;
698 int len;
699
700 MD5_begin(&ctx);
701 while ((buf = hash_buf(f, &len)) != NULL)
702 MD5_hash(buf, len, &ctx);
703 MD5_end(val, &ctx);
704
705 return hash_string(val, MD5_DIGEST_LENGTH);
706 }
707
708 static const char *sha256_hash(FILE *f)
709 {
710 SHA256_CTX ctx;
711 unsigned char val[SHA256_DIGEST_LENGTH];
712 void *buf;
713 int len;
714
715 SHA256_Init(&ctx);
716 while ((buf = hash_buf(f, &len)) != NULL)
717 SHA256_Update(&ctx, buf, len);
718 SHA256_Final(val, &ctx);
719
720 return hash_string(val, SHA256_DIGEST_LENGTH);
721 }
722
723
724 struct hash_type {
725 const char *name;
726 const char *(*func)(FILE *f);
727 int len;
728 };
729
730 struct hash_type types[] = {
731 { "md5", md5_hash, MD5_DIGEST_LENGTH },
732 { "sha256", sha256_hash, SHA256_DIGEST_LENGTH },
733 };
734
735
736 static int usage(const char *progname)
737 {
738 int i;
739
740 fprintf(stderr, "Usage: %s <hash type> [options] [<file>...]\n"
741 "Options:\n"
742 " -n Print filename(s)\n"
743 "\n"
744 "Supported hash types:", progname);
745
746 for (i = 0; i < ARRAY_SIZE(types); i++)
747 fprintf(stderr, "%s %s", i ? "," : "", types[i].name);
748
749 fprintf(stderr, "\n");
750 return 1;
751 }
752
753 static struct hash_type *get_hash_type(const char *name)
754 {
755 int i;
756
757 for (i = 0; i < ARRAY_SIZE(types); i++) {
758 struct hash_type *t = &types[i];
759
760 if (!strcmp(t->name, name))
761 return t;
762 }
763 return NULL;
764 }
765
766
767 static int hash_file(struct hash_type *t, const char *filename, bool add_filename)
768 {
769 const char *str;
770
771 if (!filename || !strcmp(filename, "-")) {
772 str = t->func(stdin);
773 } else {
774 struct stat path_stat;
775 stat(filename, &path_stat);
776 if (S_ISDIR(path_stat.st_mode)) {
777 fprintf(stderr, "Failed to open '%s': Is a directory\n", filename);
778 return 1;
779 }
780
781 FILE *f = fopen(filename, "r");
782
783 if (!f) {
784 fprintf(stderr, "Failed to open '%s'\n", filename);
785 return 1;
786 }
787 str = t->func(f);
788 fclose(f);
789 }
790
791 if (!str) {
792 fprintf(stderr, "Failed to generate hash\n");
793 return 1;
794 }
795
796 if (add_filename)
797 printf("%s %s\n", str, filename ? filename : "-");
798 else
799 printf("%s\n", str);
800 return 0;
801 }
802
803
804 int main(int argc, char **argv)
805 {
806 struct hash_type *t;
807 const char *progname = argv[0];
808 int i, ch;
809 bool add_filename = false;
810
811 while ((ch = getopt(argc, argv, "n")) != -1) {
812 switch (ch) {
813 case 'n':
814 add_filename = true;
815 break;
816 default:
817 return usage(progname);
818 }
819 }
820
821 argc -= optind;
822 argv += optind;
823
824 if (argc < 1)
825 return usage(progname);
826
827 t = get_hash_type(argv[0]);
828 if (!t)
829 return usage(progname);
830
831 if (argc < 2)
832 return hash_file(t, NULL, add_filename);
833
834 for (i = 0; i < argc - 1; i++) {
835 int ret = hash_file(t, argv[1 + i], add_filename);
836 if (ret)
837 return ret;
838 }
839
840 return 0;
841 }