from Crypto.Cipher import AES
from binascii import b2a_hex,a2b_hex
import base64
def the_str16(st): #补16位
st=zwencode(st)
while len(st)%16!=0:
st=st+’\0′
return str.encode(st)
def zwencode(st): #编码
st=base64.b64encode(st.encode(‘utf-8’))
st=st.decode()
return st
def zwdecode(st): #解码
missing_padding = 4 – len(st) % 4
if missing_padding:
st += ‘=’* missing_padding
st=base64.b64decode(st)
st=st.decode(‘utf-8’)
return st
def encryt_ecb(key,st): #加密
st=the_str16(st)
key=the_str16(key)
aes=AES.new(key,AES.MODE_ECB)
text_str=aes.encrypt(st)
return b2a_hex(text_str)
def decryt_ecb(key,st): #解密
key=the_str16(key)
aes=AES.new(key,AES.MODE_ECB)
text_str=aes.decrypt(a2b_hex(st))
return text_str
if __name__==’__main__’:
isjiami=input(‘输入encode加密,decode解密:’)
if isjiami == ‘encode’:
text=input(‘输入要加密字符:’)
key=input(‘输入key:’)
try:
print(encryt_ecb(key,text).decode())
except:
print(‘加密失败’)
if isjiami == ‘decode’:
text=input(‘输入要解密字符:’)
key=input(‘输入key:’)
try:
print(zwdecode(decryt_ecb(key,text).decode()))
except:
print(‘解密失败’)