From c3597658551402ed82b1e60b2969b647812a30ee Mon Sep 17 00:00:00 2001 From: Emile Clark-Boman Date: Fri, 27 Jun 2025 03:09:53 +1000 Subject: [PATCH] added naive SHA256 and RSA implementations --- imp/crypto/hash.py | 7 +++++++ imp/crypto/rsa.py | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 imp/crypto/hash.py create mode 100644 imp/crypto/rsa.py diff --git a/imp/crypto/hash.py b/imp/crypto/hash.py new file mode 100644 index 0000000..e7811ec --- /dev/null +++ b/imp/crypto/hash.py @@ -0,0 +1,7 @@ +import hashlib + +def sha256(data: bytes, as_bytes: bool = False) -> bytes: + hasher = hashlib.sha256() + hasher.update(data) + hash = hasher.digest() + return hash if as_bytes else int.from_bytes(hash) diff --git a/imp/crypto/rsa.py b/imp/crypto/rsa.py new file mode 100644 index 0000000..09cd94d --- /dev/null +++ b/imp/crypto/rsa.py @@ -0,0 +1,18 @@ +''' +Simplification of Euler's Totient function knowing +the prime factorisation for the public key N value. +''' +def _totient(p: int, q: int) -> int: + return (p - 1) * (q - 1) + +''' +Implements RSA encryption as modular exponentiation. +''' +def encrypt(plaintext: int, e: int, N: int) -> int: + return pow(plaintext, e, N) +def decrypt(ciphertext: int, d: int, N: int) -> int: + return pow(ciphertext, d, N) + +def gen_private_key(e: int, p: int, q: int) -> int: + return pow(e, -1, _totient(p, q)) +