Python 实现AEC CBC 加密解密方式

安装

python 在 Windows下使用AES时要安装的是pycryptodome 模块   pip install pycryptodome 

python 在 Linux下使用AES时要安装的是pycrypto模块   pip install pycrypto 

CBC加密需要一个十六位的key(密钥)和一个十六位iv(偏移量)

介绍

使用AES加密,秘钥key为36o%SituationSIS,被加密明文为用户名+空格+密码,用户名不可包含空格

例:admin admin123

被加密的明文长度必须是key长度的整数倍,转成16进制字符串,是因为aes为块加密,如果要加密数据为不足块大小或不为块大小的整数倍数据时,就需要涉及填充和链加密模式,本次使用的CBC是一种循环模式,前一个分组的密文和当前分组的明文异或操作后再加密,这样做的目的是增强破解难度,从网上找到一个比较容易理解的原理图:

 

 

 

代码

# -*- coding: utf-8 -*-
import base64
import logging

from Crypto.Cipher import AES


class AESCipher:
    """
    AES 工具类
    """

    def __init__(self, key, iv):
        # 只截取16位
        self.key = key[:16]
        # 16位字符,用来填充缺失内容,可固定值也可随机字符串,具体选择看需求
        self.iv = iv[:16]

    def __pad(self, text):
        """
        填充方式,加密内容必须为16字节的倍数,若不足则使用self.iv进行填充
        """
        text_length = len(text)
        amount_to_pad = AES.block_size - (text_length % AES.block_size)
        if amount_to_pad == 0:
            amount_to_pad = AES.block_size
        pad = chr(amount_to_pad)
        return text + pad * amount_to_pad

    def __unpad(self, text):
        pad = ord(text[-1])
        return text[:-pad]

    def encrypt(self, raw):
        """
        加密
        """
        raw = self.__pad(raw)
        print raw
        # 可以选择加密方式
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        return base64.b64encode(cipher.encrypt(raw))

    def decrypt(self, enc):
        """
        解密
        """
        enc = base64.b64decode(enc)
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        return self.__unpad(cipher.decrypt(enc).decode("utf-8"))

def __unpad(text):
    pad = ord(text[-1])
    return text[:-pad]


if __name__ == '__main__':
    e = AESCipher('36o%SituationSIS', "36o%SituationSIS")
    secret_data = "admin admin123"
    enc_str = e.encrypt(secret_data)
    print('enc_str: ' + enc_str.decode())
    dec_str = e.decrypt(enc_str)
    print('dec str: ' + dec_str)

 

posted @ 2021-06-17 18:46  你的小可爱吖  阅读(1239)  评论(0编辑  收藏  举报