在 C/C++ 中使用 libtomcrypt 计算加密哈希
问题:
你想在 C/C++ 中计算任何字符串的哈希。LibTomCrypt 是 WTFPL 许可的,所以它是商业和非商业项目的好选择。
解决方案
本文描述了一个简约的解决方案。有关更多信息,请查阅官方文档。
这是一个哈希 C 字符串的最小 C 实现示例。
hash_sha1_c.c
#include <tomcrypt.h>
/**
* 使用 SHA1 算法哈希给定的字节序列
* @param input 输入序列指针
* @param inputSize 输入序列的大小
* @return 指向结果数据的 malloc 分配指针。20 字节长。
*/
unsigned char* hashSHA1(const char* input, unsigned long inputSize) {
//初始化
unsigned char* hashResult = (unsigned char*)malloc(sha1_desc.hashsize);
//初始化ize a state variable for the hash
hash_state md;
sha1_init(&md);
//处理文本 - 记住你可以多次调用 process()
sha1_process(&md, (const unsigned char*) input, inputSize);
//完成哈希计算
sha1_done(&md, hashResult);
// 返回结果
return hashResult;
}使用此函数后,你需要 free() 它分配并返回的内存。
其他哈希算法
为了使用其他算法(例如 SHA256 或 MD5),你需要替换两件事:1. 哈希名称(本例中为 sha1_)替换为其对应名称(记住替换每个出现的地方!)2. SHA1 的哈希大小为 20 字节,其他哈希可能不同,例如 SHA256 为 32
查阅文档,图 4.1 “内置软件哈希” 获取有效哈希描述符及其对应哈希大小的列表。
C++
即使你可以在 C++ 中使用上述 C 代码而无需任何修改,你可能想哈希 std::string 实例。
hash_sha1_cpp.cpp
/**
* 使用 SHA1 算法哈希给定的输入字符串
* @param input 输入序列指针
* @param inputSize 输入序列的大小
* @return 指向结果数据的 new[] 分配指针。20 字节长。
*/
unsigned char* hashSHA1(const std::string& input) {
//初始化
unsigned char* hashResult = new unsigned char[sha1_desc.hashsize];
//初始化ize a state variable for the hash
hash_state md;
sha1_init(&md);
//处理文本 - 记住你可以多次调用 process()
sha1_process(&md, (const unsigned char*) input.c_str(), input.size());
//完成哈希计算
sha1_done(&md, hashResult);
// 返回结果
return hashResult;
}如何使用这些函数
在大多数情况下,你想将结果哈希作为十六进制字符串打印到 stdout。以下是如何使用 C++ 代码的示例。
hash_sha1_use_example.cpp
#include <string>
int main(int argc, char** argv) {
std::string text = "abcdef";
unsigned char* hashResult = hashSHA1(text);
//作为十六进制字符串打印到 stdout
for (int x = 0; x < 20; x++) {
printf("%x", hashResult[x]); //Hex-format
}
printf("\n");
//删除哈希结果指针
delete[] hashResult;
return 0;
}此代码片段打印 1f8ac1f23c5b5bc1167bda84b833e5c57a77d2。
Check out similar posts by category:
C/C++, Cryptography
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow