我试图用C ++哈希系统时间。我使用chrono库以此方式计算了系统时间。
#include<iostream>
#include<chrono>
#include<ctime>
int main()
{
auto timenow = chrono::system_clock::to_time_t(chrono::system_clock::now());
std::cout<<"The time is "<<ctime(&timenow)<<std::endl;
return 0;
}
但是这次我在哈希处理中遇到了问题。使用SHA1哈希算法将这段时间转换为唯一的哈希字符串。
我尝试包括库#include "sha1.h"
和#include<openssl/sha1.h>
。但是这些没有用
(已安装openssl库)。有人可以帮我找出正确的方法吗?
答案 0 :(得分:0)
您可能希望#include <openssl/sha.h>
获得所有可用的安全哈希算法。
这将使您可以使用所有这些功能:
int SHA1_Init(SHA_CTX *c);
int SHA1_Update(SHA_CTX *c, const void *data, size_t len);
int SHA1_Final(unsigned char *md, SHA_CTX *c);
unsigned char *SHA1(const unsigned char *d, size_t n,
unsigned char *md);
在这种情况下,您可以只执行一次以下操作:
unsigned char result[20] = {};
SHA1(const char*)&timenow, sizeof(timenow), result);
或者很长的路要走
#include <iostream>
#include <iomanip>
#include <openssl/sha.h>
#include <time.h>
#include <stdint.h>
int main() {
// time_t can be 32-bit or 64-bit
// so force timenow to be 64-bit, so we'll have consistent
// hash values across different machine architectures
uint64_t timenow = time(nullptr);
unsigned char result[20]={};
// hash it
SHA_CTX ctx = {};
SHA1_Init(&ctx);
SHA1_Update(&ctx, (const char*)&timenow, sizeof(timenow));
SHA1_Final(result, &ctx);
// print the result
std::cout << "Current unix epoch time is " << timenow << std::endl;
for (auto x = 0; x < 20; x++) {
std::cout << std::hex << std::setfill('0') << std::setw(2) << (unsigned int)(result[x]);
}
std::cout << std::endl;
return 0;
};
别忘了链接到加密货币库-lcrypto
示例编译并运行:
$ g++ source.cpp -lcrypto -o demo
$ ./demo
Current unix epoch time is 1601974311
cc227522246af31e4c9bff9d3f78166f62a19695
$ ./demo
Current unix epoch time is 1601974314
15d03343855d674330cbfc5dc435cc3d320e2788
此外,您真正要做什么? time_t时间戳的哈希值本身并不十分有趣或安全。鉴于从1970年1月1日以来只有大约10亿秒,因此可以将其微调。