Created
March 5, 2021 02:08
-
-
Save leafsummer/4ecf32d424c0d831a4553339e172eae7 to your computer and use it in GitHub Desktop.
[python aes cbc encrypt]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# FileName : aes_python.py | |
# must install the pycrypto at frist, cmd: pip install pycrypto | |
import hashlib | |
from Crypto.Cipher import AES | |
import base64 | |
class AESCipher(object): | |
def __init__(self, key): | |
self.key = key.encode('utf-8') | |
# self.key = hashlib.sha256(self.key).digest()[:16] | |
# 16位字符,用来填充缺失内容,可固定值也可随机字符串,具体选择看需求 | |
self.iv = "1234567890123456".encode('utf-8') | |
def pkcs7padding(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) | |
# print(type(text)), print(type(pad)) | |
if not isinstance(text, str): | |
pad = bytes(pad, encoding="utf-8") | |
return text + pad * amount_to_pad | |
def unpadding(self, text): | |
pad = text[-1] | |
if isinstance(pad, str): | |
pad = ord(pad) | |
return text[:-pad] | |
def encrypt(self, content): | |
""" | |
AES加密 | |
""" | |
cipher = AES.new(self.key, AES.MODE_CBC, self.iv) | |
# 处理明文 | |
content_padding = self.pkcs7padding(content) | |
# 加密 | |
encrypt_bytes = cipher.encrypt(content_padding) | |
# 重新编码 | |
result = base64.b64encode(encrypt_bytes) | |
return result | |
def decrypt(self, content): | |
""" | |
AES解密 | |
""" | |
cipher = AES.new(self.key, AES.MODE_CBC, self.iv) | |
content = base64.b64decode(content) | |
text = cipher.decrypt(content) | |
# print(text) | |
return self.unpadding(text) | |
if __name__ == '__main__': | |
e = AESCipher('8ymWLWJzYA1MvLF8') | |
secret_data = b"6860795567181583<REQDATA></REQDATA>242BB99CE386F2B1EA19CCCF606D20E2" | |
enc_str = e.encrypt(secret_data) | |
print('enc_str: ') | |
print(enc_str) | |
dec_str = e.decrypt(enc_str) | |
print('dec str: ') | |
print(dec_str) | |
enc_str = 'zIRPHt1uMiP68IZRki+1Gz3FkVU8RrofGHoC7GD8cGWNeRK3X2jc5HCYulqbq6uC7YvkUqJoge1anoBp3a+3VDmuTH1xwWFH56EC9YMk1Yg=' | |
dec_str = e.decrypt(enc_str) | |
print('dec str: ') | |
print(dec_str) | |
with open("./xff-xri.pcap", "rb") as f: | |
f_content = f.read() | |
enc_content = e.encrypt(f_content) | |
# print('enc_content: ' + enc_str) | |
dec_content = e.decrypt(enc_content) | |
print(f_content == dec_content) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment