3
|
1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis |
|
2 * |
|
3 * LibTomCrypt is a library that provides various cryptographic |
|
4 * algorithms in a highly modular and flexible manner. |
|
5 * |
|
6 * The library is free for all purposes without any express |
|
7 * guarantee it works. |
|
8 * |
|
9 * Tom St Denis, [email protected], http://libtomcrypt.org |
|
10 */ |
|
11 #include <mycrypt.h> |
|
12 |
|
13 /* PKCS #5, Algorithm #1 */ |
|
14 #ifdef PKCS_5 |
|
15 |
|
16 int pkcs_5_alg1(const unsigned char *password, unsigned long password_len, |
|
17 const unsigned char *salt, |
|
18 int iteration_count, int hash_idx, |
|
19 unsigned char *out, unsigned long *outlen) |
|
20 { |
|
21 int err; |
|
22 unsigned long x; |
143
|
23 hash_state *md; |
|
24 unsigned char *buf; |
3
|
25 |
|
26 _ARGCHK(password != NULL); |
|
27 _ARGCHK(salt != NULL); |
|
28 _ARGCHK(out != NULL); |
|
29 _ARGCHK(outlen != NULL); |
|
30 |
|
31 /* test hash IDX */ |
|
32 if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) { |
|
33 return err; |
|
34 } |
|
35 |
143
|
36 /* allocate memory */ |
|
37 md = XMALLOC(sizeof(hash_state)); |
|
38 buf = XMALLOC(MAXBLOCKSIZE); |
|
39 if (md == NULL || buf == NULL) { |
|
40 if (md != NULL) { |
|
41 XFREE(md); |
|
42 } |
|
43 if (buf != NULL) { |
|
44 XFREE(buf); |
|
45 } |
|
46 return CRYPT_MEM; |
|
47 } |
|
48 |
3
|
49 /* hash initial password + salt */ |
143
|
50 if ((err = hash_descriptor[hash_idx].init(md)) != CRYPT_OK) { |
|
51 goto __ERR; |
|
52 } |
|
53 if ((err = hash_descriptor[hash_idx].process(md, password, password_len)) != CRYPT_OK) { |
|
54 goto __ERR; |
|
55 } |
|
56 if ((err = hash_descriptor[hash_idx].process(md, salt, 8)) != CRYPT_OK) { |
|
57 goto __ERR; |
|
58 } |
|
59 if ((err = hash_descriptor[hash_idx].done(md, buf)) != CRYPT_OK) { |
|
60 goto __ERR; |
|
61 } |
3
|
62 |
|
63 while (--iteration_count) { |
|
64 // code goes here. |
143
|
65 x = MAXBLOCKSIZE; |
3
|
66 if ((err = hash_memory(hash_idx, buf, hash_descriptor[hash_idx].hashsize, buf, &x)) != CRYPT_OK) { |
143
|
67 goto __ERR; |
3
|
68 } |
|
69 } |
|
70 |
|
71 /* copy upto outlen bytes */ |
|
72 for (x = 0; x < hash_descriptor[hash_idx].hashsize && x < *outlen; x++) { |
|
73 out[x] = buf[x]; |
|
74 } |
|
75 *outlen = x; |
143
|
76 err = CRYPT_OK; |
|
77 __ERR: |
3
|
78 #ifdef CLEAN_STACK |
143
|
79 zeromem(buf, MAXBLOCKSIZE); |
|
80 zeromem(md, sizeof(hash_state)); |
3
|
81 #endif |
|
82 |
143
|
83 XFREE(buf); |
|
84 XFREE(md); |
|
85 |
|
86 return err; |
3
|
87 } |
|
88 |
|
89 #endif |