需要支持HMACSHA256算法,GitHub找到源碼具體地址https://github.com/aperezdc/hmac-sha256/blob/master/hmac-sha256.c
移植到目標平臺,稍作處理測試ok了,原理:
1.輸入密鑰key和固定的數據(0x36)進行異或操作生成一個64B的數據kx;
2.使用kx+輸入數據執行sha256算法得到32B的out;
3.使用密鑰key和固定的數據(0x5C)進行異或操作生成一個64B的數據kx';
4.使用kx'+第2步生成的out執行sha256算法得到32B的out,此結果就是HMACSHA256算法輸出;
綜述:HMAC加密算法是一種基於數據摘要算法和共享密鑰的消息認證協議.它可以有效地防止數據在傳輸過程中被篡改,維護了數據的完整性、可靠性和安全性.
#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, key_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
key3(16B hex):0102030405060708090a0b0c0d0e0f10
data3(40B ascll):1234567890123456789012345678901234567890
value3(32B hex):17E016631C53E274CA1B6403967AEA1A36E3D1C726588C1668CD1F93A7D9D8A7