Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
brianshen0522 committed Dec 31, 2021
1 parent 4836b13 commit d52f94c
Show file tree
Hide file tree
Showing 25 changed files with 326 additions and 0 deletions.
Binary file added code/__pycache__/cast.cpython-38.pyc
Binary file not shown.
Binary file added code/__pycache__/client.cpython-38.pyc
Binary file not shown.
Binary file added code/__pycache__/client.cpython-39.pyc
Binary file not shown.
Binary file added code/__pycache__/msg.cpython-38.pyc
Binary file not shown.
Binary file added code/__pycache__/process.cpython-38.pyc
Binary file not shown.
Binary file added code/__pycache__/process.cpython-39.pyc
Binary file not shown.
Binary file added code/__pycache__/ras.cpython-38.pyc
Binary file not shown.
Binary file added code/__pycache__/ras.cpython-39.pyc
Binary file not shown.
Binary file added code/__pycache__/rsa.cpython-38.pyc
Binary file not shown.
Binary file added code/__pycache__/server.cpython-38.pyc
Binary file not shown.
Binary file added code/__pycache__/server.cpython-39.pyc
Binary file not shown.
Binary file added code/__pycache__/var.cpython-38.pyc
Binary file not shown.
21 changes: 21 additions & 0 deletions code/cast.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import json
from var import my_id
from client import encrypt_send
from msg import find_ip

def cast_calc(cast_id):
cast_id = cast_id
if cast_id[0] == "all":
cast_id = list(json.loads(open("data/ip.json", "r").read()).keys())
if cast_id.index(my_id) + 2 == len(cast_id):
send = [int(((cast_id.index(my_id) + 1) + 1) / 2), len(cast_id)]
else:
send = [int(((cast_id.index(my_id) + 1) + 1) / 2), int((len(cast_id) + cast_id.index(my_id) + 1) / 2)]
for x in send:
send[send.index(x)] = cast_id[x-1]
return(send)

def cast(msg):
for x in cast_calc(msg[1]):
print(f"sent to {x}")
#send(find_ip(x), )
62 changes: 62 additions & 0 deletions code/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#from msg import msg_process
from rsa import sign, verify
import socket
import json
import threading

HEADER = 64
PORT = 1111
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT!"

def encrypt_send(IP, msg):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # define connection type
client.connect((IP, PORT)) #connect
message = sign(msg).encode(FORMAT) #set message
msg_length = len(message) #message len
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length) #send message len
client.send(message) #send message
while True:
rec_msg = client.recv(2048).decode(FORMAT) #rec_msg = recive message
if rec_msg:
if verify(rec_msg):
msg = eval(rec_msg)[0]
print(msg)
break;
else:
print("message has been distort")
break
msg_length = len(DISCONNECT_MESSAGE) #set disconnect message len
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length) #send disconnect message len
client.send(DISCONNECT_MESSAGE.encode(FORMAT)) #send dissconnect message
return (rec_msg);

def send(IP, msg):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # define connection type
client.connect((IP, PORT)) #connect
message = msg.encode(FORMAT) #set message
msg_length = len(message) #message len
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length) #send message len
client.send(message) #send message
while True:
rec_msg = client.recv(2048).decode(FORMAT) #rec_msg = recive message
if rec_msg:
if verify(rec_msg):
msg = eval(rec_msg)[0]
print(msg)
break;
else:
print("message has been distort")
break
msg_length = len(DISCONNECT_MESSAGE) #set disconnect message len
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length) #send disconnect message len
client.send(DISCONNECT_MESSAGE.encode(FORMAT)) #send dissconnect message
return (rec_msg);
1 change: 1 addition & 0 deletions code/data/cast_message
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[9033189795952647214, 7215574099149179501]
8 changes: 8 additions & 0 deletions code/data/ip.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"001" : "192.168.1.101",
"002" : "192.168.1.102",
"003" : "192.168.1.103",
"004" : "192.168.1.104",
"005" : "192.168.1.105",
"999" : "127.0.0.1"
}
15 changes: 15 additions & 0 deletions code/format
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[msg, signature]

msg
ip
["$ID", "!HELLO!"]
["$ID", "?IP?", "$ID"]

