2017-08-09 51 views
1

我正在使用PGP来加密文件,然后使用apache-camel进行传输。我能够使用camel-crypto进行加密和解密。如何从Java中的PGP公钥获取用户标识?

PGPDataFormat pgpDataFormat=new PGPDataFormat(); 
pgpDataFormat.setKeyFileName("0x6E1A09A4-pub.asc"); 
pgpDataFormat.setKeyUserid("[email protected]"); 
pgpDataFormat.marshal(exchange, exchange.getIn().getBody(File.class), exchange.getIn().getBody(OutputStream.class)); 

我需要提供KeyUserId和公钥。我想从公钥中提取此用户标识。

$ gpg --import 0x6E1A09A4-pub.asc      

gpg: key 6E1A09A4: public key "User <[email protected]>" imported 
gpg: Total number processed: 1 
gpg:    imported: 1 (RSA: 1) 

如果我使用gpg命令行cli导入它,它将显示userId。如何从Java中的公钥获得该用户ID?

回答

1
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(); 
} 
相关问题