[英]RSA encryption: error on decryption function
在这里的第一篇文章。 这也是我第一次使用Python进行编码。
我的RSA加密python项目确实需要帮助。
如果将解密转换为函数,则解密会显示错误的密钥错误。 (错误:错误的密钥?)但是,当我将解密功能加入加密功能时,它可以工作并解密我已加密的消息。
我可以问为什么吗? (我正在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()
在新的decrypt()
函数中, CipherText
成为一个新变量。 您需要将您在encrypt()
写入的文件内容重新加载到CipherText
。
以前,该变量仍将包含来自加密过程的数据(当在同一函数中执行加密和解密时)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.