transport
["$ID", "!CAST!", "$destination", "$msg"]
ex:["001", "!CAST!", "["all"]", "hi"]
["001", "!CAST!", "["002", "003", "004", "005"]", "hi"]

transaction
[$ACCOUNT, "!remit!", $PAYEE, $AMOUNT]
[[$ACCOUNT, "!remit!", $PAYEE, $AMOUNT], ["$ID", !verified!, $SIGNATURE]]
8 changes: 8 additions & 0 deletions code/keys/keys.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"001" : "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2PENaRAYH79nYqS8QdsVHptUP rc1XHa/cMJCuttnojNsUtJfCU9XxGhex1Rd++h1PuLdCRUD7Z2VNXUTn2s4fVeh0 pcA94xvPlM3HI+Unp61LZvtnTFdZqtNsSJxFKmYCmFmpVs8tDyXz6+3+blWswT83 w+L9Fnv4wXhT2br/nQIDAQAB",
"002" : "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCroIjiVZnbvr4Il/Sv4SoEJMFs gpMJW4FqpEZBJqXOaEymd796EKALM7refck5Y/yvGd2U/oV9XPyZsIq3tG+RuL/c fNzN5Si7BvM7UIVhmyN248yd+2sFf4Gh+pJ4rVuSJeIQOvi1TKlvTXz1fy3Ni5sZ vWeG+w/9r3z+hcKdUQIDAQAB",
"003" : "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDJ6UkbcgZ2XEyI1u74uxAP6Z6f Hw3a5QhYq/Cy9ckvC6/ejpUDvBxWeNkQz2cL+FYFEPFU3n612/tmlie8Bl3hMXvj wCdOTFWfFzMRfwcwog/PYaxWWim6ArvNn1i3PQ95/RIuT+S/buqrkY4IbHy3h5bX yRFQIjOHWxVQmOVpdQIDAQAB",
"004" : "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDr3riu2uQ2p010XSh93Sv/T2w SyF49Bw/2SUaiPrQmpTDv/Tmtk/9d33epf/zSXuVH1woyuam2kDzo6xPb78J52qw xmTRf5gKytNVng/jQu80oQco/N6HM60HZOgtXNANc3TAdj33bIr84kbmLygaO0NQ E2aecCNfyvEDuA7ZqQIDAQAB",
"005" : "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDPFb9ghBBmtEA/OYImWz8W3EK/ YfcYVQSRYVokaVWBCsV8EVX/HxDS+g0N96SzbT5T2rHLxe37ik1cku0KsBMTi5qY 5Ay44VfbsAdnjqZRvHzsVztTWBhg7iM8BoEkWleD2P/cd4MkuUR2VbaKY5iXEEni flvlGZpNKVXXxz6ZcQIDAQAB",
"999" : "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCZYsTCwu4O6B0hpH4CjjqfX3Ka jerSJA4e76NAJg9O5xjK+7QcJ7FmEecpPBW+AfSvYM4G7WwVTbgImHuEouVY9fvo o7ViW+O3CMQHN+MPujJ+9aHzaxclnbYxr4UG+OFdXQw3ySUYUp2Xfi1PaYUfe5bJ X5O8H6bhiVN8FTSPVwIDAQAB"
}
15 changes: 15 additions & 0 deletions code/keys/private.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCZYsTCwu4O6B0hpH4CjjqfX3KajerSJA4e76NAJg9O5xjK+7Qc
J7FmEecpPBW+AfSvYM4G7WwVTbgImHuEouVY9fvoo7ViW+O3CMQHN+MPujJ+9aHz
axclnbYxr4UG+OFdXQw3ySUYUp2Xfi1PaYUfe5bJX5O8H6bhiVN8FTSPVwIDAQAB
AoGAOnyQVUlZ18JHFWRxDg1oqguNmgRCRVWtMruijpvUm3wAFqoqb8/s02RBNhZs
nfKF9/ecJ8URQQBNC64E7zrj41P6xVb4sKcc8Wj6NXOABlEvvVId/wueJBkNTLlv
ScLUCB7f7JifZ3oB3aB0VS5Wk2YkznklnQhKzZAS4sRgxdECQQC3cxSTQdJLcIyX
ruNfOC8qmYE5ir3P50M3yiClsf0U/BWvDyG2BcrVNenO5poDd+e6qpuh0HzJ48zU
ci6dt9vRAkEA1gv1EaUCvwG1u/zZ/OguVBFBCpBbWvQPgHdXE4aNe3JkAt9Y6cVp
vUuSY/xyPYhkkfc4iLtvLUc6j3546k4KpwJAJ3Z4DJ1yMYxKki6q9sbNTqqq48f2
wQyMpymyEDLTsHnx6DCnHdLtKSRp4Xo1010t2jftNsf0sDFy1JijcoYkoQJBAM8z
egOfmb3u2M7moNpao+ZLYYvpXBX6pjr0y30iRjlW7Yt+S6LYsFhHHKnfiXMZYkmO
aNKrpp7NEdowUrp124cCQCeKkMoD1526L1h38VsHTGzcrYYzRfZOLwHzzTeG1Tve
RWdwdBWMCHow7Rtg02nxsF8ZJJzgDCfzDyR7jKHYtNc=
-----END RSA PRIVATE KEY-----
1 change: 1 addition & 0 deletions code/keys/public.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCZYsTCwu4O6B0hpH4CjjqfX3Ka jerSJA4e76NAJg9O5xjK+7QcJ7FmEecpPBW+AfSvYM4G7WwVTbgImHuEouVY9fvo o7ViW+O3CMQHN+MPujJ+9aHzaxclnbYxr4UG+OFdXQw3ySUYUp2Xfi1PaYUfe5bJ X5O8H6bhiVN8FTSPVwIDAQAB
65 changes: 65 additions & 0 deletions code/msg.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
from var import my_id
from client import send,encrypt_send
import json

