Question

In: Computer Science

In python Write a program to implement RSA algorithm based on the public key. def encryptmessage():...

In python

Write a program to implement RSA algorithm based on the public key.

def encryptmessage():

def decryptmessage():

encryptmessage ()

decryptmessage ()

No in-built functions and third-party APIs will be allowed.

Solutions

Expert Solution

import math
 
print("RSA ENCRYPTOR/DECRYPTOR")
print("*****************************************************")
 
#Input Prime Numbers
print("PLEASE ENTER THE 'p' AND 'q' VALUES BELOW:")
p = int(input("Enter a prime number for p: "))
q = int(input("Enter a prime number for q: "))
print("*****************************************************")
 
#Check if Input's are Prime
'''THIS FUNCTION AND THE CODE IMMEDIATELY BELOW THE FUNCTION CHECKS WHETHER THE INPUTS ARE PRIME OR NOT.'''
def prime_check(a):
    if(a==2):
        return True
    elif((a<2) or ((a%2)==0)):
        return False
    elif(a>2):
        for i in range(2,a):
            if not(a%i):
                return false
    return True
 
check_p = prime_check(p)
check_q = prime_check(q)
while(((check_p==False)or(check_q==False))):
    p = int(input("Enter a prime number for p: "))
    q = int(input("Enter a prime number for q: "))
    check_p = prime_check(p)
    check_q = prime_check(q)
 
#RSA Modulus
'''CALCULATION OF RSA MODULUS 'n'.'''
n = p * q
print("RSA Modulus(n) is:",n)
 
#Eulers Toitent
'''CALCULATION OF EULERS TOITENT 'r'.'''
r= (p-1)*(q-1)
print("Eulers Toitent(r) is:",r)
print("*****************************************************")
 
#GCD
'''CALCULATION OF GCD FOR 'e' CALCULATION.'''
def egcd(e,r):
    while(r!=0):
        e,r=r,e%r
    return e
 
#Euclid's Algorithm
def eugcd(e,r):
    for i in range(1,r):
        while(e!=0):
            a,b=r//e,r%e
            if(b!=0):
                print("%d = %d*(%d) + %d"%(r,a,e,b))
            r=e
            e=b
 
