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