"Fossies" - the Fresh Open Source Software Archive

Member "littleutils-1.2.5/littleutils/md5.c" (29 Oct 2021, 16193 Bytes) of package /linux/privat/littleutils-1.2.5.tar.lz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

    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-2018 Free Software
    4    Foundation, Inc.
    5    This file is part of the GNU C Library.
    6 
    7    This program is free software; you can redistribute it and/or modify it
    8    under the terms of the GNU General Public License as published by the
    9    Free Software Foundation; either version 3, or (at your option) any
   10    later version.
   11 
   12    This program 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 General Public License for more details.
   16 
   17    You should have received a copy of the GNU General Public License
   18    along with this program; if not, see <https://www.gnu.org/licenses/>.  */
   19 
   20 /* Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1995.  */
   21 
   22 /* Modifications for portability and partial file reads by Brian Lindholm,
   23    2004-2021.  */
   24 
   25 
   26 #include <config.h>
   27 
   28 #ifdef HAVE_STDALIGN_H
   29 # include <stdalign.h>
   30 #endif
   31 #ifdef HAVE_STDINT_H
   32 # include <stdint.h>
   33 #endif
   34 #ifdef HAVE_STDLIB_H
   35 # include <stdlib.h>
   36 #endif
   37 #ifdef HAVE_STRING_H
   38 # include <string.h>
   39 #endif
   40 #ifdef HAVE_SYS_TYPES_H
   41 # include <sys/types.h>
   42 #endif
   43 
   44 #include "md5.h"
   45 
   46 #ifdef _LIBC
   47 # include <endian.h>
   48 # if __BYTE_ORDER == __BIG_ENDIAN
   49 #  define WORDS_BIGENDIAN 1
   50 # endif
   51 /* We need to keep the namespace clean so define the MD5 function
   52    protected using leading __ .  */
   53 # define md5_init_ctx __md5_init_ctx
   54 # define md5_process_block __md5_process_block
   55 # define md5_process_bytes __md5_process_bytes
   56 # define md5_finish_ctx __md5_finish_ctx
   57 # define md5_read_ctx __md5_read_ctx
   58 # define md5_stream __md5_stream
   59 # define md5_buffer __md5_buffer
   60 #endif
   61 
   62 #ifdef WORDS_BIGENDIAN
   63 # ifdef HAVE_BYTESWAP_H
   64 #  include <byteswap.h>
   65 #  define SWAP(n) bswap_32 (n)
   66 # else
   67 #  define SWAP(n) (((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
   68 # endif
   69 #else
   70 # define SWAP(n) (n)
   71 #endif
   72 
   73 #define BLOCKSIZE 32768
   74 #if BLOCKSIZE % 64 != 0
   75 # error "invalid BLOCKSIZE"
   76 #endif
   77 
   78 /* This array contains the bytes used to pad the buffer to the next
   79    64-byte boundary.  (RFC 1321, 3.1: Step 1)  */
   80 static const unsigned char fillbuf[64] = { 0x80, 0 /* , 0, 0, ...  */ };
   81 
   82 
   83 /* Initialize structure containing state of computation.
   84    (RFC 1321, 3.3: Step 3)  */
   85 void
   86 md5_init_ctx (struct md5_ctx *ctx)
   87 {
   88   ctx->A = 0x67452301;
   89   ctx->B = 0xefcdab89;
   90   ctx->C = 0x98badcfe;
   91   ctx->D = 0x10325476;
   92 
   93   ctx->total[0] = ctx->total[1] = 0;
   94   ctx->buflen = 0;
   95 }
   96 
   97 /* Copy the 4 byte value from v into the memory location pointed to by *cp,
   98    If your architecture allows unaligned access this is equivalent to
   99    * (uint32_t *) cp = v  */
  100 static void
  101 set_uint32 (char *cp, uint32_t v)
  102 {
  103   memcpy (cp, &v, sizeof v);
  104 }
  105 
  106 /* Put result from CTX in first 16 bytes following RESBUF.  The result
  107    must be in little endian byte order.  */
  108 void *
  109 md5_read_ctx (const struct md5_ctx *ctx, void *resbuf)
  110 {
  111   char *r = resbuf;
  112   set_uint32 (r + 0 * sizeof ctx->A, SWAP (ctx->A));
  113   set_uint32 (r + 1 * sizeof ctx->B, SWAP (ctx->B));
  114   set_uint32 (r + 2 * sizeof ctx->C, SWAP (ctx->C));
  115   set_uint32 (r + 3 * sizeof ctx->D, SWAP (ctx->D));
  116 
  117   return resbuf;
  118 }
  119 
  120 /* Process the remaining bytes in the internal buffer and the usual
  121    prolog according to the standard and write the result to RESBUF.  */
  122 void *
  123 md5_finish_ctx (struct md5_ctx *ctx, void *resbuf)
  124 {
  125   /* Take yet unprocessed bytes into account.  */
  126   uint32_t bytes = ctx->buflen;
  127   size_t size = (bytes < 56) ? 64 / 4 : 64 * 2 / 4;
  128 
  129   /* Now count remaining bytes.  */
  130   ctx->total[0] += bytes;
  131   if (ctx->total[0] < bytes)
  132     ++ctx->total[1];
  133 
  134   /* Put the 64-bit file length in *bits* at the end of the buffer.  */
  135   ctx->buffer[size - 2] = SWAP (ctx->total[0] << 3);
  136   ctx->buffer[size - 1] = SWAP ((ctx->total[1] << 3) | (ctx->total[0] >> 29));
  137 
  138   memcpy (&((char *) ctx->buffer)[bytes], fillbuf, (size - 2) * 4 - bytes);
  139 
  140   /* Process last bytes.  */
  141   md5_process_block (ctx->buffer, size * 4, ctx);
  142 
  143   return md5_read_ctx (ctx, resbuf);
  144 }
  145 
  146 /* Compute MD5 message digest for bytes read from STREAM.  The
  147    resulting message digest number will be written into the 16 bytes
  148    beginning at RESBLOCK.  Readbytes == -1 implies whole file.  */
  149 int
  150 md5_stream (FILE *stream, void *resblock, off_t readbytes)
  151 {
  152   char *buffer = malloc (BLOCKSIZE + 72);
  153   if (!buffer)
  154     return 1;
  155 
  156   /* Initialize the computation context.  */
  157   struct md5_ctx ctx;
  158   md5_init_ctx (&ctx);
  159   size_t sum, target;
  160   off_t total = 0;
  161 
  162   /* Jump to end for readbytes == 0.  */
  163   if (readbytes == 0)
  164     {
  165       sum = 0;
  166       goto process_partial_block;
  167     }
  168 
  169   /* Iterate over full file contents.  */
  170   while (1)
  171     {
  172       /* We read the file in blocks of BLOCKSIZE bytes.  One call of the
  173          computation function processes the whole buffer so that with the
  174          next round of the loop another block can be read.  */
  175       size_t n;
  176       if ((readbytes < 0) || ((readbytes - total) > (off_t) BLOCKSIZE))
  177         target = (size_t) BLOCKSIZE;
  178       else
  179         target = (size_t) (readbytes - total);
  180       sum = 0;
  181 
  182       /* Read block.  Take care for partial reads.  */
  183       while (1)
  184         {
  185           /* Either process a partial fread() from this loop,
  186              or the fread() in afalg_stream may have gotten EOF.
  187              We need to avoid a subsequent fread() as EOF may
  188              not be sticky.  For details of such systems, see:
  189              https://sourceware.org/bugzilla/show_bug.cgi?id=1190  */
  190           if (((off_t) sum >= target) || feof (stream))
  191             goto process_partial_block;
  192 
  193           n = fread (buffer + sum, 1, target - sum, stream);
  194           sum += n;
  195 
  196           if (sum == BLOCKSIZE)
  197             break;
  198 
  199           if (n == 0)
  200             {
  201               /* Check for the error flag IFF N == 0, so that we don't
  202                  exit the loop after a partial read due to e.g., EAGAIN
  203                  or EWOULDBLOCK.  */
  204               if (ferror (stream))
  205                 {
  206                   free (buffer);
  207                   return 1;
  208                 }
  209               goto process_partial_block;
  210             }
  211         }
  212       total += (off_t) sum;
  213 
  214       /* Process buffer with BLOCKSIZE bytes.  Note that
  215          BLOCKSIZE % 64 == 0
  216        */
  217       md5_process_block (buffer, BLOCKSIZE, &ctx);
  218     }
  219 
  220 process_partial_block:
  221 
  222   /* Process any remaining bytes.  */
  223   if (sum > 0)
  224     md5_process_bytes (buffer, sum, &ctx);
  225 
  226   /* Construct result in desired memory.  */
  227   md5_finish_ctx (&ctx, resblock);
  228   free (buffer);
  229   return 0;
  230 }
  231 
  232 /* Compute MD5 message digest for LEN bytes beginning at BUFFER.  The
  233    result is always in little endian byte order, so that a byte-wise
  234    output yields to the wanted ASCII representation of the message
  235    digest.  */
  236 void *
  237 md5_buffer (const char *buffer, size_t len, void *resblock)
  238 {
  239   struct md5_ctx ctx;
  240 
  241   /* Initialize the computation context.  */
  242   md5_init_ctx (&ctx);
  243 
  244   /* Process whole buffer but last len % 64 bytes.  */
  245   md5_process_bytes (buffer, len, &ctx);
  246 
  247   /* Put result in desired memory area.  */
  248   return md5_finish_ctx (&ctx, resblock);
  249 }
  250 
  251 
  252 void
  253 md5_process_bytes (const void *buffer, size_t len, struct md5_ctx *ctx)
  254 {
  255   /* When we already have some bits in our internal buffer concatenate
  256      both inputs first.  */
  257   if (ctx->buflen != 0)
  258     {
  259       size_t left_over = ctx->buflen;
  260       size_t add = 128 - left_over > len ? len : 128 - left_over;
  261 
  262       memcpy (&((char *) ctx->buffer)[left_over], buffer, add);
  263       ctx->buflen += add;
  264 
  265       if (ctx->buflen > 64)
  266         {
  267           md5_process_block (ctx->buffer, ctx->buflen & ~63, ctx);
  268 
  269           ctx->buflen &= 63;
  270           /* The regions in the following copy operation cannot overlap,
  271              because ctx->buflen < 64 ≤ (left_over + add) & ~63.  */
  272           memcpy (ctx->buffer,
  273                   &((char *) ctx->buffer)[(left_over + add) & ~63],
  274                   ctx->buflen);
  275         }
  276 
  277       buffer = (const char *) buffer + add;
  278       len -= add;
  279     }
  280 
  281   /* Process available complete blocks.  */
  282   if (len >= 64)
  283     {
  284 #if !(_STRING_ARCH_unaligned || _STRING_INLINE_unaligned)
  285 # define UNALIGNED_P(p) ((uintptr_t) (p) % alignof (uint32_t) != 0)
  286       if (UNALIGNED_P (buffer))
  287         while (len > 64)
  288           {
  289             md5_process_block (memcpy (ctx->buffer, buffer, 64), 64, ctx);
  290             buffer = (const char *) buffer + 64;
  291             len -= 64;
  292           }
  293       else
  294 #endif
  295         {
  296           md5_process_block (buffer, len & ~63, ctx);
  297           buffer = (const char *) buffer + (len & ~63);
  298           len &= 63;
  299         }
  300     }
  301 
  302   /* Move remaining bytes in internal buffer.  */
  303   if (len > 0)
  304     {
  305       size_t left_over = ctx->buflen;
  306 
  307       memcpy (&((char *) ctx->buffer)[left_over], buffer, len);
  308       left_over += len;
  309       if (left_over >= 64)
  310         {
  311           md5_process_block (ctx->buffer, 64, ctx);
  312           left_over -= 64;
  313           /* The regions in the following copy operation cannot overlap,
  314              because left_over ≤ 64.  */
  315           memcpy (ctx->buffer, &ctx->buffer[16], left_over);
  316         }
  317       ctx->buflen = left_over;
  318     }
  319 }
  320 
  321 
  322 /* These are the four functions used in the four steps of the MD5 algorithm
  323    and defined in the RFC 1321.  The first function is a little bit optimized
  324    (as found in Colin Plumbs public domain implementation).  */
  325 /* #define FF(b, c, d) ((b & c) | (~b & d)) */
  326 #define FF(b, c, d) (d ^ (b & (c ^ d)))
  327 #define FG(b, c, d) FF (d, b, c)
  328 #define FH(b, c, d) (b ^ c ^ d)
  329 #define FI(b, c, d) (c ^ (b | ~d))
  330 
  331 /* Process LEN bytes of BUFFER, accumulating context into CTX.
  332    It is assumed that LEN % 64 == 0.  */
  333 
  334 void
  335 md5_process_block (const void *buffer, size_t len, struct md5_ctx *ctx)
  336 {
  337   uint32_t correct_words[16];
  338   const uint32_t *words = buffer;
  339   size_t nwords = len / sizeof (uint32_t);
  340   const uint32_t *endp = words + nwords;
  341   uint32_t A = ctx->A;
  342   uint32_t B = ctx->B;
  343   uint32_t C = ctx->C;
  344   uint32_t D = ctx->D;
  345   uint32_t lolen = len;
  346 
  347   /* First increment the byte count.  RFC 1321 specifies the possible
  348      length of the file up to 2^64 bits.  Here we only compute the
  349      number of bytes.  Do a double word increment.  */
  350   ctx->total[0] += lolen;
  351   ctx->total[1] += (len >> 31 >> 1) + (ctx->total[0] < lolen);
  352 
  353   /* Process all bytes in the buffer with 64 bytes in each round of
  354      the loop.  */
  355   while (words < endp)
  356     {
  357       uint32_t *cwp = correct_words;
  358       uint32_t A_save = A;
  359       uint32_t B_save = B;
  360       uint32_t C_save = C;
  361       uint32_t D_save = D;
  362 
  363       /* First round: using the given function, the context and a constant
  364          the next context is computed.  Because the algorithms processing
  365          unit is a 32-bit word and it is determined to work on words in
  366          little endian byte order we perhaps have to change the byte order
  367          before the computation.  To reduce the work for the next steps
  368          we store the swapped words in the array CORRECT_WORDS.  */
  369 
  370 #define OP(a, b, c, d, s, T)                                            \
  371       do                                                                \
  372         {                                                               \
  373           a += FF (b, c, d) + (*cwp++ = SWAP (*words)) + T;             \
  374           ++words;                                                      \
  375           CYCLIC (a, s);                                                \
  376           a += b;                                                       \
  377         }                                                               \
  378       while (0)
  379 
  380       /* It is unfortunate that C does not provide an operator for
  381          cyclic rotation.  Hope the C compiler is smart enough.  */
  382 #define CYCLIC(w, s) (w = (w << s) | (w >> (32 - s)))
  383 
  384       /* Before we start, one word to the strange constants.
  385          They are defined in RFC 1321 as
  386 
  387          T[i] = (int) (4294967296.0 * fabs (sin (i))), i=1..64
  388 
  389          Here is an equivalent invocation using Perl:
  390 
  391          perl -e 'foreach(1..64){printf "0x%08x\n", int (4294967296 * abs (sin $_))}'
  392        */
  393 
  394       /* Round 1.  */
  395       OP (A, B, C, D, 7, 0xd76aa478);
  396       OP (D, A, B, C, 12, 0xe8c7b756);
  397       OP (C, D, A, B, 17, 0x242070db);
  398       OP (B, C, D, A, 22, 0xc1bdceee);
  399       OP (A, B, C, D, 7, 0xf57c0faf);
  400       OP (D, A, B, C, 12, 0x4787c62a);
  401       OP (C, D, A, B, 17, 0xa8304613);
  402       OP (B, C, D, A, 22, 0xfd469501);
  403       OP (A, B, C, D, 7, 0x698098d8);
  404       OP (D, A, B, C, 12, 0x8b44f7af);
  405       OP (C, D, A, B, 17, 0xffff5bb1);
  406       OP (B, C, D, A, 22, 0x895cd7be);
  407       OP (A, B, C, D, 7, 0x6b901122);
  408       OP (D, A, B, C, 12, 0xfd987193);
  409       OP (C, D, A, B, 17, 0xa679438e);
  410       OP (B, C, D, A, 22, 0x49b40821);
  411 
  412       /* For the second to fourth round we have the possibly swapped words
  413          in CORRECT_WORDS.  Redefine the macro to take an additional first
  414          argument specifying the function to use.  */
  415 #undef OP
  416 #define OP(f, a, b, c, d, k, s, T)                                      \
  417       do                                                                \
  418         {                                                               \
  419           a += f (b, c, d) + correct_words[k] + T;                      \
  420           CYCLIC (a, s);                                                \
  421           a += b;                                                       \
  422         }                                                               \
  423       while (0)
  424 
  425       /* Round 2.  */
  426       OP (FG, A, B, C, D, 1, 5, 0xf61e2562);
  427       OP (FG, D, A, B, C, 6, 9, 0xc040b340);
  428       OP (FG, C, D, A, B, 11, 14, 0x265e5a51);
  429       OP (FG, B, C, D, A, 0, 20, 0xe9b6c7aa);
  430       OP (FG, A, B, C, D, 5, 5, 0xd62f105d);
  431       OP (FG, D, A, B, C, 10, 9, 0x02441453);
  432       OP (FG, C, D, A, B, 15, 14, 0xd8a1e681);
  433       OP (FG, B, C, D, A, 4, 20, 0xe7d3fbc8);
  434       OP (FG, A, B, C, D, 9, 5, 0x21e1cde6);
  435       OP (FG, D, A, B, C, 14, 9, 0xc33707d6);
  436       OP (FG, C, D, A, B, 3, 14, 0xf4d50d87);
  437       OP (FG, B, C, D, A, 8, 20, 0x455a14ed);
  438       OP (FG, A, B, C, D, 13, 5, 0xa9e3e905);
  439       OP (FG, D, A, B, C, 2, 9, 0xfcefa3f8);
  440       OP (FG, C, D, A, B, 7, 14, 0x676f02d9);
  441       OP (FG, B, C, D, A, 12, 20, 0x8d2a4c8a);
  442 
  443       /* Round 3.  */
  444       OP (FH, A, B, C, D, 5, 4, 0xfffa3942);
  445       OP (FH, D, A, B, C, 8, 11, 0x8771f681);
  446       OP (FH, C, D, A, B, 11, 16, 0x6d9d6122);
  447       OP (FH, B, C, D, A, 14, 23, 0xfde5380c);
  448       OP (FH, A, B, C, D, 1, 4, 0xa4beea44);
  449       OP (FH, D, A, B, C, 4, 11, 0x4bdecfa9);
  450       OP (FH, C, D, A, B, 7, 16, 0xf6bb4b60);
  451       OP (FH, B, C, D, A, 10, 23, 0xbebfbc70);
  452       OP (FH, A, B, C, D, 13, 4, 0x289b7ec6);
  453       OP (FH, D, A, B, C, 0, 11, 0xeaa127fa);
  454       OP (FH, C, D, A, B, 3, 16, 0xd4ef3085);
  455       OP (FH, B, C, D, A, 6, 23, 0x04881d05);
  456       OP (FH, A, B, C, D, 9, 4, 0xd9d4d039);
  457       OP (FH, D, A, B, C, 12, 11, 0xe6db99e5);
  458       OP (FH, C, D, A, B, 15, 16, 0x1fa27cf8);
  459       OP (FH, B, C, D, A, 2, 23, 0xc4ac5665);
  460 
  461       /* Round 4.  */
  462       OP (FI, A, B, C, D, 0, 6, 0xf4292244);
  463       OP (FI, D, A, B, C, 7, 10, 0x432aff97);
  464       OP (FI, C, D, A, B, 14, 15, 0xab9423a7);
  465       OP (FI, B, C, D, A, 5, 21, 0xfc93a039);
  466       OP (FI, A, B, C, D, 12, 6, 0x655b59c3);
  467       OP (FI, D, A, B, C, 3, 10, 0x8f0ccc92);
  468       OP (FI, C, D, A, B, 10, 15, 0xffeff47d);
  469       OP (FI, B, C, D, A, 1, 21, 0x85845dd1);
  470       OP (FI, A, B, C, D, 8, 6, 0x6fa87e4f);
  471       OP (FI, D, A, B, C, 15, 10, 0xfe2ce6e0);
  472       OP (FI, C, D, A, B, 6, 15, 0xa3014314);
  473       OP (FI, B, C, D, A, 13, 21, 0x4e0811a1);
  474       OP (FI, A, B, C, D, 4, 6, 0xf7537e82);
  475       OP (FI, D, A, B, C, 11, 10, 0xbd3af235);
  476       OP (FI, C, D, A, B, 2, 15, 0x2ad7d2bb);
  477       OP (FI, B, C, D, A, 9, 21, 0xeb86d391);
  478 
  479       /* Add the starting values of the context.  */
  480       A += A_save;
  481       B += B_save;
  482       C += C_save;
  483       D += D_save;
  484     }
  485 
  486   /* Put checksum in context given as argument.  */
  487   ctx->A = A;
  488   ctx->B = B;
  489   ctx->C = C;
  490   ctx->D = D;
  491 }