将AES类从Python 2.7移植到3.x+;

将AES类从Python 2.7移植到3.x+;,python,python-3.x,aes,python-3.6,Python,Python 3.x,Aes,Python 3.6,您好,如果您能帮助将这个AES类从Python2.7移植到3.6+,我们将不胜感激 我在下面的Python2.7中有一个工作副本,我已经很好地实现了它 import hashlib from Crypto import Random from Crypto.Cipher import AES class AESHandler: def __init__(self, cipherKey): hashedKey = hashlib.sha1(); hashedKey.up

您好,如果您能帮助将这个AES类从Python2.7移植到3.6+,我们将不胜感激

我在下面的Python2.7中有一个工作副本,我已经很好地实现了它

import hashlib
from Crypto import Random
from Crypto.Cipher import AES


class AESHandler:
    def __init__(self, cipherKey):
        hashedKey = hashlib.sha1(); hashedKey.update(cipherKey)
        self.pad = lambda self, s: s + (self.blockSize - len(s) % self.blockSize) * "\x00"
        self.unPad = lambda self, s : s.rstrip('\x00')
        self.toHex = lambda self, x:"".join([hex(ord(c))[2:].zfill(2) for c in x])
        self.blockSize = 16
        self.cipherKey = hashedKey.hexdigest()[:32]



    def aes_encrypt(self, stringIn):
        stringIn = self.pad(self, stringIn)
        initVector = Random.new().read(AES.block_size)
        cipher = AES.new(self.cipherKey, AES.MODE_CBC, initVector)
        return self.toHex(self, initVector + cipher.encrypt(stringIn))



    def aes_decrypt(self, stringIn):
        stringIn = (stringIn).decode("hex_codec")
        initVector = stringIn[:16]
        cipher = AES.new(self.cipherKey, AES.MODE_CBC, initVector)
        return self.unPad(self, cipher.decrypt(stringIn[16:]))



dataIn  = "Hello World!"
aesHandler = AESHandler("SUPER_SECRET_KEY")

encodedString = aesHandler.aes_encrypt(dataIn)
print("EncodedString: " + encodedString)

decodedString = aesHandler.aes_decrypt(encodedString)
print("DecodedString: " + decodedString)
在Python3.6中尝试运行该类时,怀疑的第一个问题是编码错误。所以我对纯文本字符串和密码密钥应用了UTF-8编码,这会导致新的错误

第一错误 改为:

self.pad = lambda self, s: s + ((self.blockSize - len(s) % self.blockSize) * "\x00").encode("UTF-8")
第三个错误
这应该能奏效。本质上,我强迫所有内部成员在需要时处理
字节

#!pip install pycrypto
import hashlib
import codecs
from Crypto import Random
from Crypto.Cipher import AES


class AESHandler:
    def __init__(self, cipherKey):
        hashedKey = hashlib.sha1(); hashedKey.update(cipherKey.encode())
        self.pad = lambda self, s: s + (self.blockSize - len(s) % self.blockSize) * b'\x00'
        self.unPad = lambda self, s : s.rstrip(b'\x00')
        self.toHex = lambda self, x: b"".join([hex(c)[2:].zfill(2).encode() for c in x])
        self.blockSize = 16
        self.cipherKey = hashedKey.hexdigest()[:32]

    def aes_encrypt(self, stringIn):
        stringIn = self.pad(self, stringIn.encode())
        initVector = Random.new().read(AES.block_size)
        cipher = AES.new(self.cipherKey, AES.MODE_CBC, initVector)
        return self.toHex(self, initVector + cipher.encrypt(stringIn))

    def aes_decrypt(self, stringIn):
        stringIn = codecs.decode(stringIn, "hex_codec")
        initVector = stringIn[:16]
        cipher = AES.new(self.cipherKey, AES.MODE_CBC, initVector)
        return self.unPad(self, cipher.decrypt(stringIn[16:])).decode()


dataIn  = "Hello World! α and ω"
aesHandler = AESHandler("SUPER_SECRET_KEY")

encodedString = aesHandler.aes_encrypt(dataIn)
print("EncodedString:", encodedString)
# EncodedString: b'e8b7621f04310fbb40bb40a22ccc4a62e67fa5124fee5bac858288615028b2519f30516bc84b9a4625c944b4a22f0599'

decodedString = aesHandler.aes_decrypt(encodedString)
print("DecodedString:", decodedString)
# DecodedString: Hello World! α and ω

