I am trying to get key id from PGP public key. After a lot of google search, I found one solution to read public keys using Bouncy Castle java APIs.
Code snippet for same is as follows:
public static PGPPublicKey readPublicKey(InputStream in) throws IOException, PGPException {
in = org.bouncycastle.openpgp.PGPUtil.getDecoderStream(in);
PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in);
PGPPublicKey key = null;
//
// iterate through the key rings.
//
Iterator<PGPPublicKeyRing> rIt = pgpPub.getKeyRings();
while (key == null && rIt.hasNext()) {
PGPPublicKeyRing kRing = rIt.next();
Iterator<PGPPublicKey> kIt = kRing.getPublicKeys();
while (key == null && kIt.hasNext()) {
PGPPublicKey k = kIt.next();
if (k.isEncryptionKey()) {
key = k;
}
}
}
if (key == null) {
throw new IllegalArgumentException("Can't find encryption(public) key in key ring.");
}
return key;
}
I generated public key using online pgp key generator tool - https://pgpkeygen.com and ran above solution on it. It produced key id in long format.
This worked for older version of jar . However, with new version of jar - bcpg-jdk15on-1.61.jar, it is not working since the constructor to PGPPublicKeyRingCollection now expects KeyFingerPrintCalculator to be provided as argument.
So the line in code,
PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in);
needs to be replaced with
PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in, new JcaKeyFingerprintCalculator());
OR
PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in, new BcKeyFingerprintCalculator());
I tried with both BC and JCA key finger print calculators, and they both gave same Key ID.
So the questions are,
Which finger print calculator should be used here?
Are there any specific scenarios where choosing one over other is relevant/required? I checked javadocs of both calculator classes but there is no much information provided.
Is there any alternate solution to get key id of a PGP public key in java? If yes, please suggest.
Please note that, I am not generating keys here - those are going to be provided by client and I do not have much information about them.
I am new to public key cryptography implementation in java. Any relevant information related to subject will be highly appreciated.
Thanks.