public static PrivateKeyEntry getFirstPrivateKeyEntryFromP12InputStream ( final InputStream p12InputStream , final String password ) throws KeyStoreException , IOException { Objects . requireNonNull ( password , "Password may be blank, but must not be null." ) ; final KeyStore keyStore = KeyStore . getInstance ( "PKCS12" ) ; try { keyStore . load ( p12InputStream , password . toCharArray ( ) ) ; } catch ( NoSuchAlgorithmException | CertificateException e ) { throw new KeyStoreException ( e ) ; } final Enumeration < String > aliases = keyStore . aliases ( ) ; final KeyStore . PasswordProtection passwordProtection = new KeyStore . PasswordProtection ( password . toCharArray ( ) ) ; while ( aliases . hasMoreElements ( ) ) { final String alias = aliases . nextElement ( ) ; KeyStore . Entry entry ; try { try { entry = keyStore . getEntry ( alias , passwordProtection ) ; } catch ( final UnsupportedOperationException e ) { entry = keyStore . getEntry ( alias , null ) ; } } catch ( final UnrecoverableEntryException | NoSuchAlgorithmException e ) { throw new KeyStoreException ( e ) ; } if ( entry instanceof KeyStore . PrivateKeyEntry ) { return ( PrivateKeyEntry ) entry ; } } throw new KeyStoreException ( "Key store did not contain any private key entries." ) ; }
Returns the first private key entry found in the given keystore . If more than one private key is present the key that is returned is undefined .