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:it.cnr.icar.eric.server.security.authentication.CertificateAuthority.java

/** Extension request to sign specified cert and return the signed cert. */
@SuppressWarnings("static-access")
public RegistryResponseHolder signCertificateRequest(UserType user, RegistryRequestType req,
        Map<?, ?> idToRepositoryItemMap) throws RegistryException {

    RegistryResponseHolder respHolder = null;
    RegistryResponseType ebRegistryResponseType = null;
    ServerRequestContext context = null;

    try {/*from ww w  .j  a v a  2s.  c o m*/
        context = new ServerRequestContext("CertificateAUthority.signCertificateRequest", req);
        context.setUser(user);

        if (idToRepositoryItemMap.keySet().size() == 0) {
            throw new MissingRepositoryItemException(
                    ServerResourceBundle.getInstance().getString("message.KSRepItemNotFound"));
        }

        String id = (String) idToRepositoryItemMap.keySet().iterator().next();

        Object obj = idToRepositoryItemMap.get(id);
        if (!(obj instanceof RepositoryItem)) {
            throw new InvalidContentException();
        }
        RepositoryItem ri = (RepositoryItem) obj; //This is the JKS keystore containing cert to be signed            

        //Read original cert from keystore
        InputStream is = ri.getDataHandler().getInputStream();
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(is, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray());
        is.close();
        X509Certificate cert = (X509Certificate) keyStore
                .getCertificate(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ);

        //Sign the cert
        cert = signCertificate(cert);

        //Replace cert with signed cert in keystore
        keyStore.deleteEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ);
        keyStore.setCertificateEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_RESP, cert);

        //Add CA root cert (RegistryOPerator's cert) to keystore.
        keyStore.setCertificateEntry(bu.FREEBXML_REGISTRY_CACERT_ALIAS, getCACertificate());

        Certificate[] certChain = new Certificate[2];
        certChain[0] = cert;
        certChain[1] = getCACertificate();
        validateChain(certChain);

        File repositoryItemFile = File.createTempFile(".eric-ca-resp", ".jks");
        repositoryItemFile.deleteOnExit();
        FileOutputStream fos = new java.io.FileOutputStream(repositoryItemFile);
        keyStore.store(fos, bu.FREEBXML_REGISTRY_KS_PASS_RESP.toCharArray());
        fos.flush();
        fos.close();

        DataHandler dh = new DataHandler(new FileDataSource(repositoryItemFile));
        RepositoryItemImpl riNew = new RepositoryItemImpl(id, dh);

        ebRegistryResponseType = bu.rsFac.createRegistryResponseType();
        ebRegistryResponseType.setStatus(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success);

        HashMap<String, Object> respIdToRepositoryItemMap = new HashMap<String, Object>();
        respIdToRepositoryItemMap.put(id, riNew);

        respHolder = new RegistryResponseHolder(ebRegistryResponseType, respIdToRepositoryItemMap);

    } catch (RegistryException e) {
        context.rollback();
        throw e;
    } catch (Exception e) {
        context.rollback();
        throw new RegistryException(e);
    }

    context.commit();
    return respHolder;
}

From source file:com.hpe.elderberry.TaxiiConnection.java

private List<Certificate> addPemsToStore(KeyStore store, List<String> pems) throws CertificateException {
    List<Certificate> result = new ArrayList<>(pems.size());

    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    pems.forEach(pem -> {/*from w  ww  . jav  a  2  s .  c  o m*/
        try {
            X509Certificate cert = (X509Certificate) factory.generateCertificate(toInputStream(pem));
            store.setCertificateEntry(randomUUID().toString(), cert);
            result.add(cert);
        } catch (Exception e) {
            throw new RuntimeException("unable to load PEM: " + pem + ", " + e.getMessage(), e);
        }
    });

    return result;
}

From source file:org.kitodo.production.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);/*from w w  w .  j  a va2  s  .co m*/

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

    }
}

From source file:org.strongswan.android.ui.VpnProfileImportActivity.java

