RSA encryption and decryption

asked 2021-05-03 06:17:38 +0200

updated 2021-05-03 23:56:53 +0200

slelievre gravatar image

''' I have the RSA code, code works when we give input to encryption and take decryption output (plaintext and output are same), but when we encrypt plaintext separately and take its output and give it to decryption code as input separately, the output, is not the same as encryption input (plaintext and output are not same). Can someone please explain why is this happening? '''

import sympy
from datetime import datetime
from sage.all import ZZ, GF
start_time =
print("RSA Encryption and Decryption")
print("Values of 'p' AND 'q' are as follows:")
p = sympy.randprime(2, 100)               #Input Prime Number
print ("p = ", p)
q = sympy.randprime(2, 100)               #Input Prime Number
print ("q = ", q)
s = sympy.randprime(2, 100)               #Input Prime Number
print ("s = ", s)

n = p * q * s
print ("RSA Modulus,n = ",n)           #RSA Modulus
r = (p-1)*(q-1)*(s-1)                         #Eulers Toitent
e = ZZ.random_element(r)
while gcd(e, r) != 1:                 #GCD
    e = ZZ.random_element(r)          #e Value Calculation
print ("Public Key = ", e)
bezout = xgcd(e, r);
d = Integer(mod(bezout[1], r));       #d, Private Key
print ("d =", d)
text = 'samu'
print ("Message, m = ", text)
m = [ord(c) for c in text]
c = [power_mod(i, e, n) for i in m]    #Encryption
cipher = [chr(a) for a in c]
print ("Ciphertext, cipher =", cipher)


cipher = input("Enter Cipher text to be decrypted")   #cipher input
print('Cipher text to be decrypted :', cipher) '''
c = [ord(a) for a in cipher]    #conversion of cipher text to the list of ascii values c

print('c =',c)

d = [power_mod(j, d, n) for j in c]    #Decryption
print('d =',d)

characters = [chr(ascii) for ascii in d]
print ("Decrypted text, d = ", ''.join(characters))
print ("Plaintext/ Message,  m = ", text)
print ("Decrypted Message,   d = ", ''.join(characters))
if(text == ''.join(characters)):
    print ("Thus we encrypted and decrypted text using RSA algorithm")
    print("Not sucessfull")

end_time =
print('Time taken for execution of the program: {} '.format(end_time - start_time))
edit retag flag offensive close merge delete


The code works fine for me. What is your concern?

Max Alekseyev gravatar imageMax Alekseyev ( 2021-05-04 16:11:49 +0200 )edit

yes code works but if you encrypt separately, and decrypt its output separately what you get is not plaintext.

moreofsaaamu gravatar imagemoreofsaaamu ( 2021-05-07 08:35:05 +0200 )edit

Can you illustrate this discrepancy with an actual example?

Max Alekseyev gravatar imageMax Alekseyev ( 2021-05-10 01:45:34 +0200 )edit