近期项目中HTTPS通讯中,token需要使用HMAC-MD5算法生成,往上找了一些资料后,仍不能满足自身需求,故次一记。
前期准备:
①下载Cryptopp库(我下载的是8.8.0 Release版本):Crypto++ Library 8.9 | Free C++ Class Library of Cryptographic Schemes
②进行编译,根据自身情况进行VS环境配置
将cryptdll、cryptlib编译后分别按文件夹分类保存
【lib:cryptlib.lib、cryptopp.lib】【dll:cryptopp.dll】
也可以直接下载我编译好的:
HMAC-SHA256算法实现:
#include <iostream>
#include <string>
#include <cryptopp/hmac.h>
#include <cryptopp/sha.h>
int main()
{
std::string key = "mysecretkey";
std::string data = "Hello, HMAC!";
CryptoPP::HMAC<CryptoPP::SHA256> hmac((const byte*)key.data(), key.size());
byte digest[CryptoPP::SHA256::DIGESTSIZE];
hmac.Update((const byte*)data.data(), data.size());
hmac.Final(digest);
std::cout << "HMAC-SHA256: ";
for (int i = 0; i < CryptoPP::SHA256::DIGESTSIZE; i++) {
printf("%02x", digest[i]);
}
std::cout << std::endl;
return 0;
}
MD5算法实现:
std::string crypto::md5(std::string text)
{
std::string digest;
CryptoPP::Weak1::MD5 md5;
CryptoPP::HashFilter hashfilter(md5);
hashfilter.Attach(new CryptoPP::HexEncoder(new CryptoPP::StringSink(digest), false));
hashfilter.Put(reinterpret_cast<const unsigned char*>(text.c_str()), text.length());
hashfilter.MessageEnd();
return digest;
}
HMAC-MD5算法实现:
#include "hmac.h"
#include "md5.h"
{
QJsonObject json;
json["key"] = "1234567890";
QJsonDocument document;
document.setObject(json);
QByteArray ba = document.toJson(QJsonDocument::Compact);//Indented : Compact
std::string key = "apple";
std::string body = ba.data();
CryptoPP::HMAC<CryptoPP::Weak1::MD5> hmac((const CryptoPP::byte*)key.data(), key.size());
CryptoPP::byte digest[CryptoPP::Weak1::MD5::DIGESTSIZE];
hmac.Update((const CryptoPP::byte*)body.data(), body.size());
hmac.Final(digest);
std::cout << "HMAC-MD5: ";
for (int i = 0; i < CryptoPP::Weak1::MD5::DIGESTSIZE; i++) {
printf("%02x", digest[i]);
}
std::cout << std::endl;
}