首页 > 解决方案 > LookupError: 'hex' 不是文本编码;使用 codecs.encode() 处理任意编解码器

问题描述

我正在使用 python 3 为 AES 做一些代码,我想将字符串转换为十六进制。

我的代码

   PlaintextString = "secret message!"
   CipherKeyString = "password is here"

  
    PlaintextArray = []
    CipherKeyArray = []

    while len(PlaintextArray) < IOBlockSize: PlaintextArray.append(0)
    while len(CipherKeyArray) < CipherKeySize: CipherKeyArray.append(0)

    for i in range(len(list(PlaintextString))): PlaintextArray[i] = int(list(PlaintextString)[i].encode("hex"), 16)  # 16 stands for HEX
    for i in range(len(list(CipherKeyString))): CipherKeyArray[i] = int(list(CipherKeyString)[i].encode("hex"), 16)  # 16 stands for HEX

但我收到了这个错误

LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs

请帮我

谢谢你

标签: pythonhexaes

解决方案


结论

使用UTF-8作为文本编码,并将字符串转换为字节而不是列表。

PlaintextString = "secret message!"
CipherKeyString = "password is here"

PlaintextArray = PlaintextString.encode('utf8')
CipherKeyArray = CipherKeyString.encode('utf8')

您可以使用下标将任何字节读取为整数。

PlaintextArray # b'secret message!'
PlaintextArray[1] # 101(e)
PlaintextArray[-1] # 31(!)

解释

要将字符串转换为十六进制(二进制),您必须确定字符串的文本编码。例如,通常使用UTF-8作为文本编码将 Unicode 字符转换为二进制。

在 python3 中,用于STRING.encode(ENCODING)将字符串转换为字节。

'some string'.encode('utf8') # b'some string'
'文字列'.encode('utf8') # b'\xe6\x96\x87\xe5\xad\x97\xe5\x88\x97'

前缀b意味着该值是字节而不是字符串

转换为字节后,您可以将任何字节读取为带有下标的整数BYTES[INDEX]。字符串的其他操作(如切片)也可用于字节。

b = 'abc'.encode('utf8') # b'abc'
b[0] # 97(a)
b[1] # 98(b)
b[2] # 99(c)
b[-2] # 98(b)
b[0:2] # b'ab'

推荐阅读