問題背景
工作中阔逼,在和其他服務(wù)供應(yīng)商對(duì)接時(shí)她按,有時(shí)需要使用AES加密方式實(shí)現(xiàn)接口的聯(lián)調(diào)床未。算法邏輯需要自己實(shí)現(xiàn)医舆,現(xiàn)把流程整理如下:
另俘侠,基于這篇文章 使用 PyCrypto 進(jìn)行 AES/ECB/PKCS#5(7) 加密,PKC7填充方式等同于PKC5填充方式蔬将。
安裝依賴
pip3 install crypto
代碼實(shí)現(xiàn)
包括完整的代碼及注解
import base64
from Crypto.Cipher import AES
class AESCipher:
def __init__(self, key):
self.key = key[0:16] #只截取16位
self.iv = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" # 16位字符爷速,用來填充缺失內(nèi)容,可固定值也可隨機(jī)字符串霞怀,具體選擇看需求惫东。
def __pad(self, text):
"""填充方式,加密內(nèi)容必須為16字節(jié)的倍數(shù),若不足則使用self.iv進(jìn)行填充"""
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)
return text + pad * amount_to_pad
def __unpad(self, text):
pad = ord(text[-1])
return text[:-pad]
def encrypt(self, raw):
"""加密"""
raw = self.__pad(raw)
cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
return base64.b64encode(cipher.encrypt(raw))
def decrypt(self, enc):
"""解密"""
enc = base64.b64decode(enc)
cipher = AES.new(self.key, AES.MODE_CBC, self.iv )
return self.__unpad(cipher.decrypt(enc).decode("utf-8"))
if __name__ == '__main__':
e = AESCipher('8ymWLWJzYA1MvLF8')
secret_data = "6860795567181583<REQDATA></REQDATA>242BB99CE386F2B1EA19CCCF606D20E2"
enc_str = e.encrypt(secret_data)
print('enc_str: ' + enc_str.decode())
dec_str = e.decrypt(enc_str)
print('dec str: ' + dec_str)
輸出
>>> enc_str: gO80A2YMTzkYTzSe6MDjwYLq2X3Du6WXP5CEj1qdaX7b39Egp1Dxj+CGs+PqWkuRkKhPNTt8BPQZfRpi4zj+1UxXjYkO51sRLwgARTlZDKY=
>>> dec str: 6860795567181583<REQDATA></REQDATA>242BB99CE386F2B1EA19CCCF606D20E2