Wednesday, March 7, 2012

C++: Generate SHA-512 hash


The EVP interfaces from OpenSSL library can compute the SHA hash in C/C++ programming. The document in OpenSSL web site gives an example in http://www.openssl.org/docs/crypto/EVP_DigestInit.html. So does the MAN page of the function EVP_DigestInit().

It is not a single function call that can do the job. The serial EVP functions involved are:

 const EVP_MD *md = EVP_get_digestbyname("sha512");
 EVP_MD_CTX_init(&mdctx);
 EVP_DigestInit_ex(&mdctx, md, NULL);
 EVP_DigestUpdate(&mdctx, mess1, strlen(mess1));
 EVP_DigestUpdate(&mdctx, mess2, strlen(mess2));
 EVP_DigestFinal_ex(&mdctx, md_value, &md_len);
 EVP_MD_CTX_cleanup(&mdctx);

In the document, EVP_MAX_MD_SIZE is defined as 36. Actually it is 64 in the real OpenSSL library. Perhaps the upgrade it because the result of SHA-512 is 64 bytes (512 bits).

To verify the output of your implementation, you can use the openssl command line:

 echo -n "string to be hashed" | openssl dgst -sha512

The -n option of the echo command is important. Without it, the trailing newline of the echo command will cause a different result.

No comments:

 
Get This <