字节类型加密解密
from Crypto.Cipher import AES
class Aes_byte:
iv: bytes = []
key: bytes = []
BLOCK_SIZE: int = 16
def __init__(self, key: bytes, iv: bytes, BLOCK_SIZE: int = 16):
self.iv = iv
self.key = key
self.BLOCK_SIZE = BLOCK_SIZE
pass
def __str__(self):
print("AES加密和解密---字节类型")
pass
def pad(self, value) -> bytes:
count = len(value)
if (count % self.BLOCK_SIZE != 0):
add = self.BLOCK_SIZE - (count % self.BLOCK_SIZE)
else:
add = 0
text = value + ("\0".encode() * add)
return text
def AES_encrypt(self, data: bytes) -> bytes:
buffter = self.pad(data)
cryptor = AES.new(self.key, AES.MODE_CBC, self.iv)
return cryptor.encrypt(buffter)
def AES_decrypt(self, data: bytes) -> bytes:
buffter = self.pad(data)
cryptor = AES.new(self.key, AES.MODE_CBC, self.iv)
return cryptor.decrypt(buffter)
if __name__ == "__main__":
public_path: str = "./response/加密解密/"
key_path: str = "./response/加密解密/key.key"
with open(key_path, "rb") as File:
key = File.read()
with open(public_path + "666.ts", "rb") as VideoBuffter:
video = VideoBuffter.read()
b = Aes_byte(key, bytes(16)).AES_encrypt(video)
with open(public_path + "encrypt.ts", "ab") as VideoBuffter:
VideoBuffter.write(b)
with open(public_path + "encrypt.ts", "rb") as VideoBuffter_en:
b = Aes_byte(key, bytes(16)).AES_decrypt(VideoBuffter_en.read())
with open(public_path + "decrypt.ts", "ab") as VideoBuffter_de:
VideoBuffter_de.write(b)
字符串加密解密
import base64
from Crypto.Cipher import AES
class Aes_str:
iv: str = []
key: str = []
BLOCK_SIZE: int = 16
def __init__(self, key: str, iv: str, BLOCK_SIZE: int = 16):
self.iv = iv
self.key = key
self.BLOCK_SIZE = BLOCK_SIZE
pass
def __str__(self):
print("AES加密和解密---字符串")
pass
def pad(self, data):
pad_data = data
for i in range(0, 16 - len(data)):
pad_data = pad_data + ' '
return pad_data
def AES_encrypt(self, data):
if len(data) < 16:
data = self.pad(data)
AES_obj = AES.new(self.key.encode("utf-8"), AES.MODE_CBC, self.iv.encode("utf-8"))
AES_encrypt_str = AES_obj.encrypt(data.encode("utf-8"))
AES_encrypt_str = base64.b64encode(AES_encrypt_str)
AES_encrypt_str = AES_encrypt_str.decode("utf-8")
return AES_encrypt_str
def AES_decrypt(self, data):
data = data.encode("utf-8")
data = base64.b64decode(data)
AES_decrypt_obj = AES.new(self.key.encode("utf-8"), AES.MODE_CBC, self.iv.encode("utf-8"))
AES_decrypt_str = AES_decrypt_obj.decrypt(data)
AES_decrypt_str = AES_decrypt_str.strip()
AES_decrypt_str = AES_decrypt_str.decode("utf-8")
return AES_decrypt_str
if __name__ == "__main__":
data = "123456"
data = Aes_str("bunny20010212123", "bunny20010212---").AES_encrypt(data)
print(data)
data = Aes_str("bunny20010212123", "bunny20010212---").AES_decrypt(data)
print(data)