Example usage for java.security.cert CertificateFactory generateCertificate

List of usage examples for java.security.cert CertificateFactory generateCertificate

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory generateCertificate.

Prototype

public final Certificate generateCertificate(InputStream inStream) throws CertificateException 

Source Link

Document

Generates a certificate object and initializes it with the data read from the input stream inStream .

Usage

From source file:net.unicon.cas.support.wsfederation.WsFederationUtils.java

/**
 * getSigningCredential loads up an X509Credential from a file.
 *
 * @param resource the signing certificate file
 * @return an X509 credential//from w w w .  j  a v a  2 s . c  o m
 */
public static X509Credential getSigningCredential(final Resource resource) {
    try (final InputStream inputStream = resource.getInputStream()) {
        //grab the certificate file
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        final X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(inputStream);

        //get the public key from the certificate
        final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(
                certificate.getPublicKey().getEncoded());

        //generate public key to validate signatures
        final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        final PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

        //add the public key
        final BasicX509Credential publicCredential = new BasicX509Credential();
        publicCredential.setPublicKey(publicKey);
        LOGGER.debug("getSigningCredential: key retrieved.");
        return publicCredential;
    } catch (final Exception ex) {
        LOGGER.error("I/O error retrieving the signing cert: {}", ex);
        return null;
    }
}

From source file:com.cedarsoft.crypt.X509Support.java

/**
 * Reads the x509 certificate from the given url
 *
 * @param certificateUrl the certificate url
 * @return the certificate//from ww w.java2  s . com
 *
 * @throws IOException if any.
 * @throws GeneralSecurityException
 *                             if any.
 */
@Nonnull
public static X509Certificate readCertificate(@Nonnull URL certificateUrl)
        throws IOException, GeneralSecurityException {
    //Read the cert
    DataInputStream in = new DataInputStream(certificateUrl.openStream());
    try {
        CertificateFactory cf = CertificateFactory.getInstance(X_509_CERTIFICATE_TYPE);
        X509Certificate certificate = (X509Certificate) cf.generateCertificate(in);
        certificate.checkValidity();
        return certificate;
    } finally {
        in.close();
    }
}

From source file:learn.encryption.ssl.SSLContext_Https.java

public static SSLContext getSSLContext2(String servercerfile, String clientkeyStore, String clientPass) {
    if (sslContext != null) {
        return sslContext;
    }//from   ww w.j  av a  2 s  .  c om
    try {
        // ??, ??assets
        //InputStream inputStream = App.getInstance().getAssets().open("serverkey.cer");
        InputStream inputStream = new FileInputStream(new File(servercerfile));
        // ??
        CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");
        Certificate cer = cerFactory.generateCertificate(inputStream);
        // ?KeyStore
        KeyStore keyStore = KeyStore.getInstance("PKCS12");//eclipse?jksandroidPKCS12??
        keyStore.load(null, null);
        keyStore.setCertificateEntry("trust", cer);

        // KeyStoreTrustManagerFactory
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        sslContext = SSLContext.getInstance("TLS");

        //?clientKeyStore(android??bks)
        //KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        KeyStore clientKeyStore = KeyStore.getInstance("jks");
        //clientKeyStore.load(App.getInstance().getAssets().open("clientkey.bks"), "123456".toCharArray());
        clientKeyStore.load(new FileInputStream(new File(clientkeyStore)), clientPass.toCharArray());

        // ?clientKeyStorekeyManagerFactory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(clientKeyStore, clientPass.toCharArray());

        // ?SSLContext  trustManagerFactory.getTrustManagers()
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());//new TrustManager[]{trustManagers}??
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sslContext;
}

From source file:org.wso2.carbon.apimgt.rest.api.publisher.utils.CertificateRestApiUtils.java

/**
 * To get the decoded certificate input stream.
 *
 * @param certificate Relevant encoded certificate
 * @return Input stream of the certificate.
 * @throws APIManagementException API Management Exception.
 *//*from ww w.ja  v a 2 s .c o m*/
