std::string and sha256 hashing

Hi,

I'm having a bit of a struggle getting a SHA hash routine working with a string input.

The problem seems to lie with the update element(SHA256_Update being openssl's SHA256_Update routine) :
1
2
3
4
typedef unsigned char Byte;
void mynamespace::Sha256::Update(mynamespace::Byte *buffer, int bytesRead) {
    SHA256_Update(&sha256, buffer, bytesRead);
}


When called in the context of reading a file, it works without problem :
1
2
3
 while ((bytes_read = fread(pBuffer, 1, mynamespace::kBufferSize, f))) {
        Update(pBuffer, bytes_read);
    }


But no matter what I try I can't get it to work with string input :
1
2
3
4
5
6
std::string canocJPFinal;
mynamespace::Sha256 sha_calculator;
    sha_calculator.Update(canocJPFinal.c_str(),canocJPFinal.size());
    sha_calculator.Final();
myprog.cpp:74: error: invalid conversion from 'const char*' to 'unsigned char*'
myprog.cpp:74: error:   initializing argument 1 of 'void mynamespace::Sha256::Update(unsigned char*, size_t)'


I've tried all sorts of things to fix it .... casting, copying the string to a byte array, I just can't get it to work ! I'm sure I'm doing something stupid, but I think I've reached the point where I need a second pair of eyes on the problem.

I've even tried to copy the function argumentconcept from openssl's sha.h, but that doesn't help either :
1
2
3
void mynamespace::Sha256::Update(unsigned void* buffer, std::size_t bytesRead) {
    SHA256_Update(&sha256, buffer, bytesRead);
}
Last edited on
.c_str() and .data() return const char*. You need a char*. You can use & on the first element in the string to get that.
sha_calculator.Update(&canocJPFinal[0],canocJPFinal.size());
I'd use this:
sha_calculator.Update(reinterpret_cast<unsigned char *>(canocJPFinal.data()), canocJPFinal.size());
Ah, yes you'll have to cast the pointer because it's unsigned char, not char.
Hi Peter87 and modoran,

modoran, re: your answer, the compiler gives :
error: reinterpret_cast from type 'const char*' to type 'unsigned char*' casts away constness.

Am going to try adding a < const_cast> and will feedback. Will also try peter's idea.
Same errorr with this:

sha_calculator.Update(const_cast<unsigned char*>(reinterpret_cast<unsigned char *>(canocJPFinal.data())),canocJPFinal.size());

Peter's gives :

1
2
 error: invalid conversion from 'char*' to 'unsigned char*'
 error:   initializing argument 1 of 'void mynamespace::Sha256::Update(unsigned char*, size_t)'
sha_calculator.Update(reinterpret_cast<unsigned char*>(&canocJPFinal[0]), canocJPFinal.size());
I think you need to deal with the const-ness first, then cast the data type

sha_calculator.Update(reinterpret_cast<unsigned char*>(const_cast<char*>(canocJPFinal.data())),canocJPFinal.size());
Last edited on
That did the trick.. Thanks Texan40.
Topic archived. No new replies allowed.