Verification of PGP signature using BouncyCastle

2019-09-11 21:01发布

问题:

I've generated a PGP Signature:

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2

iQEcBBABCAAGBQJYnkPxAAoJEBFjzYGyXBOsXRoH/3O4bwKK45aUN+m0N4jsZ+n5
W8R/aGti/llvJ62tHBCO5BIp/pp+b1Gdv99xtnJXHu/f0TqPYj+fwq4vfaorNTtA
Vtq8MaMesw1OWZEfu/lyjNOwdg81FUlYkw0Bjo3H/MxWjWYUiHmJo+OGriyf5dv/
433ZqitZMxLHCfZsuoU5teZ0BPUSoNjF6hOFK3ZI7QXsgYUyohzW2goy9bDVCKRq
e73CHpnMKCrnDc+/4+sK349bD/cZp6/c0T8b7cBCeBGGilPD6ovJUQE5vhGTKnJM
lgyxhA87tw9wqFwpZXDr0nzOP+MFfE9WRGecVYZ9G+LP/biefSe5iWRaPIcZIi0=
=qUHb
-----END PGP SIGNATURE-----

The code is here, implemented with BouncyCastle:

(sign "project.clj"
      "project.clj.asc"
      <FILENAME>
      "98B9A74D")

I want to be able to read this Signature and verify it using the public key. How would this be turned back into a BouncyCastle org.bouncycastle.openpgp.PGPSignature object?

回答1:

How would this be turned back into a BouncyCastle ... PGPSignature object?

Extracting the relevant code from org.bouncycastle.openpgp.examples.DetachedSignatureProcessor provided in the bcpg jar and specializing it to your case (armored, uncompressed):

InputStream in = new org.bouncycastle.bcpg.ArmoredInputStream (new FileInputStream (filename));
// or substitute other InputStream depending on where this data is available
org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory pgpFact = new org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory(in);
org.bouncycastle.openpgp.PGPSignatureList p3 = (org.bouncycastle.openpgp.PGPSignatureList)pgpFact.nextObject();
org.bouncycastle.openpgp.PGPSignature sig = p3.get(0);
in.close(); // not in example but needed in quality code

I want to be able to read this Signature and verify it using the public key.

The remainder of that example shows a way to verify such a PGPSignature given the publickey (in the example from a pubring file) and the relevant data (in the example also a file).