You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
107 lines
3.3 KiB
107 lines
3.3 KiB
import base64
|
|
import os
|
|
import socket
|
|
import struct
|
|
import sys
|
|
from Crypto.Hash import SHA256
|
|
from Crypto.Signature import PKCS1_v1_5
|
|
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
|
|
from main import *
|
|
|
|
|
|
def Sign(s, filepath):
|
|
# 文件内容签名
|
|
privkey = open('my-private.pem', "rb").read().decode("utf-8")
|
|
key = RSA.importKey(privkey)
|
|
data1 = open(filepath, "rb").read()
|
|
h = SHA256.new(data1)
|
|
signer = PKCS1_v1_5.new(key)
|
|
signature1 = signer.sign(h)
|
|
sig = base64.b64encode(signature1)
|
|
s.send(sig)
|
|
|
|
|
|
def save_file(content):
|
|
f = open('Cipher.txt', 'w+')
|
|
f.write(content)
|
|
f.close()
|
|
|
|
|
|
def send_message():
|
|
while True:
|
|
try:
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
s.connect(('127.0.0.1', 6666))
|
|
except socket.error as msr:
|
|
print(msr)
|
|
print(sys.exit(1))
|
|
|
|
# 接收对方公钥
|
|
print("#Receive the other party's public key...#")
|
|
fileinfo_size = struct.calcsize('128sq')
|
|
buf = s.recv(fileinfo_size)
|
|
if buf:
|
|
filename, filesize = struct.unpack('128sq', buf)
|
|
fn = filename.decode().strip('\x00')
|
|
new_filename = os.path.join('./', 'new_' + fn)
|
|
recvd_size = 0
|
|
fp = open(new_filename, 'wb')
|
|
while not recvd_size == filesize:
|
|
if filesize - recvd_size > 1024:
|
|
data = s.recv(1024)
|
|
recvd_size += len(data)
|
|
else:
|
|
data = s.recv(1024)
|
|
recvd_size = filesize
|
|
fp.write(data)
|
|
fp.close()
|
|
print('#Receive successfully..................#')
|
|
# END
|
|
|
|
# 发送己方公钥
|
|
print("#Sending public key now................#")
|
|
head = struct.pack(b'128sq', bytes(os.path.basename('my-public.pem'), encoding='utf-8'),
|
|
os.stat('my-public.pem').st_size)
|
|
s.send(head)
|
|
fp = open('my-public.pem', 'rb')
|
|
while True:
|
|
data = fp.read(1024)
|
|
if not data:
|
|
break
|
|
s.send(data)
|
|
fp.close()
|
|
# END
|
|
|
|
# 文件加密发送
|
|
filepath = input('#Please input the file you want to send: ')
|
|
with open(filepath, 'r') as f:
|
|
ciphertext = f.readline()
|
|
f.close()
|
|
with open("new_my-public.pem") as f:
|
|
key = f.read()
|
|
rsakey = RSA.importKey(key)
|
|
cipher = Cipher_pkcs1_v1_5.new(rsakey)
|
|
cipher_text = base64.b64encode(cipher.encrypt(ciphertext.encode('utf-8')))
|
|
print(cipher_text.decode('utf-8'))
|
|
save_file(cipher_text.decode('utf-8'))
|
|
|
|
head = struct.pack(b'128sq', bytes(os.path.basename('Cipher.txt'), encoding='utf-8'),
|
|
os.stat('Cipher.txt').st_size)
|
|
s.send(head)
|
|
|
|
fp = open('Cipher.txt', 'rb')
|
|
while True:
|
|
data = fp.read(1024)
|
|
if not data:
|
|
print('{0} send over...\n'.format('Cipher.txt'))
|
|
break
|
|
s.send(data)
|
|
fp.close()
|
|
Sign(s, filepath)
|
|
s.close()
|
|
# END
|
|
|
|
|
|
if __name__ == '__main__':
|
|
send_message()
|