编辑以修复
toHex()
不使用
字节

现在已修复,仍有2个字符串需要编码。非常感谢下面的帮助,我发布了最后的工作副本

import hashlib
import codecs
from Crypto import Random
from Crypto.Cipher import AES


class AESHandler:
    def __init__(self, cipherKey):
        hashedKey = hashlib.sha1(); hashedKey.update(cipherKey.encode())
        self.pad = lambda self, s: s + (self.blockSize - len(s) % self.blockSize) * b'\x00'
        self.unPad = lambda self, s : s.rstrip(b'\x00')
        self.toHex = lambda self, x: b"".join([hex(c)[2:].zfill(2).encode() for c in x])
        self.blockSize = 16
        self.cipherKey = hashedKey.hexdigest()[:32]

    def aes_encrypt(self, stringIn):
        stringIn = self.pad(self, stringIn.encode())
        initVector = Random.new().read(AES.block_size)
        cipher = AES.new(self.cipherKey.encode(), AES.MODE_CBC, initVector)
        return self.toHex(self, initVector + cipher.encrypt(stringIn))

    def aes_decrypt(self, stringIn):
        stringIn = codecs.decode(stringIn, "hex_codec")
        initVector = stringIn[:16]
        cipher = AES.new(self.cipherKey.encode(), AES.MODE_CBC, initVector)
        return self.unPad(self, cipher.decrypt(stringIn[16:])).decode()


dataIn  = "Hello World!"
aesHandler = AESHandler("SUPER_SECRET_KEY")

encodedString = aesHandler.aes_encrypt(dataIn)
print("EncodedString:", encodedString)

decodedString = aesHandler.aes_decrypt(encodedString)
print("DecodedString:", decodedString)

