将Base64编码的字符串转换为十六进制整数。

4

我有一个24位字符的base64编码的nonce:

nonce = "azRzAi5rm1ry/l0drnz1vw=="

我需要一个16字节的整型:

0x6b3473022e6b9b5af2fe5d1dae7cf5bf

My best attempt:

from base64 import b64decode

b64decode(nonce)

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

如何从base64字符串中获取整数?


binascii.hexlify(b64decode(nonce)) 或者在Python3中,b64decode(nonce).hex() - John Zwinck
2个回答

5
为了从字符串中获取整数,可以这样做:

代码:

# 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

2
您可以这样进行转换:
>>> import codecs
>>> decoded = base64.b64decode(nonce)
>>> b_string = codecs.encode(decoded, 'hex')
>>> b_string
b'6b3473022e6b9b5af2fe5d1dae7cf5bf'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接