neuhalje / bouncy-gpg

Make using Bouncy Castle with OpenPGP fun again!
https://neuhalje.github.io/bouncy-gpg/
Other
205 stars 58 forks source link

KeySelection using Realname. #68

Open GiuseppeMP opened 2 years ago

GiuseppeMP commented 2 years ago

Hello everyone,

Describe the bug I'm cannot use legacy keys that have been generated without email.

To Reproduce Try to use keys generated without Email, just Realname. in GPG shell works, in java throws no key suitable found.

Expected behavior Find the Key by the RealName if email is not present.

Additional context To resolve it in my project, I implemented this strategy:

public class ByEmailKeyAndJustRealnameKeySelectionStrategy extends Rfc4880KeySelectionStrategy {

    private static final String ENTRE_BRACKETS = "<.*>";

    /**
     * @param dateOfTimestampVerification The date used for key expiration date
     *                                    checks as "now".
     */
    public ByEmailKeyAndJustRealnameKeySelectionStrategy() {
        super(Instant.now(), true, true);
    }

    /**
     * Return all keyrings that ARE valid keys for the given uid.
     *
     * If the uid does not already include '&lt;...&gt;' then wrap it in
     * "&lt;uid&gt;"
     * to filter for e-mails. E.g. "peter@example.com" will be converted to
     * "&lt;peter@example.com&gt;" but "Klaus &lt;klaus@example.com&gt;" or
     * "&lt;klaus@example.com&gt;" will be left untouched.
     * If the uids does not match with email format; will be left untouched.
     *
     * @param uid           the userid as passed by upstream.
     * @param keyringConfig the keyring config
     * @param purpose       what is the requested key to be used for
     *
     * @return Set with keyrings, never null.
     *
     * @throws PGPException Something with BouncyCastle went wrong
     * @throws IOException  IO is dangerous
     */
    @SuppressWarnings({ "PMD.LawOfDemeter" })
    @Override
    protected Set<PGPPublicKeyRing> publicKeyRingsForUid(final PURPOSE purpose, final String uid,
            KeyringConfig keyringConfig)
            throws IOException, PGPException {

        final Set<PGPPublicKeyRing> keyringsForUid = new HashSet<>();

        String uidQuery = uid;
        final boolean uidAlreadyInBrackets = uidAlreadyInBrackets(uid);
        final boolean isValidEmail = JMail.isValid(uid);

        if (!uidAlreadyInBrackets && isValidEmail) {
            uidQuery = "<" + uid + ">";
        }

        final Iterator<PGPPublicKeyRing> keyRings = keyringConfig.getPublicKeyRings()
                .getKeyRings(uidQuery, true, true);

        while (keyRings.hasNext()) {
            keyringsForUid.add(keyRings.next());
        }

        return keyringsForUid;
    }

    protected boolean uidAlreadyInBrackets(String uid){
        return uid.matches(ENTRE_BRACKETS);
    }

I wondering if this make sense (is it correct) and if open an Issue/Merge worths. Any thoughts?