将AES类从python2.7移植到3.x+

2024-06-01 05:46:12 发布

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

您好,如果您能帮助我们将这个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编码,这会导致新的错误。你知道吗

第一个错误

Traceback (most recent call last):
  File "AESHandler.py", line 36, in <module>
    aesHandler = AESHandler("SUPER_SECRET_KEY")
  File "AESHandler.py", line 10, in __init__
    hashedKey = hashlib.sha1(); hashedKey.update(cipherKey)
TypeError: Unicode-objects must be encoded before hashing

此时,我将UTF-8编码添加到明文字符串和密码密钥中,以解决导致下一个错误的问题。你知道吗

第二个错误

Traceback (most recent call last):
  File "AESHandler.py", line 38, in <module>
    encodedString = aesHandler.aes_encrypt(dataIn)
  File "AESHandler.py", line 20, in aes_encrypt
    stringIn = self.pad(self, stringIn)
  File "AESHandler.py", line 11, in <lambda>
    self.pad = lambda self, s: s + (self.blockSize - len(s) % self.blockSize) * "\x00"
TypeError: can't concat str to bytes

要修复此错误,我更改了:

self.pad = lambda self, s: s + (self.blockSize - len(s) % self.blockSize) * "\x00"

更改为:

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)

Tags: lambdainpyselflinefileencryptaes
2条回答

这应该能奏效。本质上,我强迫所有的内部成员在需要时处理bytes。你知道吗

#!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()不使用bytes

现在修复了,仍然有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)

相关问题 更多 >