Example usage for java.security KeyStore setCertificateEntry

List of usage examples for java.security KeyStore setCertificateEntry

Introduction

In this page you can find the example usage for java.security KeyStore setCertificateEntry.

Prototype

public final void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException 

Source Link

Document

Assigns the given trusted certificate to the given alias.

Usage

From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java

private void saveTrustedCertificate(X509Certificate cert, String alias) {
    KeyStore keyStore = loadKeyStore();
    try {/*from   w w w  .ja  va  2  s  .  c  o  m*/
        log.info("Installing trusted CA certificate {}", cert.getSubjectDN());
        keyStore.setCertificateEntry(alias, cert);
        saveKeyStore(keyStore);
    } catch (KeyStoreException e) {
        throw new CertificateException("Error saving trusted certificate", e);
    }
}

From source file:org.teiid.resource.adapter.ftp.FtpManagedConnectionFactory.java

public void setCertificate(String certificate) {
    this.certificate = certificate;
    if (this.certificate != null && Files.exists(Paths.get(this.certificate))) {
        try {/*from w  ww. j  a  v a  2s . c om*/
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); //$NON-NLS-1$
            InputStream in = Files.newInputStream(Paths.get(this.certificate));
            Certificate cert = certificateFactory.generateCertificate(in);
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            keyStore.setCertificateEntry("alias", cert); //$NON-NLS-1$
            trustManager = TrustManagerUtils.getDefaultTrustManager(keyStore);
        } catch (IOException | GeneralSecurityException e) {
            throw new TeiidRuntimeException(UTIL.getString("ftp_certificate_path", certificate, e)); //$NON-NLS-1$
        }
    }
}

From source file:com.linkedin.pinot.common.utils.ClientSSLContextGenerator.java

private TrustManager[] setupTrustManagers()
        throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException {
    // This is the cert authority that validates server's cert, so we need to put it in our
    // trustStore.
    if (_serverCACertFile != null) {
        LOGGER.info("Initializing trust store from {}", _serverCACertFile);
        FileInputStream is = new FileInputStream(new File(_serverCACertFile));
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null);/*from  ww  w.ja v a2 s  .c  o m*/
        CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
        int i = 0;
        while (is.available() > 0) {
            X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(is);
            LOGGER.info("Read certificate serial number {} by issuer {} ", cert.getSerialNumber().toString(16),
                    cert.getIssuerDN().toString());

            String serverKey = "https-server-" + i;
            trustStore.setCertificateEntry(serverKey, cert);
            i++;
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(CERTIFICATE_TYPE);
        tmf.init(trustStore);
        LOGGER.info("Successfully initialized trust store");
        return tmf.getTrustManagers();
    }
    // Server verification disabled. Trust all servers
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    } };
    return trustAllCerts;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestX509SecurityHandler.java

private void createTrustStore(String filename, String password, String alias, Certificate cert)
        throws GeneralSecurityException, IOException {
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);/*from   w  w  w  .ja va 2 s.  com*/
    ks.setCertificateEntry(alias, cert);
    FileOutputStream out = new FileOutputStream(filename);
    try {
        ks.store(out, password.toCharArray());
    } finally {
        out.close();
    }
}

From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

