Last active
October 13, 2019 01:38
-
-
Save pedrominicz/20492d5fd0c03bc554788e550f467dfc to your computer and use it in GitHub Desktop.
Simple encrypted UDP chat in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import rsa | |
import socket | |
import sys | |
import threading | |
import time | |
myPublic, myPrivate = rsa.newkeys(1024, exponent=65537) | |
otherPublic = None | |
dest = ('127.0.0.1', 5000 if len(sys.argv) > 1 else 5001) | |
def outFunc(): | |
udp = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) | |
while not otherPublic: | |
msg = str(myPublic.n).encode() | |
udp.sendto(b'\x01' + msg, dest) | |
time.sleep(1) | |
while True: | |
msg = input().encode() | |
msg = rsa.encrypt(msg, otherPublic) | |
udp.sendto(b'\x00' + msg, dest) | |
def inFunc(): | |
# Otherwise we would modify a local copy of `otherPublic`. | |
global otherPublic | |
udp = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) | |
udp.bind(('', 5001 if dest[1] == 5000 else 5000)) | |
while True: | |
msg, client = udp.recvfrom(1024) | |
if msg[0] == 0: | |
msg = rsa.decrypt(msg[1:], myPrivate).decode() | |
print(client, msg) | |
elif msg[0] == 1: | |
msg = int(msg[1:].decode()) | |
otherPublic = rsa.PublicKey(msg, 65537) | |
# Send our public key to prevent a deadlock. | |
msg = str(myPublic.n).encode() | |
udp.sendto(b'\x01' + msg, dest) | |
inT = threading.Thread(target=inFunc) | |
inT.start() | |
outT = threading.Thread(target=outFunc) | |
outT.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment