Search code examples
pythonpgp

pgpy key.decrypt is not returning decrypted text


I have a block of code that should open a pgp encrypted file, decrypt it using a private key, and then output the decrypted message to a text file. I have confirmed using GnuPG that the private key is able to decrypt both the original message and the output message, so I believe that the message and key are loading correctly and that the message is being decrypted, but for some reason, the output is being re-encrypted. I'm newish to python so I might be overlooking something simple.

    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)

EDIT This is the entire code, including the function that generates the keys, in case there is something wrong outside of the decryption function.

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()

Solution

  • For anyone who stumbles upon this, I found out what I was doing wrong. This answer worked for me. It seems that switching

    str_decrypted_message = str(decrypted_message)
    

    to

    str_decrypted_message = decrypted_message.message 
    

    solved my problem.