如何在Java中从PGP公钥中获取用户id?
我使用PGP加密文件,然后使用ApacheCamel进行传输。我能够使用加密和解密 我需要提供如何在Java中从PGP公钥中获取用户id?,java,apache-camel,gnupg,pgp,Java,Apache Camel,Gnupg,Pgp,我使用PGP加密文件,然后使用ApacheCamel进行传输。我能够使用加密和解密 我需要提供KeyUserId和公钥。我想从公钥中提取此用户id $ gpg --import 0x6E1A09A4-pub.asc gpg: key 6E1A09A4: public key "User <user@domain.com>" imported gpg: Total number processed: 1 gpg: i
KeyUserId
和公钥。我想从公钥中提取此用户id
$ gpg --import 0x6E1A09A4-pub.asc
gpg: key 6E1A09A4: public key "User <user@domain.com>" imported
gpg: Total number processed: 1
gpg: imported: 1 (RSA: 1)
$gpg--导入0x6E1A09A4-pub.asc
gpg:密钥6E1A09A4:已导入公钥“用户”
gpg:处理的总数:1
gpg:imported:1(RSA:1)
如果我使用gpg
命令行cli导入它,它将显示用户ID。在java中,如何从公钥中获取用户ID
private PGPPublicKey getPGPPublicKey(String filePath) throws IOException, PGPException {
InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));
PGPPublicKeyRingCollection pgpPublicKeyRingCollection = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(inputStream), new JcaKeyFingerprintCalculator());
Iterator keyRingIterator = pgpPublicKeyRingCollection.getKeyRings();
while (keyRingIterator.hasNext()) {
PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIterator.next();
Iterator keyIterator = keyRing.getPublicKeys();
while (keyIterator.hasNext()) {
PGPPublicKey key = (PGPPublicKey) keyIterator.next();
if (key.isEncryptionKey()) {
return key;
}
}
}
inputStream.close();
throw new IllegalArgumentException("Can't find encryption key in key ring.");
}
private String getUserId(String publicKeyFile) throws IOException, PGPException {
PGPPublicKey pgpPublicKey = getPGPPublicKey(publicKeyFile);
// You can iterate and return all the user ids if needed
return (String) pgpPublicKey.getUserIDs().next();
}
private PGPPublicKey getPGPPublicKey(String filePath) throws IOException, PGPException {
InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));
PGPPublicKeyRingCollection pgpPublicKeyRingCollection = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(inputStream), new JcaKeyFingerprintCalculator());
Iterator keyRingIterator = pgpPublicKeyRingCollection.getKeyRings();
while (keyRingIterator.hasNext()) {
PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIterator.next();
Iterator keyIterator = keyRing.getPublicKeys();
while (keyIterator.hasNext()) {
PGPPublicKey key = (PGPPublicKey) keyIterator.next();
if (key.isEncryptionKey()) {
return key;
}
}
}
inputStream.close();
throw new IllegalArgumentException("Can't find encryption key in key ring.");
}
private String getUserId(String publicKeyFile) throws IOException, PGPException {
PGPPublicKey pgpPublicKey = getPGPPublicKey(publicKeyFile);
// You can iterate and return all the user ids if needed
return (String) pgpPublicKey.getUserIDs().next();
}