PRACTICAL 5: RSA ALGORITHM

A. RSA ENCRYPT AND DECRYPT
CODE:
from math import gcd

p, q, e = 61, 53, 17
n, phi = p * q, (p - 1) * (q - 1)
while gcd(e, phi) != 1:
    e += 2
d = pow(e, -1, phi)

msg = input("Enter the message:")
cipher = [pow(ord(c), e, n) for c in msg]
plain = ''.join(chr(pow(c, d, n)) for c in cipher)

print("public key:", (e, n))
print("private key:", (d, n))
print(e)
print("original msg:", msg)
print("Encrypted:", cipher)
print("Decrypted:", plain)


B. RSA ASSIGNMENT - DIGITAL SIGNATURE
CODE:
import hashlib
from math import gcd

p, q, e = 61, 53, 17
n, phi = p * q, (p - 1) * (q - 1)
while gcd(e, phi) != 1:
    e += 2
d = pow(e, -1, phi)

msg = input("Enter the msg:")
cipher = [pow(ord(c), e, n) for c in msg]
plain = ''.join(chr(pow(c, d, n)) for c in cipher)

print("public key:", (e, n))
print("private key:", (d, n))
print("original msg:", msg)
print("Encrypted:", cipher)
print("Decrypted:", plain)

h = hashlib.sha256(msg.encode()).hexdigest()
h_int = int(h, 16)
h_mod = h_int % n
sig = pow(h_mod, d, n)
dec_hash = pow(sig, e, n)

print(f"Original msg : '{msg}'")
print(f"Full SHA-256 Hash: {h}")
print(f"Hash Integer : {h_int}")
print(f"Hash (mod n) : {h_mod}\n")
print(f"Digital Signature: {sig}\n")
print(f"Decrypted Hash : {dec_hash}")
print("Verification Result: SUCCESS - Signature is VALID!" if dec_hash == h_mod
      else "Verification Result: FAILED - Invalid signature or tampered message.")