#Extended Euclidean Algorithm
def eea(a,b):
    if(a%b==0):
        return(b,0,1)
    else:
        gcd,s,t = eea(b,a%b)
        s = s-((a//b) * t)
        print("%d = %d*(%d) + (%d)*(%d)"%(gcd,a,t,s,b))
        return(gcd,t,s)
 
#Multiplicative Inverse
def mult_inv(e,r):
    gcd,s,_=eea(e,r)
    if(gcd!=1):
        return None
    else:
        if(s<0):
            print("s=%d. Since %d is less than 0, s = s(modr), i.e., s=%d."%(s,s,s%r))
        elif(s>0):
            print("s=%d."%(s))
        return s%r
 
#e Value Calculation
'''FINDS THE HIGHEST POSSIBLE VALUE OF 'e' BETWEEN 1 and 1000 THAT MAKES (e,r) COPRIME.'''
for i in range(1,1000):
    if(egcd(i,r)==1):
        e=i
print("The value of e is:",e)
print("*****************************************************")
 
#d, Private and Public Keys
'''CALCULATION OF 'd', PRIVATE KEY, AND PUBLIC KEY.'''
print("EUCLID'S ALGORITHM:")
eugcd(e,r)
print("END OF THE STEPS USED TO ACHIEVE EUCLID'S ALGORITHM.")
print("*****************************************************")
print("EUCLID'S EXTENDED ALGORITHM:")
d = mult_inv(e,r)
print("END OF THE STEPS USED TO ACHIEVE THE VALUE OF 'd'.")
print("The value of d is:",d)
print("*****************************************************")
public = (e,n)
private = (d,n)
print("Private Key is:",private)
print("Public Key is:",public)
print("*****************************************************")
 
#Encryption
'''ENCRYPTION ALGORITHM.'''
def encrypt(pub_key,n_text):
    e,n=pub_key
    x=[]
    m=0
    for i in n_text:
        if(i.isupper()):
            m = ord(i)-65
            c=(m**e)%n
            x.append(c)
        elif(i.islower()):               
            m= ord(i)-97
            c=(m**e)%n
            x.append(c)
        elif(i.isspace()):
            spc=400
            x.append(400)
    return x
     
 
#Decryption
'''DECRYPTION ALGORITHM'''
def decrypt(priv_key,c_text):
    d,n=priv_key
    txt=c_text.split(',')
    x=''
    m=0
    for i in txt:
        if(i=='400'):
            x+=' '
        else:
            m=(int(i)**d)%n
            m+=65
            c=chr(m)
            x+=c
    return x
 
#Message
message = input("What would you like encrypted or decrypted?(Separate numbers with ',' for decryption):")
print("Your message is:",message)
 
#Choose Encrypt or Decrypt and Print
choose = input("Type '1' for encryption and '2' for decrytion.")
if(choose=='1'):
    enc_msg=encrypt(public,message)
    print("Your encrypted message is:",enc_msg)
    print("Thank you for using the RSA Encryptor. Goodbye!")
elif(choose=='2'):
    print("Your decrypted message is:",decrypt(private,message))
    print("Thank you for using the RSA Encryptor. Goodbye!")
else:
    print("You entered the wrong option.")
    print("Thank you for using the RSA Encryptor. Goodbye!")

output:

PLEASE ENTER THE 'p' AND 'q' VALUES BELOW:
Enter a prime number for p: 3
Enter a prime number for q: 5
*****************************************************
RSA Modulus(n) is: 15
Eulers Toitent(r) is: 8
*****************************************************
The value of e is: 999
*****************************************************
EUCLID'S ALGORITHM:
8 = 0*(999) + 8
999 = 124*(8) + 7
8 = 1*(7) + 1
END OF THE STEPS USED TO ACHIEVE EUCLID'S ALGORITHM.
*****************************************************
EUCLID'S EXTENDED ALGORITHM:
1 = 8*(1) + (-1)*(7)
1 = 999*(-1) + (125)*(8)
s=-1. Since -1 is less than 0, s = s(modr), i.e., s=7.
END OF THE STEPS USED TO ACHIEVE THE VALUE OF 'd'.
The value of d is: 7
*****************************************************
Private Key is: (7, 15)
Public Key is: (999, 15)
*****************************************************
What would you like encrypted or decrypted?(Separate numbers with ',' for decryption):HELLO
Your message is: HELLO
Type '1' for encryption and '2' for decrytion.1
Your encrypted message is: [13, 4, 11, 11, 14]
Thank you for using the RSA Encryptor. Goodbye!
PLEASE ENTER THE 'p' AND 'q' VALUES BELOW:
Enter a prime number for p: 3
Enter a prime number for q: 5
*****************************************************
RSA Modulus(n) is: 15
Eulers Toitent(r) is: 8
*****************************************************
The value of e is: 999
*****************************************************
EUCLID'S ALGORITHM:
8 = 0*(999) + 8
999 = 124*(8) + 7
8 = 1*(7) + 1
END OF THE STEPS USED TO ACHIEVE EUCLID'S ALGORITHM.
*****************************************************
EUCLID'S EXTENDED ALGORITHM:
1 = 8*(1) + (-1)*(7)
1 = 999*(-1) + (125)*(8)
s=-1. Since -1 is less than 0, s = s(modr), i.e., s=7.
END OF THE STEPS USED TO ACHIEVE THE VALUE OF 'd'.
The value of d is: 7
*****************************************************
Private Key is: (7, 15)
Public Key is: (999, 15)
*****************************************************
What would you like encrypted or decrypted?(Separate numbers with ',' for decryption):13,4,11,11,14
Your message is: 13,4,11,11,14
Type '1' for encryption and '2' for decrytion.2
Your decrypted message is: HELLO
Thank you for using the RSA Encryptor. Goodbye!

Related Solutions

Write a GUI based Python program that will allow the user to perform (i) generate RSA...
Write a GUI based Python program that will allow the user to perform (i) generate RSA keys, (ii) encrypt a given message and (iii) decrypt the message without using any cryptographic library. Your program will generate the values of p unless the user provides them manually. Then the program will generate the keys (private and public). Then the program will allow the user to enter his/her message to be encrypted. Finally, the program will perform the decryption operation as well....
Java/Python/C++ Assignment Write a program to implement one round of AES-128 Input is the key and...
Java/Python/C++ Assignment Write a program to implement one round of AES-128 Input is the key and plaintext a. Show the plaintext as a 4x4 matrix b. Show the result after adding RoundKey0 c. Show the result after SubBytes d. Show the result after ShiftRows e. Show the result after MixColumns f. Show the result after first round
Write a Python program that: Create the algorithm in both flowchart and pseudocode forms for the...
Write a Python program that: Create the algorithm in both flowchart and pseudocode forms for the following requirements: Reads in a series of positive integers,  one number at a time;  and Calculate the product (multiplication) of all the integers less than 25,  and Calculate the sum (addition) of all the integers greater than or equal to 25. Use 0 as a sentinel value, which stops the input loop. [ If the input is 0 that means the end of the input list. ]...
Write a design algorithm and a python program which asks the user for the length of...
Write a design algorithm and a python program which asks the user for the length of the three sides of two triangles. It should compute the perimeter of the two triangles and display it. It should also display which triangle has the greater perimeter. If both have the same perimeter it should display that the perimeters are the same. Formula: Perimeter of triangleA = (side1A + side2A +side3A) See the 2 sample outputs. Enter side1 of TriangleA: 2 Enter side2...
Python English algorithm explanation Write a program that asks the user for the name of a...
Python English algorithm explanation Write a program that asks the user for the name of a file in the current directory. Then, open the file and process the content of the file. 1)If the file contains words that appear more than once, print “We found duplicates.” 2)If the file does not contain duplicate words, print “There are no duplicates.”
Python English algorithm explanation Write a program that asks the user for the name of a...
Python English algorithm explanation Write a program that asks the user for the name of a file in the current directory. Then, open the file and process the content of the file. 1)If the file contains words that appear more than once, print “We found duplicates.” 2)If the file does not contain duplicate words, print “There are no duplicates.”
Implement the CPU scheduling algorithm MLFQ in python. Have the program answer the table. Multilevel Feedback...
Implement the CPU scheduling algorithm MLFQ in python. Have the program answer the table. Multilevel Feedback Queue (absolute priority in higher queues)             Queue 1 uses RR scheduling with Tq = 5             Queue 2 uses RR scheduling with Tq = 10             Queue 3 uses FCFS All processes enter first queue 1. If time quantum (Tq) expires before CPU burst is complete, the process is downgraded to next lower priority queue. Processes are not downgraded when preempted by a...
In Python write a function with prototype “def dictsort(d):” which will return a list of key-value...
In Python write a function with prototype “def dictsort(d):” which will return a list of key-value pairs of the dictionary as tuples (key, value), reverse sorted by value (highest first) and where multiple keys with the same value appear alphabetically (lowest first).
a) In a public-key system using RSA, n=77 and its public key is e=23. What is...
a) In a public-key system using RSA, n=77 and its public key is e=23. What is the private key d? Show your steps of calculation. b) Let M=3. Compute its cipher text under the above RSA. Please use the divide conquer algorithm to compute the exponential function for the cipher text.
given a hash finction H(), and an RSA encrypting algorithm. The public and private keys for...
given a hash finction H(), and an RSA encrypting algorithm. The public and private keys for Alice are PUa, and PRa, respectively. A. Describe how Alice can produce a digital siguature of a message "M. and how Bob can verify the sigature. B. Does the process described in part (a) above provide authentication? Give reason.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT