python3.x 16进制字符串转字节字符串、base64、base32加解密

版权声明:喜欢就点个赞吧,有啥疑问可以留言交流~ https://blog.csdn.net/m0_38015368/article/details/89217472

问题

将一个十六进制字符串解码成一个字节字符串或者将一个字节字符串编码成一个十六进制字符串。

解决方案

有两种方法:

  • 使用 binascii 模块
  • 使用 base64 模块

使用 binascii 模块

import binascii
string = b'hello'
# Encode as hex
string_hex = binascii.b2a_hex(string)
# Decode back to bytes
string_row = binascii.a2b_hex(string_hex)

print(string_hex)
print(string_row)

使用 base64 模块

binascii 模块不用,base64 模块中由16进制字符串转字节字符串时16进制字符串中必须为大写,因此转字节字符串时需要配合upper()使用。

import base64

string = b'hello'
# Encode as hex
# base16 就是16进制
string_hex = base64.b16encode(string)
# Decode back to bytes
string_row = base64.b16decode(string_hex)

print(string_hex)
print(string_row)
# 当获取的16进制字符串不确定大小时配合 lower 函数使用
string_row =  base64.b16decode(string_hex.upper())

base64 模块中 base64 / base32 加密、解密

import base64

string = b'zzz'
string_32encode = base64.b32encode(string) 
string_32decode = base64.b32decode(string_32encode)

string_64encode = base64.b64encode(string) 
string_64decode = base64.b64decode(string_64encode)

print(string_32encode)
print(string_32decode)
print(string_64encode)
print(string_64decode)

参考:编码和解码十六进制数

猜你喜欢

转载自blog.csdn.net/m0_38015368/article/details/89217472