Juliana Correa / totp
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers hash.cpp Source File

hash.cpp

00001 #include "sha1.h"
00002 #include <string.h>
00003 
00004 void hmac_sha1(unsigned char const *key, size_t keylen, unsigned char const *in, size_t inlen, unsigned char *resbuf)
00005 {
00006     struct SHA1Context inner;
00007     struct SHA1Context outer;
00008     unsigned char tmpkey[20];
00009     unsigned char digest[20];
00010     unsigned char block[64];
00011 
00012     const int IPAD = 0x36;
00013     const int OPAD = 0x5c;
00014 
00015     if (keylen > 64) {
00016         struct SHA1Context keyhash;
00017         SHA1Reset(&keyhash);
00018         SHA1Input(&keyhash, key, keylen);
00019         SHA1Result(&keyhash, tmpkey);
00020         key = tmpkey;
00021         keylen = 20;
00022     }
00023 
00024     for (size_t i = 0; i < sizeof(block); i++) {
00025         block[i] = IPAD ^ (i < keylen ? key[i] : 0);
00026     }
00027     SHA1Reset(&inner);
00028     SHA1Input(&inner, block, 64);
00029     SHA1Input(&inner, in, inlen);
00030     SHA1Result(&inner, digest);
00031 
00032     for (size_t i = 0; i < sizeof(block); i++) {
00033         block[i] = OPAD ^ (i < keylen ? key[i] : 0);
00034     }
00035     SHA1Reset(&outer);
00036     SHA1Input(&outer, block, 64);
00037     SHA1Input(&outer, digest, 20);
00038     SHA1Result(&outer, resbuf);
00039 }