十六进制编解码器是否已从python 3.3中排除?当我写代码的时候
>>> s="Hallo"
>>> s.encode('hex')
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
s.encode('hex')
LookupError: unknown encoding: hex那是什么意思?我知道binascii.hexlify(),但是.encode()方法还是不错的!有什么建议吗?
发布于 2012-11-18 14:03:05
不,使用encode()进行十六进制化并不好。
使用hex编解码器的方式在Python2中有效,因为您可以在Python2中对8位字符串调用encode(),即您可以对已经编码的内容进行编码。那也太没道理了。encode()用于将Unicode字符串编码为8位字符串,而不是将8位字符串编码为8位字符串。
在Python3中,您不能再对8位字符串调用encode(),因此hex编解码器变得毫无意义,并被删除。
尽管理论上您可以有一个hex编解码器,并像这样使用它:
>>> import codecs
>>> hexlify = codecs.getencoder('hex')
>>> hexlify(b'Blaah')[0]
b'426c616168'使用binascii更简单、更好:
>>> import binascii
>>> binascii.hexlify(b'Blaah')
b'426c616168'发布于 2018-02-20 20:13:14
上面的答案是相同的,但我对其进行了修改,使其适用于python3。
import binascii
from Crypto.Cipher import AES
from Crypto import Random
def encrypt(passwrd, message):
msglist = []
key = bytes(passwrd, "utf-8")
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CFB, iv)
msg = iv + cipher.encrypt(bytes(message, "utf-8"))
msg = binascii.hexlify(msg)
for letter in str(msg):
msglist.append(letter)
msglist.remove("b")
msglist.remove("'")
msglist.remove("'")
for letter in msglist:
print(letter, end="")
print("")
def decrypt(passwrd, message):
msglist = []
key = bytes(passwrd, "utf-8")
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CFB, iv)
msg = cipher.decrypt(binascii.unhexlify(bytes(message, "utf-8")))[len(iv):]
for letter in str(msg):
msglist.append(letter)
msglist.remove("b")
msglist.remove("'")
msglist.remove("'")
for letter in msglist:
print(letter, end="")
print("")https://stackoverflow.com/questions/13435922
复制相似问题