def find_ip(id):
ip_file = open("data/ip.json", "r")
ip_list = json.loads(ip_file.read())
return(ip_list[id])

def cast_calc(cast_id):
cast_id = cast_id
if cast_id[0] == "all":
cast_id = list(json.loads(open("data/ip.json", "r").read()).keys())
if cast_id.index(my_id) + 2 == len(cast_id):
send = [int(((cast_id.index(my_id) + 1) + 1) / 2), len(cast_id)]
else:
send = [int(((cast_id.index(my_id) + 1) + 1) / 2), int((len(cast_id) + cast_id.index(my_id) + 1) / 2)]
for x in send:
send[send.index(x)] = cast_id[x-1]
return(send)

def cast(msg):
orig_msg = msg
msg = eval(eval(msg)[0])
msg_hash = hash(str(msg))
hash_file = open("data/cast_message", "r")
hash_list = eval(hash_file.read())
hash_file.close()
if msg_hash in hash_list:
print("repeat")
pass
else:
hash_list.append(msg_hash)
hash_file = open("data/cast_message", "w")
hash_file.write(str(hash_list))
hash_file.close()
for x in cast_calc(msg[2][1]):
print(f"sent to {x}")
#print(orig_msg)
send(find_ip(x), str(orig_msg))

def msg_process(msg):
orig_msg = msg
msg = eval(eval(msg)[0])
time = msg[0]
id = msg[1]
action = msg[2]
if action[0] == '!HELLO!':
print(f"hello form {id} at {time}")
result = ['!message_recived!']
elif action[0] == '?IP?':
print(f"asking {action[1]}'s ip form {id} at {time}")
result = ['!IP!', f"{find_ip(action[1])}"]
elif action[0] == '!IP!':
print(action[1])
elif action[0] == '!CAST!':
print(f"cast {action[2]} to {action[1]} form {id} at {time}")
cast(orig_msg)
result = ['!message_recived!']
else:
result = ['!message_not_recognized!']
if result:
return(result)
else:
return
48 changes: 48 additions & 0 deletions code/rsa.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
from Crypto.Hash import SHA
import base64
import os
import json

