sha1.c
changeset 53 ea43dbad123b
parent 52 7f21abb9ff17
equal deleted inserted replaced
52:7f21abb9ff17 53:ea43dbad123b
   175 #ifdef SHA1HANDSOFF  /* make SHA1Transform overwrite its own static vars */
   175 #ifdef SHA1HANDSOFF  /* make SHA1Transform overwrite its own static vars */
   176     SHA1Transform(context->state, context->buffer);
   176     SHA1Transform(context->state, context->buffer);
   177 #endif
   177 #endif
   178 #endif
   178 #endif
   179 }
   179 }
       
   180 
       
   181 
       
   182 /* https://www.ietf.org/rfc/rfc2104.txt */
       
   183 void SHA1Hmac(const uint8_t *key, const uint32_t keylen, const uint8_t *msg, const uint32_t msglen, uint8_t digest[SHA1_DIGEST_LENGTH])
       
   184 {
       
   185     SHA1_CTX sha1;
       
   186     uint8_t block[64];  // 512 bits.
       
   187     uint8_t xori[sizeof (block)];
       
   188     uint8_t xoro[sizeof (block)];
       
   189     int i;
       
   190 
       
   191     memset(block, '\0', sizeof (block));
       
   192     if (keylen <= sizeof (block)) {
       
   193         memcpy(block, key, keylen);
       
   194     } else {
       
   195         /* SHA-1 the key itself to shrink it down. */
       
   196         SHA1Init(&sha1);
       
   197         SHA1Update(&sha1, key, keylen);
       
   198         SHA1Final(block, &sha1);
       
   199     }
       
   200 
       
   201     for (i = 0; i < sizeof (block); i++) {
       
   202         const uint8_t b = block[i];
       
   203         xori[i] = b ^ 0x36;  /* XOR block vs ipad value */
       
   204         xoro[i] = b ^ 0x5C;  /* XOR block vs opad value */
       
   205     }
       
   206 
       
   207     SHA1Init(&sha1);
       
   208     SHA1Update(&sha1, xori, sizeof (xori));
       
   209     SHA1Update(&sha1, msg, msglen);
       
   210     SHA1Final(block, &sha1);
       
   211 
       
   212     SHA1Init(&sha1);
       
   213     SHA1Update(&sha1, xoro, sizeof (xoro));
       
   214     SHA1Update(&sha1, block, SHA1_DIGEST_LENGTH);
       
   215     SHA1Final(digest, &sha1);
       
   216 }
       
   217