added naive SHA256 and RSA implementations

This commit is contained in:
Emile Clark-Boman 2025-06-27 03:09:53 +10:00
parent cb1b757ca2
commit c359765855
2 changed files with 25 additions and 0 deletions

7
imp/crypto/hash.py Normal file
View file

@ -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)

18
imp/crypto/rsa.py Normal file
View file

@ -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))