Search in sources :

Example 1 with PEMKeyPair

use of com.github.zhenwei.pkix.openssl.PEMKeyPair in project LinLong-Java by zhenwei1108.

the class JcaPKIXIdentityBuilder method build.

/**
 * Build an identity from the passed in key and certificate stream in PEM format.
 *
 * @param keyStream         the PEM stream containing the key
 * @param certificateStream the PEM stream containing the certificate
 * @return an identity object.
 * @throws IOException          on a general parsing error.
 * @throws CertificateException on a certificate parsing error.
 */
public JcaPKIXIdentity build(InputStream keyStream, InputStream certificateStream) throws IOException, CertificateException {
    PEMParser keyParser = new PEMParser(new InputStreamReader(keyStream));
    PrivateKey privKey;
    Object keyObj = keyParser.readObject();
    if (keyObj instanceof PEMKeyPair) {
        PEMKeyPair kp = (PEMKeyPair) keyObj;
        privKey = keyConverter.getPrivateKey(kp.getPrivateKeyInfo());
    } else if (keyObj instanceof PrivateKeyInfo) {
        privKey = keyConverter.getPrivateKey((PrivateKeyInfo) keyObj);
    } else {
        // TODO: handle encrypted private keys
        throw new IOException("unrecognised private key file");
    }
    PEMParser certParser = new PEMParser(new InputStreamReader(certificateStream));
    List certs = new ArrayList();
    Object certObj;
    while ((certObj = certParser.readObject()) != null) {
        certs.add(certConverter.getCertificate((X509CertificateHolder) certObj));
    }
    return new JcaPKIXIdentity(privKey, (X509Certificate[]) certs.toArray(new X509Certificate[certs.size()]));
}
Also used : PrivateKey(java.security.PrivateKey) PEMParser(com.github.zhenwei.pkix.openssl.PEMParser) InputStreamReader(java.io.InputStreamReader) JcaPKIXIdentity(com.github.zhenwei.pkix.jcajce.JcaPKIXIdentity) X509CertificateHolder(com.github.zhenwei.pkix.cert.X509CertificateHolder) ArrayList(java.util.ArrayList) PEMKeyPair(com.github.zhenwei.pkix.openssl.PEMKeyPair) ArrayList(java.util.ArrayList) List(java.util.List) IOException(java.io.IOException) PrivateKeyInfo(com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo) X509Certificate(java.security.cert.X509Certificate)

Aggregations

PrivateKeyInfo (com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo)1 X509CertificateHolder (com.github.zhenwei.pkix.cert.X509CertificateHolder)1 JcaPKIXIdentity (com.github.zhenwei.pkix.jcajce.JcaPKIXIdentity)1 PEMKeyPair (com.github.zhenwei.pkix.openssl.PEMKeyPair)1 PEMParser (com.github.zhenwei.pkix.openssl.PEMParser)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 PrivateKey (java.security.PrivateKey)1 X509Certificate (java.security.cert.X509Certificate)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1