1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3 * LibTomCrypt is a library that provides various cryptographic
4 * algorithms in a highly modular and flexible manner.
6 * The library is free for all purposes without any express
13 PKCS #5, Algorithm #2, Tom St Denis
19 @param password The input password (or key)
20 @param password_len The length of the password (octets)
21 @param salt The salt (or nonce)
22 @param salt_len The length of the salt (octets)
23 @param iteration_count # of iterations desired for PKCS #5 v2 [read specs for more]
24 @param hash_idx The index of the hash desired
25 @param out [out] The destination for this algorithm
26 @param outlen [in/out] The max size and resulting size of the algorithm output
27 @return CRYPT_OK if successful
29 int pkcs_5_alg2(const unsigned char *password, unsigned long password_len,
30 const unsigned char *salt, unsigned long salt_len,
31 int iteration_count, int hash_idx,
32 unsigned char *out, unsigned long *outlen)
36 unsigned long stored, left, x, y;
37 unsigned char *buf[2];
40 LTC_ARGCHK(password != NULL);
41 LTC_ARGCHK(salt != NULL);
42 LTC_ARGCHK(out != NULL);
43 LTC_ARGCHK(outlen != NULL);
46 if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {
50 buf[0] = XMALLOC(MAXBLOCKSIZE * 2);
51 hmac = XMALLOC(sizeof(hmac_state));
52 if (hmac == NULL || buf[0] == NULL) {
61 /* buf[1] points to the second block of MAXBLOCKSIZE bytes */
62 buf[1] = buf[0] + MAXBLOCKSIZE;
68 /* process block number blkno */
69 zeromem(buf[0], MAXBLOCKSIZE*2);
71 /* store current block number and increment for next pass */
72 STORE32H(blkno, buf[1]);
75 /* get PRF(P, S||int(blkno)) */
76 if ((err = hmac_init(hmac, hash_idx, password, password_len)) != CRYPT_OK) {
79 if ((err = hmac_process(hmac, salt, salt_len)) != CRYPT_OK) {
82 if ((err = hmac_process(hmac, buf[1], 4)) != CRYPT_OK) {
86 if ((err = hmac_done(hmac, buf[0], &x)) != CRYPT_OK) {
90 /* now compute repeated and XOR it in buf[1] */
91 XMEMCPY(buf[1], buf[0], x);
92 for (itts = 1; itts < iteration_count; ++itts) {
93 if ((err = hmac_memory(hash_idx, password, password_len, buf[0], x, buf[0], &x)) != CRYPT_OK) {
96 for (y = 0; y < x; y++) {
97 buf[1][y] ^= buf[0][y];
101 /* now emit upto x bytes of buf[1] to output */
102 for (y = 0; y < x && left != 0; ++y) {
103 out[stored++] = buf[1][y];
111 #ifdef LTC_CLEAN_STACK
112 zeromem(buf[0], MAXBLOCKSIZE*2);
113 zeromem(hmac, sizeof(hmac_state));
125 /* ref: $Format:%D$ */
126 /* git commit: $Format:%H$ */
127 /* commit time: $Format:%ai$ */