c++ openssl sha 使用样例

link_libraries(ssl) link_libraries(crypto)

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <openssl/sha.h>

using namespace std;

string sha1(const string str)
{
    SHA_CTX ctx;
    unsigned char result[20];
    char result_str[40];
    SHA1_Init(&ctx);
    SHA1_Update(&ctx, str.c_str(), str.size());
    SHA1_Final(result, &ctx);

    for(int i=0;i!=20;i++)
    {
        sprintf(result_str+i*2, "%02x", result[i]);
    }
    return string(result_str);
}

string sha256(const string str)
{
    char buf[2];
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, str.c_str(), str.size());
    SHA256_Final(hash, &sha256);
    std::string NewString = "";
    for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
    {
        sprintf(buf,"%02x",hash[i]);
        NewString = NewString + buf;
    }
    return NewString;
}

string sha512(const string str)
{
    char buf[2];
    unsigned char hash[SHA512_DIGEST_LENGTH];
    SHA512_CTX sha512;
    SHA512_Init(&sha512);
    SHA512_Update(&sha512, str.c_str(), str.size());
    SHA512_Final(hash, &sha512);
    std::string NewString = "";
    for(int i = 0; i < SHA512_DIGEST_LENGTH; i++)
    {
        sprintf(buf,"%02x",hash[i]);
        NewString = NewString + buf;
    }
    return NewString;
}

int main() {
    string x="asicx9hd1038hdnsiadh90183ndbsajk ska dajkon 130";
    cout<<sha1(x)<<endl;
    cout << sha256(x) << endl;
    cout<<sha512(x)<<endl;
    return 0;
}
文章目录