def create ():
random_generator = Random.new().read
print("creating key pair")
rsa = RSA.generate(1024, random_generator)
private_pem = rsa.exportKey()
with open("keys/private.pem", "wb") as f:
f.write(private_pem)
print("private key......done")
public_pem = rsa.publickey().exportKey()
public_pem = public_pem.decode()
f = open("keys/public.pem", "w")
f.write(public_pem[27:-25].replace("\n", " "))
f.close
print("public key......done")
print("done")

def sign (message):
rsakey = RSA.importKey(open("keys/private.pem").read())
signer = Signature_pkcs1_v1_5.new(rsakey)
digest = SHA.new()
#print(type(message), message)
digest.update(message.encode("utf-8"))
sign = signer.sign(digest)
signature = base64.b64encode(sign)
message = [message, signature.decode("utf-8")]
return(str(message))

def verify(input_data):
message = eval(input_data)[0]
signature = eval(input_data)[1]
pub = "-----BEGIN PUBLIC KEY-----"+"\n"+json.loads(open("keys/keys.json", "r").read())[f'{eval(message)[1]}'].replace(" ", "\n")+"\n"+"-----END PUBLIC KEY-----"
rsakey = RSA.importKey(pub)
verifier = Signature_pkcs1_v1_5.new(rsakey)
hsmsg = SHA.new()
hsmsg.update(message.encode("utf-8"))
is_verify = verifier.verify(hsmsg, base64.b64decode(signature))
if is_verify == True:
return("verified")
else:
return("doctored")
48 changes: 48 additions & 0 deletions code/server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from var import my_id
from rsa import verify, sign
from msg import msg_process
import socket
import threading
import time
import os
HEADER = 64 #set header length
PORT = 1111 #set server listening port
ADDR = ("0.0.0.0", PORT)
FORMAT = 'utf-8' #set format
DISCONNECT_MESSAGE = "!DISCONNECT!" #set disconnect message

def handle_connection(conn, addr):
connected = True
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT) #print(f"msg length:{msg_length}")
if msg_length:
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
#print(f"raw msg:{msg}")
if msg == DISCONNECT_MESSAGE:
connected = False
#print("connection end")
else:#msg
if verify(msg) == "verified":#if message is verified
reply = msg_process(msg)
conn.send(sign(f"[{int(time.time())},'{my_id}' ,{reply}]").encode(FORMAT))
else:#if message is doctored
conn.send(DISCONNECT_MESSAGE.encode(FORMAT))
conn.close()

def server_start():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #set connection type
try:
print("[STARTING] server is starting...")
server.bind(ADDR) #start server
server.listen() #listening
print(f"[LISTENING] Server is listening on port {PORT}")
while True:
conn, addr = server.accept() #accept connection
handle_msg = threading.Thread(target=handle_connection, args=(conn, addr)) #set a threat(handle_connection)
handle_msg.start() #start thread(handle_connection)
except:
out = os.popen("sudo netstat -ltpn |grep 1111").read()
out = out[80:out.find("/")]
if out:
os.system(f"sudo kill -9 {out}")
33 changes: 33 additions & 0 deletions code/validator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import threading
import os
import json
import time
from msg import find_ip
from server import server_start
from client import encrypt_send
from var import my_id

if os.name == "nt":
os.system("cls")
else:
os.system("clear")

if os.sys.argv[1] == "server":
server = threading.Thread(target = server_start())
server.start()
else:
while True:
id = input("who do you want to send it to?")
action = input("what do you want to do?")
if action == "hello":
encrypt_send(find_ip(id), f"['{int(time.time())}','{my_id}', ['!HELLO!']]")
elif action == "ip":
ask_ip = input("who's ip?")
encrypt_send(find_ip(id), f"['{int(time.time())}','{my_id}', ['?IP?', '{ask_ip}']]")
elif action == "cast":
participate = input("who do you want to send it to?")
msg_to_cast = input("what message do you wnat to send?")
encrypt_send(find_ip(id), f"['{int(time.time())}','{my_id}', ['!CAST!', {participate.split(' ')}, '{msg_to_cast}']]")
else:
msg = input('msg?')
encrypt_send(find_ip(id), f"['{int(time.time())}','{my_id}', '{msg}']")
1 change: 1 addition & 0 deletions code/var.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
my_id = "999"

0 comments on commit d52f94c

Please sign in to comment.