0

I am trying to perform a SHA256 hash on the message digest of a RIPEMD 160 hash. I am using the OpenSSL library on the Mac platform. The issue I am having is the intermediary process of taking the message digest of the RIPEMD 160 and then performing another SHA256 hash on it. So far I have only been able to perform 1) a SHA256 Hash on a string, 2) a RIPEMD160 hash on a string in isolation. I need to perform a RIPEMD160 hash on a previous SHA256 message digest then perform a second SHA256 hash on the RIPEMD 160 digest......

SHA256 digest-> RIPEMD160 hash function-> RIPEMD160 digest -> 2nd SHA256 Hash function. I hope this makes sense....?

Code for SHA256 Hash function on just a String

string sha256(const string str)
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, str.c_str(), str.size());
SHA256_Final(hash, &sha256);
stringstream ss;

for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
{

    ss << hex << setw(2) << setfill('0') << (int)hash[i];
}
return ss.str();

}

Code for RIPEMD160 Hash on just a String

 int main()
 {

  unsigned char digest[RIPEMD160_DIGEST_LENGTH];

  char string[] = "hello world";

  RIPEMD160((unsigned char*)&string, strlen(string), (unsigned 
  char*)&digest);

  char mdString[RIPEMD160_DIGEST_LENGTH*2+1];

     for(int i = 0; i < RIPEMD160_DIGEST_LENGTH; i++)
     sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);

     printf("RIPEMD160 digest: %s\n", mdString);

  return 0;

}

Anita George
  • 1,145
  • 6
  • 18

1 Answers1

0

Code for SHA256 Hash function on just a String

SHA256 doesn't operate on strings. SHA256 operates on bytes. Unfortunately, in C, they are frequently the same data type.

Once you leave Caesar and Vigenere behind cryptography doesn't work on strings. This is very important to remember.


Assuming that your input data IS a text string, and it IS currently represented in the expected encoding (US-ASCII / ISO-8859-1 / UTF-8) then, after correcting some bad pointers, your code is fine:

unsigned char digest[RIPEMD160_DIGEST_LENGTH];
...
RIPEMD160((unsigned char*)string, strlen(string), (unsigned char*)digest);

Now digest contains your RIPEMD160 digest. We recall that cryptography only operates on bytes, and that digest is bytes, and we get

unsigned char hash[SHA256_DIGEST_LENGTH];

SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, digest, RIPEMD160_DIGEST_LENGTH);
SHA256_Final(hash, &sha256);

Or the accelerator version, like you did with RIPEMD160:

unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256(digest, RIPEMD160_DIGEST_LENGTH, hash);
bartonjs
  • 30,352
  • 2
  • 71
  • 111