HMAC256算法实现c/c++

本文介绍了如何在C/C++中实现HMAC-SHA256算法,包括头文件`hmacsha256.h`和源文件`hmacsha256.c`的内容,并提供了调用示例,经实际测试验证其功能正常。
摘要由CSDN通过智能技术生成

hmacsha256.h

#ifndef _HMAC_SHA_256_H_
#define _HMAC_SHA_256_H_

#define SHA256_BLOCKLEN  64ul //size of message block buffer
#define SHA256_DIGESTLEN 32ul //size of digest in uint8_t
#define SHA256_DIGESTINT 8ul  //size of digest in uint32_t

// #ifndef PBKDF2_SHA256_STATIC
// #define PBKDF2_SHA256_DEF extern
// #else
// #define PBKDF2_SHA256_DEF static
// #endif

#include "stdint.h"

#define PBKDF2_SHA256_DEF extern

typedef struct sha256_ctx_t
{
    uint64_t len;                 // processed message length
    uint32_t h[SHA256_DIGESTINT]; // hash state
    uint8_t buf[SHA256_BLOCKLEN]; // message block buffer
} SHA256_CTX;

PBKDF2_SHA256_DEF void sha256_init(SHA256_CTX *ctx);
PBKDF2_SHA256_DEF void sha256_update(SHA256_CTX *ctx, const uint8_t *m, uint32_t mlen);
// resets state: calls sha256_init
PBKDF2_SHA256_DEF void sha256_final(SHA256_CTX *ctx, uint8_t *md);

typedef struct hmac_sha256_ctx_t
{
    uint8_t buf[SHA256_BLOCKLEN]; // key block buffer, not needed after init
    uint32_t h_inner[SHA256_DIGESTINT];
    uint32_t h_outer[SHA256_DIGESTINT];
    SHA256_CTX sha;
} HMAC_SHA256_CTX;

PBKDF2_SHA256_DEF void hmac_sha256_init(HMAC_SHA256_CTX *hmac, const uint8_t *key, uint32_t keylen);
PBKDF2_SHA256_DEF void hmac_sha256_update(HMAC_SHA256_CTX *hmac, const uint8_t *m, uint32_t mlen);
// resets state to hmac_sha256_init
PBKDF2_SHA256_DEF void hmac_sha256_final(HMAC_SHA256_CTX *hmac, uint8_t *md);

PBKDF2_SHA256_DEF void pbkdf2_sha256(HMAC_SHA256_CTX *ctx,
    const uint8_t *key, uint32_t keylen, const uint8_t *salt, uint32_t saltlen, uint32_t rounds,
    uint8_t *dk, uint32_t dklen);

#endif // _HMAC_SHA_256_H_

hmacsha256.c

#include "hmacsha256.h" 
#include <string.h>

//#define ROR(n,k) ((n >> k) | (n << (32 - k)))

static uint32_t ror(uint32_t n, uint32_t k)
{
    return (n >> k) | (n << (32 - k));
}

#define ROR(n,k) ror(n,k)

#define CH(x,y,z)  (z ^ (x & (y ^ z)))
#define MAJ(x,y,z) ((x & y) | (z & (x | y)))
#define S0(x)      (ROR(x, 2) ^ ROR(x,13) ^ ROR(x,22))
#define
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值