I am trying to build small app to generate Bitcoin Address (for sake of understanding).
I use OpenSSL library.
I managed to convert private key to public key, hashed public key with sha256, and result was fine. But, then, problem appears when I try to run sha256 result trough ripemd160.
- I tested ripemd160 function with plain string and it works fine
- I did converted sha256 result to string
- Still I get wrong result
Here's my main:
int _tmain(int argc, _TCHAR* argv[])
{
char sha256_buffer[65];
char ripemd160_buffer[41];
char *pvt_key = "18E14A7B6A307F426A94F8114701E7C8E774E7F9A47E2C2035DB29A206321725";
unsigned char *pub_hex = priv2pub((const unsigned char *)pvt_key, POINT_CONVERSION_UNCOMPRESSED );
//printf("%s\n", pub_hex);
std::string pub_key_string = hex_to_string(reinterpret_cast<char*>(pub_hex));
sha256(&pub_key_string[0], sha256_buffer);
printf("%s\n", sha256_buffer);
std::string hash256_string = hex_to_string(reinterpret_cast<char*>(sha256_buffer));
ripemd160(&hash256_string[0], ripemd160_buffer);
printf("%s\n", ripemd160_buffer);
return 0;
}
Here's my ripemd160 function:
void ripemd160(char *string, char outputBuffer[41])
{
unsigned char hash[RIPEMD160_DIGEST_LENGTH];
RIPEMD160_CTX ripemd160;
RIPEMD160_Init(&ripemd160);
RIPEMD160_Update(&ripemd160, string, strlen(string));
RIPEMD160_Final(hash, &ripemd160);
for (int i = 0; i < RIPEMD160_DIGEST_LENGTH; i++)
{
sprintf_s(outputBuffer + (i * 2), sizeof(outputBuffer + (i * 2)), "%02x", hash[i]);
}
outputBuffer[40] = 0;
}
Here's my hex to string function:
string hex_to_string(const string& in)
{
string output;
if ((in.length() % 2) != 0) {
throw runtime_error("String is not valid length ...");
}
size_t cnt = in.length() / 2;
for (size_t i = 0; cnt > i; ++i) {
uint32_t s = 0;
stringstream ss;
ss << hex << in.substr(i * 2, 2);
ss >> s;
output.push_back(static_cast<unsigned char>(s));
}
return output;
}
I am using example from
https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses
This is the Ripemd-160 I suppose to get:
010966776006953D5567439E5E39F86A0D273BEE
This is the Ripemd-160 I am actually getting:
6c9814cf2a93131c8d3263158896e786de7a3f21
ripemd160(sha256_buffer, ripemd160_buffer);
printf("%s\n", ripemd160_buffer);
– RogerT May 08 '16 at 09:23