Reputation: 4951
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?
Upvotes: 5
Views: 11496
Reputation: 49812
To get an integer from the string, you can do:
# Python 3
decoded = int.from_bytes(b64decode(nonce), 'big')
# Python 2
decoded = int(b64decode(nonce).encode('hex'), 16)
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))
0x6b3473022e6b9b5af2fe5d1dae7cf5bf
Upvotes: 5
Reputation: 1104
You can convert like this:
>>> import codecs
>>> decoded = base64.b64decode(nonce)
>>> b_string = codecs.encode(decoded, 'hex')
>>> b_string
b'6b3473022e6b9b5af2fe5d1dae7cf5bf'
Upvotes: 2