1 /* Functions to compute MD5 message digest of files or memory blocks.
2 according to the definition of MD5 in RFC 1321 from April 1992.
3 Copyright (C) 1995-1997, 1999-2001, 2005-2006, 2008-2025 Free Software
5 This file is part of the GNU C Library.
7 This file is free software: you can redistribute it and/or modify
8 it under the terms of the GNU Lesser General Public License as
9 published by the Free Software Foundation; either version 2.1 of the
10 License, or (at your option) any later version.
12 This file is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public License
18 along with this program. If not, see <https://www.gnu.org/licenses/>. */
20 /* Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1995. */
30 # include "unlocked-io.h"
37 # if __BYTE_ORDER == __BIG_ENDIAN
38 # define WORDS_BIGENDIAN 1
40 /* We need to keep the namespace clean so define the MD5 function
41 protected using leading __ . */
42 # define md5_init_ctx __md5_init_ctx
43 # define md5_process_block __md5_process_block
44 # define md5_process_bytes __md5_process_bytes
45 # define md5_finish_ctx __md5_finish_ctx
46 # define md5_stream __md5_stream
49 #define BLOCKSIZE 32768
50 #if BLOCKSIZE % 64 != 0
51 # error "invalid BLOCKSIZE"
54 /* Compute MD5 message digest for bytes read from STREAM. The
55 resulting message digest number will be written into the 16 bytes
56 beginning at RESBLOCK. */
58 md5_stream (FILE *stream
, void *resblock
)
60 switch (afalg_stream (stream
, "md5", resblock
, MD5_DIGEST_SIZE
))
66 char *buffer
= malloc (BLOCKSIZE
+ 72);
74 /* Iterate over full file contents. */
77 /* We read the file in blocks of BLOCKSIZE bytes. One call of the
78 computation function processes the whole buffer so that with the
79 next round of the loop another block can be read. */
83 /* Read block. Take care for partial reads. */
86 /* Either process a partial fread() from this loop,
87 or the fread() in afalg_stream may have gotten EOF.
88 We need to avoid a subsequent fread() as EOF may
89 not be sticky. For details of such systems, see:
90 https://sourceware.org/bugzilla/show_bug.cgi?id=1190 */
92 goto process_partial_block
;
94 n
= fread (buffer
+ sum
, 1, BLOCKSIZE
- sum
, stream
);
103 /* Check for the error flag IFF N == 0, so that we don't
104 exit the loop after a partial read due to e.g., EAGAIN
111 goto process_partial_block
;
115 /* Process buffer with BLOCKSIZE bytes. Note that
118 md5_process_block (buffer
, BLOCKSIZE
, &ctx
);
121 process_partial_block
:
123 /* Process any remaining bytes. */
125 md5_process_bytes (buffer
, sum
, &ctx
);
127 /* Construct result in desired memory. */
128 md5_finish_ctx (&ctx
, resblock
);