单向散列算法运算速度实测

测试环境:CentOS 6.4 X86_64位 VMWare虚拟机 1G RAM  (物理主机CPU i7-3770 3.4GHz)

测试代码(使用openssl的hash库):

#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include <ctime>
#include <stdio.h>
using namespace std;

#include <openssl/sha.h>
#include <openssl/md5.h>

string md5(const string str)
{
    unsigned char hash[MD5_DIGEST_LENGTH];
    MD5_CTX md5;
    MD5_Init(&md5);
    MD5_Update(&md5, str.c_str(), str.size());
    MD5_Final(hash, &md5);
    stringstream ss;

    for(int i = 0; i < MD5_DIGEST_LENGTH; i++) 
    {
        ss << hex << setw(2) << setfill('0') << (int)hash[i];
    }
    return ss.str();
}

string 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);
    stringstream ss;

    for(int i = 0; i < SHA256_DIGEST_LENGTH; i++) //32
    {
        ss << hex << setw(2) << setfill('0') << (int)hash[i];
    }
    return ss.str();
}

string sha512(const string str)
{
    unsigned char hash[SHA512_DIGEST_LENGTH];
    SHA512_CTX sha512;
    SHA512_Init(&sha512);
    SHA512_Update(&sha512, str.c_str(), str.size());
    SHA512_Final(hash, &sha512);
    stringstream ss;
    for(int i = 0; i < SHA512_DIGEST_LENGTH; i++) //64
    {
        ss << hex << setw(2) << setfill('0') << (int)hash[i];
    }
    return ss.str();
}

int main()
{
    //MD5
    time_t t1=time(0);
    cout << "MD5:" << endl;
    cout << t1 << endl;
    for(int i=0;i<10000000;i++)
    {
        char pwd[32];
        sprintf(pwd, "%d", i);
        md5(pwd);
    }
    time_t t2=time(0);
    cout << t2 << endl;
    cout << t2-t1 <<endl;

    //SHA256
    t1=time(0);
    cout << "SHA256:" << endl;
    cout << t1 << endl;
    for(int i=0;i<10000000;i++)
    {
        char pwd[32];
        sprintf(pwd, "%d", i);
        sha256(pwd);
    }
    t2=time(0);
    cout << t2 << endl;
    cout << t2-t1 <<endl;

    //SHA512
    t1=time(0);
    cout << "SHA512:" << endl;
    cout << t1 << endl;
    for(int i=0;i<10000000;i++)
    {
        char pwd[32];
        sprintf(pwd, "%d", i);
        sha512(pwd);
    }
    t2=time(0);
    cout << t2 << endl;
    cout << t2-t1 <<endl;

    return 0;
}

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

运行:  ./sha

结果:

MD5:
1409193206
1409193228
22
SHA256:
1409193228
1409193263
35
SHA512:
1409193263
1409193318
55

分别执行了1000万次HASH运算, MD5用了22秒, SHA256用了35秒,SHA512用了55秒。

运算时间基本处于同一量级,使用SHA256或SHA512代替MD5是非常必要的。

因环境差异对结果影响较大,数据仅供备忘和参考。

原文地址:https://www.cnblogs.com/-U2-/p/3941189.html