List of usage examples for java.security.cert CertificateFactory getInstance
public static final CertificateFactory getInstance(String type, Provider provider) throws CertificateException
From source file:org.kse.crypto.x509.X509CertUtil.java
/** * PKCS #7 encode a number of certificates. * * @return The encoding/* w w w. j a v a 2 s .co m*/ * @param certs * The certificates * @throws CryptoException * If there was a problem encoding the certificates */ public static byte[] getCertsEncodedPkcs7(X509Certificate[] certs) throws CryptoException { try { ArrayList<Certificate> encodedCerts = new ArrayList<Certificate>(); Collections.addAll(encodedCerts, certs); CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce()); CertPath cp = cf.generateCertPath(encodedCerts); return cp.getEncoded(PKCS7_ENCODING); } catch (CertificateException | NoSuchProviderException e) { throw new CryptoException(res.getString("NoPkcs7Encode.exception.message"), e); } }
From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java
private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data, String type, String fileName, String path, String storepass, KeyStore store) throws KeystoreEditorException { OutputStream fos = null;//from w ww.j a v a 2 s.c o m try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) { if (StringUtils.isBlank(alias)) { throw new IllegalArgumentException("Alias cannot be null."); } Path storeFile = Paths.get(path); //check the two most common key/cert stores first (pkcs12 and jks) if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) { //priv key + cert chain KeyStore pkcs12Store = KeyStore.getInstance("PKCS12"); pkcs12Store.load(inputStream, storePassword.toCharArray()); Certificate[] chain = pkcs12Store.getCertificateChain(alias); Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray()); if (key != null) { store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain); fos = Files.newOutputStream(storeFile); store.store(fos, storepass.toCharArray()); } } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) { //java keystore file KeyStore jks = KeyStore.getInstance("jks"); jks.load(inputStream, storePassword.toCharArray()); Enumeration<String> aliases = jks.aliases(); //we are going to store all entries from the jks regardless of the passed in alias while (aliases.hasMoreElements()) { String jksAlias = aliases.nextElement(); if (jks.isKeyEntry(jksAlias)) { Key key = jks.getKey(jksAlias, keyPassword.toCharArray()); Certificate[] certificateChain = jks.getCertificateChain(jksAlias); store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain); } else { Certificate certificate = jks.getCertificate(jksAlias); store.setCertificateEntry(jksAlias, certificate); } } fos = Files.newOutputStream(storeFile); store.store(fos, storepass.toCharArray()); //need to parse der separately from pem, der has the same mime type but is binary hence checking both } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) { ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream); ASN1Primitive asn1Primitive = asn1InputStream.readObject(); X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC"); Certificate certificate = certificateFactory .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded())); X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject(); RDN cn = x500name.getRDNs(BCStyle.CN)[0]; String cnStr = IETFUtils.valueToString(cn.getFirst().getValue()); if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) { store.setCertificateEntry(cnStr, certificate); } store.setCertificateEntry(alias, certificate); fos = Files.newOutputStream(storeFile); store.store(fos, storepass.toCharArray()); //if it isn't one of the stores we support, it might be a key or cert by itself } else if (isPemParsable(type, fileName)) { //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); PEMParser pemParser = new PEMParser(reader); Object object; boolean setEntry = false; while ((object = pemParser.readObject()) != null) { if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) { PEMKeyPair pemKeyPair; if (object instanceof PEMEncryptedKeyPair) { PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object; JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder(); pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair( jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray())); } else { pemKeyPair = (PEMKeyPair) object; } KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair); PrivateKey privateKey = keyPair.getPrivate(); Certificate[] chain = store.getCertificateChain(alias); if (chain == null) { chain = buildCertChain(alias, store); } store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain); setEntry = true; } else if (object instanceof X509CertificateHolder) { X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object; CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC"); Certificate certificate = certificateFactory .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded())); X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate) .getSubject(); RDN cn = x500name.getRDNs(BCStyle.CN)[0]; String cnStr = IETFUtils.valueToString(cn.getFirst().getValue()); if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) { store.setCertificateEntry(cnStr, certificate); } store.setCertificateEntry(alias, certificate); setEntry = true; } else if (object instanceof ContentInfo) { ContentInfo contentInfo = (ContentInfo) object; if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) { CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo); OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure(); ASN1Set certificates = originatorInfo.getCertificates(); setEntry = importASN1CertificatesToStore(store, setEntry, certificates); } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) { SignedData signedData = SignedData.getInstance(contentInfo.getContent()); ASN1Set certificates = signedData.getCertificates(); setEntry = importASN1CertificatesToStore(store, setEntry, certificates); } } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) { PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object; Certificate[] chain = store.getCertificateChain(alias); if (chain == null) { chain = buildCertChain(alias, store); } try { store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain); setEntry = true; } catch (KeyStoreException keyEx) { try { PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(), keyPassword.toCharArray()); store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(), chain); setEntry = true; } catch (GeneralSecurityException e) { LOGGER.error( "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.", e); throw keyEx; } } } } if (setEntry) { fos = Files.newOutputStream(storeFile); store.store(fos, storepass.toCharArray()); } } } catch (Exception e) { LOGGER.error("Unable to add entry {} to store", alias, e); throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e); } finally { if (fos != null) { try { fos.close(); } catch (IOException ignore) { } } } init(); }
From source file:org.apache.ws.security.components.crypto.Merlin.java
/** * Singleton certificate factory for this Crypto instance. * <p/>/* w w w.j a v a2 s. c om*/ * * @return Returns a <code>CertificateFactory</code> to construct * X509 certificates * @throws org.apache.ws.security.WSSecurityException */ @Override public CertificateFactory getCertificateFactory() throws WSSecurityException { String provider = getCryptoProvider(); String keyStoreProvider = null; if (keystore != null) { keyStoreProvider = keystore.getProvider().getName(); } //Try to find a CertificateFactory that generates certs that are fully //compatible with the certs in the KeyStore (Sun -> Sun, BC -> BC, etc...) CertificateFactory factory = null; if (provider != null) { factory = certFactMap.get(provider); } else if (keyStoreProvider != null) { factory = certFactMap.get(mapKeystoreProviderToCertProvider(keyStoreProvider)); if (factory == null) { factory = certFactMap.get(keyStoreProvider); } } else { factory = certFactMap.get("DEFAULT"); } if (factory == null) { try { if (provider == null || provider.length() == 0) { if (keyStoreProvider != null && keyStoreProvider.length() != 0) { try { factory = CertificateFactory.getInstance("X.509", mapKeystoreProviderToCertProvider(keyStoreProvider)); certFactMap.put(keyStoreProvider, factory); certFactMap.put(mapKeystoreProviderToCertProvider(keyStoreProvider), factory); } catch (Exception ex) { LOG.debug(ex); //Ignore, we'll just use the default since they didn't specify one. //Hopefully that will work for them. } } if (factory == null) { factory = CertificateFactory.getInstance("X.509"); certFactMap.put("DEFAULT", factory); } } else { factory = CertificateFactory.getInstance("X.509", provider); certFactMap.put(provider, factory); } certFactMap.put(factory.getProvider().getName(), factory); } catch (CertificateException e) { throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "unsupportedCertType", null, e); } catch (NoSuchProviderException e) { throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "noSecProvider", null, e); } } return factory; }
From source file:edu.vt.middleware.crypt.CryptProvider.java
/** * <p>This creates a <code>CertificateFactory</code> using the supplied type * name.</p>/*from w w w .jav a 2 s . c om*/ * * @param type <code>String</code> * * @return <code>CertificateFactory</code> * * @throws CryptException if the type is not available from any provider or * the provider is not available in the environment */ public static CertificateFactory getCertificateFactory(final String type) throws CryptException { final Log logger = LogFactory.getLog(CryptProvider.class); CertificateFactory cf = null; for (int i = 0; i < providers.length; i++) { try { cf = CertificateFactory.getInstance(type, providers[i]); } catch (CertificateException e) { if (logger.isDebugEnabled()) { logger.debug( "Could not get instance of certificate factory type " + type + " from " + providers[i]); } } catch (NoSuchProviderException e) { if (logger.isDebugEnabled()) { logger.debug("Could not find provider " + providers[i]); } } finally { if (cf != null) { break; } } } if (cf == null) { try { cf = CertificateFactory.getInstance(type); } catch (CertificateException e) { if (logger.isDebugEnabled()) { logger.debug("Could not get instance of certificate factory type " + type); } throw new CryptException(e.getMessage()); } } return cf; }
From source file:org.kse.crypto.x509.X509CertUtil.java
/** * PKI Path encode a number of certificates. * * @return The encoding/*from ww w . ja v a2s. c o m*/ * @param certs * The certificates * @throws CryptoException * If there was a problem encoding the certificates */ public static byte[] getCertsEncodedPkiPath(X509Certificate[] certs) throws CryptoException { try { ArrayList<Certificate> encodedCerts = new ArrayList<Certificate>(); Collections.addAll(encodedCerts, certs); CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce()); CertPath cp = cf.generateCertPath(encodedCerts); return cp.getEncoded(PKI_PATH_ENCODING); } catch (CertificateException | NoSuchProviderException e) { throw new CryptoException(res.getString("NoPkcs7Encode.exception.message"), e); } }
From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java
/** * PKCS #7 encode a number of certificates. * * @return The encoding// w w w . j av a 2 s. c o m * @param certs * The certificates * @throws CryptoException * If there was a problem encoding the certificates */ public static byte[] getCertsEncodedPkcs7(X509Certificate[] certs) throws CryptoException { try { ArrayList<Certificate> encodedCerts = new ArrayList<Certificate>(); Collections.addAll(encodedCerts, certs); CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce()); CertPath cp = cf.generateCertPath(encodedCerts); return cp.getEncoded(PKCS7_ENCODING); } catch (CertificateException e) { throw new CryptoException(res.getString("NoPkcs7Encode.exception.message"), e); } catch (NoSuchProviderException e) { throw new CryptoException(res.getString("NoPkcs7Encode.exception.message"), e); } }
From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java
/** * PKI Path encode a number of certificates. * * @return The encoding//from w ww . j av a2s.c o m * @param certs * The certificates * @throws CryptoException * If there was a problem encoding the certificates */ public static byte[] getCertsEncodedPkiPath(X509Certificate[] certs) throws CryptoException { try { ArrayList<Certificate> encodedCerts = new ArrayList<Certificate>(); Collections.addAll(encodedCerts, certs); CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce()); CertPath cp = cf.generateCertPath(encodedCerts); return cp.getEncoded(PKI_PATH_ENCODING); } catch (CertificateException e) { throw new CryptoException(res.getString("NoPkcs7Encode.exception.message"), e); } catch (NoSuchProviderException e) { throw new CryptoException(res.getString("NoPkcs7Encode.exception.message"), e); } }
From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java
private boolean importASN1CertificatesToStore(KeyStore store, boolean setEntry, ASN1Set certificates) throws KeystoreEditorException { Enumeration certificateEnumeration = certificates.getObjects(); try {// w w w.java 2s. c o m while (certificateEnumeration.hasMoreElements()) { ASN1Primitive asn1Primitive = ((ASN1Encodable) certificateEnumeration.nextElement()) .toASN1Primitive(); org.bouncycastle.asn1.x509.Certificate instance = org.bouncycastle.asn1.x509.Certificate .getInstance(asn1Primitive); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC"); Certificate certificate = certificateFactory .generateCertificate(new ByteArrayInputStream(instance.getEncoded())); X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject(); RDN cn = x500name.getRDNs(BCStyle.CN)[0]; store.setCertificateEntry(IETFUtils.valueToString(cn.getFirst().getValue()), certificate); setEntry = true; } } catch (CertificateException | NoSuchProviderException | KeyStoreException | IOException e) { throw new KeystoreEditorException("Unable to import ASN1 certificates to store", e); } return setEntry; }
From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java
/** * CRL- ? , ? ? , ? ?/*from www . java 2s.c o m*/ * ? * * @param crlName */ private void loadCrlObject(String crlName) { TypeOfCrlLoaded oldState = MAP_OF_LOAD_CRL_LABEL.get(crlName); if (TypeOfCrlLoaded.LOADING.equals(oldState)) { return; } MAP_OF_LOAD_CRL_LABEL.put(crlName, TypeOfCrlLoaded.LOADING); String location = MAP_OF_CRL_PATH.get(crlName); try { URL url = new URL(location); HttpURLConnection conn = null; if (useProxy) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort)); conn = (HttpURLConnection) url.openConnection(proxy); } else { conn = (HttpURLConnection) url.openConnection(); } conn.setUseCaches(false); conn.setDoInput(true); conn.connect(); if (conn.getResponseCode() == 200) { CertificateFactory cf = CertificateFactory.getInstance("X.509", "KALKAN"); X509CRL crlObject = (X509CRL) cf.generateCRL(conn.getInputStream()); MAP_OF_XCRL.put(crlName, crlObject); } else { String msg = "(1) ? CRL- : '" + location + "' : " + conn.getResponseCode() + " , " + conn.getResponseMessage(); log.warning(msg); } } catch (Exception e) { String msg = "(1) ? CRL- : '" + location + "' : " + e.getMessage(); log.warning(msg); } //MAP_OF_LOAD_CRL_LABEL.put(crlName, oldState ) ; MAP_OF_LOAD_CRL_TIME.put(crlName, new Date()); MAP_OF_LOAD_CRL_LABEL.put(crlName, TypeOfCrlLoaded.LOADED); }