Post
Topic
Board Development & Technical Discussion
Merits 2 from 2 users
Re: How to convert a compressed public key into uncompressed one in Python?
by
PowerGlove
on 30/08/2022, 19:23:16 UTC
⭐ Merited by nc50lc (1) ,NotATether (1)
I found the error. If inputting 0x... hex values with str() conversion into the function, it is going to output incorrect values.
Yup, you were accidentally passing '272351126323155009915566305515988222562668831973356296881287277305661165837788' into the function instead of '025A2146590B80D1F0D97CC7104E702011AFFF21BFAF817F5C7002446369BA9DDC'. Smiley

I'm glad it's working now. You can make the script a little shorter by getting rid of the "pow_mod" function and using the built-in "pow" directly, like so (code taken from your PNG):

Code:
def compressedToUncompressed(compressed_key):
    p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f
    y_parity = int(compressed_key[:2]) - 2
    x = int(compressed_key[2:], 16)
    a = (pow(x, 3, p) + 7) % p
    y = pow(a, (p+1)//4, p)
    if y % 2 != y_parity:
        y = -y % p
    uncompressed_key = '04{:x}{:x}'.format(x, y)
    return uncompressed_key

assert compressedToUncompressed('025A2146590B80D1F0D97CC7104E702011AFFF21BFAF817F5C7002446369BA9DDC') == '045a2146590b80d1f0d97cc7104e702011afff21bfaf817f5c7002446369ba9ddc9bd5dcd1b4a737244d6bb7b96e256391b8597d3a7972a6f8ca9096d4aea1f37e'
assert compressedToUncompressed('035728F4692D85D411DF3643CD69FE05C411A0D507C7D814008F56C8F260AD7ED9') == '045728f4692d85d411df3643cd69fe05c411a0d507c7d814008f56c8f260ad7ed99e2df8d9cb1a575d55264692629ae22e518bc14ad02592941c13be6755c72973'
assert compressedToUncompressed('039E87EB177890FDD788B95843ED53AD4FB6E877E3F730EF1E73593964C2AB9D15') == '049e87eb177890fdd788b95843ed53ad4fb6e877e3f730ef1e73593964c2ab9d15a3b647c8c4a0766420917b7b445cdcd6bfec2900175c5534c6113954f3ff00d9'