python 实现aes加密解密 ecb模式和其他模式

shengge0 2020-01-01

ecb模式:(这种不需要偏移向量iv,安全性较低,代码出处忘了)

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

"""
aes加密算法
ECB模式
"""


def add_to_16(text):
    if len(text.encode(‘utf-8‘))%16:
        add = 16 - len(text.encode(‘utf-8‘)) % 16
    else:
        add = 0
    text = text + ("\0"*add)
    return text.encode(‘utf-8‘)


def encrypt(text):
    key = "1234567890123456".encode(‘utf-8‘)
    mode = AES.MODE_ECB
    text = add_to_16(text)
    cryptos = AES.new(key, mode)
    cipher_text = cryptos.encrypt(text)
    return b2a_hex(cipher_text)


def decrypto(text):
    key = "1234567890123456".encode(‘utf-8‘)
    mode = AES.MODE_ECB
    cryptor = AES.new(key,mode)
    plain_text = cryptor.decrypt(a2b_hex(text))
    return bytes.decode(plain_text).rstrip(‘\0‘)


text = open(r‘xxxxxx‘, ‘r‘, encoding=‘utf-8‘).read()
print(text[:100])
d = decrypto(text)
f = open(‘xxxxxxxxx1‘, ‘w+‘)
f.write(d)
f.close()

其他模式:参考百度,没有测试。

https://www.jianshu.com/p/d18c13681bbc

相关推荐