简体   繁体   English

RSA加密:解密功能出错

[英]RSA encryption: error on decryption function

First post here. 在这里的第一篇文章。 It is also my first time on coding on Python. 这也是我第一次使用Python进行编码。

I really need help for my RSA encryption python project. 我的RSA加密python项目确实需要帮助。

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) (我正在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()

In your new decrypt() function, CipherText becomes a new variable. 在新的decrypt()函数中, CipherText成为一个新变量。 You need to reload the contents of the file you wrote to in encrypt() into CipherText . 您需要将您在encrypt()写入的文件内容重新加载到CipherText

Previously, the variable would've still contained the data from your encryption process (when encryption and decryption were performed in the same function). 以前,该变量仍将包含来自加密过程的数据(当在同一函数中执行加密和解密时)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM