diff --git a/README.md b/README.md index 8a2e11f..5383b3c 100755 --- a/README.md +++ b/README.md @@ -13,6 +13,12 @@ When you send a message: 1. A data packet is sent to the recipient server’s listening port. 2. The server receives, parses and processes the packet, then renders the message. +## Dependencies + +``` + # apt install python3-pycryptodome +``` + ## Contribution This project is not yet open to public contributions. Once the initial version is completed, it will be opened for public contribution and pull requests will be accepted. diff --git a/initialisation.py b/initialisation.py index 9ebe637..c8d5daf 100755 --- a/initialisation.py +++ b/initialisation.py @@ -1,8 +1,8 @@ #!/usr/bin/python3 -import ressenger_exceptions -import pathlib +import ressenger_exceptions, ressenger_cryptography +import pathlib, shutil, pickle -def initialise(password, username='default', force=False): +def initialise(password, b32address, username='default', port=5273, force=False): profile_path=pathlib.Path('~/.ressenger/').expanduser() if profile_path.exists(): if (profile_path.is_file() or profile_path.is_symlink()): @@ -11,8 +11,14 @@ def initialise(password, username='default', force=False): else: raise FileExistsError('Cannot create ~/.ressenger/ folder, is a file exists there?') profile_path.mkdir(parents=True, exist_ok=True) - - -if __name__=="__main__": - initialise(password=input("Please set up a password for encryption: ")) - exit() + user_path=pathlib.Path(f'~/.ressenger/{username}').expanduser() + if user_path.exists(): + if force: + if (user_path.is_file() or user_path.is_symlink()): + user_path.unlink() + else: + shutil.rmtree(user_path) + else: + raise FileExistsError(f'Cannot create ~/.ressenger/{username} file, is a file exists there?') + with open(user_path, 'wb') as file: + file.write(ressenger_cryptography.encrypt_bytes(pickle.dumps({'port':port, 'b32address':b32address}, protocol=pickle.HIGHEST_PROTOCOL), password)) diff --git a/ressenger_cryptography.py b/ressenger_cryptography.py index a93a4bf..34b6161 100755 --- a/ressenger_cryptography.py +++ b/ressenger_cryptography.py @@ -1 +1,23 @@ #!/usr/bin/python3 +from Cryptodome.Cipher import AES +from Cryptodome.Protocol.KDF import PBKDF2 +from Cryptodome.Random import get_random_bytes +from Cryptodome.Util.Padding import pad, unpad + +def encrypt_bytes(data: bytes, password: str, *, salt: bytes = None) -> bytes: + if salt is None: + salt = get_random_bytes(16) + key = PBKDF2(password, salt, dkLen=32, count=100_000) + iv = get_random_bytes(16) + cipher = AES.new(key, AES.MODE_CBC, iv) + ct = cipher.encrypt(pad(data, AES.block_size)) + return salt + iv + ct + +def decrypt_bytes(token: bytes, password: str) -> bytes: + salt = token[:16] + iv = token[16:32] + ct = token[32:] + key = PBKDF2(password, salt, dkLen=32, count=100_000) + cipher = AES.new(key, AES.MODE_CBC, iv) + pt = unpad(cipher.decrypt(ct), AES.block_size) + return pt