C++调用openssl使用sha256,并取结果前64位作为uint64

参考:unix - Generate sha256 with OpenSSL and C++ - Stack Overflow

代码如下:

#include "openssl/sha.h"
#include <string>
#include <iostream>
using namespace std;
inline uint64_t sha256(const string str) {
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, str.c_str(), str.size());
    SHA256_Final(hash, &sha256);

    uint64_t result = 0;
    for (int i = 0; i != 8; ++i) {
        result |= hash[i] << (56 - i * 8);    // += could have also been used
    }
    return result;
}
int main(void) {
    cout << "start hash test" << endl;
    string test = "test";
    uint64_t result = sha256(test);
    cout << "hash result is:" << result << endl;
    return 0;
}

编译运行:

-> % g++ -o test test.cpp -I/opt/ssl/include/ -L/opt/ssl/lib/ -lcrypto 
-> % ./test
start hash test
hash result is:18446744072095727077
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页