public static ByteArrayInputStream getDecodedCertificate(String certificate) throws APIManagementException {
    byte[] cert = (Base64.decodeBase64(certificate.getBytes(StandardCharsets.UTF_8)));
    ByteArrayInputStream serverCert = new ByteArrayInputStream(cert);
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        if (serverCert.available() > 0) {
            Certificate generatedCertificate = cf.generateCertificate(serverCert);
            X509Certificate x509Certificate = (X509Certificate) generatedCertificate;
            return new ByteArrayInputStream(x509Certificate.getEncoded());
        }
    } catch (CertificateException e) {
        throw new APIManagementException("Error while decoding the certificate", e);
    }
    return null;
}

From source file:org.apache.ofbiz.base.util.KeyStoreUtil.java

public static X509Certificate readCertificate(byte[] certChain) throws CertificateException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bais = new ByteArrayInputStream(certChain);
    return (X509Certificate) cf.generateCertificate(bais);
}

From source file:JALPTest.java

/**
 * Creates a Producer using the given command line params.
 *
 * @param xml            the ApplicationMetadataXML
 * @param socketPath      a String which is the path to the socket
 * @param privateKeyPath   a String which is the path to the private key in DER format
 * @param publicKeyPath      a String which is the path to the public key in DER format
 * @param certPath         a String which is the path to the certificate
 * @param hasDigest         a Boolean, true to set a digest method in the producer
 * @return   the created Producer//from  w w  w  . j  ava 2 s  . c  o m
 * @throws Exception
 */
private static Producer createProducer(ApplicationMetadataXML xml, String socketPath, String privateKeyPath,
        String publicKeyPath, String certPath, Boolean hasDigest) throws Exception {
    Producer producer = new Producer(xml);
    producer.setSocketFile(socketPath);

    if (privateKeyPath != null && !"".equals(privateKeyPath)) {

        File privateKeyFile = new File(privateKeyPath);
        DataInputStream privateDis = new DataInputStream(new FileInputStream(privateKeyFile));
        byte[] privateKeyBytes = new byte[(int) privateKeyFile.length()];
        privateDis.readFully(privateKeyBytes);
        privateDis.close();

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        KeySpec privateKs = new PKCS8EncodedKeySpec(privateKeyBytes);
        PrivateKey privateKey = keyFactory.generatePrivate(privateKs);

        File publicKeyFile = new File(publicKeyPath);
        DataInputStream publicDis = new DataInputStream(new FileInputStream(publicKeyFile));
        byte[] publicKeyBytes = new byte[(int) publicKeyFile.length()];
        publicDis.readFully(publicKeyBytes);
        publicDis.close();

        KeySpec publicKs = new X509EncodedKeySpec(publicKeyBytes);
        PublicKey publicKey = keyFactory.generatePublic(publicKs);

        producer.setPrivateKey(privateKey);
        producer.setPublicKey(publicKey);
    }

    if (certPath != null && !"".equals(certPath)) {
        InputStream inputStream = new FileInputStream(certPath);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);
        inputStream.close();
        producer.setCertificate(cert);
    }

    if (hasDigest) {
        producer.setDigestMethod(DMType.SHA256);
    }

    return producer;
}

From source file:io.kubernetes.client.util.SSLUtils.java

