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

2024-09-28 05:17:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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

但我犯了这个错误

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

请帮帮我

多谢各位


Tags: 代码inforlenisrangelistencode
1条回答
网友
1楼 · 发布于 2024-09-28 05:17:59

结论

使用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'

相关问题 更多 >

    热门问题