C++实现sha1哈希填充
时间: 2023-07-09 12:53:35 浏览: 47
SHA-1是一种哈希算法,它使用一个512位的消息块,将其填充并迭代压缩成160位的哈希值。C++中可以使用以下代码实现SHA-1哈希填充:
```c++
#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstring>
#include <openssl/sha.h>
std::string sha1(const std::string& str) {
unsigned char hash[SHA_DIGEST_LENGTH];
SHA_CTX sha1;
SHA1_Init(&sha1);
SHA1_Update(&sha1, str.c_str(), str.size());
SHA1_Final(hash, &sha1);
std::stringstream ss;
ss << std::hex << std::setfill('0');
for (int i = 0; i < SHA_DIGEST_LENGTH; i++) {
ss << std::setw(2) << static_cast<unsigned int>(hash[i]);
}
return ss.str();
}
int main() {
std::string str = "hello world";
std::string hash = sha1(str);
std::cout << hash << std::endl;
return 0;
}
```
在这个示例中,我们使用了OpenSSL库中的SHA-1哈希函数。我们首先定义一个长度为20的unsigned char数组来存储哈希值,然后使用SHA_CTX结构体来初始化SHA-1上下文。接下来,我们使用SHA1_Update函数将要哈希的字符串添加到上下文中,并使用SHA1_Final函数将哈希值存储到hash数组中。最后,我们使用std::stringstream将哈希值转换为十六进制字符串并返回。