List of usage examples for java.security.cert CertificateFactory generateCertificate
public final Certificate generateCertificate(InputStream inStream) throws CertificateException
From source file:nl.nikhef.eduroam.WiFiEduroam.java
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) // Step 3 for android 4.0 - 4.2 private void installClientCertificate() { try {//from w ww .j a v a 2 s. c om updateStatus("Inputting client certificate."); // Parse the certificate that we got from the server CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream( Base64.decode(certificate.replaceAll("-----(BEGIN|END) CERTIFICATE-----", ""))); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in); client_cert_name = ssid + " " + INT_CLIENT_CERT_NAME; // Create a pkcs12 certificate/private key combination Security.addProvider(new BouncyCastleProvider()); KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(null, null); Certificate chain[] = new Certificate[] { (Certificate) cert }; keystore.setKeyEntry(client_cert_name, csr.getPrivate(), null, chain); ByteArrayOutputStream out = new ByteArrayOutputStream(); keystore.store(out, ssid.toCharArray()); out.flush(); byte[] buffer = out.toByteArray(); out.close(); // Install the private key/client certificate combination Intent intent = KeyChain.createInstallIntent(); intent.putExtra(KeyChain.EXTRA_NAME, ssid + " " + INT_CLIENT_CERT_NAME); intent.putExtra(KeyChain.EXTRA_PKCS12, buffer); startActivityForResult(intent, 3); } catch (CertificateException e) { e.printStackTrace(); throw new RuntimeException("Certificate error."); } catch (KeyStoreException e) { e.printStackTrace(); System.out.println(e.getMessage()); throw new RuntimeException("Certificate error: KeyStore"); } catch (NoSuchProviderException e) { e.printStackTrace(); throw new RuntimeException("Certificate error: Provider"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new RuntimeException("Certificate error: Algorithm"); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Certificate error: IO"); } }
From source file:be.fedict.trust.service.bean.DownloaderMDB.java
private void processColdStartMessage(ColdStartMessage coldStartMessage) { if (null == coldStartMessage) { return;// w w w . ja v a 2s.c o m } String crlUrl = coldStartMessage.getCrlUrl(); String certUrl = coldStartMessage.getCertUrl(); LOG.debug("cold start CRL URL: " + crlUrl); LOG.debug("cold start CA URL: " + certUrl); File crlFile = download(crlUrl); File certFile = download(certUrl); // parsing CertificateFactory certificateFactory; try { certificateFactory = CertificateFactory.getInstance("X.509"); } catch (CertificateException e) { LOG.debug("certificate factory error: " + e.getMessage(), e); crlFile.delete(); certFile.delete(); return; } X509Certificate certificate = null; try { certificate = (X509Certificate) certificateFactory.generateCertificate(new FileInputStream(certFile)); } catch (Exception e) { LOG.debug("error DER-parsing certificate"); try { PEMReader pemReader = new PEMReader(new FileReader(certFile)); certificate = (X509Certificate) pemReader.readObject(); pemReader.close(); } catch (Exception e2) { retry("error PEM-parsing certificate", e, certFile, crlFile); } } certFile.delete(); X509CRL crl = null; try { crl = (X509CRL) certificateFactory.generateCRL(new FileInputStream(crlFile)); } catch (Exception e) { retry("error parsing CRL", e, crlFile); } // first check whether the two correspond try { crl.verify(certificate.getPublicKey()); } catch (Exception e) { LOG.error("no correspondence between CRL and CA"); LOG.error("CRL issuer: " + crl.getIssuerX500Principal()); LOG.debug("CA subject: " + certificate.getSubjectX500Principal()); crlFile.delete(); return; } LOG.debug("CRL matches CA: " + certificate.getSubjectX500Principal()); // skip expired CAs Date now = new Date(); Date notAfter = certificate.getNotAfter(); if (now.after(notAfter)) { LOG.warn("CA already expired: " + certificate.getSubjectX500Principal()); crlFile.delete(); return; } // create database entitities CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO .findCertificateAuthority(certificate); if (null != certificateAuthority) { LOG.debug("CA already in cache: " + certificate.getSubjectX500Principal()); crlFile.delete(); return; } /* * Lookup Root CA's trust point via parent certificates' CA entity. */ LOG.debug( "Lookup Root CA's trust point via parent certificates' CA entity - Don't have Issuer's Serial Number??"); String parentIssuerName = certificate.getIssuerX500Principal().toString(); CertificateAuthorityEntity parentCertificateAuthority = this.certificateAuthorityDAO .findCertificateAuthority(parentIssuerName); if (null == parentCertificateAuthority) { LOG.error("CA not found for " + parentIssuerName + " ?!"); crlFile.delete(); return; } LOG.debug("parent CA: " + parentCertificateAuthority.getName()); TrustPointEntity parentTrustPoint = parentCertificateAuthority.getTrustPoint(); if (null != parentTrustPoint) { LOG.debug("trust point parent: " + parentTrustPoint.getName()); LOG.debug("previous trust point fire data: " + parentTrustPoint.getFireDate()); } else { LOG.debug("no parent trust point"); } // create new CA certificateAuthority = this.certificateAuthorityDAO.addCertificateAuthority(certificate, crlUrl); // prepare harvesting certificateAuthority.setTrustPoint(parentTrustPoint); certificateAuthority.setStatus(Status.PROCESSING); if (null != certificateAuthority.getTrustPoint() && null == certificateAuthority.getTrustPoint().getFireDate()) { try { this.schedulingService.startTimer(certificateAuthority.getTrustPoint()); } catch (InvalidCronExpressionException e) { LOG.error("invalid cron expression"); crlFile.delete(); return; } } // notify harvester String crlFilePath = crlFile.getAbsolutePath(); try { this.notificationService.notifyHarvester(certificate.getSubjectX500Principal().toString(), crlFilePath, false); } catch (JMSException e) { crlFile.delete(); throw new RuntimeException(e); } }
From source file:org.jenkins_ci.update_center.Main.java
private X509Certificate loadCertificate(CertificateFactory cf, File f) throws CertificateException, IOException { FileInputStream in = new FileInputStream(f); try {//ww w. ja va 2s. c o m X509Certificate c = (X509Certificate) cf.generateCertificate(in); c.checkValidity(); return c; } finally { in.close(); } }
From source file:org.apache.xml.security.keys.storage.implementations.CertsInFilesystemDirectoryResolver.java
/** * Method readCertsFromHarddrive/* w w w .ja va 2s. c om*/ * * @throws StorageResolverException */ private void readCertsFromHarddrive() throws StorageResolverException { File certDir = new File(this.merlinsCertificatesDir); List<String> al = new ArrayList<String>(); String[] names = certDir.list(); for (int i = 0; i < names.length; i++) { String currentFileName = names[i]; if (currentFileName.endsWith(".crt")) { al.add(names[i]); } } CertificateFactory cf = null; try { cf = CertificateFactory.getInstance("X.509"); } catch (CertificateException ex) { throw new StorageResolverException("empty", ex); } if (cf == null) { throw new StorageResolverException("empty"); } for (int i = 0; i < al.size(); i++) { String filename = certDir.getAbsolutePath() + File.separator + (String) al.get(i); File file = new File(filename); boolean added = false; String dn = null; try { FileInputStream fis = new FileInputStream(file); X509Certificate cert = (X509Certificate) cf.generateCertificate(fis); fis.close(); //add to ArrayList cert.checkValidity(); this.certs.add(cert); dn = cert.getSubjectDN().getName(); added = true; } catch (FileNotFoundException ex) { if (log.isDebugEnabled()) { log.debug("Could not add certificate from file " + filename, ex); } } catch (IOException ex) { if (log.isDebugEnabled()) { log.debug("Could not add certificate from file " + filename, ex); } } catch (CertificateNotYetValidException ex) { if (log.isDebugEnabled()) { log.debug("Could not add certificate from file " + filename, ex); } } catch (CertificateExpiredException ex) { if (log.isDebugEnabled()) { log.debug("Could not add certificate from file " + filename, ex); } } catch (CertificateException ex) { if (log.isDebugEnabled()) { log.debug("Could not add certificate from file " + filename, ex); } } if (added && log.isDebugEnabled()) { log.debug("Added certificate: " + dn); } } }
From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java
public void importCertToStore(String fileName, String certData, String keyStoreName) throws SecurityConfigException { try {//from w w w. j a va 2 s. c o m if (keyStoreName == null) { throw new SecurityConfigException("Key Store name can't be null"); } KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId); KeyStore ks = keyMan.getKeyStore(keyStoreName); byte[] bytes = Base64.decode(certData); CertificateFactory factory = CertificateFactory.getInstance("X.509"); X509Certificate cert; try { cert = (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException e) { log.error(e.getMessage(), e); throw new SecurityConfigException("Invalid format of the provided certificate file"); } if (ks.getCertificateAlias(cert) != null) { // We already have this certificate in the key store - ignore // adding it twice return; } ks.setCertificateEntry(fileName, cert); keyMan.updateKeyStore(keyStoreName, ks); } catch (SecurityConfigException e) { throw e; } catch (Exception e) { String msg = "Error when importing cert to the keyStore"; log.error(msg, e); throw new SecurityConfigException(msg, e); } }
From source file:org.codice.ddf.security.filter.login.LoginFilter.java
private void validateHolderOfKeyConfirmation(SamlAssertionWrapper assertion, X509Certificate[] x509Certs) throws SecurityServiceException { List<String> confirmationMethods = assertion.getConfirmationMethods(); boolean hasHokMethod = false; for (String method : confirmationMethods) { if (OpenSAMLUtil.isMethodHolderOfKey(method)) { hasHokMethod = true;/* w w w. j a v a 2 s . c om*/ } } if (hasHokMethod) { if (x509Certs != null && x509Certs.length > 0) { List<SubjectConfirmation> subjectConfirmations = assertion.getSaml2().getSubject() .getSubjectConfirmations(); for (SubjectConfirmation subjectConfirmation : subjectConfirmations) { if (OpenSAMLUtil.isMethodHolderOfKey(subjectConfirmation.getMethod())) { Element dom = subjectConfirmation.getSubjectConfirmationData().getDOM(); Node keyInfo = dom.getFirstChild(); Node x509Data = keyInfo.getFirstChild(); Node dataNode = x509Data.getFirstChild(); Node dataText = dataNode.getFirstChild(); X509Certificate tlsCertificate = x509Certs[0]; if (dataNode.getLocalName().equals("X509Certificate")) { String textContent = dataText.getTextContent(); byte[] byteValue = Base64.getMimeDecoder().decode(textContent); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(byteValue)); //check that the certificate is still valid cert.checkValidity(); //HoK spec section 2.5: //relying party MUST ensure that the certificate bound to the assertion matches the X.509 certificate in its possession. //Matching is done by comparing the base64-decoded certificates, or the hash values of the base64-decoded certificates, byte-for-byte. //if the certs aren't the same, verify if (!tlsCertificate.equals(cert)) { //verify that the cert was signed by the same private key as the TLS cert cert.verify(tlsCertificate.getPublicKey()); } } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException e) { throw new SecurityServiceException( "Unable to validate Holder of Key assertion with certificate."); } } else if (dataNode.getLocalName().equals("X509SubjectName")) { String textContent = dataText.getTextContent(); //HoK spec section 2.5: //relying party MUST ensure that the subject distinguished name (DN) bound to the assertion matches the DN bound to the X.509 certificate. //If, however, the relying party does not trust the certificate issuer to issue such a DN, the attesting entity is not confirmed and the relying party SHOULD disregard the assertion. if (!tlsCertificate.getSubjectDN().getName().equals(textContent)) { throw new SecurityServiceException( "Unable to validate Holder of Key assertion with subject DN."); } } else if (dataNode.getLocalName().equals("X509IssuerSerial")) { //we have no way to support this confirmation type so we have to throw an error throw new SecurityServiceException( "Unable to validate Holder of Key assertion with issuer serial. NOT SUPPORTED"); } else if (dataNode.getLocalName().equals("X509SKI")) { String textContent = dataText.getTextContent(); byte[] tlsSKI = tlsCertificate.getExtensionValue("2.5.29.14"); byte[] assertionSKI = Base64.getMimeDecoder().decode(textContent); if (tlsSKI != null && tlsSKI.length > 0) { ASN1OctetString tlsOs = ASN1OctetString.getInstance(tlsSKI); ASN1OctetString assertionOs = ASN1OctetString.getInstance(assertionSKI); SubjectKeyIdentifier tlsSubjectKeyIdentifier = SubjectKeyIdentifier .getInstance(tlsOs.getOctets()); SubjectKeyIdentifier assertSubjectKeyIdentifier = SubjectKeyIdentifier .getInstance(assertionOs.getOctets()); //HoK spec section 2.5: //relying party MUST ensure that the value bound to the assertion matches the Subject Key Identifier (SKI) extension bound to the X.509 certificate. //Matching is done by comparing the base64-decoded SKI values byte-for-byte. If the X.509 certificate does not contain an SKI extension, //the attesting entity is not confirmed and the relying party SHOULD disregard the assertion. if (!Arrays.equals(tlsSubjectKeyIdentifier.getKeyIdentifier(), assertSubjectKeyIdentifier.getKeyIdentifier())) { throw new SecurityServiceException( "Unable to validate Holder of Key assertion with subject key identifier."); } } else { throw new SecurityServiceException( "Unable to validate Holder of Key assertion with subject key identifier."); } } } } } else { throw new SecurityServiceException("Holder of Key assertion, must be used with 2-way TLS."); } } }
From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java
public String importCertToStore(String certData, String keyStoreName) throws SecurityConfigException { String alias = null;// w ww.ja v a2 s . co m try { if (keyStoreName == null) { throw new SecurityConfigException("Key Store name can't be null"); } KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId); KeyStore ks = keyMan.getKeyStore(keyStoreName); byte[] bytes = Base64.decode(certData); CertificateFactory factory = CertificateFactory.getInstance("X.509"); X509Certificate cert; try { cert = (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(bytes)); } catch (Exception e) { throw new SecurityConfigException("Invalid format of the provided certificate file", e); } if (ks.getCertificateAlias(cert) != null) { // We already have this certificate in the key store - ignore // adding it twice return null; } alias = cert.getSubjectDN().getName(); ks.setCertificateEntry(alias, cert); keyMan.updateKeyStore(keyStoreName, ks); return alias; } catch (SecurityConfigException e) { throw e; } catch (Exception e) { String msg = "Error when importing cert to keyStore"; log.error(msg, e); throw new SecurityConfigException(msg); } }
From source file:org.sakaiproject.nakamura.auth.saml.SamlAuthenticationHandler.java
@Activate @Modified//from ww w . ja v a2 s . c o m protected void activate(Map<?, ?> props) throws Exception { serverUrl = PropertiesUtil.toString(props.get(SERVER_URL), null); entityIdLabel = PropertiesUtil.toString(props.get(ENTITY_ID_LABEL), DEFAULT_ENTITY_ID_LABEL); entityId = PropertiesUtil.toString(props.get(ENTITY_ID), DEFAULT_ENTITY_ID); logoutUrl = PropertiesUtil.toString(props.get(LOGOUT_URL), null); missingLocalUserUrl = PropertiesUtil.toString(props.get(MISSING_LOCAL_USER_URL), DEFAULT_MISSING_LOCAL_USER_URL); autoCreateUser = PropertiesUtil.toBoolean(props.get(SSO_AUTOCREATE_USER), DEFAULT_SSO_AUTOCREATE_USER); updateAttrsOnLogin = PropertiesUtil.toBoolean(props.get(UPDATE_ATTRS_ON_LOGIN), DEFAULT_UPDATE_ATTRS_ON_LOGIN); signatureLocation = PropertiesUtil.toString(props.get(SIGNATURE_LOCATION), DEFAULT_SIGNATURE_LOCATION); String certPath = PropertiesUtil.toString(props.get(CERTIFICATE), null); loginUrl = serverUrl; if (!serverUrl.endsWith("&")) { if (serverUrl.contains("?")) { loginUrl += "&"; } else { loginUrl += "?"; } } loginUrl += entityIdLabel + "=" + entityId; matchDestination = PropertiesUtil.toString(props.get(MATCH_DESTINATION), DEFAULT_MATCH_DESTINATION); if (MATCH_DESTINATION_NONE.equals(matchDestination)) { uriComparator = TRUE_URI_COMPARATOR; } else if (MATCH_DESTINATION_SIMPLE.equals(matchDestination)) { // only compare the scheme + server + context (no querystring) uriComparator = SIMPLE_URI_COMPARATOR; } else if (MATCH_DESTINATION_HOST.equals(matchDestination)) { uriComparator = HOST_ONLY_URI_COMPARATOR; } else { uriComparator = new BasicURLComparator(); } decoder.setURIComparator(uriComparator); if (certPath != null) { File f = new File(certPath); if (f.exists() && f.isFile()) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream is = new BufferedInputStream(new FileInputStream(f)); certificate = (X509Certificate) cf.generateCertificate(is); } else { CertificateFactory cf = CertificateFactory.getInstance("X.509-base64"); InputStream is = new ByteArrayInputStream(certPath.getBytes()); certificate = (X509Certificate) cf.generateCertificate(is); } } else { certificate = null; } }
From source file:org.strongswan.android.ui.VpnProfileImportActivity.java
public void handleProfile(ProfileLoadResult data) { mProgress.dismiss();/*from w ww. jav a2 s . c o m*/ mProfile = null; if (data != null && data.ThrownException == null) { try { JSONObject obj = new JSONObject(data.Profile); mProfile = parseProfile(obj); } catch (JSONException e) { mExistsWarning.setVisibility(View.VISIBLE); mExistsWarning.setText(e.getLocalizedMessage()); mHideImport = true; invalidateOptionsMenu(); return; } } if (mProfile == null) { String error = null; if (data.ThrownException != null) { try { throw data.ThrownException; } catch (FileNotFoundException e) { error = getString(R.string.profile_import_failed_not_found); } catch (UnknownHostException e) { error = getString(R.string.profile_import_failed_host); } catch (SSLHandshakeException e) { error = getString(R.string.profile_import_failed_tls); } catch (Exception e) { e.printStackTrace(); } } if (error != null) { Toast.makeText(this, getString(R.string.profile_import_failed_detail, error), Toast.LENGTH_LONG) .show(); } else { Toast.makeText(this, R.string.profile_import_failed, Toast.LENGTH_LONG).show(); } finish(); return; } mExisting = mDataSource.getVpnProfile(mProfile.getUUID()); mExistsWarning.setVisibility(mExisting != null ? View.VISIBLE : View.GONE); mBasicDataGroup.setVisibility(View.VISIBLE); mName.setText(mProfile.getName()); mGateway.setText(mProfile.getGateway()); mSelectVpnType.setText(getResources().getStringArray(R.array.vpn_types)[mProfile.getVpnType().ordinal()]); mUsernamePassword .setVisibility(mProfile.getVpnType().has(VpnTypeFeature.USER_PASS) ? View.VISIBLE : View.GONE); if (mProfile.getVpnType().has(VpnTypeFeature.USER_PASS)) { mUsername.setText(mProfile.getUsername()); if (mProfile.getUsername() != null && !mProfile.getUsername().isEmpty()) { mUsername.setEnabled(false); } } mUserCertificate .setVisibility(mProfile.getVpnType().has(VpnTypeFeature.CERTIFICATE) ? View.VISIBLE : View.GONE); mRemoteCertificate.setVisibility(mProfile.Certificate != null ? View.VISIBLE : View.GONE); mImportUserCert.setVisibility(mProfile.PKCS12 != null ? View.VISIBLE : View.GONE); if (mProfile.getVpnType() .has(VpnTypeFeature.CERTIFICATE)) { /* try to load an existing certificate with the default name */ if (mUserCertLoading == null) { mUserCertLoading = getString(R.string.profile_cert_alias, mProfile.getName()); getLoaderManager().initLoader(USER_CERT_LOADER, null, mUserCertificateLoaderCallbacks); } updateUserCertView(); } if (mProfile.Certificate != null) { try { CertificateFactory factory = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) factory .generateCertificate(new ByteArrayInputStream(mProfile.Certificate)); KeyStore store = KeyStore.getInstance("LocalCertificateStore"); store.load(null, null); String alias = store.getCertificateAlias(certificate); mCertEntry = new TrustedCertificateEntry(alias, certificate); ((TextView) mRemoteCert.findViewById(android.R.id.text1)).setText(mCertEntry.getSubjectPrimary()); ((TextView) mRemoteCert.findViewById(android.R.id.text2)).setText(mCertEntry.getSubjectSecondary()); } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException e) { e.printStackTrace(); mRemoteCertificate.setVisibility(View.GONE); } } }
From source file:com.vmware.identity.sts.ws.SignatureValidator.java
/** * Decode a byte array to an Certificate object. *///from ww w .j a v a 2 s . c o m private X509Certificate decodeCertificate(byte[] certificateDer) { assert certificateDer != null; ByteArrayInputStream stream = new ByteArrayInputStream(certificateDer); CertificateFactory certFactory; try { certFactory = CertificateFactory.getInstance("X.509"); } catch (CertificateException e) { throw new IllegalStateException( "Internal error: X.509 Certificate " + "Factory is not available (uncompliant JRE?)", e); } X509Certificate certificate = null; try { certificate = (X509Certificate) certFactory.generateCertificate(stream); } catch (CertificateException e) { throw new WSFaultException(FaultKey.WSSE_INVALID_SECURITY_TOKEN, e); } return certificate; }