├── requirements.txt ├── demo.gif ├── config.py ├── LICENSE ├── README.md ├── client.py ├── .gitignore └── server.py /requirements.txt: -------------------------------------------------------------------------------- 1 | simple-scrypt -------------------------------------------------------------------------------- /demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/upkoding/e2e-encyption-demo/HEAD/demo.gif -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | BASE = 5 # bilangan prima 2 | MODULUS = 23 # bilangan prima 3 | 4 | SERVER_ADDRESS = ('localhost', 8000) 5 | BUFSIZE = 1024 -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 UpKoding 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # e2e-encyption-demo 2 | 3 | Demo Enkripsi End-to-end dengan metode [Diffie–Hellman key exchange](https://en.wikipedia.org/wiki/Diffie–Hellman_key_exchange) dengan Python. Demo ini hanyalah sebagai contoh dan bukan untuk digunakan di production. 4 | 5 | Dimana teknik yang sama kemungkinan digunakan oleh Whatsapp atau Telegram dalam mengimplementasikan End-to-end encryption mereka, namun pastinya tidak sesederhana yang ini :) 6 | 7 | ![Image](https://raw.githubusercontent.com/upkoding/e2e-encyption-demo/main/demo.gif) 8 | 9 | > Terlihat diatas dimana terminal kiri adalah user Alice, terminal tengah adalah log server dan yang paling kanan adalah user Bob. Dimana pesan yang dikirimkan oleh Alice dan Bob terenkripsi dan tidak dapat dibaca di server tanpa mengetahui Private Key yang masing masing hanya dimiliki oleh Alice dan Bob. 10 | 11 | ## Coba sendiri 12 | 13 | 1. Install dependencies 14 | 15 | ``` 16 | pip install simple-crypt 17 | ``` 18 | 19 | 2. Jalankan server 20 | ``` 21 | python server.py 22 | ``` 23 | 24 | 3. Jalankan client 1 dan 2 di terminal berbeda 25 | ``` 26 | python client.py Bambang 27 | python client.py Jono 28 | ``` 29 | 30 | Demo ini adalah bahan penunjang untuk salah satu video di [Channel Youtube UpKoding](https://www.youtube.com/c/UpKoding/videos) mengenai **[Cara Kerja End-to-end encryption di Whatsapp/Telegram](https://youtu.be/jk3alKS0RFw)**. 31 | -------------------------------------------------------------------------------- /client.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | import json 4 | import threading 5 | import random 6 | import base64 7 | from simplecrypt import encrypt, decrypt 8 | 9 | 10 | from config import SERVER_ADDRESS, BUFSIZE, MODULUS, BASE 11 | 12 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 13 | sock.connect(SERVER_ADDRESS) 14 | 15 | secret_key = random.randint(1, MODULUS) 16 | public_key = (BASE ** secret_key) % MODULUS 17 | e2e_key = None 18 | 19 | 20 | def calculate_e2ekey(pubkey): 21 | global e2e_key 22 | e2e_key = (pubkey ** secret_key) % MODULUS 23 | 24 | 25 | def send_message(text): 26 | sock.send(bytes(json.dumps({'type': 'message', 'text': text}), 'utf8')) 27 | 28 | 29 | def handle_read(): 30 | 31 | while True: 32 | data = sock.recv(BUFSIZE).decode('utf8') 33 | data = json.loads(data) 34 | 35 | if data.get('type') == 'init': 36 | # public key lawan chat 37 | pubkey = data.get('pubkey') 38 | calculate_e2ekey(pubkey) 39 | print('system\t>>\tReady! (e2e key={})'.format(e2e_key)) 40 | 41 | if data.get('type') == 'system': 42 | print('system\t>>\t{}'.format(data['text'])) 43 | 44 | # hanya tampilkan pesan dari lawan chat atau system 45 | if data.get('type') == 'message' and data.get('name') != sys.argv[1]: 46 | decoded = base64.b64decode(data['text']) 47 | text = decrypt(str(e2e_key), decoded) 48 | print('{}\t>>\t{}'.format(data['name'], text.decode('utf8'))) 49 | 50 | 51 | if __name__ == '__main__': 52 | print('\nsecret_key={}'.format(secret_key)) 53 | print('public_key={}\n\n'.format(public_key)) 54 | 55 | try: 56 | # send init message first 57 | sock.send( 58 | bytes(json.dumps({'type': 'init', 'name': sys.argv[1], 'pubkey': public_key}), 'utf8')) 59 | thread = threading.Thread(target=handle_read).start() 60 | 61 | while True: 62 | msg = input() 63 | if msg == 'quit': 64 | send_message('quit') 65 | break 66 | else: 67 | chipertext = encrypt(str(e2e_key), msg) 68 | send_message(base64.b64encode(chipertext).decode('utf8')) 69 | finally: 70 | sock.close() 71 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | from threading import Thread 3 | import json 4 | 5 | from config import SERVER_ADDRESS, BUFSIZE 6 | 7 | # database sementara untuk memegang info clients 8 | clients = {} 9 | 10 | 11 | def system_message(client, text): 12 | client.send( 13 | bytes(json.dumps({'type': 'system', 'text': text}), 'utf8')) 14 | 15 | 16 | def broadcast(data): 17 | for client in clients: 18 | client.send(bytes(json.dumps(data), 'utf8')) 19 | 20 | 21 | def handle_client(client): 22 | while True: 23 | try: 24 | data = client.recv(BUFSIZE).decode('utf8') 25 | if data: 26 | msg = json.loads(data) 27 | print(msg) 28 | # Contoh protokol pesan sederhana: 29 | # {"type": "init", "name": "eka", "pubkey": "13"} 30 | # {"type": "message", "text": "Halo"} 31 | 32 | if msg.get('type') == 'init': 33 | clients[client] = msg 34 | 35 | if len(clients) < 2: 36 | # baru 1 orang, tunggu... 37 | system_message(client, 'Menunggu teman chat...') 38 | else: 39 | # sudah lengkap, kirimkan info ke lawan chat 40 | for client1 in clients: 41 | for client2 in clients: 42 | if client1 != client2: 43 | client1.send( 44 | bytes(json.dumps(clients[client2]), 'utf8')) 45 | 46 | if msg.get('type') == 'message': 47 | if msg.get('text') == 'quit': 48 | raise Exception('quit') 49 | 50 | msg['name'] = clients[client].get('name') 51 | broadcast(msg) 52 | 53 | except Exception as e: 54 | del clients[client] 55 | break 56 | 57 | client.close() 58 | 59 | 60 | if __name__ == '__main__': 61 | 62 | server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 63 | 64 | print('[INFO] Server berjalan di localhost:8000') 65 | server.bind(SERVER_ADDRESS) 66 | server.listen(1) 67 | 68 | while True: 69 | client, addr = server.accept() 70 | # Biar simple kita batasi client cuma 2 71 | if len(clients) == 2: 72 | system_message(client, 'quit') 73 | client.close() 74 | else: 75 | Thread(target=handle_client, args=(client,)).start() 76 | 77 | server.close() 78 | --------------------------------------------------------------------------------