Python 3.6.5的坑 AES padding
from Crypto.Cipher import AES
key = ‘DF11-FB15-B7B2-15AB-47B7-7AC4-C6F9-5EFE‘
cryptor = AES.new(key.encode(‘utf-8‘),AES.MODE_CBC,str(key[0:16]).encode(‘utf-8‘))
text = b‘1234567890abc‘
encrypted= cryptor.encrypt(pad_text(text));
def pad_text(s):
‘‘‘Pad an input string according to PKCS#7‘‘‘
BS = AES.block_size
return s + (BS - len(s) % BS) * chr(BS - len(s) % BS).encode("utf-8")
"""
註意啦,
1)當text是二進制流時, chr(BS - len(s) % BS).encode("utf-8")裏的".encode("utf-8")"是不能少的, 不然會有如下錯誤:
TypeError: can‘t concat str to bytes
2)Key必須要.encode(‘utf-8‘): key.encode(‘utf-8‘) , 32位的key
3)IV必須要.encode(‘utf-8‘) : str(key[0:16]).encode(‘utf-8‘),從32位的key取16位當做IV的輸入值
#Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
#Crypto 1.4.1
"""
Python 3.6.5的坑 AES padding