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, tomstdenis (at) gmail.com, http://libtomcrypt.com 10 */ 11 #include <tomcrypt.h> 12 13 /** 14 @file pkcs_5_1.c 15 PKCS #5, Algorithm #1, Tom St Denis 16 */ 17 #ifdef PKCS_5 18 /** 19 Execute PKCS #5 v1 20 @param password The password (or key) 21 @param password_len The length of the password (octet) 22 @param salt The salt (or nonce) which is 8 octets long 23 @param iteration_count The PKCS #5 v1 iteration count 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 28 */ 29 int pkcs_5_alg1(const unsigned char *password, unsigned long password_len, 30 const unsigned char *salt, 31 int iteration_count, int hash_idx, 32 unsigned char *out, unsigned long *outlen) 33 { 34 int err; 35 unsigned long x; 36 hash_state *md; 37 unsigned char *buf; 38 39 LTC_ARGCHK(password != NULL); 40 LTC_ARGCHK(salt != NULL); 41 LTC_ARGCHK(out != NULL); 42 LTC_ARGCHK(outlen != NULL); 43 44 /* test hash IDX */ 45 if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) { 46 return err; 47 } 48 49 /* allocate memory */ 50 md = XMALLOC(sizeof(hash_state)); 51 buf = XMALLOC(MAXBLOCKSIZE); 52 if (md == NULL || buf == NULL) { 53 if (md != NULL) { 54 XFREE(md); 55 } 56 if (buf != NULL) { 57 XFREE(buf); 58 } 59 return CRYPT_MEM; 60 } 61 62 /* hash initial password + salt */ 63 if ((err = hash_descriptor[hash_idx].init(md)) != CRYPT_OK) { 64 goto LBL_ERR; 65 } 66 if ((err = hash_descriptor[hash_idx].process(md, password, password_len)) != CRYPT_OK) { 67 goto LBL_ERR; 68 } 69 if ((err = hash_descriptor[hash_idx].process(md, salt, 8)) != CRYPT_OK) { 70 goto LBL_ERR; 71 } 72 if ((err = hash_descriptor[hash_idx].done(md, buf)) != CRYPT_OK) { 73 goto LBL_ERR; 74 } 75 76 while (--iteration_count) { 77 /* code goes here. */ 78 x = MAXBLOCKSIZE; 79 if ((err = hash_memory(hash_idx, buf, hash_descriptor[hash_idx].hashsize, buf, &x)) != CRYPT_OK) { 80 goto LBL_ERR; 81 } 82 } 83 84 /* copy upto outlen bytes */ 85 for (x = 0; x < hash_descriptor[hash_idx].hashsize && x < *outlen; x++) { 86 out[x] = buf[x]; 87 } 88 *outlen = x; 89 err = CRYPT_OK; 90 LBL_ERR: 91 #ifdef LTC_CLEAN_STACK 92 zeromem(buf, MAXBLOCKSIZE); 93 zeromem(md, sizeof(hash_state)); 94 #endif 95 96 XFREE(buf); 97 XFREE(md); 98 99 return err; 100 } 101 102 #endif 103 104 /* $Source: /cvs/libtom/libtomcrypt/src/misc/pkcs5/pkcs_5_1.c,v $ */ 105 /* $Revision: 1.5 $ */ 106 /* $Date: 2006/03/31 14:15:35 $ */ 107