diff --git a/draft_code/modwebsocket_test.py b/draft_code/modwebsocket_test.py new file mode 100644 index 00000000..e55138b5 --- /dev/null +++ b/draft_code/modwebsocket_test.py @@ -0,0 +1,39 @@ +#import network +import socket +import ubinascii +from websocket import websocket + + +# Create and connect socket +sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +#sock.connect(('echo.websocket.org', 80)) +sock.connect(socket.getaddrinfo('echo.websocket.org', 80)[0][-1]) +#getaddrinfo('localhost', 5000)[0][-1] + +# Perform WebSocket handshake +key = ubinascii.b2a_base64(b'random_bytes_here').strip() +handshake = ( + 'GET / HTTP/1.1\r\n' + 'Host: echo.websocket.org\r\n' + 'Upgrade: websocket\r\n' + 'Connection: Upgrade\r\n' + 'Sec-WebSocket-Key: {}\r\n' + 'Sec-WebSocket-Version: 13\r\n' + '\r\n' +).format(key.decode()) +sock.send(handshake.encode()) +response = sock.recv(1024).decode() +print(f"reponse: {response}") +if '101 Switching Protocols' not in response: + raise Exception('Handshake failed') + +# Create WebSocket object +ws = websocket(sock, True) + +# Send and receive data +ws.write('Hello, WebSocket!') +data = ws.read(1024) +print('Received:', data) + +# Close connection +ws.close() diff --git a/draft_code/secp256k1.py b/draft_code/secp256k1.py new file mode 100644 index 00000000..7262ec89 --- /dev/null +++ b/draft_code/secp256k1.py @@ -0,0 +1,51 @@ +import secp256k1 +import hashlib +from binascii import hexlify + +def secp256k1_example(): + """Usage example for secp256k1 usermodule""" + + # randomize context from time to time + # - it helps against sidechannel attacks + # secp256k1.context_randomize(os.urandom(32)) + + # some random secret key + secret = hashlib.sha256(b"secret key").digest() + + print("Secret key:", hexlify(secret).decode()) + + # Makes sense to check if secret key is valid. + # It will be ok in most cases, only if secret > N it will be invalid + if not secp256k1.ec_seckey_verify(secret): + raise ValueError("Secret key is invalid") + + # computing corresponding pubkey + pubkey = secp256k1.ec_pubkey_create(secret) + + # serialize the pubkey in compressed format + sec = secp256k1.ec_pubkey_serialize(pubkey, secp256k1.EC_COMPRESSED) + print("Public key:", hexlify(sec).decode()) + + # this is how you parse the pubkey + pubkey = secp256k1.ec_pubkey_parse(sec) + + # Signature generation: + + # hash of the string "hello" + msg = hashlib.sha256(b"hello").digest() + # signing + sig = secp256k1.ecdsa_sign(msg, secret) + + # serialization + der = secp256k1.ecdsa_signature_serialize_der(sig) + + print("Signature:", hexlify(der).decode()) + + # verification + if secp256k1.ecdsa_verify(sig, msg, pubkey): + print("Signature is valid") + else: + printf("Invalid signature") + +if __name__ == '__main__': + secp256k1_example()