pythonpython-2.7encryptionrsam2crypto

RSA encryption: error on decryption function


First post here. It is also my first time on coding on Python.

I really need help for my RSA encryption python project.

My decryption shows my wrong key error if I turn the decryption into a function. (Error: wrong key?) But when i join the decrypt function into my encrypt function, it works and decrypts the message that i have been encrypted.

Can I ask why? (I'm running it on Linux Ubuntu)

 import os
 import M2Crypto

def encrypt():

   pubkey = (raw_input('Enter choosen public key:'))
   loadpub = M2Crypto.RSA.load_pub_key (pubkey + '-public.pem')

   encrypt = (raw_input('Enter message to decrypt:'))
   CipherText = loadpub.public_encrypt (encrypt, M2Crypto.RSA.pkcs1_oaep_padding)

   print "Encrypted message:"
   print CipherText.encode ('base64')
   f = open ('encryption.txt', 'w')
   f.write(str(CipherText.encode ('base64'))) #write ciphertext to file
   f.close()

def decrypt():
   privkey = (raw_input('Enter choosen private key:'))
   loadprivkey = M2Crypto.RSA.load_key (privkey + '-private.pem')

   try:
    PlainText = loadprivkey.private_decrypt (CipherText, M2Crypto.RSA.pkcs1_oaep_padding)
   except:
    print "Error: wrong key?"
    PlainText = ""

   if PlainText != "":
    print "Message decrypted by " + privkey + " :"
    print PlainText

 def first():
  print "Press 1 for encryption."
  print "Press 2 for decryption."
  qwe = (raw_input(''))
  if qwe == '1':
    encrypt()
    first()
  elif qwe == '2':
    decrypt()
    first()
  else: 
    print "Please enter a correct number"
    first()

  if __name__ == '__main__':
    first()

Solution

  • In your new decrypt() function, CipherText becomes a new variable. You need to reload the contents of the file you wrote to in encrypt() into CipherText.

    Previously, the variable would've still contained the data from your encryption process (when encryption and decryption were performed in the same function).