Search code examples
javabouncycastlepgp

java sign public pgp key with bouncycastle


I've got a doubt.. I have to sign a pgp public key using bouncycastle api supposedly. Now: to my understanding signing a key with another means ultimately adding to this public key a "certificate". Thus lacking any other way, I've gone blind searching in the library. my only find so far has been method generateCertification inside PGPSignatureGenerator. But this method generate a certification between a master PgpPublicKey and another PgpPublicKey.. And this strikes me as strange: I assumed that in order to trust another public key, that has to be signed with your own private pgp key just like in regular x.509 with CA certification in a manner.. This was assumption by some methods that I saw when trying to get some ideas from other library: didisoft for example has a similar method on a keystore where you have to provide the PgpPrivatekey keyuid...

Anyone has any hint or a piece of code to propose? Thanks in advance.


Solution

  • Here's a Codeexample to sign a public Key:

        PGPSecretKey mySecretKey;
        PGPPublicKey publicKeyToBeSigned; 
        PGPPrivateKey pgpPrivKey = mySecretKey
                .extractPrivateKey(new JcePBESecretKeyDecryptorBuilder()
                        .setProvider("BC").build("password for your private key"));
        PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
                new JcaPGPContentSignerBuilder(mySecretKey.getPublicKey()
                        .getAlgorithm(), PGPUtil.SHA512));
        signatureGenerator.init(PGPSignature.DIRECT_KEY, pgpPrivKey);
    
        PGPSignature signature = signatureGenerator.generateCertification(
                id, publicKeyToBeSigned);
    

    This piece of code just creates the signature. You need to add it to your the public key then:

    PGPPublicKey.addCertification(publicKeyToBeSigned, signature);
    

    Hope that helps you :)