代码之家  ›  专栏  ›  技术社区  ›  Gangaraju Anjali Pavithra

如何在Java中从PGP公钥中获取用户id?

  •  2
  • Gangaraju Anjali Pavithra  · 技术社区  · 7 年前

    camel-crypto .

    PGPDataFormat pgpDataFormat=new PGPDataFormat();
    pgpDataFormat.setKeyFileName("0x6E1A09A4-pub.asc");
    pgpDataFormat.setKeyUserid("user@domain.com");
    pgpDataFormat.marshal(exchange, exchange.getIn().getBody(File.class), exchange.getIn().getBody(OutputStream.class));
    

    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

    1 回复  |  直到 7 年前
        1
  •  4
  •   Siva    7 年前
    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();
    }