HMAC SHA256 算法原理和实现

Golang 通过第三方库支持 JWT,JWT的签名算法使用了 HMAC SHA256 算法。

JWT 通常在请求头中的Authorization字段,使用Bearer schema:

Authorization: Bearer <token>

 

1. HMAC SHA256 算法原理

  • 1.输入密钥key和固定的数据(0x36)进行异或操作生成一个64B的数据kx;
  • 2.使用kx+输入数据执行sha256算法得到32B的out;
  • 3.使用密钥key和固定的数据(0x5C)进行异或操作生成一个64B的数据kx';
  • 4.使用kx'+第2步生成的out执行sha256算法得到32B的out,此结果就是HMACSHA256算法输出。

综述:HMAC加密算法是一种基于数据摘要算法和共享密钥的消息认证协议.它可以有效地防止数据在传输过程中被篡改,维护了数据的完整性、可靠性和安全性。

 

2. HMAC SHA256 算法实现

GitHub 源码地址: https://github.com/aperezdc/hmac-sha256/blob/master/hmac-sha256.c

#ifndef HMAC_SHA256_H
#define HMAC_SHA256_H    
#define B 64    
#define I_PAD 0x36
#define O_PAD 0x5C        
#define HMAC_SHA256_DIGEST_SIZE 32  /* Same as SHA-256's output size. */
#define SHA256_DIGEST_SIZE 32    
    
#endif /* !HMAC_SHA256_H */
void hmac_sha256 (const u8 *key, u32 key_len,const u8 *data, u32 data_len,u8 *out)
{ 
    u16 i;
    u8 kh[SHA256_DIGEST_SIZE];
    u8 tmpdata[1024];
 
    if (key_len > B) {//如果key长度大于64B,那么需要先对key进行sha256运算,换成32B数据,否则不处理       
        sha256( key, key_len, kh);
        key_len = SHA256_DIGEST_SIZE;
        key = kh;
    }

    /*
     * (1) append zeros to the end of K to create a B byte string
     *     (e.g., if K is of length 20 bytes and B=64, then K will be
     *     appended with 44 zero bytes 0x00)
     * (2) XOR (bitwise exclusive-OR) the B byte string computed in step
     *     (1) with ipad
     */
    u8 kx[B];
    for ( i = 0; i < key_len; i++) kx[i] = I_PAD ^ key[i];//key异或0x36,填充前部分kx
    for ( i = key_len; i < B; i++) kx[i] = I_PAD ^ 0;//剩余部分填充0x36,生成kx数据

    /*
     * (3) append the stream of data 'text' to the B byte string resulting
     *     from step (2)
     * (4) apply H to the stream generated in step (3)
     */  
    memcpy(tmpdata,kx,B);
    memcpy(&tmpdata[B],data,data_len);
    sha256(tmpdata, data_len+B, out);//把kx和输入数据拼接起来算一次sha256

    /*
     * (5) XOR (bitwise exclusive-OR) the B byte string computed in
     *     step (1) with opad
     * NOTE: The "kx" variable is reused.
     */
    for ( i = 0; i < key_len; i++) kx[i] = O_PAD ^ key[i];//key异或0x5C,填充前部分kx
    for ( i = key_len; i < B; i++) kx[i] = O_PAD ^ 0;//剩余部分填充0x5C,生成kx数据

    /*
     * (6) append the H result from step (4) to the B byte string
     *     resulting from step (5)
     * (7) apply H to the stream generated in step (6) and output
     *     the result
     */

    memcpy(tmpdata,kx,B);
    memcpy(&tmpdata[B],out,SHA256_DIGEST_SIZE);
    sha256(tmpdata, SHA256_DIGEST_SIZE+B, out);//把kx和上一步生成的32B数据拼接起来再算一次sha256,输出结果。
}

测试数据:

key1(32B hex):0102030405060708090a0b0c0d0e0f100102030405060708090a0b0c0d0e0f10
data1(40B ascll):1234567890123456789012345678901234567890
value1(32B hex):3B7F4D300E7930592F87718F8E7D284649AED889FDDE7D4B99FCA41F9EA1D35F