Mercurial > dropbear
diff hmac_init.c @ 143:5d99163f7e32 libtomcrypt-orig
import of libtomcrypt 0.99
author | Matt Johnston <matt@ucc.asn.au> |
---|---|
date | Sun, 19 Dec 2004 11:34:45 +0000 |
parents | 7faae8f46238 |
children |
line wrap: on
line diff
--- a/hmac_init.c Tue Jun 15 14:07:21 2004 +0000 +++ b/hmac_init.c Sun Dec 19 11:34:45 2004 +0000 @@ -35,53 +35,80 @@ int hmac_init(hmac_state *hmac, int hash, const unsigned char *key, unsigned long keylen) { - unsigned char buf[MAXBLOCKSIZE]; + unsigned char *buf; unsigned long hashsize; unsigned long i, z; int err; _ARGCHK(hmac != NULL); - _ARGCHK(key != NULL); + _ARGCHK(key != NULL); + /* valid hash? */ if ((err = hash_is_valid(hash)) != CRYPT_OK) { return err; } + hmac->hash = hash; + hashsize = hash_descriptor[hash].hashsize; /* valid key length? */ if (keylen == 0) { return CRYPT_INVALID_KEYSIZE; } - hmac->hash = hash; + /* allocate ram for buf */ + buf = XMALLOC(HMAC_BLOCKSIZE); + if (buf == NULL) { + return CRYPT_MEM; + } - // (1) make sure we have a large enough key - hashsize = hash_descriptor[hash].hashsize; + /* allocate memory for key */ + hmac->key = XMALLOC(HMAC_BLOCKSIZE); + if (hmac->key == NULL) { + XFREE(buf); + return CRYPT_MEM; + } + + /* (1) make sure we have a large enough key */ if(keylen > HMAC_BLOCKSIZE) { - z = (unsigned long)sizeof(hmac->key); + z = HMAC_BLOCKSIZE; if ((err = hash_memory(hash, key, keylen, hmac->key, &z)) != CRYPT_OK) { - return err; + goto __ERR; } if(hashsize < HMAC_BLOCKSIZE) { zeromem((hmac->key) + hashsize, (size_t)(HMAC_BLOCKSIZE - hashsize)); } keylen = hashsize; } else { - memcpy(hmac->key, key, (size_t)keylen); + XMEMCPY(hmac->key, key, (size_t)keylen); if(keylen < HMAC_BLOCKSIZE) { zeromem((hmac->key) + keylen, (size_t)(HMAC_BLOCKSIZE - keylen)); } } - // Create the initial vector for step (3) + /* Create the initial vector for step (3) */ for(i=0; i < HMAC_BLOCKSIZE; i++) { buf[i] = hmac->key[i] ^ 0x36; } - // Pre-pend that to the hash data - hash_descriptor[hash].init(&hmac->md); - hash_descriptor[hash].process(&hmac->md, buf, HMAC_BLOCKSIZE); + /* Pre-pend that to the hash data */ + if ((err = hash_descriptor[hash].init(&hmac->md)) != CRYPT_OK) { + goto __ERR; + } - return CRYPT_OK; + if ((err = hash_descriptor[hash].process(&hmac->md, buf, HMAC_BLOCKSIZE)) != CRYPT_OK) { + goto __ERR; + } + goto done; +__ERR: + /* free the key since we failed */ + XFREE(hmac->key); +done: +#ifdef CLEAN_STACK + zeromem(buf, HMAC_BLOCKSIZE); +#endif + + XFREE(buf); + return err; } #endif