需要使用aes加密,記錄一下
import base64
from Crypto.Cipher import AES
AES_KEY = 'aw123zsc212s9ju0' # It must be 16, 24 or 32 bytes long (respectively for *AES-128*, *AES-192* or *AES-256*).
def add_to_16(text: str) -> bytes:
"""
不足16位的地方補全位數
:param text: 源字符串
:return: 補足字符串
"""
b_text = text.encode('utf-8')
# 計算需要補的為位數
if len(text) % 16:
add = 16 - (len(b_text) % 16)
else:
add = 0
return b_text + (b'\0' * add)
def encrypt_by_aes(text: str, key: str) -> str:
"""
加密函數
:param text: 源字符串
:param key: 密鑰
:return: 加密字符串
"""
key = key.encode('utf-8')
text = add_to_16(text) # 如果長度不夠補足 16 位
cryptos = AES.new(key, AES.MODE_ECB) # 使用ECB模式
cipher_text = cryptos.encrypt(text) # 加密
return base64.standard_b64encode(cipher_text).decode('utf-8') # 將加密結果轉為base64編碼輸出
def decrypt_by_aes(text: str, key: str):
"""
解密函數
:param text: 加密字符串
:param key: 密鑰
:return: 解密結果
"""
key = key.encode('utf-8')
text = text.encode('utf-8')
text = base64.b64decode(text) # 先使用base64解碼
cryptos = AES.new(key, AES.MODE_ECB)
cipher_text = cryptos.decrypt(text) # 解密
return cipher_text.decode('utf-8').strip('\0')
if __name__ == '__main__':
source_str = 'hello'
encrypt_str = encrypt_by_aes(source_str, AES_KEY)
decrypt_str = decrypt_by_aes(encrypt_str, AES_KEY)
print(encrypt_str)
print(decrypt_str)
輸出結果:
CNCNntzveSN8tZ8Y1PifWQ==
hello