public static KeyStore createKeyStore(InputStream certInputStream, InputStream keyInputStream,
        String clientKeyAlgo, char[] clientKeyPassphrase, String keyStoreFile, char[] keyStorePassphrase)
        throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException,
        KeyStoreException {/*from  ww w. jav a 2 s  . c o m*/
    CertificateFactory certFactory = CertificateFactory.getInstance("X509");
    X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream);

    byte[] keyBytes = decodePem(keyInputStream);

    PrivateKey privateKey;

    KeyFactory keyFactory = KeyFactory.getInstance(clientKeyAlgo);
    try {
        // First let's try PKCS8
        privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
    } catch (InvalidKeySpecException e) {
        // Otherwise try PKCS8
        RSAPrivateCrtKeySpec keySpec = decodePKCS1(keyBytes);
        privateKey = keyFactory.generatePrivate(keySpec);
    }

    KeyStore keyStore = KeyStore.getInstance("JKS");
    if (keyStoreFile != null && keyStoreFile.length() > 0) {
        keyStore.load(new FileInputStream(keyStoreFile), keyStorePassphrase);
    } else {
        loadDefaultKeyStoreFile(keyStore, keyStorePassphrase);
    }

    String alias = cert.getSubjectX500Principal().getName();
    keyStore.setKeyEntry(alias, privateKey, clientKeyPassphrase, new Certificate[] { cert });

    return keyStore;
}

From source file:org.apache.ofbiz.base.util.KeyStoreUtil.java

public static Certificate pemToCert(Reader r) throws IOException, CertificateException {
    String header = "-----BEGIN CERTIFICATE-----";
    String footer = "-----END CERTIFICATE-----";

    BufferedReader reader = new BufferedReader(r);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);

    String line;/*w  w  w.  j av  a2 s .c o  m*/

    // ignore up to the header
    while ((line = reader.readLine()) != null && !line.equals(header)) {
    }

    // no header found
    if (line == null) {
        throw new IOException("Error reading certificate, missing BEGIN boundary");
    }

    // in between the header and footer is the actual certificate
    while ((line = reader.readLine()) != null && !line.equals(footer)) {
        line = line.replaceAll("\\s", "");
        ps.print(line);
    }

    // no footer found
    if (line == null) {
        throw new IOException("Error reading certificate, missing END boundary");
    }
    ps.close();

    // decode the buffer to a X509Certificate

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    byte[] certBytes = Base64.decodeBase64(baos.toByteArray());
    return cf.generateCertificate(new ByteArrayInputStream(certBytes));
}

From source file:nextflow.k8s.client.SSLUtils.java

public static KeyStore createKeyStore(InputStream certInputStream, InputStream keyInputStream,
        String clientKeyAlgo, char[] clientKeyPassphrase, String keyStoreFile, char[] keyStorePassphrase)
        throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException,
        KeyStoreException {/* w  w w .  j  a v  a  2s.c o  m*/
    CertificateFactory certFactory = CertificateFactory.getInstance("X509");
    X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream);

    byte[] keyBytes = decodePem(keyInputStream);

    PrivateKey privateKey;

    KeyFactory keyFactory = KeyFactory.getInstance(clientKeyAlgo);
    try {
        // First let's try PKCS8
        privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
    } catch (InvalidKeySpecException e) {
        // Otherwise try PKCS1
        RSAPrivateCrtKeySpec keySpec = decodePKCS1(keyBytes);
        privateKey = keyFactory.generatePrivate(keySpec);
    }

    KeyStore keyStore = KeyStore.getInstance("JKS");
    if (keyStoreFile != null && keyStoreFile.length() > 0) {
        keyStore.load(new FileInputStream(keyStoreFile), keyStorePassphrase);
    } else {
        loadDefaultKeyStoreFile(keyStore, keyStorePassphrase);
    }

    String alias = cert.getSubjectX500Principal().getName();
    keyStore.setKeyEntry(alias, privateKey, clientKeyPassphrase, new Certificate[] { cert });

    return keyStore;
}

From source file:com.isa.ws.utiles.UtilesSWHelper.java

/**
 * Converts a byte array to a X509Certificate instance.
 * @param bytes the byte array/*from w  ww  . j  ava2 s. c  om*/
 * @return a X509Certificate instance
 * @throws CertificateException if the conversion fails
 */
public static X509Certificate fromByteArrayToX509Certificate(byte[] bytes) throws CertificateException {
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    InputStream in = new ByteArrayInputStream(bytes);
    X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
    return cert;
}