new upstream release (3.3.0); modify package compatibility for Stretch
[ossec-hids.git] / src / os_crypto / md5 / md5_op.c
1 /* Copyright (C) 2009 Trend Micro Inc.
2  * All right reserved.
3  *
4  * This program is a free software; you can redistribute it
5  * and/or modify it under the terms of the GNU General Public
6  * License (version 2) as published by the FSF - Free Software
7  * Foundation
8  */
9
10 /* OS_crypto/md5 Library
11  * APIs for many crypto operations
12  */
13
14 #include <stdio.h>
15 #include <string.h>
16
17 #include "md5_op.h"
18 #include "md5.h"
19 #include "headers/defs.h"
20
21
22 int OS_MD5_File(const char *fname, os_md5 output, int mode)
23 {
24     FILE *fp;
25     MD5_CTX ctx;
26     unsigned char buf[1024 + 1];
27     unsigned char digest[16];
28     size_t n;
29
30     memset(output, 0, 33);
31     buf[1024] = '\0';
32
33     fp = fopen(fname, mode == OS_BINARY ? "rb" : "r");
34     if (!fp) {
35         return (-1);
36     }
37
38     MD5Init(&ctx);
39     while ((n = fread(buf, 1, sizeof(buf) - 1, fp)) > 0) {
40         buf[n] = '\0';
41         MD5Update(&ctx, buf, (unsigned)n);
42     }
43
44     MD5Final(digest, &ctx);
45
46     for (n = 0; n < 16; n++) {
47         snprintf(output, 3, "%02x", digest[n]);
48         output += 2;
49     }
50
51     fclose(fp);
52
53     return (0);
54 }
55
56 int OS_MD5_Str(const char *str, os_md5 output)
57 {
58     unsigned char digest[16];
59
60     int n;
61
62     MD5_CTX ctx;
63     MD5Init(&ctx);
64     MD5Update(&ctx, (const unsigned char *)str, (unsigned)strlen(str));
65     MD5Final(digest, &ctx);
66
67     output[32] = '\0';
68     for (n = 0; n < 16; n++) {
69         snprintf(output, 3, "%02x", digest[n]);
70         output += 2;
71     }
72
73     return (0);
74 }