public void addPublicKey(KeyStore ks, KeyPair keyPair, String keyPairName, String keyPairSubjectDN)
        throws CryptoException {
    try {//from   ww w.  j  ava 2s .c o  m
        X509Certificate cert = generateV3Certificate(keyPair, keyPairSubjectDN);
        ks.setCertificateEntry(keyPairName, cert);

    } catch (KeyStoreException e) {
        this.logger.error("KeyStoreException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    }
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Creates JKS-file that can be used with JDK. The alias for the private key is set to 'privateKey' and the private key password is null.
 * /*from ww  w  .j  a  v a2s. co m*/
 * @param alias
 *            the alias used for the key entry
 * @param privKey
 *            RSA private key
 * @param password
 *            user's password
 * @param cert
 *            user certificate
 * @param cachain
 *            CA-certificate chain or null if only one cert in chain, in that case use 'cert'.
 * 
 * @return KeyStore containing JKS-keystore
 * 
 * @exception Exception
 *                if input parameters are not OK or certificate generation fails
 */
public static KeyStore createJKS(final String alias, final PrivateKey privKey, final String password,
        final X509Certificate cert, final Certificate[] cachain) throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">createJKS: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    final String caAlias = "cacert";

    // Certificate chain
    if (cert == null) {
        throw new IllegalArgumentException("Parameter cert cannot be null.");
    }
    int len = 1;
    if (cachain != null) {
        len += cachain.length;
    }
    final Certificate[] chain = new Certificate[len];
    chain[0] = cert;
    if (cachain != null) {
        System.arraycopy(cachain, 0, chain, 1, cachain.length);
    }

    // store the key and the certificate chain
    final KeyStore store = KeyStore.getInstance("JKS");
    store.load(null, null);

    // First load the key entry
    final X509Certificate[] usercert = new X509Certificate[1];
    usercert[0] = cert;
    store.setKeyEntry(alias, privKey, password.toCharArray(), usercert);

    // Add the root cert as trusted
    if (cachain != null) {
        if (!CertTools.isSelfSigned(cachain[cachain.length - 1])) {
            throw new IllegalArgumentException("Root cert is not self-signed.");
        }
        store.setCertificateEntry(caAlias, cachain[cachain.length - 1]);
    }

    // Set the complete chain
    log.debug("Storing cert chain of length " + chain.length);
    store.setKeyEntry(alias, privKey, password.toCharArray(), chain);
    if (log.isTraceEnabled()) {
        log.trace("<createJKS: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    return store;
}

From source file:com.isecpartners.gizmo.HttpRequest.java

private KeyManagerFactory createKeyManagerFactory(String cname) throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException,
        InvalidKeyException, SignatureException, NoSuchProviderException, NoCertException {
    X509Certificate cert = KeyStoreManager.getCertificateByHostname(cname);
    cybervillains.ca.KeyStoreManager.getCertificateByHostname(cname);

    if (cert == null) {
        throw new NoCertException();
    }//from w  ww .  j  a va2  s . c om

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, pass);

    ks.setCertificateEntry(cname, cert);
    ks.setKeyEntry(cname, KeyStoreManager.getPrivateKeyForLocalCert(cert), pass,
            new X509Certificate[] { cert });

    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, pass);

    return kmf;
}

From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

/**
 *
 * @param ks/*w  w  w.  j a v a  2s . c o m*/
 * @param keyPair
 * @param keyPairName
 * @param keyPairSubjectDN
 * @param before
 * @param expiry
 * @throws CryptoException
 */
public void addPublicKey(KeyStore ks, KeyPair keyPair, String keyPairName, String keyPairSubjectDN,
        Calendar before, Calendar expiry) throws CryptoException {
    try {
        X509Certificate cert = generateV3Certificate(keyPair, keyPairSubjectDN, before, expiry);
        ks.setCertificateEntry(keyPairName, cert);

    } catch (KeyStoreException e) {
        this.logger.error("KeyStoreException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    }
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

private void loadCertificates(String path, String passwd) {
    /* wenn die Zertifikate noch nicht im Keystore sind, jetzt einlesen */
    File myPfad = new File(path);
    if (!myPfad.exists()) {
        try (FileOutputStream ksos = (FileOutputStream) serviceManager.getFileService().write(myPfad.toURI());
                // TODO: Rename parameters to something more meaningful,
                // this is quite specific for the GDZ
                FileInputStream cacertFile = new FileInputStream(ConfigCore.getParameter("ldap_cert_root"));
                FileInputStream certFile2 = new FileInputStream(ConfigCore.getParameter("ldap_cert_pdc"))) {

            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cacert = (X509Certificate) cf.generateCertificate(cacertFile);
            X509Certificate servercert = (X509Certificate) cf.generateCertificate(certFile2);

            KeyStore ks = KeyStore.getInstance("jks");
            char[] password = passwd.toCharArray();

            // TODO: Let this method really load a keystore if configured
            // initialize the keystore, if file is available, load the
            // keystore
            ks.load(null);/*from  w  ww  . j  av  a 2 s  .  c om*/

            ks.setCertificateEntry("ROOTCERT", cacert);
            ks.setCertificateEntry("PDC", servercert);
            ks.store(ksos, password);
        } catch (Exception e) {
            logger.error(e);
        }

    }
}

From source file:org.kitodo.services.data.LdapServerService.java

private void loadCertificates(String path, String passwd, LdapServer ldapServer) {
    /* wenn die Zertifikate noch nicht im Keystore sind, jetzt einlesen */
    File myPfad = new File(path);
    if (!myPfad.exists()) {
        try (FileOutputStream ksos = (FileOutputStream) serviceManager.getFileService().write(myPfad.toURI());
                // TODO: Rename parameters to something more meaningful,
                // this is quite specific for the GDZ
                FileInputStream cacertFile = new FileInputStream(ldapServer.getRootCertificate());
                FileInputStream certFile2 = new FileInputStream(ldapServer.getPdcCertificate())) {

            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cacert = (X509Certificate) cf.generateCertificate(cacertFile);
            X509Certificate servercert = (X509Certificate) cf.generateCertificate(certFile2);

            KeyStore ks = KeyStore.getInstance("jks");
            char[] password = passwd.toCharArray();

            // TODO: Let this method really load a keystore if configured
            // initialize the keystore, if file is available, load the
            // keystore
            ks.load(null);/*ww  w. j  a va  2s .c om*/

            ks.setCertificateEntry("ROOTCERT", cacert);
            ks.setCertificateEntry("PDC", servercert);
            ks.store(ksos, password);
        } catch (IOException | CertificateException | KeyStoreException | NoSuchAlgorithmException
                | RuntimeException e) {
            logger.error(e.getMessage(), e);
        }

    }
}