C语言 hmac_sha256代码
时间: 2024-09-28 12:05:11 浏览: 74
在C语言中,HMAC-SHA256是一种常用的密码安全哈希函数,它结合了密钥和消息通过SHA-256算法计算得出的安全散列值。以下是使用OpenSSL库实现HMAC-SHA256的基本代码片段:
```c
#include <openssl/hmac.h>
#include <openssl/sha.h>
#include <string.h>
size_t hmac_sha256(const unsigned char *key, size_t key_len,
const unsigned char *data, size_t data_len,
unsigned char *digest) {
HMAC_CTX ctx;
unsigned char hmac[SHA256_DIGEST_LENGTH];
HMAC_Init_ex(&ctx, key, key_len, EVP_sha256(), NULL);
HMAC_Update(&ctx, data, data_len);
HMAC_Final(&ctx, hmac, sizeof(hmac));
// Copy the digest to the provided buffer
memcpy(digest, hmac, SHA256_DIGEST_LENGTH);
HMAC_CTX_cleanup(&ctx); // Don't forget to clean up
return SHA256_DIGEST_LENGTH;
}
// 使用示例:
const char* secret_key = "your_secret_key";
unsigned char message[] = "Hello, World!";
size_t message_len = strlen((char*)message);
unsigned char hash[SHA256_DIGEST_LENGTH];
hmac_sha256((unsigned char*)secret_key, strlen(secret_key), message, message_len, hash);
// 现在`hash`包含了HMAC-SHA256的结果,可以用于后续验证或存储
```
阅读全文