public static X509Certificate getCertfromPEM ( InputStream certStream ) throws IOException , CertificateException , NoSuchProviderException { String beginKey = "-----BEGIN CERTIFICATE-----" ; String endKey = "-----END CERTIFICATE-----" ; BufferedReader bufRdr = new BufferedReader ( new InputStreamReader ( certStream ) ) ; ByteArrayOutputStream ostr = new ByteArrayOutputStream ( ) ; PrintStream opstr = new PrintStream ( ostr ) ; String temp ; while ( ( temp = bufRdr . readLine ( ) ) != null && ! temp . equals ( beginKey ) ) continue ; if ( temp == null ) throw new IOException ( "Error in " + certStream . toString ( ) + ", missing " + beginKey + " boundary" ) ; while ( ( temp = bufRdr . readLine ( ) ) != null && ! temp . equals ( endKey ) ) opstr . print ( temp ) ; if ( temp == null ) throw new IOException ( "Error in " + certStream . toString ( ) + ", missing " + endKey + " boundary" ) ; opstr . close ( ) ; byte [ ] certbuf = Base64 . decode ( ostr . toByteArray ( ) ) ; // X509Certificate object CertificateFactory cf = CertificateFactory . getInstance ( "X.509" , "SC" ) ; X509Certificate x509cert = ( X509Certificate ) cf . generateCertificate ( new ByteArrayInputStream ( certbuf ) ) ; return x509cert ; }
Reads a certificate in PEM - format from an InputStream . The stream may contain other things the first certificate in the stream is read .