BouncyCastle-GPG。从秘密密钥中提取公共密钥

时间:2020-09-24 10:32:08

标签: java bouncycastle gnupg

我正在使用以下Java代码从秘密密钥中提取公共密钥:

PGPSecretKeyRingCollection ring = new PGPSecretKeyRingCollection(decoderStream,
            new JcaKeyFingerprintCalculator());
Iterator<PGPSecretKeyRing> it = ring.getKeyRings();
while (it.hasNext()) {
    PGPSecretKeyRing key = it.next();
    Iterator<PGPPublicKey> itpublic = key.getPublicKeys();
    while (itpublic.hasNext()) {
        PGPPublicKey pubKey = itpublic.next();
        // use this pubKey
    }
}

如果我尝试在ArmoredOutputStream中导出该密钥,则会得到类似以下内容的信息:

    -----BEGIN PGP PUBLIC KEY BLOCK-----
    Version: BCPG v1.66
    
    hQEMA6GfAr1vmvVrAQf/XF/6DqSxZu0dXXVnhfxoot+YTLBrwnec/af72R8G1aJI
    [...]
    =eLkg
    -----END PGP PUBLIC KEY BLOCK-----

如果我使用此密钥对Java代码中的某些内容进行加密,则一切正常。

如果我使用此密钥从命令行(或其他客户端(如Kleopatra))加密文件:

$ gpg --import pubKey.gpg
$ gpg --encrypt ...

我收到“无法使用的公钥”错误。

我从Java代码中导出公钥是否出错?

1 个答案:

答案 0 :(得分:0)

您必须使用所有PublicKeyRing,而不仅仅是主公钥:

List<PGPPublicKey> list = new ArrayList<>();
Iterator<PGPSecretKeyRing> it = ring.getKeyRings();
while (it.hasNext()) {
    PGPSecretKeyRing secretRing = it.next();
    Iterator<PGPPublicKey> itpublic = secretRing.getPublicKeys();
    while (itpublic.hasNext()) {
        PGPPublicKey pub = itpublic.next();
        list.add(pub);
    }
    Iterator<PGPPublicKey> itextrapublic = secretRing.getExtraPublicKeys();
    while (itextrapublic.hasNext()) {
        PGPPublicKey pub = itextrapublic.next();
        list.add(pub);
    }
}
PGPPublicKeyRing publicRing = new PGPPublicKeyRing(list);
publicRing.encode(armoredOutputStream)