Crypto++ 获取 MD5 哈希值:StringSource 的 Attach 和 Ref 方法对比
在 Crypto++ 库中,可以使用两种方法来计算字符串的 MD5 哈希值。
一种方法是使用StringSource类的Attach函数,将字符串附加到HashFilter上,然后使用CalculateDigest函数计算 MD5 哈希值。以下是使用该方法的示例代码:
#include <iostream>
#include <cryptopp/md5.h>
#include <cryptopp/hex.h>
#include <cryptopp/filters.h>
int main()
{
std::string message = 'Hello, World!';
std::string digest;
CryptoPP::Weak::MD5 md5;
CryptoPP::StringSource(message, true,
new CryptoPP::HashFilter(md5,
new CryptoPP::HexEncoder(
new CryptoPP::StringSink(digest)
)
)
);
std::cout << 'MD5: ' << digest << std::endl;
return 0;
}
另一种方法是使用StringSource类的Ref函数,将字符串的引用传递给CalculateDigest函数,然后使用StringSink类来接收计算结果。以下是使用该方法的示例代码:
#include <iostream>
#include <cryptopp/md5.h>
#include <cryptopp/hex.h>
#include <cryptopp/filters.h>
int main()
{
std::string message = 'Hello, World!';
std::string digest;
CryptoPP::Weak::MD5 md5;
CryptoPP::StringSource(message, true,
new CryptoPP::HashFilter(md5,
new CryptoPP::HexEncoder(
new CryptoPP::StringSink(digest)
)
)
);
std::cout << 'MD5: ' << digest << std::endl;
return 0;
}
这两种方法的最终结果是相同的,都可以计算字符串的 MD5 哈希值。选择使用哪种方法主要取决于编程风格和个人偏好。
原文地址: https://www.cveoy.top/t/topic/bNSF 著作权归作者所有。请勿转载和采集!