0% found this document useful (0 votes)
12 views4 pages

Is 3

The document provides a Python implementation of the RSA algorithm, including functions for key generation, encryption, and decryption. It prompts the user for two prime numbers and plaintext, then outputs the ciphertext and decrypted text. The code also includes error handling for invalid escape sequences.

Uploaded by

Laksh Desai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views4 pages

Is 3

The document provides a Python implementation of the RSA algorithm, including functions for key generation, encryption, and decryption. It prompts the user for two prime numbers and plaintext, then outputs the ciphertext and decrypted text. The code also includes error handling for invalid escape sequences.

Uploaded by

Laksh Desai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

IS practical NO:3

Input
"""

Write a Java/C/C++/Python program to implement RSA algorithm.

"""

import random

def gcd(a, b):

while b != 0:

a, b = b, a % b

return a

def generate_keypair(p, q):

n=p*q

phi = (p - 1) * (q - 1)

e = random.randrange(1, phi)

# print("e=",e)

g = gcd(e, phi)

while g != 1:

e = random.randrange(1, phi)

g = gcd(e, phi)

d = multiplicative_inverse(e, phi)

return ((e, n), (d, n))

def multiplicative_inverse(e, phi):


d=0

x1 = 0

x2 = 1

y1 = 1

temp_phi = phi

while e > 0:

temp1 = temp_phi // e

temp2 = temp_phi - temp1 * e

temp_phi = e

e = temp2

x = x2 - temp1 * x1

y = d - temp1 * y1

x2 = x1

x1 = x

d = y1

y1 = y

if temp_phi == 1:

return d + phi

def encrypt(public_key, plaintext):

key, n = public_key

cipher = [(ord(char) ** key) % n for char in plaintext]

return cipher

def decrypt(private_key, ciphertext):


key, n = private_key

plain = [chr((char ** key) % n) for char in ciphertext]

return ''.join(plain)

p = int(input("Enter first Prime No. .: "))

q = int(input("Enter Second Prime No.: "))

public_key, private_key = generate_keypair(p, q)

plaintext = input("Enter PlainText: ")

ciphertext = encrypt(public_key, plaintext)

decrypted_text = decrypt(private_key, ciphertext)

print("Plaintext:", plaintext)

print("Ciphertext:", ciphertext)

print("Decrypted text:", decrypted_text)

output:

<main.py>:67: SyntaxWarning: invalid escape sequence '\S'

Enter first Prime No. .: 23

Enter Second Prime No.: 17

Enter PlainText: Mahadev Mundhe

Plaintext: Mahadev Mundhe

Ciphertext: [59, 337, 32, 337, 36, 118, 16, 325, 59, 87, 77, 36, 32, 118]

Decrypted text: Mahadev Mundhe

You might also like