EDIT: After taking adivce I have rearranged the parameters & types. But the application crashes when I call the digest() function now? Any ideas whats going wrong?
const std::string message = "to be encrypted";
unsigned char* hashMessage;
SHA256::getInstance()->digest( message, hashMessage ); // crash occurs here, what am I doing wrong?
printf("AFTER: n"); //, hashMessage); // line never reached
I am using an open source implementation of the SHA256 algorithm in C++. My problem is understanding how to pass a unsigned char* version of my string so it can be hashed?
This is the function that takes a unsigned char* version of my string:
void SHA256::digest(const std::string &buf, unsigned char *dig) {
init();
update(reinterpret_cast<const unsigned char *>(buf.c_str()), static_cast<unsigned int>(buf.length()));
final();
digest(dig);
}
How can I convert my string(which I want hashed) to an unsigned char*?
The following code I have made causes a runtime error when I go to print out the string contents:
const std::string hashOutput;
char message[] = "to be encrypted";
printf("BEFORE: %s bb\n", hashOutput.c_str());
SHA256::getInstance()->digest( hashOutput, reinterpret_cast<unsigned char *>(message) );
printf("AFTER: %s\n", hashOutput.c_str()); // CRASH occurs here
PS: I have been looking at many implementations of SHA256 & they all take an unsigned char* as the message to be hashed. Why do they do that? Why not a char* or a string instead?
The reason that
unsigned charis used is that it has guaranteed behaviours under bitwise operations, shifts, and overflow.char, (when it corresponds tosigned char) does not give any of these guarantees, and so is far less useable for operations intended to act directly on the underlying bits in a string.The answer to the question: “why does it crash?” is “you got lucky!”. Your code has undefined behaviour. In short, you are writing through a pointer
hashMessagethat has never been initialised to point to any memory. A short investigation of the source code for the library that you are using reveals that it requires thedigestpointer to point to a block of valid memory that is at leastSHA256_DIGEST_SIZEchars long.To fix this problem, all that you need to do is to make sure that the pointer that you pass in as the
digestargument (hashMessage) is properly initialised, and points to a block of memory of sufficient size. In code: