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:
- gpg --decrypt -a
- Then it prompts you for the encrypted message
- Then it prompts for private key.
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")
...?
To input the encrypted string, you can
echo
it out first then pipe in thegpg
command.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
:The Python code will then look something like this:
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.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>
withcat <filepath>
: