(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()

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

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


3 Answers 3


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')
>>> r.encode('hex')

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

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"))



A greeting.


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


Then you should get the expected result~

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

  • 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 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.