List of usage examples for java.security.cert CertificateFactory getInstance
public static final CertificateFactory getInstance(String type) throws CertificateException
From source file:org.commonjava.util.jhttpc.INTERNAL.util.SSLUtils.java
public static KeyStore decodePEMTrustStore(final String pemContent, final String aliasPrefix) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException { Logger logger = LoggerFactory.getLogger(SSLUtils.class); final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null);/*from ww w . ja va2 s.com*/ final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); final List<String> lines = readLines(pemContent); final StringBuilder current = new StringBuilder(); final List<String> entries = new ArrayList<String>(); for (String line : lines) { if (line == null) { continue; } if (line.startsWith("-----BEGIN")) { current.setLength(0); } else if (line.startsWith("-----END")) { entries.add(current.toString()); } else { current.append(line); } } logger.trace("Found {} entries to decode.", entries.size()); int i = 0; for (final String entry : entries) { logger.trace("Decoding certificate info from:\n\n{}\n\n", entry); final byte[] data = decodeBase64(entry); final Certificate c = certFactory.generateCertificate(new ByteArrayInputStream(data)); X509Certificate cert = (X509Certificate) c; Set<String> aliases = new HashSet<String>(); if (i < 1) { aliases.add(aliasPrefix); } else { aliases.add(aliasPrefix + i); } extractAliases(cert, aliases); KeyStore.TrustedCertificateEntry ksEntry = new KeyStore.TrustedCertificateEntry(cert); for (String alias : aliases) { ks.setEntry(alias, ksEntry, null); logger.trace("Storing trusted cert under alias: {}\n with DN: {}", alias, cert.getSubjectDN().getName()); } logger.trace("Certificate added."); i++; } return ks; }
From source file:dk.itst.oiosaml.sp.metadata.CRLChecker.java
public void checkCertificates(IdpMetadata metadata, Configuration conf) { for (String entityId : metadata.getEntityIDs()) { Metadata md = metadata.getMetadata(entityId); for (X509Certificate certificate : md.getAllCertificates()) { String url = getCRLUrl(conf, entityId, certificate); if (url == null) { log.debug("No CRL configured in oiosaml-sp.properties, and no CRL found in certificate"); continue; }// w ww .j av a 2s . co m try { URL u = new URL(url); InputStream is = u.openStream(); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509CRL crl = (X509CRL) cf.generateCRL(is); is.close(); if (log.isDebugEnabled()) log.debug("CRL for " + url + ": " + crl); if (!checkCRLSignature(crl, certificate, conf)) { md.setCertificateValid(certificate, false); } else { X509CRLEntry revokedCertificate = crl.getRevokedCertificate(certificate.getSerialNumber()); boolean revoked = revokedCertificate != null; log.debug( "Certificate status for " + entityId + ": " + revoked + " - cert: " + certificate); Audit.log(Operation.CRLCHECK, false, entityId, "Revoked: " + revoked); md.setCertificateValid(certificate, !revoked); } } catch (MalformedURLException e) { log.error("Unable to parse url " + url, e); throw new WrappedException(Layer.BUSINESS, e); } catch (IOException e) { log.error("Unable to read CRL from " + url, e); throw new WrappedException(Layer.BUSINESS, e); } catch (GeneralSecurityException e) { throw new WrappedException(Layer.BUSINESS, e); } } } }
From source file:be.fedict.eid.applet.service.signer.ooxml.OPCKeySelector.java
public OPCKeySelector(URL opcUrl, String signatureResourceName) { this.opcUrl = opcUrl; this.signatureResourceName = signatureResourceName; try {/*from w ww . j a v a2s . c o m*/ JAXBContext relationshipsJAXBContext = JAXBContext.newInstance(ObjectFactory.class); this.relationshipsUnmarshaller = relationshipsJAXBContext.createUnmarshaller(); } catch (JAXBException e) { throw new RuntimeException("JAXB error: " + e.getMessage(), e); } try { this.certificateFactory = CertificateFactory.getInstance("X.509"); } catch (CertificateException e) { throw new RuntimeException("CertificateFactory error: " + e.getMessage(), e); } }
From source file:FileSystemDirectoryCertStore.java
/** * Creates a new instance over a directory using the specified extensions * @param dirPath the path for the base directory * @param certsFilesExts extensions for included certificate files * @param crlsFilesExts extensions for included CRL files * @throws CertificateException if there's an error reading the certificates * @throws CRLException if there's an error reading the CRLs *///w ww . j av a 2s .c om public FileSystemDirectoryCertStore(String dirPath, final String[] certsFilesExts, final String[] crlsFilesExts) throws CertificateException, CRLException { File dir = new File(dirPath); if (!dir.exists() || !dir.isDirectory()) throw new IllegalArgumentException("Specified path doesn't exist or doesn't refer a directory"); Collection contentList = new ArrayList(); CertificateFactory cf = CertificateFactory.getInstance("X.509"); transverseDirToFindContent(dir, contentList, certsFilesExts, crlsFilesExts, cf); try { this.content = CertStore.getInstance("Collection", new CollectionCertStoreParameters(contentList)); return; } catch (InvalidAlgorithmParameterException ex) { } catch (NoSuchAlgorithmException ex) { } // ToDo: this is a bit ugly! throw new CertificateException("Error getting Collection CertStore"); }
From source file:be.fedict.eid.dss.protocol.simple.client.SignatureResponseProcessor.java
/** * Main constructor./*from w w w .jav a 2 s .c om*/ * * @param serviceFingerprint * the service X509 certificate fingerprint (SHA1) used to * validate the signatory of the service signature. */ public SignatureResponseProcessor(byte[] serviceFingerprint) { try { this.certificateFactory = CertificateFactory.getInstance("X.509"); } catch (CertificateException e) { throw new RuntimeException("could not create certificate factory instance: " + e.getMessage(), e); } this.serviceFingerprint = serviceFingerprint; }
From source file:learn.encryption.ssl.SSLContext_Https.java
public static SSLContext getSSLContext2(String servercerfile, String clientkeyStore, String clientPass) { if (sslContext != null) { return sslContext; }// ww w . ja v a 2s . 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:gov.nih.nci.cacisweb.action.SecureFTPAddAction.java
@Override public String execute() throws Exception { log.debug("execute() - START"); String secureFTPPropertyFileLocation = CaCISUtil .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_PROPERTIES_FILE_LOCATION); String secureFTPKeystoreLocation = CaCISUtil.getPropertyFromPropertiesFile(secureFTPPropertyFileLocation, CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_TRUSTSTORE_LOCATION_PROP_NAME)); String secureFTPKeystorePassword = CaCISUtil.getPropertyFromPropertiesFile(secureFTPPropertyFileLocation, CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_TRUSTSTORE_PASSWORD_PROP_NAME)); try {/*www.j a v a2 s .co m*/ CaCISUtil caCISUtil = new CaCISUtil(); KeyStore keystore = caCISUtil.getKeystore(secureFTPKeystoreLocation, CaCISWebConstants.COM_KEYSTORE_TYPE_JKS, secureFTPKeystorePassword); if (keystore.containsAlias(secureFTPBean.getCertificateAlias())) { log.error(getText("secureFTPBean.duplicateKey")); addFieldError("secureFTPBean.certificateAlias", getText("secureFTPBean.duplicateKey")); } if (StringUtils.contains(secureFTPBean.getCertificateAlias(), "ftps")) { if (StringUtils.isBlank(secureFTPBean.getCertificateFileName())) { log.error(getText("secureFTPBean.certificateRequired")); addFieldError("secureFTPBean.certificateFileName", getText("secureFTPBean.certificateRequired")); caCISUtil.releaseKeystore(); return INPUT; } else { caCISUtil.releaseKeystore(); FileInputStream certificateStream = new FileInputStream(secureFTPBean.getCertificate()); CertificateFactory cf = CertificateFactory.getInstance("X.509"); java.security.cert.Certificate cert = cf.generateCertificate(certificateStream); // Add the certificate keystore.setCertificateEntry(secureFTPBean.getCertificateAlias(), cert); // Save the new keystore contents FileOutputStream out = new FileOutputStream(new File(secureFTPKeystoreLocation)); keystore.store(out, secureFTPKeystorePassword.toCharArray()); out.close(); } } // add the new entry to FTP configuration properties file PropertiesConfiguration config = new PropertiesConfiguration( CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_CONFIG_FILE_LOCATION)); config.setProperty(secureFTPBean.getCertificateAlias(), ""); config.save(); } catch (KeystoreInstantiationException kie) { log.error(kie.getMessage()); addActionError(getText("exception.keystoreInstantiation")); return ERROR; } catch (CertificateException ce) { log.error(CaCISUtil.getStackTrace(ce)); addActionError(getText("exception.certification")); return INPUT; } addActionMessage(getText("secureFTPBean.addCertificateSuccessful")); log.debug("execute() - END"); return SUCCESS; }
From source file:be.apsu.extremon.probes.xkms2.XKMS2Probe.java
public XKMS2Probe() throws CertificateException { super();//from ww w .jav a2s . co m this.trustService = new XKMS2Client(confStr("url")); this.certChain = new LinkedList<X509Certificate>(); this.delay = confInt("delay", DEFAULT_DELAY); this.domain = confStr("trust.domain").toUpperCase(); this.returnRevocationData = confBool("return.revocation.data", false); this.expectedFailure = confStr("expected.failure") != null ? confStr("expected.failure").toLowerCase() : null; this.running = false; final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); final String[] chain = confStr("chain").toLowerCase().split(","); for (String certName : chain) { final String encodedCert = confStr("cert." + certName); final X509Certificate cert = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(encodedCert))); this.certChain.add(cert); } start(); log("initialized"); }
From source file:org.commonjava.maven.galley.transport.htcli.internal.SSLUtils.java
public static KeyStore readCerts(final String pemContent, final String aliasPrefix) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException { final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null);/*from ww w. java 2 s . c o m*/ final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); final List<String> lines = readLines(pemContent); final StringBuilder current = new StringBuilder(); final List<String> entries = new ArrayList<String>(); for (final String line : lines) { if (line == null) { continue; } if (line.startsWith("-----BEGIN")) { current.setLength(0); } else if (line.startsWith("-----END")) { entries.add(current.toString()); } else { current.append(line.trim()); } } int i = 0; for (final String entry : entries) { final byte[] data = decodeBase64(entry); final Certificate c = certFactory.generateCertificate(new ByteArrayInputStream(data)); ks.setCertificateEntry(aliasPrefix + i, c); i++; } return ks; }
From source file:com.formkiq.core.service.propertystore.PropertyStoreDatabase.java
@Override public Optional<Certificate> retrieveCertificate() throws CertificateException { Optional<Certificate> result = Optional.empty(); String certstring = this.propertyService.getProperty(null, CERTIFICATE_KEY); if (!isEmpty(certstring)) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); result = Optional.of(cf.generateCertificate(new ByteArrayInputStream(Strings.getBytes(certstring)))); }// w w w. j a v a2 s . c o m return result; }