5

(Note: I'm using http://www.royalforkblog.com/2014/08/11/graphical-address-generator/ (use "bitcoin" as the phrase for generating the private key)

I'm trying to take the first step in going from a publickey to an address.

For example, if this is my public key:

publickey = 02218AD6CDC632E7AE7D04472374311CEBBBBF0AB540D2D08C3400BB844C654231

This should be the result of the next step:

ripemd160(sha256(publickey)) = 5238C71458E464D9FF90299ABCA4A1D7B9CB76AB

However, when I try to do this in python, I fail to get the same result:

>>> hashlib.new('sha256', '02218AD6CDC632E7AE7D04472374311CEBBBBF0AB540D2D08C3400BB844C654231').hexdigest()
'6e28eefe40e5855ed8cdf0599ec12e52f73a5b222c84ba957b4dcdd2d8a9cf2a'

>>> hashlib.new('ripemd160', '6e28eefe40e5855ed8cdf0599ec12e52f73a5b222c84ba957b4dcdd2d8a9cf2a').hexdigest()
'e607ff4fa71ef33ca357415e3d2f781c4cedacc3'

Where am I going wrong when using sha256 and ripemd160 in my python code?

2

3 Answers 3

6

moshaholo has the right answer, but not quite the right code.

>>> publickey = '02218AD6CDC632E7AE7D04472374311CEBBBBF0AB540D2D08C3400BB844C654231'.decode('hex')
>>> s = hashlib.new('sha256',    publickey).digest()
>>> r = hashlib.new('ripemd160', s        ).digest()
>>> s.encode('hex')
'ea571f53cb3a9865d3dc74735e0c16643d319c6ad81e199b9c8408cecbcec7bb'
>>> r.encode('hex')
'5238c71458e464d9ff90299abca4a1d7b9cb76ab'

Notice that publickey, s, and r are all binary byte strings (because .digest() is being used instead of .hexdigest()). The only reason to convert them to hex-encoded strings is for display purposes. You can display them directly if you like, but it's not pretty....

>>> publickey
'\x02!\x8a\xd6\xcd\xc62\xe7\xae}\x04G#t1\x1c\xeb\xbb\xbf\n\xb5@\xd2\xd0\x8c4\x00\xbb\x84LeB1'
3

In Python3:

#!/usr/bin/env python3

import hashlib
import codecs

publickey = codecs.decode('025914AE6A4B33A9EB1AF17FB818556F5FC849A2B9AAF176C48983BABD75A76432', 'hex')
s = hashlib.new('sha256', publickey).digest()
r = hashlib.new('ripemd160', s).digest()

print(codecs.encode(s, 'hex').decode("utf-8"))
print(codecs.encode(r, 'hex').decode("utf-8"))

Output:

c8bf4c378130fc18fcf732051e95fce4646771639097ea19b59fb5d005bf3998
cb6af4b9e44a21f9767e8989c4413c417a8b8511

A greeting.

0

The hex string should be transaformed to bytes first.
Change the string to

b'02218AD6CDC632E7AE7D04472374311CEBBBBF0AB540D2D08C3400BB844C654231'

Then you should get the expected result~

Here is a relevant post About performing SHA-256 hashing on the public key

1
  • This is for Python 3.x FWIW, Python 2.x doesn't distinguish between byte strings and strings, but the main thing is to be sure the hex chars are run through binascii.unhexlify first Commented Apr 23, 2015 at 5:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.