Search code examples
python-3.xubuntuencryptiongnupg

How to pass encrypted message and passphrase when using `os.system` to call gpg?


I have an encrypted message as a string in python. I want to decrypt it with a program called gpg.

In terminal, using gpg requires:

  1. gpg --decrypt -a
  2. Then it prompts you for the encrypted message
  3. Then it prompts for private key.

enter image description here

Is there a way to do all of this in python when the encrypted message is saved in a variable in python? I know you use the os module to make terminal commands to other programs.

import os
import getpass
message = '093j0rawrkj2or2r'
private_key = getpass.getpass()
os.system("gpg --decrypt -a")
...?

Solution

  • To input the encrypted string, you can echo it out first then pipe in the gpg command.

    echo <message> | gpg --decrypt ...
    

    To input the passphrase, there are a number of ways depending on your env and gpg version. What worked on my Ubuntu 18.04.2 with gpg 2.2.4 was to use --pinentry-mode=loopback and then passing in --passphrase:

    gpg --decrypt -a --pinentry-mode=loopback --passphrase="yourpassphrase" 
    

    The Python code will then look something like this:

    import os
    
    message = '093j0rawrkj2or2r'
    command = "echo '{}' | gpg --decrypt -a --pinentry-mode=loopback --passphrase=yourpassphrase".format(message)
    os.system(command)
    

    But putting the actual --passphrase-yourpassphrase is very insecure. An alternative is to put the passphrase in some file then use --passphrase-file option instead.

    import os
    
    message = '093j0rawrkj2or2r'
    command = "echo '{}' | gpg --decrypt -a --pinentry-mode=loopback --passphrase-file=yourpassphrasefile".format(message)
    os.system(command)
    

    I don't know where you got the encrypted message, but I usually work with encrypted files. If the encrypted input is from a file, just replace echo <string> with cat <filepath>:

    cat somefile.txt | gpg --decrypt -a --pinentry-mode=loopback --passphrase-file=yourpassphrasefile