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 爱好者使用。

注:python3 安装 Crypto 是 pip3 install pycryptodome

 

程序结构:

|--Cipher_AES.py
|
|--demo_Cipher_AES.py
|

Cipher_AES.py(封装Crypto.Cipher.AES)

'''
Created on 2018年7月7日

@author: ray
'''

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


class Cipher_AES:
    cipher = getattr(Crypto.Cipher, "AES")
    pad = {"default": lambda x, y: x + (y - len(x) % y) * " ".encode("utf-8"),
           "PKCS5Padding": lambda x, y: x + (y - len(x) % y) * chr(y - len(x) % y).encode("utf-8")}
    unpad = {"default": lambda x: x.rstrip(),
             "PKCS5Padding": lambda x: x[:-ord(x[-1])]}
    encode = {"base64": base64.encodebytes,
              "hex": binascii.b2a_hex}
    decode = {"base64": base64.decodebytes,
              "hex": binascii.a2b_hex}

    def __init__(self, key=None, iv=None, cipher_method=None, pad_method="default", code_method=None):
        self.__key = key if key else "abcdefgh12345678"     # 密钥(长度必须为16、24、32)
        self.__iv = iv if iv else Crypto.Random.new().read(Cipher_AES.cipher.block_size)    # 向量(长度与密钥一致,ECB模式不需要)
        self.__cipher_method = cipher_method.upper() if cipher_method and isinstance(cipher_method, str) else "MODE_ECB"   # 加密方式,["MODE_ECB"|"MODE_CBC"|"MODE_CFB"]等
        self.__pad_method = pad_method          # 填充方式,解决 Java 问题选用"PKCS5Padding"
        self.__code_method = code_method        # 编码方式,目前只有"base64"、"hex"两种
        if self.__cipher_method == "MODE_CBC":
            self.__cipher = Cipher_AES.cipher.new(self.__key.encode("utf-8"), Cipher_AES.cipher.MODE_CBC, self.__iv.encode("utf-8"))
        else:
            self.__cipher = Cipher_AES.cipher.new(self.__key.encode("utf-8"), Cipher_AES.cipher.MODE_ECB)

    def __getitem__(self, item):
        def get3value(item):
            return item.start, item.stop, item.step
        type_, method, _ = get3value(item)
        dict_ = getattr(Cipher_AES, type_)
        return dict_[method] if method in dict_ else dict_["default"]

    def encrypt(self, text):
        cipher_text = b"".join([self.__cipher.encrypt(i) for i in self.text_verify(text.encode("utf-8"))])
        encode_func = Cipher_AES.encode.get(self.__code_method)
        if encode_func:
            cipher_text = encode_func(cipher_text)
        return cipher_text.decode("utf-8").rstrip()

    def decrypt(self, cipher_text):
        cipher_text = cipher_text.encode("utf-8")
        decode_func = Cipher_AES.decode.get(self.__code_method)
        if decode_func:
            cipher_text = decode_func(cipher_text)
        return self.pad_or_unpad("unpad",  self.__cipher.decrypt(cipher_text).decode("utf-8"))

    def text_verify(self, text):
        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_or_unpad("pad", text)

    def pad_or_unpad(self, type_, contents):
        lambda_func = self[type_: self.__pad_method]
        return lambda_func(contents, len(self.__key)) if type_=="pad" else lambda_func(contents)

使用方法:

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

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

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

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

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

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

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

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

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

 

来段调用封装类 Cipher_AES 的 demo_Cipher_AES.py,方便大家理解:

from Cipher_AES import Cipher_AES

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

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

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
请注意,Python代码的格式对于程序的正确性非常重要。下面是修改后的代码: ```python from Crypto.Cipher import AES, PKCS1_OAEP from Crypto.Random import get_random_bytes from Crypto.Util.Padding import pad, unpad from Crypto.PublicKey import RSA # 生成RSA公私钥对 key = RSA.generate(2048) pub_key = key.publickey() # 加载明文文件 with open('p_text.txt', 'rb') as f: plain_text = f.read() # 生成随机密钥 session_key = get_random_bytes(16) # 用接收方公钥加密会话密钥 cipher_rsa = PKCS1_OAEP.new(pub_key) encrypted_key = cipher_rsa.encrypt(session_key) # 使用OFB模式加密明文文件 cipher_aes = AES.new(session_key, AES.MODE_OFB) cipher_text = cipher_aes.encrypt(pad(plain_text, AES.block_size)) # 保存密文文件 with open('c_text.txt', 'wb') as f: f.write(cipher_text) # 接收方用私钥解密会话密钥 cipher_rsa = PKCS1_OAEP.new(key) decrypted_key = cipher_rsa.decrypt(encrypted_key) # 用会话密钥解密密文文件 cipher_aes = AES.new(decrypted_key, AES.MODE_OFB) decrypted_text = unpad(cipher_aes.decrypt(cipher_text), AES.block_size) # 保存解密后的明文文件 with open('p1_text.txt', 'wb') as f: f.write(decrypted_text) # 比较明文文件和解密后的明文文件 with open('p_text.txt', 'rb') as f1, open('p1_text.txt', 'rb') as f2: if f1.read() == f2.read(): print('文件一致') else: print('文件不一致') ``` 这段代码的主要修改是对缩进进行了修正,使其符合 Python 代码的语法要求。同时,可以看到这段代码使用了 Python 标准库中的 `Crypto` 模块,来实现 RSA 和 AES 算法的加密和解密。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值