BouncyCastle-GPG。从密钥中提取 Public 密钥
BouncyCastle - GPG. Extract Public Key from Secret Key
我正在使用此 java 代码从密钥中提取 public 密钥:
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 ...
我收到“无法使用 public 密钥”错误。
我从 java 代码导出的 public 密钥有问题吗?
您必须使用所有的 PublicKeyRing,而不仅仅是主 public 密钥:
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)
我正在使用此 java 代码从密钥中提取 public 密钥:
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 ...
我收到“无法使用 public 密钥”错误。
我从 java 代码导出的 public 密钥有问题吗?
您必须使用所有的 PublicKeyRing,而不仅仅是主 public 密钥:
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)