January 10th, 2016, 07:37 PM
I am trying to recreate the SHA256 function in C++, but have run into an issue. I found the below code on a website that seems to work other than one small portion. Visual Studio threw a notice at me about sprintf being deprecated and to use sprintf_s, so I changed that line to sprintf_s and after I get an error that says "Debug Assertion Failed! Expression: ("Buffer to small", 0)".... any ideas?
Posted a snippet of the code, if the whole thing is necessary let me know. I have a feeling it has to do with the sprintf_s function though.
string sha256(string input)
unsigned char digest[SHA256::DIGEST_SIZE];
SHA256 ctx = SHA256();
ctx.update( (unsigned char*)input.c_str(), input.length());
buf[2*SHA256::DIGEST_SIZE] = 0;
for (int i = 0; i < SHA256::DIGEST_SIZE; i++)
sprintf_s(buf + i * 2, 2, "%02x", digest[i]);
cout << sha256("Test");
January 10th, 2016, 07:55 PM
This seems to work, but would like a second opinion:
sprintf_s(buf + i * 2, sizeof(buf) - (i * 2), "%02x", digest[i]);
January 10th, 2016, 10:53 PM
why isn't your second argument to sprintf_s 3 ?
You're always printing 3 characters, 2 hexes and a NUL.
Shouldn't the digest size be one longer to account for the terminating NUL ?
Since this is C++ is there an unsigned string type that would be more appropriate?
[/code] are essential for python code and Makefiles!