Convert base64-encoded string into hex int
Asked Answered
M

2

5

I have a base64-encoded nonce as a 24-character string:

nonce = "azRzAi5rm1ry/l0drnz1vw=="

And I want a 16-byte int:

0x6b3473022e6b9b5af2fe5d1dae7cf5bf

My best attempt:

from base64 import b64decode

b64decode(nonce)

>> b'k4s\x02.k\x9bZ\xf2\xfe]\x1d\xae|\xf5\xbf'

How can I get an integer from the base64 string?

Malformation answered 26/2, 2018 at 5:28 Comment(1)
binascii.hexlify(b64decode(nonce)) or in Python3, b64decode(nonce).hex().Hawsepipe
B
5

To get an integer from the string, you can do:

Code:

# Python 3
decoded = int.from_bytes(b64decode(nonce), 'big')

# Python 2
decoded = int(b64decode(nonce).encode('hex'), 16)

Test Code:

nonce = "azRzAi5rm1ry/l0drnz1vw=="
nonce_hex = 0x6b3473022e6b9b5af2fe5d1dae7cf5bf
from base64 import b64decode

decoded = int.from_bytes(b64decode(nonce), 'big')

# PY 2
# decoded = int(b64decode(nonce).encode('hex'), 16)

assert decoded == nonce_hex
print(hex(decoded))

Results:

0x6b3473022e6b9b5af2fe5d1dae7cf5bf
Beem answered 26/2, 2018 at 5:48 Comment(0)
F
2

You can convert like this:

>>> import codecs
>>> decoded = base64.b64decode(nonce)
>>> b_string = codecs.encode(decoded, 'hex')
>>> b_string
b'6b3473022e6b9b5af2fe5d1dae7cf5bf'
Froemming answered 26/2, 2018 at 5:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.