測試AES加密之PyCryptodome

#-*- coding:utf-8 -*-
from Crypto.Cipher import AES
import base64
import json 
class Crypt(object):
	secret_key = '1234567812345678'
	iv = '1234567812345678'
	def encypt(self,s):
		#加密
		PADDING='\0'
		pad_it = lambda s: s+(16 - len(s)%16)*PADDING
		cipher=AES.new(str.encode(self.secret_key),AES.MODE_CBC,str.encode(self.iv))
		msg =cipher.encrypt(str.encode(pad_it(s)))
		print("base64參數")
		print(msg)
		print(len(msg))
		print("base64補充完後的長度:")#應該是4的倍數
		print(base64.b64encode(msg))
		print(len(base64.b64encode(msg)))
		return base64.b64encode(msg) #python3不太一樣:因爲3.x中字符都爲unicode編碼,而b64encode函數的參數爲byte類型,所以必須先轉碼。
	def descypt(self,s):
		#解密
		cipherX = AES.new(str.encode(self.secret_key) ,AES.MODE_CBC,str.encode(self.iv))
		bytedt = base64.b64decode(s)
		print("base64解密完的字節爲:")
		print(bytedt)
		y = cipherX.decrypt(bytedt)
		return str(y, 'UTF-8').strip('\0')
		
s = input("請輸入明文:")
print("輸出明文的長度:")
print(type(s))
print(len(s))


s=eval(s)
print(type(s))
print(len(s))


s1=json.dumps(s);
print(type(s1))
print(len(s1))


obj=Crypt();
a=obj.encypt(s1)
print("輸出加密後的密文:")
print(a)


b=obj.descypt(a)
#paramt=str(ret,'UTF-8').replace('\n','')
print("輸出解密後的明文:")
print(b)

運行結果爲:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章