Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I need assistance utilizing RSA encryption and also decryption in Python. 

I'm making a private/public key pair, encoding a message with keys and composing message to a file. At that point I'm reading ciphertext from document and decrypting text utilizing key.

I'm experiencing difficulty with the decryption segment. As you can find in my code beneath, when I put in decoded = key.decrypt(message) that the program works, yet the decrypted message is encrypted once more. It appears as though it isn't reading the ciphertext from the file. 

Would anyone be able to assist me with composing this code so decryption reads ciphertext from document and afterward utilizes key to decrypt ciphertext?

import Crypto

from Crypto.PublicKey import RSA

from Crypto import Random

random_generator = Random.new().read

key = RSA.generate(1024, random_generator) #generate public and private keys

publickey = key.publickey # pub key export for exchange

encrypted = publickey.encrypt('encrypt this message', 32)

#message to encrypt is in the above line 'encrypt this message'

print 'encrypted message:', encrypted #ciphertext

f = open ('encryption.txt', 'w'w)

f.write(str(encrypted)) #write ciphertext to file

f.close()

#decrypted code below

f = open ('encryption.txt', 'r')

message = f.read()

decrypted = key.decrypt(message)

print 'decrypted', decrypted

f = open ('encryption.txt', 'w')

f.write(str(message))

f.write(str(decrypted))

f.close()

1 Answer

0 votes
by (26.4k points)

To make it work you need to change over key from str to tuple before decryption(ast.literal_eval function). Here is the fixed code:

import Crypto

from Crypto.PublicKey import RSA

from Crypto import Random

import ast

random_generator = Random.new().read

key = RSA.generate(1024, random_generator) #generate pub and priv key

publickey = key.publickey() # pub key export for exchange

encrypted = publickey.encrypt('encrypt this message', 32)

#message to encrypt is in the above line 'encrypt this message'

print 'encrypted message:', encrypted #ciphertext

f = open ('encryption.txt', 'w')

f.write(str(encrypted)) #write ciphertext to file

f.close()

#decrypted code below

f = open('encryption.txt', 'r')

message = f.read()

decrypted = key.decrypt(ast.literal_eval(str(encrypted)))

print 'decrypted', decrypted

f = open ('encryption.txt', 'w')

f.write(str(message))

f.write(str(decrypted))

f.close()

Want to learn python to get expertise in the concepts of python? Join python certification course and get certified

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 20, 2019 in DevOps and Agile by chandra (29.3k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...