Skip to content

Instantly share code, notes, and snippets.

@tomgco
Created July 1, 2013 13:17
Show Gist options
  • Save tomgco/5900657 to your computer and use it in GitHub Desktop.
Save tomgco/5900657 to your computer and use it in GitHub Desktop.
void
HMAC_SHA1_Init(HMAC_SHA1_CTX *ctx, const u_int8_t *key, u_int key_len)
{
u_int8_t k_ipad[SHA1_BLOCK_LENGTH];
int i;
if (key_len > SHA1_BLOCK_LENGTH) {
SHA1Init(&ctx->ctx);
SHA1Update(&ctx->ctx, key, key_len);
SHA1Final(ctx->key, &ctx->ctx);
ctx->key_len = SHA1_DIGEST_LENGTH;
} else {
bcopy(key, ctx->key, key_len);
ctx->key_len = key_len;
}
bzero(k_ipad, SHA1_BLOCK_LENGTH);
bcopy(ctx->key, k_ipad, ctx->key_len);
for (i = 0; i < SHA1_BLOCK_LENGTH; i++)
k_ipad[i] ^= 0x36;
SHA1Init(&ctx->ctx);
SHA1Update(&ctx->ctx, k_ipad, SHA1_BLOCK_LENGTH);
explicit_bzero(k_ipad, sizeof k_ipad);
}
void
HMAC_SHA1_Update(HMAC_SHA1_CTX *ctx, const u_int8_t *data, u_int len)
{
SHA1Update(&ctx->ctx, data, len);
}
void
HMAC_SHA1_Final(u_int8_t digest[SHA1_DIGEST_LENGTH], HMAC_SHA1_CTX *ctx)
{
u_int8_t k_opad[SHA1_BLOCK_LENGTH];
int i;
SHA1Final(digest, &ctx->ctx);
bzero(k_opad, SHA1_BLOCK_LENGTH);
bcopy(ctx->key, k_opad, ctx->key_len);
for (i = 0; i < SHA1_BLOCK_LENGTH; i++)
k_opad[i] ^= 0x5c;
SHA1Init(&ctx->ctx);
SHA1Update(&ctx->ctx, k_opad, SHA1_BLOCK_LENGTH);
SHA1Update(&ctx->ctx, digest, SHA1_DIGEST_LENGTH);
SHA1Final(digest, &ctx->ctx);
explicit_bzero(k_opad, sizeof k_opad);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment