List of usage examples for java.security KeyStore setCertificateEntry
public final void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException
From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java
/** * Generates a self-signed certificate based on the keypair and saves it in the keystore. * Should only be used to init the CA.//w ww.j av a2 s . co m */ public void initCA(String rootCertX500Name, String mcidregCertX500Name, String crlUrl, String ocspUrl, String outputCaCrlPath) { if (KEYSTORE_PASSWORD == null) { KEYSTORE_PASSWORD = "changeit"; } if (ROOT_KEYSTORE_PATH == null) { ROOT_KEYSTORE_PATH = "mc-root-keystore.jks"; } if (INTERMEDIATE_KEYSTORE_PATH == null) { INTERMEDIATE_KEYSTORE_PATH = "mc-it-keystore.jks"; } if (TRUSTSTORE_PASSWORD == null) { TRUSTSTORE_PASSWORD = "changeit"; } if (TRUSTSTORE_PATH == null) { TRUSTSTORE_PATH = "mc-truststore.jks"; } if (CRL_URL == null) { CRL_URL = crlUrl; } if (OCSP_URL == null) { OCSP_URL = ocspUrl; } KeyPair cakp = generateKeyPair(); KeyPair imkp = generateKeyPair(); KeyStore rootks = null; KeyStore itks; KeyStore ts; FileOutputStream rootfos = null; FileOutputStream itfos = null; FileOutputStream tsfos = null; try { rootks = KeyStore.getInstance(KEYSTORE_TYPE); // KeyStore.getDefaultType() rootks.load(null, KEYSTORE_PASSWORD.toCharArray()); itks = KeyStore.getInstance(KEYSTORE_TYPE); // KeyStore.getDefaultType() itks.load(null, KEYSTORE_PASSWORD.toCharArray()); // Store away the keystore. rootfos = new FileOutputStream(ROOT_KEYSTORE_PATH); itfos = new FileOutputStream(INTERMEDIATE_KEYSTORE_PATH); X509Certificate cacert; try { cacert = buildAndSignCert(generateSerialNumber(), cakp.getPrivate(), cakp.getPublic(), cakp.getPublic(), new X500Name(rootCertX500Name), new X500Name(rootCertX500Name), null, "ROOTCA"); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } X509Certificate imcert; try { imcert = buildAndSignCert(generateSerialNumber(), cakp.getPrivate(), cakp.getPublic(), imkp.getPublic(), new X500Name(rootCertX500Name), new X500Name(mcidregCertX500Name), null, "INTERMEDIATE"); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } Certificate[] certChain = new Certificate[1]; certChain[0] = cacert; rootks.setKeyEntry(ROOT_CERT_ALIAS, cakp.getPrivate(), KEYSTORE_PASSWORD.toCharArray(), certChain); rootks.store(rootfos, KEYSTORE_PASSWORD.toCharArray()); rootks = KeyStore.getInstance(KeyStore.getDefaultType()); rootks.load(null, KEYSTORE_PASSWORD.toCharArray()); certChain = new Certificate[2]; certChain[0] = imcert; certChain[1] = cacert; itks.setKeyEntry(INTERMEDIATE_CERT_ALIAS, imkp.getPrivate(), KEYSTORE_PASSWORD.toCharArray(), certChain); itks.store(itfos, KEYSTORE_PASSWORD.toCharArray()); // Store away the truststore. ts = KeyStore.getInstance(KeyStore.getDefaultType()); ts.load(null, TRUSTSTORE_PASSWORD.toCharArray()); tsfos = new FileOutputStream(TRUSTSTORE_PATH); ts.setCertificateEntry(ROOT_CERT_ALIAS, cacert); ts.setCertificateEntry(INTERMEDIATE_CERT_ALIAS, imcert); ts.store(tsfos, TRUSTSTORE_PASSWORD.toCharArray()); } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { safeClose(rootfos); safeClose(itfos); safeClose(tsfos); KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection( KEYSTORE_PASSWORD.toCharArray()); PrivateKeyEntry rootCertEntry; try { rootCertEntry = (PrivateKeyEntry) rootks.getEntry(ROOT_CERT_ALIAS, protParam); generateRootCACRL(rootCertX500Name, null, rootCertEntry, outputCaCrlPath); } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) { // todo, I think is an irrecoverable state, but we should not throw exception from finally, perhaps this code should not be in a finally block log.error("unable to generate RootCACRL", e); } } }
From source file:org.hyperic.util.security.DatabaseSSLProviderImpl.java
private X509TrustManager getCustomTrustManager(final X509TrustManager defaultTrustManager, final KeystoreConfig keystoreConfig, final boolean acceptUnverifiedCertificates, final KeyStore trustStore) { return new X509TrustManager() { private final Log log = LogFactory.getLog(X509TrustManager.class); public X509Certificate[] getAcceptedIssuers() { return defaultTrustManager.getAcceptedIssuers(); }// w ww.j a va 2 s . c o m public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { try { defaultTrustManager.checkServerTrusted(chain, authType); } catch (CertificateException e) { CertificateExpiredException expiredCertException = getCertExpiredException(e); if (expiredCertException != null) { log.error("Fail the connection because received certificate is expired. " + "Please update the certificate.", expiredCertException); throw new CertificateException(e); } if (acceptUnverifiedCertificates) { log.info("Import the certification. (Received certificate is not trusted by keystore)"); importCertificate(chain); } else { log.warn( "Fail the connection because received certificate is not trusted by keystore: alias=" + keystoreConfig.getAlias() + ", path=" + keystoreConfig.getFilePath()); log.debug( "Fail the connection because received certificate is not trusted by keystore: alias=" + keystoreConfig.getAlias() + ", path=" + keystoreConfig.getFilePath() + ", acceptUnverifiedCertificates=" + acceptUnverifiedCertificates, e); throw new CertificateException(e); } } } private CertificateExpiredException getCertExpiredException(Exception e) { while (e != null) { if (e instanceof CertificateExpiredException) { return (CertificateExpiredException) e; } e = (Exception) e.getCause(); } return null; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { defaultTrustManager.checkClientTrusted(chain, authType); } private void importCertificate(X509Certificate[] chain) throws CertificateException { FileOutputStream keyStoreFileOutputStream = null; boolean hasLock = false; final boolean debug = log.isDebugEnabled(); final StopWatch watch = new StopWatch(); try { for (X509Certificate cert : chain) { String[] cnValues = AbstractVerifier.getCNs(cert); String alias; if (cnValues != null && cnValues.length > 0) { alias = cnValues[0]; } else { alias = "UnknownCN"; } alias += "-ts=" + System.currentTimeMillis(); trustStore.setCertificateEntry(alias, cert); } KEYSTORE_WRITER_LOCK.lockInterruptibly(); hasLock = true; keyStoreFileOutputStream = new FileOutputStream(keystoreConfig.getFilePath()); trustStore.store(keyStoreFileOutputStream, keystoreConfig.getFilePassword().toCharArray()); } catch (FileNotFoundException e) { // Can't find the keystore in the path log.error("Can't find the keystore in " + keystoreConfig.getFilePath() + ". Error message:" + e.getMessage(), e); } catch (NoSuchAlgorithmException e) { log.error("The algorithm is not supported. Error message:" + e.getMessage(), e); } catch (Exception e) { // expect KeyStoreException, IOException log.error("Exception when trying to import certificate: " + e.getMessage(), e); } finally { close(keyStoreFileOutputStream); keyStoreFileOutputStream = null; if (hasLock) { KEYSTORE_WRITER_LOCK.unlock(); } if (debug) log.debug("importCert: " + watch); } } private void close(FileOutputStream keyStoreFileOutputStream) { if (keyStoreFileOutputStream != null) { try { keyStoreFileOutputStream.close(); } catch (IOException e) { log.error(e, e); } } } }; }
From source file:mitm.application.djigzo.workflow.impl.KeyAndCertificateWorkflowImpl.java
private void getPFXTransacted(Collection<X509Certificate> certificates, char[] password, boolean includeRoot, OutputStream pfx) throws KeyStoreException { try {/*from www . jav a2 s .c o m*/ KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); keyStore.load(null); for (X509Certificate certificate : certificates) { if (certificate == null) { continue; } X509CertStoreEntry entry = keyAndCertStore.getByCertificate(certificate); if (entry != null && entry.getCertificate() != null) { KeyAndCertificate keyAndCertificate = keyAndCertStore.getKeyAndCertificate(entry); if (keyAndCertificate != null) { if (!certificate.equals(keyAndCertificate.getCertificate())) { throw new IllegalStateException("Certificate mismatch."); } X509Certificate[] chain = null; /* * Build a certificate chain so we add the chain (if valid) */ try { CertificatePathBuilder pathBuilder = pathBuilderFactory.createCertificatePathBuilder(); CertPathBuilderResult pathBuilderResult = pathBuilder.buildPath(certificate); X509Certificate root = null; if (includeRoot && pathBuilderResult instanceof PKIXCertPathBuilderResult) { TrustAnchor trustAnchor = ((PKIXCertPathBuilderResult) pathBuilderResult) .getTrustAnchor(); if (trustAnchor != null) { root = trustAnchor.getTrustedCert(); } } CertPath certPath = pathBuilderResult.getCertPath(); if (certPath != null && CollectionUtils.isNotEmpty(certPath.getCertificates())) { List<X509Certificate> completePath = new LinkedList<X509Certificate>(); for (Certificate fromPath : certPath.getCertificates()) { if (!(fromPath instanceof X509Certificate)) { /* * only X509Certificates are supported */ continue; } completePath.add((X509Certificate) fromPath); } if (root != null && includeRoot) { completePath.add(root); } chain = new X509Certificate[completePath.size()]; chain = completePath.toArray(chain); } } catch (CertPathBuilderException e) { logger.warn( "Could not build a path. Message: " + ExceptionUtils.getRootCauseMessage(e)); } if (ArrayUtils.getLength(chain) == 0) { chain = new X509Certificate[] { certificate }; } String alias = X509CertificateInspector.getThumbprint(certificate); if (keyAndCertificate.getPrivateKey() != null) { keyStore.setKeyEntry(alias, keyAndCertificate.getPrivateKey(), password, chain); } else { keyStore.setCertificateEntry(alias, certificate); } } } } keyStore.store(pfx, password); } catch (NoSuchAlgorithmException e) { throw new KeyStoreException(e); } catch (CertificateException e) { throw new KeyStoreException(e); } catch (IOException e) { throw new KeyStoreException(e); } catch (CertStoreException e) { throw new KeyStoreException(e); } catch (NoSuchProviderException e) { throw new NoSuchProviderRuntimeException(e); } catch (SecurityFactoryFactoryException e) { throw new KeyStoreException(e); } }
From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java
private static void importIdpMetadata(Options options, CommandLine cmd, String unisonXMLFile, TremoloType ttRead, TremoloType ttWrite, String ksPath, KeyStore ks) throws ParserConfigurationException, SAXException, IOException, FileNotFoundException, UnmarshallingException, Exception, Base64DecodingException, CertificateException, KeyStoreException, NoSuchAlgorithmException, JAXBException, PropertyException { logger.info("Import SP Metadata into the IdP"); logger.info("Loading Metadata..."); String metadataFile = loadOption(cmd, "pathToMetaData", options); InitializationService.initialize();/*from w w w . jav a 2s. c o m*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Element root = builder.parse(new InputSource(new InputStreamReader(new FileInputStream(metadataFile)))) .getDocumentElement(); EntityDescriptor ed = (EntityDescriptor) XMLObjectSupport.getUnmarshaller(root).unmarshall(root); logger.info("Loading IdP..."); String idpName = loadOption(cmd, "idpName", options); ApplicationType idp = null; for (ApplicationType app : ttWrite.getApplications().getApplication()) { if (app.getName().equalsIgnoreCase(idpName)) { idp = app; } } if (idp == null) { throw new Exception("IdP '" + idpName + "' not found"); } SPSSODescriptor sp = ed.getSPSSODescriptor("urn:oasis:names:tc:SAML:2.0:protocol"); TrustType trust = null; trust = new TrustType(); if (sp.getID() == null) { trust.setName(ed.getEntityID()); } else { trust.setName(sp.getID()); } for (AssertionConsumerService svc : sp.getAssertionConsumerServices()) { if (svc.getBinding().equalsIgnoreCase("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST")) { ParamType pt = new ParamType(); pt.setName("httpPostRespURL"); pt.setValue(svc.getLocation()); trust.getParam().add(pt); } } ParamType pt = new ParamType(); pt.setName("signAssertion"); pt.setValue(Boolean.toString(sp.getWantAssertionsSigned().booleanValue())); trust.getParam().add(pt); if (pt.getValue().equalsIgnoreCase("false")) { pt = new ParamType(); pt.setName("signResponse"); pt.setValue("true"); trust.getParam().add(pt); } else { pt = new ParamType(); pt.setName("signResponse"); pt.setValue("false"); trust.getParam().add(pt); } boolean first = true; for (NameIDFormat nameid : sp.getNameIDFormats()) { if (first) { pt = new ParamType(); pt.setName("defaultNameId"); pt.setValue(nameid.getFormat()); trust.getParam().add(pt); first = false; } pt = new ParamType(); pt.setName("nameIdMap"); pt.setValue(nameid.getFormat() + "="); trust.getParam().add(pt); } boolean encryptAssertion = false; boolean signAssertion = false; for (KeyDescriptor kd : sp.getKeyDescriptors()) { if (kd.getUse().equals(UsageType.SIGNING)) { String base64 = kd.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0).getValue(); String name = "verify-" + ed.getEntityID() + "-sp-sig"; ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(base64)); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Collection<? extends Certificate> c = cf.generateCertificates(bais); if (c.size() > 1) { int j = 0; Iterator<? extends Certificate> i = c.iterator(); while (i.hasNext()) { Certificate certificate = (Certificate) i.next(); ks.setCertificateEntry(name + "-" + j, certificate); } } else { ks.setCertificateEntry(name, c.iterator().next()); } pt = new ParamType(); pt.setName("spSigKey"); pt.setValue(name); trust.getParam().add(pt); signAssertion = true; } if (kd.getUse().equals(UsageType.ENCRYPTION)) { String base64 = kd.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0).getValue(); String name = "verify-" + ed.getEntityID() + "-sp-enc"; ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(base64)); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Collection<? extends Certificate> c = cf.generateCertificates(bais); if (c.size() > 1) { int j = 0; Iterator<? extends Certificate> i = c.iterator(); while (i.hasNext()) { Certificate certificate = (Certificate) i.next(); ks.setCertificateEntry(name + "-" + j, certificate); } } else { ks.setCertificateEntry(name, c.iterator().next()); } pt = new ParamType(); pt.setName("spEncKey"); pt.setValue(name); trust.getParam().add(pt); encryptAssertion = true; } } pt = new ParamType(); pt.setName("encAssertion"); pt.setValue(encryptAssertion ? "true" : "false"); trust.getParam().add(pt); if (!signAssertion) { pt = new ParamType(); pt.setName("spSigKey"); pt.setValue(""); trust.getParam().add(pt); } if (!encryptAssertion) { pt = new ParamType(); pt.setName("spEncKey"); pt.setValue(""); trust.getParam().add(pt); } pt = new ParamType(); pt.setName("defaultAuthCtx"); pt.setValue(""); trust.getParam().add(pt); TrustType cur = null; for (TrustType trustType : idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust()) { if (trustType.getName().equals(trust.getName())) { cur = trustType; break; } } if (cur != null) { idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust().remove(cur); } idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust().add(trust); OpenUnisonUtils.storeMethod(unisonXMLFile, ttWrite, ksPath, ks); }