/**
 * Save or update the profile depending on whether we actually have a
 * profile object or not (this was created in updateProfileData)
 *///from   w w w. ja v  a2 s.  c  o m
private void saveProfile() {
    if (verifyInput()) {
        updateProfileData();
        if (mExisting != null) {
            mProfile.setId(mExisting.getId());
            mDataSource.updateVpnProfile(mProfile);
        } else {
            mDataSource.insertProfile(mProfile);
        }
        if (mCertEntry != null) {
            try { /* store the CA/server certificate */
                KeyStore store = KeyStore.getInstance("LocalCertificateStore");
                store.load(null, null);
                store.setCertificateEntry(null, mCertEntry.getCertificate());
                TrustedCertificateManager.getInstance().reset();
            } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
                e.printStackTrace();
            }
        }
        Intent intent = new Intent(Constants.VPN_PROFILES_CHANGED);
        intent.putExtra(Constants.VPN_PROFILES_SINGLE, mProfile.getId());
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

        intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

        setResult(RESULT_OK, new Intent().putExtra(VpnProfileDataSource.KEY_ID, mProfile.getId()));
        finish();
    }
}

From source file:org.jboss.as.test.integration.auditlog.AuditLogToTLSSyslogSetup.java

private void createKeyStoreTrustStore(KeyStore keyStore, KeyStore trustStore, String DN, String alias)
        throws Exception {
    X500Principal principal = new X500Principal(DN);

    SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey
            .builder().setKeyAlgorithmName("RSA").setSignatureAlgorithmName("SHA256withRSA").setDn(principal)
            .setKeySize(1024).build();/*from  ww  w.  ja  va2s .  c o  m*/
    X509Certificate certificate = selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();

    keyStore.setKeyEntry(alias, selfSignedX509CertificateAndSigningKey.getSigningKey(),
            KEYSTORE_CREATION_PASSWORD, new X509Certificate[] { certificate });
    trustStore.setCertificateEntry(alias, certificate);
}

From source file:uk.ac.cam.ucs.webauth.RavenFilter.java

/**
 * Gets a KeyStore and initialises if necessary.
 * //from www  .j av  a  2 s.  com
 * The caller should ensure the KeyStore is persisted to a safe place.
 * 
 * @return An initialised KeyStore
 */
protected KeyStore getKeyStore() {
    // init a new keystore with the Raven certificate,
    KeyStore keyStore;
    try {
        keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, new char[] {}); // Null InputStream, no password
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        Certificate cert = factory.generateCertificate(new FileInputStream(sCertRealPath));
        keyStore.setCertificateEntry(DEFAULT_KEYNAME, cert);
    } catch (KeyStoreException e) {
        log.error("Unable to setup KeyStore", e);
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        log.error("Unable to find crypto algorithm.", e);
        throw new RuntimeException(e);
    } catch (CertificateException e) {
        log.error("Unable to load certificate.", e);
        throw new RuntimeException(e);
    } catch (FileNotFoundException e) {
        log.error("Unable to load certificate file: " + sCertRealPath, e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        log.error("General IO problem.  Unable to initialised filter.", e);
        throw new RuntimeException(e);
    }

    return keyStore;

}

From source file:org.commonjava.maven.galley.transport.htcli.internal.SSLUtils.java

