python3 Cipher_AES(封装Crypto.Cipher.AES)解析

前段时间项目组遇到了一个使用 Python 对 Java AES 加解密会留下尾巴的问题。

Java AES 加密后的密文,在用 Python 解密时,会多出一串与ASCII码对应的神秘字符。为了解决这个问题,特地对 Java 的 AES 加密类研究了一番,后发现,造成这种现象的原因是由于填充方式的不同造成的。

之后用 Python 编写了Cipher_AES,完美的解决了对 Java AES PKCS5Padding 加解密留尾巴的问题。

现将Crypto.Cipher.AES 类进行了封装,供正在迷途的 Python 爱好者使用。

'''
Created on 2018年7月7日

@author: ray
'''

import base64
import binascii
import Crypto.Cipher.AES
import Crypto.Random


pad_default = lambda x, y : x + (y - len(x) % y) * " ".encode("utf-8")
unpad_default = lambda x : x.rstrip()

pad_user_defined = lambda x, y, z : x + (y - len(x) % y) * z.encode("utf-8")
unpad_user_defined = lambda x, z : x.rstrip(z)

pad_pkcs5 = lambda x, y : x + (y - len(x) % y) * chr(y - len(x) % y).encode("utf-8")
unpad_pkcs5 = lambda x : x[:-ord(x[-1])]

class Cipher_AES:
    def __init__(self, key="abcdefgh12345678", iv=Crypto.Random.new().read(Crypto.Cipher.AES.block_size)):
        self.__key = key
        self.__iv = iv
    
    def set_key(self, key):
        self.__key = key
    def get_key(self):
        return self.__key
    
    def set_iv(self, iv):
        self.__iv = iv
    def get_iv(self):
        return self.__iv
    
    def Cipher_MODE_ECB(self):
        self.__x = Crypto.Cipher.AES.new(self.__key.encode("utf-8"), Crypto.Cipher.AES.MODE_ECB)
    def Cipher_MODE_CBC(self):
        self.__x = Crypto.Cipher.AES.new(self.__key.encode("utf-8"), Crypto.Cipher.AES.MODE_CBC, self.__iv.encode("utf-8"))
    
    def encrypt(self, text, cipher_method, code_method="", pad_method=""):
        if cipher_method.upper() == "MODE_ECB":
            self.Cipher_MODE_ECB()
        elif cipher_method.upper() == "MODE_CBC":
            self.Cipher_MODE_CBC()
        cipher_text = b"".join([self.__x.encrypt(i) for i in self.text_verify(text.encode("utf-8"), pad_method)])
        if code_method.lower() == "base64":
            return base64.encodebytes(cipher_text).decode("utf-8").rstrip()
        elif code_method.lower() == "hex":
            return binascii.b2a_hex(cipher_text).decode("utf-8").rstrip()
        else:
            return cipher_text.decode("utf-8").rstrip()
    
    def decrypt(self, cipher_text, cipher_method, code_method="", pad_method=""):
        if cipher_method.upper() == "MODE_ECB":
            self.Cipher_MODE_ECB()
        elif cipher_method.upper() == "MODE_CBC":
            self.Cipher_MODE_CBC()
        if code_method.lower() == "base64":
            cipher_text = base64.decodebytes(cipher_text.encode("utf-8"))
        elif code_method.lower() == "hex":
            cipher_text = binascii.a2b_hex(cipher_text.encode("utf-8"))
        return self.unpad_method(self.__x.decrypt(cipher_text).decode("utf-8"), pad_method)
    
    def text_verify(self, text, method):
        while len(text) > len(self.__key):
            text_slice = text[:len(self.__key)]
            text = text[len(self.__key):]
            yield text_slice
        else:
            if len(text) == len(self.__key):
                yield text
            else:
                yield self.pad_method(text, method)
    
    def pad_method(self, text, method):
        if method == "":
            return pad_default(text, len(self.__key))
        elif method == "PKCS5Padding":
            return pad_pkcs5(text, len(self.__key))
        else:
            return pad_user_defined(text, len(self.__key), method)
    
    def unpad_method(self, text, method):
        if method == "":
            return unpad_default(text)
        elif method == "PKCS5Padding":
            return unpad_pkcs5(text)
        else:
            return unpad_default(text, method)

使用方法:

加密:Cipher_AES(key [, iv]).encrypt(text, cipher_method [, code_method [, pad_method]])

解密:Cipher_AES(key [, iv]).decrypt(cipher_text, cipher_method [, code_method [, pad_method]])

key:密钥(长度必须为16、24、32)

iv:向量(长度与密钥一致,ECB模式不需要)

text:明文(需要加密的内容)

cipher_text:密文(需要解密的内容)

cipher_method:加密方法,目前只有"MODE_ECB"、"MODE_CBC"两种

code_method:编码方式,目前只有"base64"、"hex"两种

pad_method:填充方式,解决 Java 问题选用"PKCS5Padding"

 

来段demo,方便大家理解:

import Cipher_AES

key = "qwedsazxc123321a"
iv = key[::-1]
text = "我爱小姐姐,可小姐姐不爱我 - -"
cipher_method = "MODE_CBC"
code_method = "base64"
pad_method = "PKCS5Padding"
cipher_text = Cipher_AES.Cipher_AES(key, iv).encrypt(text, cipher_method, code_method, pad_method)
print(cipher_text)
text = Cipher_AES.Cipher_AES(key, iv).decrypt(cipher_text, cipher_method, code_method, pad_method)
print(text)

'''
运行结果:
uxhf+MoSko4xa+jGOyzJvYH9n5NvrCwEHbwm/A977CmGqzg+fYE0GeL5/M5v9O1o
我爱小姐姐,可小姐姐不爱我 - -
'''