1 /* sha1.c - Functions to compute SHA1 message digest of files or
2 memory blocks according to the NIST specification FIPS-180-1.
4 Copyright (C) 2000-2001, 2003-2006, 2008-2025 Free Software Foundation, Inc.
6 This file is free software: you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as
8 published by the Free Software Foundation; either version 2.1 of the
9 License, or (at your option) any later version.
11 This file is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with this program. If not, see <https://www.gnu.org/licenses/>. */
19 /* Written by Scott G. Miller
21 Robert Klep <robert@ilse.nl> -- Expansion function fix
32 # include "unlocked-io.h"
37 #define BLOCKSIZE 32768
38 #if BLOCKSIZE % 64 != 0
39 # error "invalid BLOCKSIZE"
42 /* Compute SHA1 message digest for bytes read from STREAM. The
43 resulting message digest number will be written into the 20 bytes
44 beginning at RESBLOCK. */
46 sha1_stream (FILE *stream
, void *resblock
)
48 switch (afalg_stream (stream
, "sha1", resblock
, SHA1_DIGEST_SIZE
))
54 char *buffer
= malloc (BLOCKSIZE
+ 72);
62 /* Iterate over full file contents. */
65 /* We read the file in blocks of BLOCKSIZE bytes. One call of the
66 computation function processes the whole buffer so that with the
67 next round of the loop another block can be read. */
71 /* Read block. Take care for partial reads. */
74 /* Either process a partial fread() from this loop,
75 or the fread() in afalg_stream may have gotten EOF.
76 We need to avoid a subsequent fread() as EOF may
77 not be sticky. For details of such systems, see:
78 https://sourceware.org/bugzilla/show_bug.cgi?id=1190 */
80 goto process_partial_block
;
82 n
= fread (buffer
+ sum
, 1, BLOCKSIZE
- sum
, stream
);
91 /* Check for the error flag IFF N == 0, so that we don't
92 exit the loop after a partial read due to e.g., EAGAIN
99 goto process_partial_block
;
103 /* Process buffer with BLOCKSIZE bytes. Note that
106 sha1_process_block (buffer
, BLOCKSIZE
, &ctx
);
109 process_partial_block
:;
111 /* Process any remaining bytes. */
113 sha1_process_bytes (buffer
, sum
, &ctx
);
115 /* Construct result in desired memory. */
116 sha1_finish_ctx (&ctx
, resblock
);