hmac256 加密+ base64 编码 c++11

php 源码实现加密,用于验证

$s = hash_hmac('sha256',
    'hello world',
    'writer',
    true);
echo $s;
echo base64_encode($s)

c++ 实现封装

hmac.h


#pragma once

#include <string>
#include <cmath>
#include <cstdio>

#include "hmac_sha2.h"

class HMac{
public:
    //depend on hmac_sha.h hmac_sha.c sha2.c sha2.h
    static std::string cHMacSha256(const std::string &text, const std::string &key, bool showInfo = false);

    //depend on base64
    static std::string base64Encode(const std::string & src, bool showInfo = false);
};

hmac.cpp


#include "hmac.h"


#include "hmac_sha2.h"
#include "base64.h"

#include <array>



std::string HMac::cHMacSha256(const std::string &text, const std::string &key, bool showInfo) {
    char buf[2];
    unsigned char mac[SHA256_DIGEST_SIZE];
    hmac_sha256((const unsigned char *)key.c_str(), key.length(), (const unsigned char *)text.c_str(),
                text.length(), mac, SHA256_DIGEST_SIZE);
    std::string val =  std::string{reinterpret_cast<char const*>(mac), 32};

    if(showInfo){
        printf("\n-----------------------Hash256-----------------------");
        printf("\n       Secret: %s",key.c_str());
        printf("\n      Message: %s",text.c_str());
        printf("\n  Result(Hex):");
        for(int i = 0; i < SHA256_DIGEST_SIZE; i++)
        {
            printf(" %.2x ", mac[i]);
        }
        printf("\nResult(String): %s",val.c_str());
        printf("\n***********************Hash256***********************\n");
    }

    return val;
}

std::string HMac::base64Encode(const std::string &src, bool showInfo ) {

    std::string ret = base64_encode(reinterpret_cast<const unsigned char*>(src.c_str()),src.length());
    if(showInfo){
        printf("\n-----------------------Base64-----------------------");
        printf("\nSrc: %s",src.c_str());
        printf("\nRet: %s",ret.c_str());
        printf("\n***********************Base64***********************\n");
    }

    return ret;
}

详细代码见github
csdn下载

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MStudyStudio

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值