I am using GnuPG. When gpg encrypt is called from the command line, how is a key chosen to do the encryption? It appears to me that -r, or --recipient, supplies a user id and that is the simple answer. I believe all of the examples I have looked at they show an email address for recipient, which is required input when creating your key. However, I was able to create 2 keys with the exact same user name, comment, and email address. How does gpg pick a key if there are two keys that have identical email addresses and that email address is used for the recipient? It seems to me like using key id would be the best way to do this, but I do not see that option.
Often, whenever you provide a filter to a parameter which matches multiple keys, it uses all of them (e.g.
--export). I was expecting it to do the same here. However, a basic check shows that it is not encrypting to all of them, but only to a single key, which is the one imported earliest to the keyring (the selection changes if imported in the other order). The command
--delete-keys acts in the same way as
-r, choosing just the first one present in the keyring.
You may see to which keys it was encrypted (other than by attempting a decrypt) by parsing the actual packets:
echo Hello world | gpg -e -r jdoe | gpg --list-packets
And, as noted by CBHacking, you can use key ids everywhere. Using the textual user ids are actually simplifications for better usability.
Taking a tip from https://lists.gnupg.org/pipermail/gnupg-users/2005-June/026022.html (which I found by searching "GPG duplicate key"), you can specify keys by ID anywhere you specify them at all (such as
gpg -sear 104763A0, which signs, encrypts, and base64-encodes to the recipient whose public key ID matches 104763A0). I tested this on my machine and it worked fine.
I don't know what happens if you try specifying a key that is ambiguous. Likely options are the first key in the key ring (this is what the person at the link above said was happening), the key furthest from expiration, they key you trust most, or some other sort (which might in turn influence the "first in the key ring" thing).