Search code examples
pythongnupg

Python: Symmetric Encryption with GPG and Subprocess


I'm trying to achieve the functionality provided by the following bash command in Python.

echo "$DATA" | gpg --symmetric --armor --batch --passphrase "${KEY}"

So far I've tried to use subprocess but am having difficulty passing in the data. I tried giving it as a command in the list of parameters to send to subprocess but that just effectively echos the the entire thing.

cmd = f"| gpg --symmetric --armor --batch --passphrase {key}".split()                                                  
temp = ["echo", f"\"{data}\""]
temp.extend(cmd)                                                                                                                      
res = subprocess.run(temp, stdout=subprocess.PIPE, universal_newlines=True)                                                          
encrypted = res.stdout.strip()

I'm also interested in using the python-gnupg module but have not yet figured out how to replicate the above with it either.

Thanks in advance for any help!


Solution

  • You can use the input argument to run()/check_output():

    from getpass import getpass
    import subprocess
    
    key = getpass("KEY: ")
    data = b'Symmetric Encryption with GPG and Subprocess'
    command = ["gpg", "--symmetric", "--armor", "--batch", "--passphrase", key]
    
    out = subprocess.check_output(command, input=data, universal_newlines=False)
    

    Note that GNU echo will, by default, append a newline. Use echo -n to not print the trailing \n. Either way, you'll want to be careful to mimic this in Python.