测试AES加密之PyCryptodome

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huanhuanq1209/article/details/80949630
#-*- 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)

运行结果为:


猜你喜欢

转载自blog.csdn.net/huanhuanq1209/article/details/80949630
今日推荐