Jakub Pastuszuk
Jakub Pastuszuk

Reputation: 1038

PythonGnuPG generate keys, encrypt and decrypt a message

Using Python-GnuPG I want to

  1. Create PGP keys
  2. Encrypt a message
  3. Decrypt a message

Currently code looks following:

import string
import random
import gnupg

random_string_length = 20
random_gpg_key_passphrase = "".join(
        random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(random_string_length))

gpg = gnupg.GPG(homedir="gpg")
cs_gpg_key_input_dict = {
    "key_type":  "RSA",
    "key_length": 4096,
    "passphrase": random_gpg_key_passphrase
}
python_gnupg_key_generation_input_data = gpg.gen_key_input(**cs_gpg_key_input_dict)
gpg_key_pair = gpg.gen_key(python_gnupg_key_generation_input_data)

encrypted_data = gpg.encrypt("message", gpg_key_pair.fingerprint,
                                             passphrase=random_gpg_key_passphrase, always_trust=True)

msg = str(encrypted_data)
decrypted_data = gpg.decrypt(msg, passphrase=random_gpg_key_passphrase, always_trust=True)

Unfortunately, the encryption returns error:

raise ValueError("Unknown status message: %r" % key)
ValueError: Unknown status message: 'ENCRYPTION_COMPLIANCE_MODE'

Yet it still generates encryption ASCII armour message Hovewer decryption results in Crypt object with False bool value of ok property and following stderr property:

[GNUPG:] ENC_TO <XXX> 1 0
[GNUPG:] KEY_CONSIDERED <YYY> 0
[GNUPG:] PINENTRY_LAUNCHED 7570 gnome3:curses 1.1.0 - - :0
[GNUPG:] KEY_CONSIDERED <YYY> 0
gpg: encrypted with 4096-bit RSA key, ID <XXX>, created 2019-10-01
      "ZZZ"
gpg: public key decryption failed: Inappropriate ioctl for device
[GNUPG:] ERROR pkdecrypt_failed <QQQ>
[GNUPG:] BEGIN_DECRYPTION
[GNUPG:] DECRYPTION_FAILED
gpg: decryption failed: No secret key
[GNUPG:] END_DECRYPTION

Not sure where exactly error occurs and how to handle it

Upvotes: 4

Views: 2784

Answers (1)

Jakub Pastuszuk
Jakub Pastuszuk

Reputation: 1038

After hours of looking, I've found that it is needed to add --pinentry-mode loopback option to gpg init as follows:

cs_gpg_options = ['--pinentry-mode loopback']
gpg = gnupg.GPG(homedir="gpg", options=cs_gpg_options)

After that, encryption/decryption process should succeed (note that, stderr is still produced as it is whole output of GPG tool)

Upvotes: 5

Related Questions