python实现 HmacSHA256加密算法

一般来说,sha256算法通常和base64算法一起搭配使用。

废话不多说,直接上代码:

from hashlib import sha256
import hmac, base64

def get_sha256(data, key):
    key = key.encode('utf-8')       # sha256加密的key
    message = data.encode('utf-8')  # 待sha256加密的内容
    sign = base64.b64encode(hmac.new(key, message, digestmod=sha256).digest()).decode()
    return sign

if __name__ == '__main__':
    key = 'HappyNewYear123456'
    data_str = '一段测试的字符串,祝你新年快乐哦!'
    sign = get_sha256(data_str, key)
    print(sign)
    

运行结果:

vhypRB3c3w9YiQpX/iAdJVLHjJ3y18XXJ86e6DWH1cQ=
  • 6
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C++中,可以使用Crypto++库来实现HMAC-SHA256加密算法。Crypto++是一个开源的加密库,提供了各种常见的加密算法实现。 以下是一个示例代码,演示如何使用Crypto++库来进行HMAC-SHA256加密: ```cpp #include <iostream> #include <string> #include <cryptopp/cryptlib.h> #include <cryptopp/hmac.h> #include <cryptopp/sha.h> #include <cryptopp/filters.h> #include <cryptopp/hex.h> std::string hmac_sha256(const std::string& key, const std::string& message) { CryptoPP::HMAC<CryptoPP::SHA256> hmac((const byte*)key.data(), key.size()); std::string digest; CryptoPP::StringSource(message, true, new CryptoPP::HashFilter(hmac, new CryptoPP::HexEncoder(new CryptoPP::StringSink(digest)))); return digest; } int main() { std::string key = "secret_key"; std::string message = "Hello, World!"; std::string hmac = hmac_sha256(key, message); std::cout << "HMAC-SHA256: " << hmac << std::endl; return 0; } ``` 在上面的示例中,我们首先包含了Crypto++库的相关头文件。然后定义了一个名为`hmac_sha256`的函数,用于计算HMAC-SHA256值。该函数接受一个密钥和一个消息作为输入,并返回计算得到的HMAC-SHA256值。 在`main`函数中,我们指定了一个密钥和一个消息,然后调用`hmac_sha256`函数计算HMAC-SHA256值,并将结果打印输出。 需要注意的是,为了成功编译上述代码,需要先安装Crypto++库,并在编译时链接Crypto++库。具体的安装和链接方法可以参考Crypto++的官方文档或相关教程。 请确保在实际应用中使用安全的密钥和消息,并采取适当的安全措施来保护数据。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值