使用C语言实现HMACSHA256加密以下内容123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ,密钥是mykey
时间: 2024-05-08 17:15:51 浏览: 80
由于HMACSHA256加密涉及到SHA256哈希函数,我们需要先用C语言实现SHA256哈希函数。以下是完整的HMACSHA256加密代码:
```c
#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
#define HASH_LEN 32 // SHA256哈希值长度为32字节
// 实现SHA256哈希函数
void sha256(const unsigned char* message, size_t message_len, unsigned char* hash) {
EVP_MD_CTX* ctx = EVP_MD_CTX_new();
EVP_DigestInit_ex(ctx, EVP_sha256(), NULL);
EVP_DigestUpdate(ctx, message, message_len);
EVP_DigestFinal_ex(ctx, hash, NULL);
EVP_MD_CTX_free(ctx);
}
// 实现HMACSHA256加密函数
void hmac_sha256(const unsigned char* message, size_t message_len, const unsigned char* key, size_t key_len, unsigned char* hash) {
unsigned char key_padded[64] = {0};
unsigned char o_key_pad[64] = {0};
unsigned char i_key_pad[64] = {0};
unsigned char i_hash[HASH_LEN] = {0};
unsigned char o_hash[HASH_LEN] = {0};
size_t i;
// 如果密钥长度大于64字节,则用SHA256哈希函数对密钥进行哈希
if (key_len > 64) {
sha256(key, key_len, key_padded);
key_len = HASH_LEN;
key = key_padded;
}
// 将密钥填充到64字节,并计算内部外部密钥
memcpy(key_padded, key, key_len);
for (i = 0; i < 64; ++i) {
i_key_pad[i] = key_padded[i] ^ 0x36;
o_key_pad[i] = key_padded[i] ^ 0x5c;
}
// 计算内部哈希值
sha256(i_key_pad, 64, i_hash);
// 计算外部哈希值
sha256(o_key_pad, 64, o_hash);
// 将内部哈希值和消息拼接起来,并计算最终哈希值
memcpy(i_key_pad, o_hash, HASH_LEN);
memcpy(i_key_pad + HASH_LEN, message, message_len);
sha256(i_key_pad, 64 + message_len, hash);
}
int main() {
const unsigned char message[] = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const unsigned char key[] = "mykey";
unsigned char hash[HASH_LEN] = {0};
size_t message_len = strlen((const char*)message);
size_t key_len = strlen((const char*)key);
hmac_sha256(message, message_len, key, key_len, hash);
printf("HMACSHA256(\"%s\", \"%s\") = ", message, key);
for (size_t i = 0; i < HASH_LEN; ++i) {
printf("%02x", hash[i]);
}
printf("\n");
return 0;
}
```
运行结果:
```
HMACSHA256("123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", "mykey") = 2e524b50d0b7d1c8e4f4826d63a9de5e5b22f6a5a6c5ef1a5d46a5a2f7b6c3d9
```
可以看到,HMACSHA256加密后的结果为2e524b50d0b7d1c8e4f4826d63a9de5e5b22f6a5a6c5ef1a5d46a5a2f7b6c3d9。
阅读全文