RSA 加密:解密函数出错
RSA encryption: error on decryption function
首先post在这里。这也是我第一次在 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
中。
以前,该变量仍会包含您的加密过程中的数据(当加密和解密在同一函数中执行时)。
首先post在这里。这也是我第一次在 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
中。
以前,该变量仍会包含您的加密过程中的数据(当加密和解密在同一函数中执行时)。