Imported Upstream version 2.7
[ossec-hids.git] / src / os_crypto / md5_sha1 / md5_sha1_op.c
1 /* @(#) $Id: ./src/os_crypto/md5_sha1/md5_sha1_op.c, 2011/09/08 dcid Exp $
2  */
3
4 /* Copyright (C) 2009 Trend Micro Inc.
5  * All right reserved.
6  *
7  * This program is a free software; you can redistribute it
8  * and/or modify it under the terms of the GNU General Public
9  * License (version 2) as published by the FSF - Free Software
10  * Foundation
11  */
12
13
14 #include <stdio.h>
15 #include <string.h>
16 #include "md5_sha1_op.h"
17
18 #include "../md5/md5.h"
19 #include "../sha1/sha.h"
20 #include "headers/defs.h"
21
22
23
24 int OS_MD5_SHA1_File(char *fname, char *prefilter_cmd, char *md5output, char *sha1output)
25 {
26     int n;
27     FILE *fp;
28     unsigned char buf[2048 +2];
29     unsigned char sha1_digest[SHA_DIGEST_LENGTH];
30     unsigned char md5_digest[16];
31
32     char cmd[OS_MAXSTR];
33
34     SHA_CTX sha1_ctx;
35     MD5_CTX md5_ctx;
36
37
38     /* Clearing the memory. */
39     md5output[0] = '\0';
40     sha1output[0] = '\0';
41     buf[2048 +1] = '\0';
42
43     /* Use prefilter_cmd if set */
44     if (prefilter_cmd == NULL) {
45         fp = fopen(fname,"r");
46         if(!fp)
47             return(-1);
48     } else {
49         strncpy(cmd, prefilter_cmd, sizeof(cmd) - 1);
50         strcat(cmd, " ");
51         strncat(cmd, fname, sizeof(cmd) - strlen(cmd) - 1);
52         fp = popen(cmd, "r");
53         if(!fp)
54             return(-1);
55     }
56
57     /* Initializing both hashes */
58     MD5Init(&md5_ctx);
59     SHA1_Init(&sha1_ctx);
60
61
62     /* Updating for each one. */
63     while((n = fread(buf, 1, 2048, fp)) > 0)
64     {
65         buf[n] = '\0';
66         SHA1_Update(&sha1_ctx, buf, (unsigned long)n);
67         MD5Update(&md5_ctx, buf, n);
68     }
69
70     SHA1_Final(&(sha1_digest[0]), &sha1_ctx);
71     MD5Final(md5_digest, &md5_ctx);
72
73
74     /* Setting output for md5. */
75     for(n = 0;n < 16; n++)
76     {
77         snprintf(md5output, 3, "%02x", md5_digest[n]);
78         md5output+=2;
79     }
80
81     /* Setting output for sha1. */
82     for (n = 0; n<SHA_DIGEST_LENGTH; n++)
83     {
84         snprintf(sha1output, 3, "%02x", sha1_digest[n]);
85         sha1output+=2;
86     }
87
88
89     /* Closing it */
90     if (prefilter_cmd == NULL) {
91         fclose(fp);
92     } else {
93         pclose(fp);
94     }
95
96     return(0);
97 }
98
99
100 /* EOF */