Encrypting to One Key
Once the the Context is set the main issues with encrypting data is essentially reduced to
key selection and the keyword arguments specified in the
gpg.Context().encrypt()
method.
Those keyword arguments are:
recipients
, a list of keys encrypted to (covered in greater detail in the following section);sign
, whether or not to sign the plaintext data, see subsequent sections on signing and verifying signatures below (defaults toTrue
);sink
, to write results or partial results to a secure sink instead of returning it (defaults toNone
);passphrase
, only used when utilising symmetric encryption (defaults toNone
);always_trust
, used to override the trust model settings for recipient keys (defaults toFalse
);add_encrypt_to
, utilises any preconfigured encrypt-to or default-key settings in the user's gpg.conf file (defaults toFalse
);prepare
, prepare for encryption (defaults toFalse
);expect_sign
, prepare for signing (defaults toFalse
);compress
, compresses the plaintext prior to encryption (defaults toTrue
).
import gpg a_key = "0x12345678DEADBEEF" text = b"""Some text to test with. Since the text in this case must be bytes, it is most likely that the input form will be a separate file which is opened with "rb" as this is the simplest method of obtaining the correct data format. """ c = gpg.Context(armor=True) rkey = list(c.keylist(pattern=a_key, secret=False)) ciphertext, result, sign_result = c.encrypt(text, recipients=rkey, sign=False) with open("secret_plans.txt.asc", "wb") as f: f.write(ciphertext)
Though this is even more likely to be used like this; with the plaintext input read from a file, the recipient keys used for encryption regardless of key trust status and the encrypted output also encrypted to any preconfigured keys set in the gpg.conf file:
import gpg a_key = "0x12345678DEADBEEF" with open("secret_plans.txt", "rb") as f: text = f.read() c = gpg.Context(armor=True) rkey = list(c.keylist(pattern=a_key, secret=False)) ciphertext, result, sign_result = c.encrypt(text, recipients=rkey, sign=True, always_trust=True, add_encrypt_to=True) with open("secret_plans.txt.asc", "wb") as f: f.write(ciphertext)
If the recipients
paramater is empty then the plaintext is encrypted
symmetrically. If no passphrase
is supplied as a parameter or via a
callback registered with the Context()
then an out-of-band prompt for the
passphrase via pinentry will be invoked.