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 /* The Mask Generation Function (MGF1) for PKCS #1 -- Tom St Denis */ |
|
14 |
|
15 #ifdef PKCS_1 |
|
16 |
|
17 int pkcs_1_mgf1(const unsigned char *seed, unsigned long seedlen, |
|
18 int hash_idx, |
|
19 unsigned char *mask, unsigned long masklen) |
|
20 { |
|
21 unsigned long hLen, counter, x; |
|
22 int err; |
143
|
23 hash_state *md; |
|
24 unsigned char *buf; |
3
|
25 |
|
26 _ARGCHK(seed != NULL); |
|
27 _ARGCHK(mask != NULL); |
|
28 |
|
29 /* ensure valid hash */ |
|
30 if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) { |
|
31 return err; |
|
32 } |
|
33 |
|
34 /* get hash output size */ |
|
35 hLen = hash_descriptor[hash_idx].hashsize; |
|
36 |
143
|
37 /* allocate memory */ |
|
38 md = XMALLOC(sizeof(hash_state)); |
|
39 buf = XMALLOC(hLen); |
|
40 if (md == NULL || buf == NULL) { |
|
41 if (md != NULL) { |
|
42 XFREE(md); |
|
43 } |
|
44 if (buf != NULL) { |
|
45 XFREE(buf); |
|
46 } |
|
47 return CRYPT_MEM; |
|
48 } |
|
49 |
3
|
50 /* start counter */ |
|
51 counter = 0; |
|
52 |
|
53 while (masklen > 0) { |
|
54 /* handle counter */ |
|
55 STORE32H(counter, buf); |
|
56 ++counter; |
|
57 |
|
58 /* get hash of seed || counter */ |
143
|
59 if ((err = hash_descriptor[hash_idx].init(md)) != CRYPT_OK) { |
|
60 goto __ERR; |
|
61 } |
|
62 if ((err = hash_descriptor[hash_idx].process(md, seed, seedlen)) != CRYPT_OK) { |
|
63 goto __ERR; |
3
|
64 } |
143
|
65 if ((err = hash_descriptor[hash_idx].process(md, buf, 4)) != CRYPT_OK) { |
|
66 goto __ERR; |
3
|
67 } |
143
|
68 if ((err = hash_descriptor[hash_idx].done(md, buf)) != CRYPT_OK) { |
|
69 goto __ERR; |
3
|
70 } |
|
71 |
|
72 /* store it */ |
|
73 for (x = 0; x < hLen && masklen > 0; x++, masklen--) { |
|
74 *mask++ = buf[x]; |
|
75 } |
|
76 } |
|
77 |
143
|
78 err = CRYPT_OK; |
|
79 __ERR: |
|
80 #ifdef CLEAN_STACK |
|
81 zeromem(buf, hLen); |
|
82 zeromem(md, sizeof(hash_state)); |
|
83 #endif |
|
84 |
|
85 XFREE(buf); |
|
86 XFREE(md); |
|
87 |
|
88 return err; |
3
|
89 } |
|
90 |
|
91 #endif /* PKCS_1 */ |