密码学课程设计-混合加密
场景设置
Alice发送一个文件给Bob。文件使用AES加密。AES的密钥使用Bob的公钥加密,Bob使用私钥解密。(RSA)
目录
程序
-
Alice端的文件
Alice.py Alice发送文件 AES.py AES RSA.py RSA public.pem Bob公钥 (可以自己生成)
-
Bob端的文件
Bob.py Bob接受文件 decode.py Bob解密文件 RSA.py RSA AES.py AES private.pem Bob私钥 (也可以使用python自带的函数生成)
运行截图
代码
Alice.py
#
#Alice端
#
import socket
import struct
import os
import json
import AES
import RSA
import time
import base64
from tkinter import *
#软件界面
root = Tk()
root.geometry('450x500')
root.title('TK Hello Alice')
l1 = Label(root, text="ip")
l1.pack()
xls_text = StringVar()
xls = Entry(root, textvariable = xls_text)
xls_text.set("127.0.0.1")
xls.pack()
l2 = Label(root, text="port")
l2.pack()
sheet_text = StringVar()
sheet = Entry(root, textvariable = sheet_text)
sheet_text.set("1234")
sheet.pack()
l3 = Label(root, text="Aes_key(16)")
l3.pack()
loop_text = StringVar()
loop = Entry(root, textvariable = loop_text)
loop_text.set("keyskeyskeyskeys")
loop.pack()
l6 = Label(root, text="想要发送的文件")
l6.pack()
loop1_text = StringVar()
loop1 = Entry(root, textvariable = loop1_text)
loop1_text.set("E:\\encodecc\\23.jpg")
loop1.pack()
l4 = Label(root, text="加密后的文件名")
l4.pack()
loop2_text = StringVar()
loop2 = Entry(root, textvariable = loop2_text)
loop2_text.set("E:\\encodecc\\elsd")
loop2.pack()
l5 = Label(root, text="加密后的Aes_key")
l5.pack()
loop3_text = StringVar()
loop3 = Entry(root, textvariable = loop3_text)
loop3_text.set("E:\\encodecc\\Aes_key")
loop3.pack()
#config
#发送文件函数
def run(ip,port):
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect((ip,port))
print("connect success....")
filepath = loop2_text.get()
size = os.stat(filepath).st_size
f= struct.pack("l",os.stat(filepath).st_size)
client.send(f)
img = open(filepath,"rb")
client.sendall(img.read())
img.close()
client.close()
#发送key函数
def run1(ip,port):
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect((ip,port))
print("connect success....")
filepath = loop3_text.get()
size = os.stat(filepath).st_size
f= struct.pack("l",os.stat(filepath).st_size)
client.send(f)
img = open(filepath,"rb")
client.sendall(img.read())
img.close()
client.close()
#本地加密
def click():
pc = AES.PrpCrypt(loop_text.get())
with open(loop1_text.get(),'rb') as fw:
tu = base64.b64encode(fw.read())
fw.close()
data = tu.decode()
c = b''
k = 0
print('Encoding....')
#AES加密文件
for i in range(int(len(data)/120)):
c = c + pc.encrypt(data[k:k+120])
k = k+ 120
if(int(i)%1000 == 0):
print(str(100*(k+1)/int(len(data)))+'%')
c = c + pc.encrypt(data[:-len(data)%120])
with open(loop2_text.get(),'wb') as fq:
fq.write(c)
fq.close()
a = RSA.rsaEncrypt(loop_text.get(),RSA.load_pubkey())
with open(loop3_text.get(),"wb") as fe:
fe.write(a)
fe.close()
run(xls_text.get(),int(sheet_text.get()))
time.sleep(5)
run1(xls_text.get(),int(sheet_text.get()))
Button(root, text="press", command = click).pack()
root.mainloop()
AES.py
#
#AES 函数文件
#
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
import base64
import RSA
#读取文件 返回字节流
def readfile(file):
with open(file,'rb') as fp:
tu = base64.b64encode(fp.read())
fp.close()
return(tu)
class PrpCrypt(object):
def __init__(self, key):
self.key = key.encode('utf-8')
self.mode = AES.MODE_CBC
#AES加密函数
def encrypt(self, text):
text = text.encode('utf-8')
cryptor = AES.new(self.key, self.mode, b'0000000000000000')
length = 16
count = len(text)
if count < length:
add = (length - count)
text = text + ('\0' * add).encode('utf-8')
elif count > length:
add = (length - (count % length))
text = text + ('\0' * add).encode('utf-8')
self.ciphertext = cryptor.encrypt(text)
return b2a_hex(self.ciphertext)
#AES解密函数
def decrypt(self, text):
cryptor = AES.new(self.key, self.mode, b'0000000000000000')
plain_text = cryptor.decrypt(a2b_hex(text))
return bytes.decode(plain_text).rstrip('\0')
RSA.py
import rsa
# rsa加密
def rsaEncrypt(str,pubkey):
content = str.encode('utf-8')
crypto = rsa.encrypt(content, pubkey)
return (crypto)
# rsa解密
def rsaDecrypt(str, pk):
content = rsa.decrypt(str, pk)
con = content.decode('utf-8')
return con
def load_pubkey():
with open('public.pem', "rb") as publickfile:
p = publickfile.read()
pubkey = rsa.PublicKey.load_pkcs1(p)
return pubkey
def load_privkey():
with open('private.pem', "rb") as privatefile:
p = privatefile.read()
privkey = rsa.PrivateKey.load_pkcs1(p)
return privkey
public.pem(公钥)
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBALNizjNKI4w7Y2Ug2A7QwLP7HLEHWQTNCzATbpWXWgYw2knTd3ZiXjxj
vWqoaapkSHnloDZi915/jq6WvsE8w/dtUWxS+1J9NDxMDbKKxWIO0LN0MjmI0C6V
EBrOAFL/cJtvaPm66m2McSAPVYErAZVh60ABTYeILkpkI/YuJFjRAgMBAAE=
-----END RSA PUBLIC KEY-----
Bob.py
#服务器端
import socket
import struct
import os.path
from tkinter import *
root = Tk()
root.geometry('450x500')
root.title('TK Hello Bob')
l1 = Label(root, text="ip")
l1.pack()
xls_text = StringVar()
xls = Entry(root, textvariable = xls_text)
xls_text.set("127.0.0.1")
xls.pack()
l2 = Label(root, text="port")
l2.pack()
sheet_text = StringVar()
sheet = Entry(root, textvariable = sheet_text)
sheet_text.set("1234")
sheet.pack()
def run1(ip,port):
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((ip,port))
server.listen(2)
while True:
print("start...")
sock,adddr = server.accept()
d = sock.recv(struct.calcsize("l"))
total_size = struct.unpack("l",d)
num = total_size[0]//1024
data = b''
for i in range(num):
data += sock.recv(1024)
data += sock.recv(total_size[0]%1024)
if os.path.exists("tupian"):
with open("Aes_key","wb") as f:
f.write(data)
else:
with open("tupian","wb") as f:
f.write(data)
sock.close()
sock.close()
def click():
q1 = Label(root, text="start...")
q1.pack()
q2 = Label(root, text="file recv")
q2.pack()
run1(xls_text.get(),int(sheet_text.get()))
Button(root, text="press", command = click).pack()
root.mainloop()
decode.py
import RSA
import AES
import base64
from tkinter import *
root = Tk()
root.geometry('450x500')
root.title('TK Decode')
l1 = Label(root, text="Aes_key路径")
l1.pack() #这里的side可以赋值为LEFT RTGHT TOP BOTTOM
xls_text = StringVar()
xls = Entry(root, textvariable = xls_text)
xls_text.set("E:\\encodecc\\Bob\\Aes_key")
xls.pack()
l2 = Label(root, text="待解密文件路径")
l2.pack() #这里的side可以赋值为LEFT RTGHT TOP BOTTOM
sheet_text = StringVar()
sheet = Entry(root, textvariable = sheet_text)
sheet_text.set("E:\\encodecc\\Bob\\tupian")
sheet.pack()
l3 = Label(root, text="文件命名")
l3.pack() #这里的side可以赋值为LEFT RTGHT TOP BOTTOM
loop_text = StringVar()
loop = Entry(root, textvariable = loop_text)
loop_text.set("E:\\encodecc\\Bob\\tupian.jpg")
loop.pack()
def click():
with open(xls_text.get(),"rb") as fe:
fd = fe.read()
fe.close()
Aes_key = RSA.rsaDecrypt(fd, RSA.load_privkey())
#print(Aes_key)
pc = AES.PrpCrypt(Aes_key)
with open(sheet_text.get(),'rb') as fq:
pian = fq.read()
fq.close()
c = ''
k = 0
print('Decoding....')
data = pian.decode()
#print(len(data))
if len(data)>=256:
for i in range(int(len(data)/256)):
bfg = pc.decrypt(data[k:k+256])
k = k +256
c = c + bfg
c = c.encode()
#print(c)
tu_b = base64.b64decode(c)
#print(tu_b)
with open(loop_text.get(),'wb') as fq:
fq.write(tu_b)
fq.close()
l1 = Label(root, text="ok you get it success")
l1.pack() #这里的side可以赋值为LEFT RTGHT TOP BOTTOM
if len(data)<256:
c = pc.decrypt(data)
c = c.encode()
#print(c)
tu_b = base64.b64decode(c)
#print(tu_b)
with open(loop_text.get(),'wb') as fq:
fq.write(tu_b)
fq.close()
l1 = Label(root, text="ok you get it success")
l1.pack() #这里的side可以赋值为LEFT RTGHT TOP BOTTOM
Button(root, text="press", command = click).pack()
root.mainloop()
private.pem(私钥)
-----BEGIN RSA PRIVATE KEY-----
MIICYAIBAAKBgQCzYs4zSiOMO2NlINgO0MCz+xyxB1kEzQswE26Vl1oGMNpJ03d2
Yl48Y71qqGmqZEh55aA2Yvdef46ulr7BPMP3bVFsUvtSfTQ8TA2yisViDtCzdDI5
iNAulRAazgBS/3Cbb2j5uuptjHEgD1WBKwGVYetAAU2HiC5KZCP2LiRY0QIDAQAB
AoGASgsPh7YjZB+jUDu1UrAxylhtKFkbElM8OfTbYV2eqA2EHJLvrWq+8PhOV/b5
3n4UOFRiw/AnoNbP4xqPe2ZmKIcJsg+Pnz/pCqUZCO3oZ7InmO3lEoDPtt7BNu5U
FrgcNFR2h10yfGjRCgSW8oqrZlE7h8s/Gtgpw8QY9bY8ktECRQDW7dfcFbYbAdUd
RTSqx3ntEUUHikQIW7lyFoxBzA6FuqepccyY3eg7UiHgZinc/GUiW4Htj2odpHHX
1YhqSv+mMDTIJQI9ANWqOMMZpokiUClDhn8Hzk41QPBfsBZz2mnAzbDqCrbPneKW
51To++U4kl1D0udBeMIAUNX4WGPEizmIPQJEV5X3OG30lw7pHRN9wfamPjCic88p
qEpQyShdIdcZN+/3sTp5yPXtVHdE7OBVQQPt5tFpojimYswHxI/1FnPXuI6+g60C
PGTK/CPtQcaHTVFp7VSXlhcGwC+ktCijVnF05pOClLNQlaaCkXZYwhuL6F/e0usM
066Q/5EwqmHGIfdt8QJFAIMUV2LibX1fQR9pQ4Ol5TL/o3XhjE0mKT7uWY4jwxwF
nTA2Axs47Bn6mI3kzCVTMZM3UuYzX5fuw4Hr6U+1ExxSzdsh
-----END RSA PRIVATE KEY-----