Implement petnames and pubkeys

This commit is contained in:
Anthony Wang 2022-10-01 12:26:37 -04:00
parent 5091466feb
commit 5f4af2f5ee
Signed by: a
GPG key ID: 42A5B952E6DD8D38
2 changed files with 55 additions and 9 deletions

6
gen.py
View file

@ -1,4 +1,4 @@
from base64 import b64encode
from base64 import urlsafe_b64encode
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519
@ -10,7 +10,7 @@ private_bytes = private_key.private_bytes(
encryption_algorithm=serialization.NoEncryption()
)
with open('privkey', 'wb') as f:
f.write(b64encode(private_bytes))
f.write(urlsafe_b64encode(private_bytes))
public_key = private_key.public_key()
@ -19,4 +19,4 @@ public_bytes = public_key.public_bytes(
format=serialization.PublicFormat.Raw
)
with open('pubkey', 'wb') as f:
f.write(b64encode(public_bytes))
f.write(urlsafe_b64encode(public_bytes))

View file

@ -1,19 +1,65 @@
from http.server import HTTPServer, BaseHTTPRequestHandler
from inbox import Send, Fetch
from sys import argv
from urllib import parse
from requests import post
from inbox import Send, Fetch, inbox
petname_to_pubkey = {}
pubkey_to_server = {}
class HTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
'''Fetch the user inbox'''
user = parse.parse_qs(parse.urlsplit(self.path).query)['user'][0]
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(str(Fetch(self.path)).encode('utf-8'))
self.wfile.write(str(Fetch(user)).encode('utf-8'))
def do_POST(self):
Send(self.rfile.read(int(self.headers['Content-Length'])), self.path)
data = self.rfile.read(int(self.headers['Content-Length']))
func = parse.urlsplit(self.path).path[1:]
p = parse.parse_qs(parse.urlsplit(self.path).query)
user = p['user'][0]
if func == 'send':
# Send to inbox
recipient = p['recipient'][0]
# If recipient is petname, convert to pubkey
if user in petname_to_pubkey and recipient in petname_to_pubkey[user]:
recipient_pubkey = petname_to_pubkey[user][recipient]
else:
recipient_pubkey = recipient
# Send it
if recipient_pubkey in inbox:
Send(data, recipient_pubkey)
else:
server = pubkey_to_server[recipient_pubkey]
path = self.path.replace(recipient, recipient_pubkey)
post('http://'+server+path, data=data).text
elif func == 'name':
# Update petname
pubkey = p['pubkey'][0]
petname = p['petname'][0]
server = p['server'][0]
petname_to_pubkey[user][petname] = pubkey
pubkey_to_server[pubkey] = server
elif func == 'register':
# Register new user
inbox[user] = []
petname_to_pubkey[user] = {}
else:
print('Not implemented')
self.send_response(200)
self.end_headers()
server = HTTPServer(("0.0.0.0", 8000), HTTPRequestHandler)
server = HTTPServer(("0.0.0.0", int(argv[1])), HTTPRequestHandler)
server.serve_forever()