Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

C++ Sha1 issue with using char *

#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());
    // do stuff with string1
    free(string1);

    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;
    return 0;
}

My output always the same..

./sha
da39a3ee5e6b4b0d3255bfef95601890afd80709

Even i change the content of data to "hello panda" or "hello ki" also give me the same output.

Update: I took away the free

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

The sha change everytime, even i did not change the content of data

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
char *string1 = strdup(data.c_str());
// do stuff with string1
free(string1);

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

There's your error.

  • You created string1
  • You used it
  • You freed it
  • You used it again

Don't free what you still need to use.


In addition to that:

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

What you're doing here is passing the address of char* string1 converted to an unsigned char*. What you want to do is pass string1 instead of &string1. The same applies to digest.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...