【问题标题】:BouncyCastle - GPG. Extract Public Key from Secret KeyBouncyCastle - GPG。从密钥中提取公钥
【发布时间】:2020-09-24 10:32:08
【问题描述】:

我正在使用这个 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 代码导出的公钥有什么问题吗?

【问题讨论】:

  • 我不知道这与您的特定问题有何关系,但总的来说,非对称加密的整个想法是生成一对具有此属性的密钥,您无法从其他。
  • 使用 GPG 客户端,您可以导入密钥,然后从该文件导出公钥

标签: java bouncycastle gnupg


【解决方案1】:

你必须使用所有的 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)

【讨论】:

    猜你喜欢
    • 2012-07-13
    • 1970-01-01
    • 2020-02-12
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    相关资源
    最近更新 更多