C++ sha256加密(openssl库)

转载声明:本文为转载文章

本文原地址:https://my.oschina.net/bobwei/blog/524147

安全散列算法

安全散列算法(英语:Secure Hash Algorithm)是一种能计算出一个数字消息所对应到的,长度固定的字符串(又称消息摘要)的算法。且若输入的消息不同,它们对应到不同字符串的概率很高;而SHA是FIPS所认证的五种安全散列算法。这些算法之所以称作“安全”是基于以下两点(根据官方标准的描述):

由消息摘要反推原输入消息,从计算理论上来说是很困难的。

想要找到两组不同的消息对应到相同的消息摘要,从计算理论上来说也是很困难的。任何对输入消息的变动,都有很高的概率导致其产生的消息摘要迥异。

SHA家族的五个算法,分别是SHA-1、SHA-224、SHA-256、SHA-384,和SHA-512,由美国国家安全局(NSA)所设计,并由美国国家标准与技术研究院(NIST)发布;是美国的政府标准。后四者有时并称为SHA-2。SHA-1在许多安全协议中广为使用,包括TLS和SSL、PGP、SSH、S/MIME和IPsec,曾被视为是MD5(更早之前被广为使用的散列函数)的后继者。

在这里,我用的是SHA-256加密,代码如下:

sha256.cpp

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>

using namespace std;

#include <openssl/sha.h>
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;
}

int main() {
    string x;
    cout<<"Please enter:";
    getline(cin,x);
    cout << sha256(x) << endl;
    return 0;
}

编译:g++ -lssl -lcrypto -o sha256 sha256.cpp

原文地址:https://www.cnblogs.com/spmt/p/12522383.html