简体   繁体   English

将base64编码的字符串转换为十六进制int

[英]Convert base64-encoded string into hex int

I have a base64-encoded nonce as a 24-character string: 我有一个以base64编码的随机数作为24个字符的字符串:

nonce = "azRzAi5rm1ry/l0drnz1vw=="

And I want a 16-byte int: 我想要一个16字节的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? 如何从base64字符串中获取整数?

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

You can convert like this: 您可以这样转换:

>>> import codecs
>>> decoded = base64.b64decode(nonce)
>>> b_string = codecs.encode(decoded, 'hex')
>>> b_string
b'6b3473022e6b9b5af2fe5d1dae7cf5bf'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将字节字符串转换为 base64 编码的字符串(输出不是字节字符串) - Convert byte string to base64-encoded string (output not being a byte string) 如何将 Base64DataURL 转换为 base64 编码的图像字节 - How to convert Base64DataURL to base64-encoded image bytes 将 Base64 编码字节转换为 Int - Convert Base64 encoded bytes to Int 尝试将 BufferedReader 上传到 Python 中的 Azure Blob 存储时,base64 编码的字符串无效 - Invalid base64-encoded string when trying to upload BufferedReader to Azure Blob Storage in Python 无效的 base64 编码字符串:数据字符数不能是 4 的倍数以上 1 - Invalid base64-encoded string: number of data characters cannot be 1 more than a multiple of 4 python:无效的base64编码字符串:数据字符数(5)不能比4的倍数多1 - python: Invalid base64-encoded string: number of data characters (5) cannot be 1 more than a multiple of 4 将base64编码的字符串转换为二进制 - Convert a base64 encoded string to binary 将 HEX 字符串转换为 Python 中的 base64 - Convert HEX string into base64 in Python 如何反序列化base64编码的数据并将其与DRF一起使用 - How to deserialize base64-encoded data and use it with DRF 在ReportLab生成的PDF中包含base64编码的图像 - Including base64-encoded image in ReportLab-generated PDF
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM