MD5 | SHA1 | SHA256

1
2
3
4
import hashlib

def get_md5(data: bytes) -> str:
return hashlib.md5(data).hexdigest()

RSA

1
2
3
4
5
6
7
8
9
10
11
12
13
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA


def rsa_encrypt(text: str, pub_key: str) -> str:
key = f"""-----BEGIN RSA PRIVATE KEY-----
{pub_key}
-----END RSA PRIVATE KEY-----
"""
rsakey = RSA.importKey(key)
cipher = PKCS1_v1_5.new(rsakey)
cipher_text = cipher.encrypt(text.encode())
return cipher_text.decode()

DES

加密

1
2
3
4
5
6
from Crypto.Cipher import DES
from Crypto.Util.Padding import pad

def encrypt(data: bytes, key, iv):
des = DES.new(key=key, mode=DES.MODE_CBC, iv=iv)
return des.encrypt(pad(data, 8))

解密

1
2
3
4
5
6
7
8
9
from Crypto.Cipher import DES
from Crypto.Util.Padding import unpad


def decrypt_des(encrypted_data: bytes, key: bytes, iv: bytes) -> bytes:
"""DES解密函数"""
des = DES.new(key=key, mode=DES.MODE_CBC, iv=iv)
decrypted = des.decrypt(encrypted_data)
return unpad(decrypted, DES.block_size)

AES

CBC模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import base64

from Crypto.Cipher import AES


class AESTool:
def __init__(self, iv, key):
self.key = key.encode("utf-8")
self.iv = iv.encode("utf-8")

def pkcs7padding(self, text):
"""
明文使用PKCS7填充
"""
bs = 16
length = len(text)
bytes_length = len(text.encode("utf-8"))
padding_size = length if (bytes_length == length) else bytes_length
padding = bs - padding_size % bs
padding_text = chr(padding) * padding
self.coding = chr(padding)
return text + padding_text

def encrypt(self, content: str):
"""
AES加密
"""
cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
content_padding = self.pkcs7padding(content)
encrypt_bytes = cipher.encrypt(content_padding.encode("utf-8"))
result = str(base64.b64encode(encrypt_bytes), encoding="utf-8")
return result

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


aes_tool = AESTool(iv, key)
aes_tool.encrypt("")
aes_tool.decrypt("")

ECB模式

1
2
3
4
5
6
7
8
9
10
import binascii

from Crypto.Cipher import AES

cipher_text = "e9ca6f21583a1533d3ff4fd47ddc463c6a1c7d2cf084d3640408abca7deabb96a58f50471171b60e02b1a8dbd32db156".encode()
key = "happy_1024_2233\0".encode() # 不足16位用 \0 代替

cipher = AES.new(key=key, mode=AES.MODE_ECB)
plain_text = cipher.decrypt(binascii.a2b_hex(cipher_text)) # hex 格式输出
print(plain_text.decode())

base64图片转换

解密

1
2
3
big_img_src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQ"
head, context = big_img_src.split(",")
background_bytes = base64.b64decode(context)

加密

1
2
image_data = open(image_name, "rb").read()
base64.b64encode(image_data).decode("utf-8")

gzip二进制数据解压

1
2
3
4
import zlib

decompressed = zlib.decompress(decrypted, 16 + zlib.MAX_WBITS)
cxs_json = json.loads(decompressed.decode())