Prac 5:RSA Algorithm
Code:-
def gcd(a,b):
    while b:
        a,b=b,a%b
    return a
def mod_inverse(e,phi):
    for d in range(1,phi):
        if (e*d)%phi==1:
            return d
    return None
def encrypt(public_key,plaintext):
    e,n=public_key
    cipher=[pow(ord(char),e,n) for char in plaintext]
    return cipher
def decrypt(private_key,ciphertext):
    d,n=private_key
    plain=''.join(chr(pow(char,d,n))for char in ciphertext)
    return plain
p=61
q=53
n=p*q
phi=(p-1)*(q-1)
e=17
while gcd(e,phi)!=1:
    e+=2
d=mod_inverse(e,phi)
public_key=(e,n)
private_key=(d,n)
msg=input("Enter the message:")
cipher_text=encrypt(public_key,msg)
decrypted_text=decrypt(private_key,cipher_text)
print("public key:",public_key)
print("private key:",private_key)
print(e)
print("original msg:",msg)
print("Encrypted:",cipher_text)
print("Decrypted:",decrypted_text)
Output:-
RSA Assingment:-
Code:-
import hashlib
def gcd(a,b):
    while b:
        a,b=b,a%b
    return a
def mod_inverse(e,phi):
    for d in range(1,phi):
        if (e*d)%phi==1:
            return d
    return None
def encrypt(public_key,plaintext):
    e,n=public_key
    cipher=[pow(ord(char),e,n) for char in plaintext]
    return cipher
def decrypt(private_key,ciphertext):
    d,n=private_key
    plain=''.join(chr(pow(char,d,n))for char in ciphertext)
    return plain
p=61
q=53
n=p*q
phi=(p-1)*(q-1)
e=17
while gcd(e,phi)!=1:
    e+=2
d=mod_inverse(e,phi)
public_key=(e,n)
private_key=(d,n)
msg=input("Enter the msg:")
cipher_text=encrypt(public_key,msg)
decrypted_text=decrypt(private_key,cipher_text)
print("public key:",public_key)
print("private key:",private_key)
print("original msg:",msg)
print("Encrypted:",cipher_text)
print("Decrypted:",decrypted_text)
hash_hex = hashlib.sha256(msg.encode('utf-8')).hexdigest()
hash_int = int(hash_hex, 16)
hash_int_mod = hash_int % n
print(f"Original msg : '{msg}'")
print(f"Full SHA-256 Hash: {hash_hex}")
print(f"Hash Integer     : {hash_int}")
print(f"Hash (mod n)     : {hash_int_mod}\n")
signature = pow(hash_int_mod, d, n)
print(f"Digital Signature: {signature}\n")
decrypted_hash = pow(signature, e, n)
print(f"Decrypted Hash   : {decrypted_hash}")
if decrypted_hash == hash_int_mod:
    print("Verification Result: SUCCESS - Signature is VALID!")
else:
    print("Verification Result: FAILED - Invalid signature or tampered message.")
Output:-
