Python LookupError:';十六进制';不是文本编码;使用codecs.encode()处理任意编解码器

Python LookupError:';十六进制';不是文本编码;使用codecs.encode()处理任意编解码器,python,hex,aes,Python,Hex,Aes,我正在使用Python3为AES编写一些代码,我想将字符串转换为十六进制 我的代码 PlaintextString = "secret message!" CipherKeyString = "password is here" PlaintextArray = [] CipherKeyArray = [] while len(PlaintextArray) < IOBlockSize: Plaintex

我正在使用Python3为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
PlaintextString=“秘密消息!”
CipherKeyString=“密码在这里”
PlaintextArray=[]
CipherKeyArray=[]
而len(PlaintextArray)
但我犯了这个错误

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

请帮帮我

谢谢你

结论 使用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'
您必须使用其中一种编码。显然,
hex
不是其中之一。