python 实现 AES ECB模式加解密

AES ECB模式加解密
使用cryptopp完成AES的ECB模式进行加解密。

AES加密数据块分组长度必须为128比特,密钥长度可以是128比特、192比特、256比特中的任意一个。(8比特 == 1字节)

在CBC、CFB、OFB、CTR模式下除了密钥外,还需要一个初始化向IV。(ECB模式不用IV)

 

代码:

  

# -*- coding=utf-8-*-
from Crypto.Cipher import AES
import os
from Crypto import Random
import base64

"""
aes加密算法
padding : PKCS7
"""

class AESUtil:

    __BLOCK_SIZE_16 = BLOCK_SIZE_16 = AES.block_size

    @staticmethod
    def encryt(str, key, iv):
        cipher = AES.new(key, AES.MODE_ECB,iv)
        x = AESUtil.__BLOCK_SIZE_16 - (len(str) % AESUtil.__BLOCK_SIZE_16)
        if x != 0:
            str = str + chr(x)*x
        msg = cipher.encrypt(str)
        # msg = base64.urlsafe_b64encode(msg).replace('=', '')
        msg = base64.b64encode(msg)
        return msg

    @staticmethod
    def decrypt(enStr, key, iv):
        cipher = AES.new(key, AES.MODE_ECB, iv)
        # enStr += (len(enStr) % 4)*"="
        # decryptByts = base64.urlsafe_b64decode(enStr)
        decryptByts = base64.b64decode(enStr)
        msg = cipher.decrypt(decryptByts)
        paddingLen = ord(msg[len(msg)-1])
        return msg[0:-paddingLen]

if __name__ == "__main__":
    key = "1234567812345678"
    iv = "1234567812345678"
    res = AESUtil.encryt("123456", key, iv)
    print res # mdSm0RmB+xAKrTah3DG31A==
    print AESUtil.decrypt(res, key, iv) # 123456

 

转载于:https://www.cnblogs.com/xuchunlin/p/11421788.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python可以使用Crypto库来实现AES加解密。具体实现方法如下: 1. 导入所需的库: ``` from Crypto.Cipher import AES from binascii import b2a_hex, a2b_hex from Crypto.Util.Padding import pad, unpad ``` 2. 创建AES对象: ``` password = b'1234567812345678' #秘钥,b就是表示为bytes类型 aes = AES.new(password,AES.MODE_ECB) #创建一个aes对象 ``` 3. 加密明文: ``` text = b'abcdefghijklmnhi' #需要加密的内容,bytes类型 en_text = aes.encrypt(text) #加密明文,bytes类型 ``` 4. 解密密文: ``` den_text = aes.decrypt(en_text) # 解密密文,bytes类型 ``` 另外,如果需要加密的数据较长,可以使用padding来填充数据,以保证数据长度为16的倍数。解密时需要先去除padding。 如果需要加密文件,可以使用类似以下代码: ``` from Crypto.Cipher import AES import os secret_key = b'xxxxxx' # Convert the secret key to bytes input_file = 'xxx.zip.enc' output_file = 'xxx.zip' # Initialize the AES cipher with the secret key and ECB mode cipher = AES.new(secret_key, AES.MODE_ECB) # Get the size of the input file file_size = os.path.getsize(input_file) # Open the input and output files with open(input_file, 'rb') as in_file, open(output_file, 'wb') as out_file: # Read and decrypt the input file in chunks while True: chunk = in_file.read(AES.block_size) if len(chunk) == 0: break out_chunk = cipher.decrypt(chunk) out_file.write(out_chunk) # Remove any padding from the output file out_file.truncate(file_size - AES.block_size + len(out_chunk)) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值