List of usage examples for java.security.cert CertificateFactory generateCertificate
public final Certificate generateCertificate(InputStream inStream) throws CertificateException
From source file:org.digidoc4j.X509Cert.java
/** * Creates an X509 certificate from a path. * * @param path X509 certificate path/* w w w.j a v a 2 s.c o m*/ * @throws Exception throws an exception if the X509 certificate parsing fails */ X509Cert(String path) throws CertificateException, IOException { logger.debug(""); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); try (FileInputStream inStream = new FileInputStream(new File(path))) { originalCert = (X509Certificate) certificateFactory.generateCertificate(inStream); } logger.debug("Certificate created from path: " + path); }
From source file:de.brendamour.jpasskit.signing.PKSigningInformationUtil.java
/** * Load a DER Certificate from an <code>InputStream</code>. * /*ww w.ja v a2 s . com*/ * The caller is responsible for closing the stream after this method returns successfully or fails. * * @param certificateInputStream * <code>InputStream</code> containing the certificate. * @return Loaded certificate. * @throws IOException * @throws CertificateException */ public X509Certificate loadDERCertificate(final InputStream certificateInputStream) throws IOException, CertificateException { try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME); Certificate certificate = certificateFactory.generateCertificate(certificateInputStream); if (certificate instanceof X509Certificate) { ((X509Certificate) certificate).checkValidity(); return (X509Certificate) certificate; } throw new IOException("The key from the input stream could not be decrypted"); } catch (IOException ex) { throw new IOException("The key from the input stream could not be decrypted", ex); } catch (NoSuchProviderException ex) { throw new IOException("The key from the input stream could not be decrypted", ex); } }
From source file:com.vmware.identity.openidconnect.server.LoginProcessor.java
private PersonUser processPersonUserCertificateLogin() throws LoginException { if (this.httpRequest .getCookieValue(SessionManager.getPersonUserCertificateLoggedOutCookieName(this.tenant)) != null) { throw new LoginException("already logged in once on this browser session", localize(ErrorMessage.LOGGED_OUT_TLS_SESSION)); }//from w ww . ja v a 2 s. co m List<X509Certificate> personUserCertificateChain; String certString64 = this.httpRequest.getHeaderValue("X-SSL-Client-Certificate"); if (!StringUtils.isEmpty(certString64)) { byte[] certBytes = Base64Utils.decodeToBytes(certString64); ByteArrayInputStream inputStream = new ByteArrayInputStream(certBytes); try { CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(inputStream); personUserCertificateChain = Arrays.asList(cert); } catch (CertificateException e) { throw new LoginException("failed to parse person user cert", localize(ErrorMessage.INVALID_CREDENTIAL), e); } } else { personUserCertificateChain = this.httpRequest.getClientCertificateChain(); if (personUserCertificateChain == null || personUserCertificateChain.size() == 0) { throw new LoginException("missing person user cert", localize(ErrorMessage.NO_CLIENT_CERT)); } } try { return this.personUserAuthenticator.authenticateByPersonUserCertificate(this.tenant, personUserCertificateChain); } catch (InvalidCredentialsException e) { throw new LoginException("invalid person user cert", localize(ErrorMessage.INVALID_CREDENTIAL), e); } catch (ServerException e) { throw new LoginException("error while authenticating person user cert", localize(ErrorMessage.RESPONDER), e); } }
From source file:org.sufficientlysecure.keychain.ui.SettingsSmartPGPAuthorityFragment.java
private boolean editAuthority(final String old_alias, final String new_alias, final int position, final String uri) { try {/*from w ww . ja va 2 s. c o m*/ final KeyStore ks = SettingsSmartPGPAuthoritiesActivity.readKeystore(getContext()); if (ks == null) { throw new KeyStoreException("no keystore found"); } Certificate old_cert = null; if (old_alias != null) { old_cert = ks.getCertificate(old_alias); ks.deleteEntry(old_alias); mAuthorities.remove(old_alias); mAdapter.notifyItemRemoved(position); } Certificate new_cert = null; if (uri == null) { new_cert = old_cert; } else { final InputStream fis = getContext().getContentResolver().openInputStream(Uri.parse(uri)); final CertificateFactory cf = CertificateFactory.getInstance("X.509"); new_cert = cf.generateCertificate(fis); if (!(new_cert instanceof X509Certificate)) { Notify.create(getActivity(), "Invalid certificate", Notify.LENGTH_LONG, Notify.Style.ERROR) .show(); return false; } fis.close(); } if (new_alias == null || new_cert == null) { Notify.create(getActivity(), "Missing alias or certificate", Notify.LENGTH_LONG, Notify.Style.ERROR) .show(); return false; } final X509Certificate x509cert = (X509Certificate) new_cert; x509cert.checkValidity(); ks.setCertificateEntry(new_alias, x509cert); SettingsSmartPGPAuthoritiesActivity.writeKeystore(getContext(), ks); mAuthorities.add(new_alias); mAdapter.notifyItemInserted(mAuthorities.size() - 1); return true; } catch (IOException e) { Notify.create(getActivity(), "failed to open certificate (" + e.getMessage() + ")", Notify.LENGTH_LONG, Notify.Style.ERROR).show(); } catch (CertificateException e) { Notify.create(getActivity(), "invalid certificate (" + e.getMessage() + ")", Notify.LENGTH_LONG, Notify.Style.ERROR).show(); } catch (KeyStoreException e) { Notify.create(getActivity(), "invalid keystore (" + e.getMessage() + ")", Notify.LENGTH_LONG, Notify.Style.ERROR).show(); } return false; }
From source file:de.brendamour.jpasskit.signing.PKSigningInformationUtil.java
/** * Load certificate file in DER format from the filesystem or the classpath * //w w w . j a v a 2s .c o m * @param filePath * @return * @throws IOException * @throws CertificateException */ public X509Certificate loadDERCertificate(final String filePath) throws IOException, CertificateException { FileInputStream certificateFileInputStream = null; try { File certFile = new File(filePath); if (!certFile.exists()) { // try loading it from the classpath URL localCertFile = PKFileBasedSigningUtil.class.getClassLoader().getResource(filePath); if (localCertFile == null) { throw new FileNotFoundException("File at " + filePath + " not found"); } certFile = new File(localCertFile.getFile()); } certificateFileInputStream = new FileInputStream(certFile); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME); Certificate certificate = certificateFactory.generateCertificate(certificateFileInputStream); if (certificate instanceof X509Certificate) { ((X509Certificate) certificate).checkValidity(); return (X509Certificate) certificate; } throw new IOException("The key from '" + filePath + "' could not be decrypted"); } catch (IOException ex) { throw new IOException("The key from '" + filePath + "' could not be decrypted", ex); } catch (NoSuchProviderException ex) { throw new IOException("The key from '" + filePath + "' could not be decrypted", ex); } finally { IOUtils.closeQuietly(certificateFileInputStream); } }
From source file:be.apsu.extremon.probes.ocsp.OCSPProbe.java
public OCSPProbe() { CertificateFactory certificateFactory = null; try {/*from w w w . java 2 s . c o m*/ certificateFactory = CertificateFactory.getInstance("X.509"); } catch (CertificateException cex) { log("Don't Have Crypto Libs:" + cex.getMessage()); System.exit(1); } try { certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(confStr("certificate")))); trustAnchorCert = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(confStr("trustanchor")))); } catch (CertificateException cex) { log("certificate and trustanchor required in config:" + cex.getMessage()); System.exit(2); } this.delay = confInt("delay", DEFAULT_DELAY); try { List<X509Certificate> certs = new ArrayList<X509Certificate>(); certs.add(this.certificate); this.certificatePath = (CertPath) certificateFactory.generateCertPath(certs); TrustAnchor trustAnchor = new TrustAnchor(this.trustAnchorCert, null); Set<TrustAnchor> trustedCertsSet = new HashSet<TrustAnchor>(); trustedCertsSet.add(trustAnchor); Set<X509Certificate> certSet = new HashSet<X509Certificate>(); certSet.add(this.trustAnchorCert); CertStoreParameters storeParams = new CollectionCertStoreParameters(certSet); CertStore store = CertStore.getInstance("Collection", storeParams); pkixParams = new PKIXParameters(trustedCertsSet); pkixParams.addCertStore(store); Security.setProperty("ocsp.enable", "true"); Security.setProperty("ocsp.responderURL", confStr("url")); Security.setProperty("ocsp.responderCertSubjectName", this.trustAnchorCert.getSubjectX500Principal().getName()); this.certificatePathValidator = CertPathValidator.getInstance("PKIX"); } catch (InvalidAlgorithmParameterException iaex) { log("Invalid Algorithm Parameter:" + iaex.getMessage()); System.exit(3); } catch (CertificateException cex) { log("Certificate Exception:" + cex.getMessage()); System.exit(4); } catch (NoSuchAlgorithmException nsaex) { log("No Such Algorithm:" + nsaex.getMessage()); System.exit(5); } catch (Exception ex) { log(ex.getMessage()); System.exit(6); } start(); log("Initialized"); }
From source file:be.fedict.trust.client.ServerCrypto.java
public X509Certificate loadCertificate(InputStream in) throws WSSecurityException { LOG.debug("loadCertificate"); CertificateFactory certificateFactory; try {// www . j a va 2 s . c o m certificateFactory = CertificateFactory.getInstance("X.509"); } catch (CertificateException e) { throw new WSSecurityException("X509 algo", e); } X509Certificate certificate; try { certificate = (X509Certificate) certificateFactory.generateCertificate(in); } catch (CertificateException e) { throw new WSSecurityException("X509 error: " + e.getMessage(), e); } if (null == this.certificate) { LOG.debug("trusting incoming certificate as is"); this.certificate = certificate; } return certificate; }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPSConnectionAndTrustConfirmationIT.java
@Test public void testTrustConfirmationAddDeleteCertificateDirectly() throws CMException, IOException, CertificateException { // Initially trust provider list is empty, we only verify by what is in // Credential Manager's Truststore (and it does not contains the certificate for https://heater.cs.man.ac.uk:7443/) // Do not forget to initialise Taverna's/Credential Manager's SSLSocketFactory credentialManager.initializeSSL();/*from ww w .j ava2 s.c om*/ URL url = new URL("https://heater.cs.man.ac.uk:7443/"); HttpsURLConnection conn; conn = (HttpsURLConnection) url.openConnection(); try { // This should fail conn.connect(); fail("Connection to https://heater.cs.man.ac.uk:7443/ should be untrusted at this point."); } catch (SSLHandshakeException sslex) { // expected to fail so all is good } finally { conn.disconnect(); } // Add heater's certificate directly to Credential Manager's Truststore // Load the test trusted certificate (belonging to heater.cs.man.ac.uk) X509Certificate trustedCertficate; URL trustedCertficateFileURL = getClass().getResource("/security/tomcat_heater_certificate.pem"); System.out.println("testTrustConfirmationAddDeleteCertificateDirectly: trusted certficate file URL " + trustedCertficateFileURL); File trustedCertFile = new File(trustedCertficateFileURL.getPath()); FileInputStream inStream = new FileInputStream(trustedCertFile); //InputStream inStream = getClass().getClassLoader().getResourceAsStream("security/tomcat_heater_certificate.pem"); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); trustedCertficate = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } String alias = credentialManager.addTrustedCertificate(trustedCertficate); HttpsURLConnection conn2 = (HttpsURLConnection) url.openConnection(); // This should work now conn2.connect(); //System.out.println(conn2.getHeaderField(0)); assertEquals("HTTP/1.1 200 OK", conn2.getHeaderField(0)); conn2.disconnect(); // Now remove certificate and see if the "trust" changes credentialManager.deleteTrustedCertificate(alias); HttpsURLConnection conn3; conn3 = (HttpsURLConnection) url.openConnection(); try { // This should fail conn3.connect(); fail("Connection to https://heater.cs.man.ac.uk:7443/ should be untrusted at this point."); } catch (SSLHandshakeException sslex) { // expected to fail so all is good } finally { conn3.disconnect(); } }
From source file:com.amazon.alexa.avs.auth.companionservice.CompanionServiceClient.java
/** * Loads the CA certificate into an in-memory keystore and creates an {@link SSLSocketFactory}. * * @return SSLSocketFactory//from w w w. jav a 2 s .c o m */ public SSLSocketFactory getPinnedSSLSocketFactory() { InputStream caCertInputStream = null; InputStream clientKeyPair = null; try { // Load the CA certificate into memory CertificateFactory cf = CertificateFactory.getInstance("X.509"); caCertInputStream = new FileInputStream(deviceConfig.getCompanionServiceInfo().getSslCaCert()); Certificate caCert = cf.generateCertificate(caCertInputStream); // Load the CA certificate into the trusted KeyStore KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); trustStore.setCertificateEntry("myca", caCert); // Create a TrustManagerFactory with the trusted KeyStore TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); // Load the client certificate and private key into another KeyStore KeyStore keyStore = KeyStore.getInstance("PKCS12"); clientKeyPair = new FileInputStream(deviceConfig.getCompanionServiceInfo().getSslClientKeyStore()); keyStore.load(clientKeyPair, deviceConfig.getCompanionServiceInfo().getSslClientKeyStorePassphrase().toCharArray()); // Create a TrustManagerFactory with the client key pair KeyStore KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, deviceConfig.getCompanionServiceInfo().getSslClientKeyStorePassphrase().toCharArray()); // Initialize the SSLContext and return an SSLSocketFactory; SSLContext sc = SSLContext.getInstance("TLS"); sc.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); return sc.getSocketFactory(); } catch (CertificateException | KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException | IOException | KeyManagementException e) { throw new RuntimeException("The KeyStore for contacting the Companion Service could not be loaded.", e); } finally { IOUtils.closeQuietly(caCertInputStream); IOUtils.closeQuietly(clientKeyPair); } }