实际上,在您迁移到Python3时,您将所有Py2字符串移植到Py3字符串。但是,Py3字符串本质上是Py2 unicode。Py2字符串更接近于
bytes()
。Henve,我认为您应该将字符串设置为
字节
。看起来您试图在不理解
字节
对象的情况下移植到python3。你将无法这样做。另外,填充方法不是很健壮,因为它只能处理纯文本的子集。此外,还可以使用
lambda
定义一系列方法。我不太确定我是否明白为什么不使用经典的
def
构造。谢谢我尝试了您的更改,但仍然得到相同的第三个错误:raise TypeError(“对象类型%s无法传递给C代码”%type(data))。谢谢我尝试了,但它仍然抛出相同的错误,但今天早上喝了一些咖啡,我使它工作了,将工作副本张贴在下面。再次感谢你的帮助。
self.pad = lambda self, s: s + ((self.blockSize - len(s) % self.blockSize) * "\x00").encode("UTF-8")
Traceback (most recent call last):
  File "AESHandler.py", line 38, in <module>
    encodedString = aesHandler.aes_encrypt(dataIn)
  File "AESHandler.py", line 22, in aes_encrypt
    cipher = AES.new(self.cipherKey, AES.MODE_CBC, initVector)
  File "/usr/local/lib/python3.6/dist-packages/Crypto/Cipher/AES.py", line 232, in new
    return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/Crypto/Cipher/__init__.py", line 79, in _create_cipher
    return modes[mode](factory, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/Crypto/Cipher/_mode_cbc.py", line 274, in _create_cbc_cipher
    cipher_state = factory._create_base_cipher(kwargs)
  File "/usr/local/lib/python3.6/dist-packages/Crypto/Cipher/AES.py", line 103, in _create_base_cipher
    result = start_operation(c_uint8_ptr(key),
  File "/usr/local/lib/python3.6/dist-packages/Crypto/Util/_raw_api.py", line 145, in c_uint8_ptr
    raise TypeError("Object type %s cannot be passed to C code" % type(data))
TypeError: Object type <class 'str'> cannot be passed to C code
import hashlib
from Crypto import Random
from Crypto.Cipher import AES


class AESHandler:
    def __init__(self, cipherKey):
        hashedKey = hashlib.sha1(); hashedKey.update(cipherKey)
        self.pad = lambda self, s: s + (self.blockSize - len(s) % self.blockSize) * "\x00"
        self.unPad = lambda self, s : s.rstrip('\x00')
        self.toHex = lambda self, x:"".join([hex(ord(c))[2:].zfill(2) for c in x])
        self.blockSize = 16
        self.cipherKey = hashedKey.hexdigest()[:32]



    def aes_encrypt(self, stringIn):
        stringIn = self.pad(self, stringIn)
        initVector = Random.new().read(AES.block_size)
        cipher = AES.new(self.cipherKey, AES.MODE_CBC, initVector)
        return self.toHex(self, initVector + cipher.encrypt(stringIn))



    def aes_decrypt(self, stringIn):
        stringIn = (stringIn).decode("hex_codec")
        initVector = stringIn[:16]
        cipher = AES.new(self.cipherKey, AES.MODE_CBC, initVector)
        return self.unPad(self, cipher.decrypt(stringIn[16:]))



dataIn  = "Hello World!"
aesHandler = AESHandler("SUPER_SECRET_KEY")

encodedString = aesHandler.aes_encrypt(dataIn)
print("EncodedString: " + encodedString)

decodedString = aesHandler.aes_decrypt(encodedString)
print("DecodedString: " + decodedString)
#!pip install pycrypto
import hashlib
import codecs
from Crypto import Random
from Crypto.Cipher import AES


class AESHandler:
    def __init__(self, cipherKey):
        hashedKey = hashlib.sha1(); hashedKey.update(cipherKey.encode())
        self.pad = lambda self, s: s + (self.blockSize - len(s) % self.blockSize) * b'\x00'
        self.unPad = lambda self, s : s.rstrip(b'\x00')
        self.toHex = lambda self, x: b"".join([hex(c)[2:].zfill(2).encode() for c in x])
        self.blockSize = 16
        self.cipherKey = hashedKey.hexdigest()[:32]

    def aes_encrypt(self, stringIn):
        stringIn = self.pad(self, stringIn.encode())
        initVector = Random.new().read(AES.block_size)
        cipher = AES.new(self.cipherKey, AES.MODE_CBC, initVector)
        return self.toHex(self, initVector + cipher.encrypt(stringIn))

    def aes_decrypt(self, stringIn):
        stringIn = codecs.decode(stringIn, "hex_codec")
        initVector = stringIn[:16]
        cipher = AES.new(self.cipherKey, AES.MODE_CBC, initVector)
        return self.unPad(self, cipher.decrypt(stringIn[16:])).decode()


dataIn  = "Hello World! α and ω"
aesHandler = AESHandler("SUPER_SECRET_KEY")

encodedString = aesHandler.aes_encrypt(dataIn)
print("EncodedString:", encodedString)
# EncodedString: b'e8b7621f04310fbb40bb40a22ccc4a62e67fa5124fee5bac858288615028b2519f30516bc84b9a4625c944b4a22f0599'

decodedString = aesHandler.aes_decrypt(encodedString)
print("DecodedString:", decodedString)
# DecodedString: Hello World! α and ω
import hashlib
import codecs
from Crypto import Random
from Crypto.Cipher import AES


class AESHandler:
    def __init__(self, cipherKey):
        hashedKey = hashlib.sha1(); hashedKey.update(cipherKey.encode())
        self.pad = lambda self, s: s + (self.blockSize - len(s) % self.blockSize) * b'\x00'
        self.unPad = lambda self, s : s.rstrip(b'\x00')
        self.toHex = lambda self, x: b"".join([hex(c)[2:].zfill(2).encode() for c in x])
        self.blockSize = 16
        self.cipherKey = hashedKey.hexdigest()[:32]

    def aes_encrypt(self, stringIn):
        stringIn = self.pad(self, stringIn.encode())
        initVector = Random.new().read(AES.block_size)
        cipher = AES.new(self.cipherKey.encode(), AES.MODE_CBC, initVector)
        return self.toHex(self, initVector + cipher.encrypt(stringIn))

    def aes_decrypt(self, stringIn):
        stringIn = codecs.decode(stringIn, "hex_codec")
        initVector = stringIn[:16]
        cipher = AES.new(self.cipherKey.encode(), AES.MODE_CBC, initVector)
        return self.unPad(self, cipher.decrypt(stringIn[16:])).decode()


dataIn  = "Hello World!"
aesHandler = AESHandler("SUPER_SECRET_KEY")

encodedString = aesHandler.aes_encrypt(dataIn)
print("EncodedString:", encodedString)

decodedString = aesHandler.aes_decrypt(encodedString)
print("DecodedString:", decodedString)