Skip to content

Instantly share code, notes, and snippets.

@ydm
Last active October 22, 2024 21:21
Show Gist options
  • Save ydm/63d7ce573cc3abc7e31de5ae6d96d314 to your computer and use it in GitHub Desktop.
Save ydm/63d7ce573cc3abc7e31de5ae6d96d314 to your computer and use it in GitHub Desktop.
Secure communication using asymmetric cryptography
#!/usr/bin/env python
from pathlib import Path
from base64 import b64encode, b64decode
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.serialization.ssh import (
SSHPrivateKeyTypes,
SSHPublicKeyTypes,
)
def encrypt(message: bytes) -> bytes:
path: Path = Path('~/.ssh/id_rsa.pub').expanduser()
with open(path, 'rb') as f:
pubkey: SSHPublicKeyTypes = serialization.load_ssh_public_key(f.read())
ciphertext: bytes = pubkey.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
c64: bytes = b64encode(ciphertext)
return c64
def decrypt(c64: bytes) -> bytes:
path: Path = Path('~/.ssh/id_rsa').expanduser()
with open(path, 'rb') as f:
privkey: SSHPrivateKeyTypes = serialization.load_ssh_private_key(
f.read(),
password=None, # TODO
)
ciphertext: bytes = b64decode(c64)
message: bytes = privkey.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return message
def main():
message: str = 'message'
c64: bytes = encrypt(message.encode('utf-8'))
decoded: bytes = decrypt(c64)
print(f'message: {message}')
print(f'encoded: {c64}')
print('decoded:', decoded.decode('utf-8'))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment