C ++ Sha每次都返回不同的值

时间:2013-07-28 18:04:12

标签: c++

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

using namespace std;

int main()
{
std::stringstream ss;

    std::string data;
    data = "hello worl";
    unsigned char digest[SHA_DIGEST_LENGTH];
    char *string1 = strdup(data.c_str());


    SHA1((unsigned char*)&string1, strlen(string1), (unsigned char*)&digest);    

    char mdString[SHA_DIGEST_LENGTH*2+1];

    for(int i = 0; i < SHA_DIGEST_LENGTH; i++)
         sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);

ss.str("");
ss << mdString;

 cout << ss.str() << std::endl;

    // do stuff with string1
    free(string1);
    return 0;
}

输出:

user1@ubuntu:~/yes/coding$ g++ -o sha sha.cpp -lcrypto
user1@ubuntu:~/yes/coding$ ./sha
1bc8b06c5cd4e774195293ea00c959173d8d3789
user1@ubuntu:~/yes/coding$ ./sha
c8cf70c522fc564aedb5894a24613542702172ca
user1@ubuntu:~/yes/coding$ ./sha
83fbda098c3549ab1347d6cf708ac85092200423
user1@ubuntu:~/yes/coding$ ./sha
ea6ccffd78236e22da412ed90a852329f59f8fd5
user1@ubuntu:~/yes/coding$ ./sha
0413799befebcb23f5a5c970e48febc7f1aa27fb
user1@ubuntu:~/yes/coding$ ./sha
7bd8e7952c78e282b8c117f8c537c456b66207d9

1 个答案:

答案 0 :(得分:4)

SHA1((unsigned char*)&string1, ...)

掉落&符号。您没有散列要哈希的文本;你正在散列四个字节,形成字符串第一个字符的地址,加上六个字节的随机垃圾,位于堆栈上string1之上。