Thread: Sha256

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2015
    Posts
    38
    Rep Power
    2

    Sha256


    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.

    Code:
    string sha256(string input)
    {
        unsigned char digest[SHA256::DIGEST_SIZE];
        memset(digest,0,SHA256::DIGEST_SIZE);
     
        SHA256 ctx = SHA256();
        ctx.init();
        ctx.update( (unsigned char*)input.c_str(), input.length());
        ctx.final(digest);
     
        char buf[2*SHA256::DIGEST_SIZE+1];
        buf[2*SHA256::DIGEST_SIZE] = 0;
        for (int i = 0; i < SHA256::DIGEST_SIZE; i++)
    		sprintf_s(buf + i * 2, 2, "%02x", digest[i]);
        return string(buf);
    }
    
    int main(){
    	cout << sha256("Test");
    	return 0;
    }
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2015
    Posts
    38
    Rep Power
    2
    This seems to work, but would like a second opinion:

    Code:
    sprintf_s(buf + i * 2, sizeof(buf) - (i * 2), "%02x", digest[i]);
  4. #3
  5. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Posts
    5,735
    Rep Power
    507
    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]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo