3
votes

I want to create a programm that can encrypt and decrypt messages and also create pgp public and private keys. The encryption process and the process of creating the keys work. However, the decryption process does not work because for some reason pgpy does not recognise that the message is encrypted.

Minimum example:

def decrypt(private_key_file,secret_phrase,emsg):
    print("message is encrypted: "+str(emsg.is_encrypted))
    private_key,_=pgpy.PGPKey.from_file(private_key_file)
    with private_key.unlock(secret_phrase):
        return str(private_key.decrypt(emsg))

message_to_encode_or_decode=input("Please enter the message to decode: ")

emsg=pgpy.PGPMessage.new(message_to_encode_or_decode,file=is_from_file)
#In this line, you can see that emsg.is_encrypted returns False and I can't figure out why
print("Message: \n"+str(emsg.is_encrypted)+"\n"+message_to_encode_or_decode)

private_key_file=input("Please enter the path to your private key file: ")
password=getpass.getpass("please enter the key's pass phrase: ")
decrypted=decrypt(private_key_file,password,emsg)
print(decrypted)

I expect to receive the message I encrypted, but I receive the original message. I checked the source code of the pgpy and the problem seems to be that the message is not recognised as encrypted.

1

1 Answers

1
votes

I know it has been a while since you posted this question but it helped me work out some PGPy questions of my own and I thought it might be useful for the next person who finds it if I posted a possible answer.

import pgpy
import getpass

def decrypt(private_key_file,secret_phrase,emsg):
    print("message is encrypted: "+str(emsg.is_encrypted))
    private_key,_=pgpy.PGPKey.from_file(private_key_file)
    with private_key.unlock(secret_phrase):
        return ((private_key.decrypt(emsg)).message).decode('utf-8')

message_to_encode_or_decode=input("Please enter the message to decode: ")

emsg=pgpy.PGPMessage.from_file(message_to_encode_or_decode)
#In this line, you can see that emsg.is_encrypted returns False and I can't figure out why
print("Message: \nEncrypted (True/False): "+str(emsg.is_encrypted)+"\nFilename: "+message_to_encode_or_decode)

private_key_file=input("Please enter the path to your private key file: ")
password=getpass.getpass("please enter the key's pass phrase: ")
decrypted=decrypt(private_key_file,password,emsg)
print(decrypted)

Without the `decode('utf-8') my sample was returning a bytearray rather than a string.