我有一段代码,可以打开一个pgp加密文件,使用私钥对其进行解密,然后将解密后的消息输出到一个文本文件。我已经使用GnuPG确认私钥能够对原始消息和输出消息进行解密,因此我相信消息和密钥加载正确,消息正在解密,但由于某种原因,输出正在重新加密。我是python新手,所以我可能忽略了一些简单的东西
key, _ = pgpy.PGPKey.from_file(key_file.name)
encrypted_message = pgpy.PGPMessage.from_file(input_file.name)
decrypted_message = key.decrypt(encrypted_message)
str_decrypted_message = str(decrypted_message)
output_file.write(str_decrypted_message)
编辑 这是完整的代码,包括生成密钥的函数,以防解密函数之外出现错误
def pgp_gen(userid, pgpcomment, mail, priv_key_file='priv_key_file.acs', pub_key_file='pub_key_file.gpg'):
key = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 4096)
uid = pgpy.PGPUID.new(userid, comment=pgpcomment, email=mail)
key.add_uid(uid, usage={KeyFlags.Sign, KeyFlags.EncryptCommunications, KeyFlags.EncryptStorage},
hashes=[HashAlgorithm.SHA256, HashAlgorithm.SHA384, HashAlgorithm.SHA512, HashAlgorithm.SHA224],
ciphers=[SymmetricKeyAlgorithm.AES256, SymmetricKeyAlgorithm.AES192, SymmetricKeyAlgorithm.AES128],
compression=[CompressionAlgorithm.ZLIB, CompressionAlgorithm.BZ2, CompressionAlgorithm.ZIP, CompressionAlgorithm.Uncompressed])
subkey = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 4096)
key.add_subkey(subkey, usage={KeyFlags.Authentication})
keystr = str(key)
pubkeystr = str(key.pubkey)
tmp_file = open(pub_key_file, 'w')
tmp_file.write(pubkeystr)
tmp_file.close()
tmp_file = open(priv_key_file, 'w')
tmp_file.write(keystr)
tmp_file.close()
sys.exit()
def pgp_en(encrypt, input_file, output_file, key_file):
if(encrypt):
key, _ = pgpy.PGPKey.from_file(key_file.name)
file_message = pgpy.PGPMessage.new(input_file.name, file=True)
encrypted_file_message = key.encrypt(file_message)
output_file.write(str(encrypted_file_message))
sys.exit()
else:
key, _ = pgpy.PGPKey.from_file(key_file.name)
encrypted_message = pgpy.PGPMessage.from_file(input_file.name)
decrypted_message = key.decrypt(encrypted_message)
str_decrypted_message = str(decrypted_message)
output_file.write(str_decrypted_message)
sys.exit()
对于任何一个偶然发现这一点的人,我发现了我做错了什么This答案对我有用。看来,转换
到
解决了我的问题
相关问题 更多 >
编程相关推荐