python - 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
请帮我
谢谢你
解决方案
结论
使用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'
推荐阅读
- c# - 与 IEquatable 不同的 LINQ 不返回不同的结果
- powerapps - 如何根据 Powerapps 中选定的下拉项导航到特定屏幕?
- xml - 如果长度大于 15,xslt 使用最后 15 个字符
- javascript - 我如何制作一个函数来检查动画是否通过了某个点
- neo4j - 查找与其他唯一节点的连接最多的节点
- python - 在python中使用背景减法进行质心跟踪
- sql - 两个斜杠之间的 T-SQL 子字符串以提取数据
- latex - 如何在 LaTex 中的枚举之间左对齐文本?
- ruby-on-rails - Rails 控制台未加载环境
- jquery - Jquery 上的“(intermediate.value).apply 不是函数”