1 /*
2 * iterated_hash.c -- nsec3 hash calculation.
3 *
4 * Copyright (c) 2001-2006, NLnet Labs. All rights reserved.
5 *
6 * See LICENSE for the license.
7 *
8 * With thanks to Ben Laurie.
9 */
10 #include "config.h"
11 #ifdef NSEC3
12 #if defined(HAVE_SHA1_INIT) && !defined(DEPRECATED_SHA1_INIT)
13 #include <openssl/sha.h>
14 #else
15 #include <openssl/evp.h>
16 #endif
17 #include <stdio.h>
18 #include <assert.h>
19
20 #include "iterated_hash.h"
21 #include "util.h"
22
23 int
iterated_hash(unsigned char out[SHA_DIGEST_LENGTH],const unsigned char * salt,int saltlength,const unsigned char * in,int inlength,int iterations)24 iterated_hash(unsigned char out[SHA_DIGEST_LENGTH],
25 const unsigned char *salt, int saltlength,
26 const unsigned char *in, int inlength, int iterations)
27 {
28 #if defined(NSEC3) && defined(HAVE_SSL)
29 #if defined(HAVE_SHA1_INIT) && !defined(DEPRECATED_SHA1_INIT)
30 SHA_CTX ctx;
31 #else
32 EVP_MD_CTX* ctx;
33 #endif
34 int n;
35 #if defined(HAVE_SHA1_INIT) && !defined(DEPRECATED_SHA1_INIT)
36 #else
37 ctx = EVP_MD_CTX_create();
38 if(!ctx) {
39 log_msg(LOG_ERR, "out of memory in iterated_hash");
40 return 0;
41 }
42 #endif
43 assert(in && inlength > 0 && iterations >= 0);
44 for(n=0 ; n <= iterations ; ++n)
45 {
46 #if defined(HAVE_SHA1_INIT) && !defined(DEPRECATED_SHA1_INIT)
47 SHA1_Init(&ctx);
48 SHA1_Update(&ctx, in, inlength);
49 if(saltlength > 0)
50 SHA1_Update(&ctx, salt, saltlength);
51 SHA1_Final(out, &ctx);
52 #else
53 if(!EVP_DigestInit(ctx, EVP_sha1()))
54 log_msg(LOG_ERR, "iterated_hash could not EVP_DigestInit");
55
56 if(!EVP_DigestUpdate(ctx, in, inlength))
57 log_msg(LOG_ERR, "iterated_hash could not EVP_DigestUpdate");
58 if(saltlength > 0) {
59 if(!EVP_DigestUpdate(ctx, salt, saltlength))
60 log_msg(LOG_ERR, "iterated_hash could not EVP_DigestUpdate salt");
61 }
62 if(!EVP_DigestFinal_ex(ctx, out, NULL))
63 log_msg(LOG_ERR, "iterated_hash could not EVP_DigestFinal_ex");
64 #endif
65 in=out;
66 inlength=SHA_DIGEST_LENGTH;
67 }
68 #if defined(HAVE_SHA1_INIT) && !defined(DEPRECATED_SHA1_INIT)
69 #else
70 EVP_MD_CTX_destroy(ctx);
71 #endif
72 return SHA_DIGEST_LENGTH;
73 #else
74 (void)out; (void)salt; (void)saltlength;
75 (void)in; (void)inlength; (void)iterations;
76 return 0;
77 #endif
78 }
79
80 #endif /* NSEC3 */
81