EIC Software
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
PHmd5Utils.cc
Go to the documentation of this file. Or view the newest version in sPHENIX GitHub for file PHmd5Utils.cc
1 
2 #include "stdio.h"
3 
4 #include "PHmd5Utils.h"
5 #include "md5.h"
6 
7 int PHmd5File(const char * filename, unsigned char *digest, int *filesize)
8 {
9  int status;
10  FILE *fp;
11  fp = fopen (filename, "r");
12 
13  if (!fp) return 1;
14 
15  status = PHmd5Stream(fp, digest, filesize);
16  fclose(fp);
17  return status;
18 }
19 
20 
21 int PHmd5Stream(FILE *stream, unsigned char *digest, int *filesize)
22 {
23  /* Important: BLOCKSIZE must be a multiple of 64. */
24 #define BLOCKSIZE 4096
25  md5_state_t state;
26  char buffer[BLOCKSIZE + 72];
27  size_t sum;
28 
29  /* Initialize the computation context. */
30  md5_init(&state);
31 
32  /* Iterate over full file contents. */
33  *filesize = 0;
34  while (1)
35  {
36  /* We read the file in blocks of BLOCKSIZE bytes. One call of the
37  computation function processes the whole buffer so that with the
38  next round of the loop another block can be read. */
39  size_t n;
40  sum = 0;
41 
42  /* Read block. Take care for partial reads. */
43  do
44  {
45  n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
46 
47  sum += n;
48  *filesize += n;
49  }
50  while (sum < BLOCKSIZE && n != 0);
51  if (n == 0 && ferror (stream))
52  return 1;
53 
54  /* If end of file is reached, end the loop. */
55  if (n == 0)
56  break;
57 
58  /* Process buffer with BLOCKSIZE bytes. Note that
59  BLOCKSIZE % 64 == 0
60  */
61  md5_append(&state, (const md5_byte_t *)buffer,BLOCKSIZE );
62  /* md5_process_block (buffer, BLOCKSIZE, &ctx); */
63  }
64 
65  /* Add the last bytes if necessary. */
66  if (sum > 0) md5_append(&state, (const md5_byte_t *)buffer,sum );
67  /* md5_process_bytes (buffer, sum, &ctx); */
68 
69  /* Construct result in desired memory. */
70  md5_finish(&state, (md5_byte_t *) digest);
71  /* md5_finish_ctx (&ctx, resblock); */
72  return 0;
73 }
74