public static KeyStore readKeyAndCert(final String pemContent, final String keyPass)
        throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException,
        InvalidKeySpecException {
    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null);/*from   ww  w  .j a  v  a 2  s. com*/

    final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    final KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    final List<String> lines = readLines(pemContent);

    String currentHeader = null;
    final StringBuilder current = new StringBuilder();
    final Map<String, String> entries = new LinkedHashMap<String, String>();
    for (final String line : lines) {
        if (line == null) {
            continue;
        }

        if (line.startsWith("-----BEGIN")) {
            currentHeader = line.trim();
            current.setLength(0);
        } else if (line.startsWith("-----END")) {
            entries.put(currentHeader, current.toString());
        } else {
            current.append(line.trim());
        }
    }

    final List<Certificate> certs = new ArrayList<Certificate>();
    for (int pass = 0; pass < 2; pass++) {
        for (final Map.Entry<String, String> entry : entries.entrySet()) {
            final String header = entry.getKey();
            final byte[] data = decodeBase64(entry.getValue());

            if (pass > 0 && header.contains("BEGIN PRIVATE KEY")) {
                final KeySpec spec = new PKCS8EncodedKeySpec(data);
                final PrivateKey key = keyFactory.generatePrivate(spec);
                ks.setKeyEntry("key", key, keyPass.toCharArray(), certs.toArray(new Certificate[] {}));
            } else if (pass < 1 && header.contains("BEGIN CERTIFICATE")) {
                final Certificate c = certFactory.generateCertificate(new ByteArrayInputStream(data));

                ks.setCertificateEntry("certificate", c);
                certs.add(c);
            }
        }
    }

    return ks;
}

From source file:mitm.common.tools.PfxTool.java

private void mergePfx() throws Exception {
    if (StringUtils.isEmpty(destFile)) {
        throw new MissingOptionException(destOption.getOpt() + " is missing.");
    }/* www. j av a 2  s.  c o m*/

    if (StringUtils.isEmpty(destPassword)) {
        throw new MissingOptionException(destPasswordOption.getOpt() + " is missing.");
    }

    KeyStore inStore = loadKeyStore(inFile, true, inPassword);
    KeyStore destStore = loadKeyStore(destFile, false, destPassword);

    Enumeration<String> aliases = inStore.aliases();

    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();

        String destAlias = retainAliases ? alias : UUID.randomUUID().toString() + "_" + alias;

        if (inStore.isKeyEntry(alias)) {
            KeyStore.Entry entry = inStore.getEntry(alias,
                    new KeyStore.PasswordProtection(inPassword.toCharArray()));

            destStore.setEntry(destAlias, entry, new KeyStore.PasswordProtection(destPassword.toCharArray()));
        } else {
            Certificate certificate = inStore.getCertificate(alias);

            destStore.setCertificateEntry(destAlias, certificate);
        }
    }

    destStore.store(new FileOutputStream(destFile), destPassword.toCharArray());
}

From source file:com.photon.phresco.framework.rest.api.util.FrameworkServiceUtil.java

public static void addCertificate(CertificateInfo info, File file) throws PhrescoException {
    char[] passphrase = "changeit".toCharArray();
    InputStream inputKeyStore = null;
    OutputStream outputKeyStore = null;
    try {//from w ww  .java  2 s .com
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        keyStore.setCertificateEntry(info.getDisplayName(), info.getCertificate());
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        outputKeyStore = new FileOutputStream(file);
        keyStore.store(outputKeyStore, passphrase);
    } catch (Exception e) {
        throw new PhrescoException(e);
    } finally {
        Utility.closeStream(inputKeyStore);
        Utility.closeStream(outputKeyStore);
    }
}

From source file:org.kaazing.maven.plugins.TrustStoreMojo.java

KeyStore getTrustStore(Map<String, String> certs, String storeType) throws Exception {

    KeyStore ks = KeyStore.getInstance(storeType);

    // Initialize an empty keystore
    ks.load(null, null);//from www.  ja  v a2 s .  c o  m

    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

    for (Map.Entry<String, String> elt : certs.entrySet()) {
        String alias = elt.getKey();

        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(elt.getValue().getBytes(UTF8));

            X509Certificate cert = (X509Certificate) certFactory.generateCertificate(bais);
            cert.checkValidity();

            getLog().info(String.format("Adding certificate with alias '%s'", alias));
            ks.setCertificateEntry(alias, cert);

        } catch (CertificateExpiredException cee) {
            getLog().error(String.format("NOT Adding certificate %s: %s", alias, cee));

        } catch (CertificateNotYetValidException cnyve) {
            getLog().error(String.format("NOT Adding certificate %s: %s", alias, cnyve));
        }
    }

    return ks;
}