md5-hmac 算法实现(收集网络中好的代码)

md5-hmac 算法实现(收集网络中好的代码)

md5-hmac.cpp

//
// Created by natpacket on 2023/8/15.
//

#include "hmac_md5.h"
#include <stdint.h>
#include <cstring>
#include <cstdio>
#include "md5.h"

#define IPAD 0x36
#define OPAD 0x5C

void hmac_md5(uint8 dest[16], const uint8 *key, uint16_t keylength, const uint8 *msg, uint32_t msglength){
    MD5_CTX s;
    uint8_t i;
    uint8_t buffer[MD5_BLOCK_SIZE];

    memset(buffer, 0, MD5_BLOCK_SIZE);

    /* if key is larger than a block we have to hash it*/
    if (keylength > MD5_BLOCK_SIZE){
        MD5(key, keylength,buffer);
    } else {
        memcpy(buffer, key, keylength);
    }

    for (i=0; i<MD5_BLOCK_SIZE; ++i){
        buffer[i] ^= IPAD;
    }
    MD5_Init(&s);
    MD5_Update(&s, buffer,MD5_BLOCK_SIZE);
    while (msglength >= MD5_BLOCK_SIZE){
        MD5_Update(&s, msg,MD5_BLOCK_SIZE);
        msg = (uint8_t*)msg + MD5_BLOCK_SIZE;
        msglength -=  MD5_BLOCK_SIZE;
    }
    MD5_Update(&s, msg, msglength);
    /* since buffer still contains key xor ipad we can do ... */
    for (i=0; i<MD5_BLOCK_SIZE; ++i){
        buffer[i] ^= IPAD ^ OPAD;
    }
    MD5_Final(&s,dest); /* save inner hash temporary to dest */
    MD5_Init(&s);
    MD5_Update(&s, buffer,MD5_BLOCK_SIZE);
    MD5_Update(&s, dest, MD5_DIGEST_SIZE);
    MD5_Final(&s,dest);
}

void test_hmac_md5(){
    uint8 dest[16];
    const uint8 key[] ="qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq";
    uint16_t keylength_b = strlen(reinterpret_cast<const char *>(key));
    const uint8 msg[] ="1234567";
    uint32_t msglength_b = strlen(reinterpret_cast<const char *>(msg));
    hmac_md5(dest,key,keylength_b,msg,msglength_b);
    printf("%s key: %s HMAC-MD5: ",msg,key);
    for (uint32 i = 0; i < MD5_DIGEST_SIZE; i++) {
        printf("%02x", dest[i]);
    }
    printf("\n");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值