List of usage examples for java.security KeyStore containsAlias
public final boolean containsAlias(String alias) throws KeyStoreException
From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java
/** * Method to get the information of the certificate. * * @param alias : Alias of the certificate which information should be retrieved * @return : The details of the certificate as a MAP. *//*from w ww. j av a 2 s . co m*/ public CertificateInformationDTO getCertificateInformation(String alias) throws CertificateManagementException { CertificateInformationDTO certificateInformation = new CertificateInformationDTO(); File trustStoreFile = new File(TRUST_STORE); try { localTrustStoreStream = new FileInputStream(trustStoreFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD); if (trustStore.containsAlias(alias)) { X509Certificate certificate = (X509Certificate) trustStore.getCertificate(alias); certificateInformation = getCertificateMetaData(certificate); } } catch (IOException e) { throw new CertificateManagementException("Error wile loading the keystore.", e); } catch (CertificateException e) { throw new CertificateManagementException("Error loading the keystore from the stream.", e); } catch (NoSuchAlgorithmException e) { throw new CertificateManagementException("Could not find the algorithm to load the certificate.", e); } catch (KeyStoreException e) { throw new CertificateManagementException("Error reading certificate contents.", e); } finally { closeStreams(localTrustStoreStream); } return certificateInformation; }
From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java
/** * Retrieve the certificate which is represented by the given alias. * * @param alias : The alias of the required certificate. * @return : The Certificate as a ByteArrayInputStream. * @throws CertificateManagementException : */// w w w. ja v a 2 s. co m public ByteArrayInputStream getCertificateContent(String alias) throws CertificateManagementException { File trustStoreFile = new File(TRUST_STORE); Certificate certificate; try { localTrustStoreStream = new FileInputStream(trustStoreFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD); if (trustStore.containsAlias(alias)) { certificate = trustStore.getCertificate(alias); return new ByteArrayInputStream(certificate.getEncoded()); } } catch (IOException e) { throw new CertificateManagementException("Error in loading the certificate.", e); } catch (CertificateException e) { throw new CertificateManagementException("Error loading certificate.", e); } catch (NoSuchAlgorithmException e) { throw new CertificateManagementException("Could not find the algorithm to load the certificate.", e); } catch (KeyStoreException e) { throw new CertificateManagementException("Error reading certificate contents.", e); } finally { closeStreams(localTrustStoreStream); } return null; }
From source file:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java
@TargetApi(18) private KeyStore initKeyStore() throws SecureLocalStorageException { try {//from w w w.ja v a 2 s. c o m KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); if (!keyStore.containsAlias(SECURELOCALSTORAGEALIAS)) { Calendar start = Calendar.getInstance(); Calendar end = Calendar.getInstance(); end.add(Calendar.YEAR, 3); KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(_cordova.getActivity()) .setAlias(SECURELOCALSTORAGEALIAS) .setSubject(new X500Principal(String.format("CN=%s, O=%s", "SecureLocalStorage", _cordova.getActivity().getBaseContext().getPackageName()))) .setSerialNumber(BigInteger.ONE).setStartDate(start.getTime()).setEndDate(end.getTime()) .build(); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore"); generator.initialize(spec); generator.generateKeyPair(); } return keyStore; } catch (Exception e) { throw new SecureLocalStorageException("Could not initialize keyStore", e); } }
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testRRNCertificate() throws Exception { // setup/*from ww w . jav a2s. c o m*/ Security.addProvider(new BeIDProvider()); final KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null); // operate assertTrue(keyStore.containsAlias("RRN")); Entry entry = keyStore.getEntry("RRN", null); assertNotNull(entry); assertTrue(entry instanceof TrustedCertificateEntry); TrustedCertificateEntry trustedCertificateEntry = (TrustedCertificateEntry) entry; assertNotNull(trustedCertificateEntry.getTrustedCertificate()); assertTrue(((X509Certificate) trustedCertificateEntry.getTrustedCertificate()).getSubjectX500Principal() .toString().contains("RRN")); assertNotNull(keyStore.getCertificate("RRN")); Certificate[] certificateChain = keyStore.getCertificateChain("RRN"); assertNotNull(certificateChain); assertEquals(2, certificateChain.length); LOG.debug("RRN subject: " + ((X509Certificate) certificateChain[0]).getSubjectX500Principal()); LOG.debug("RRN issuer: " + ((X509Certificate) certificateChain[0]).getIssuerX500Principal()); LOG.debug("root subject: " + ((X509Certificate) certificateChain[1]).getSubjectX500Principal()); LOG.debug("root issuer: " + ((X509Certificate) certificateChain[1]).getIssuerX500Principal()); }
From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java
/** * This method will remove certificate from the trust store which matches the given alias. * * @param alias : The alias which the certificate should be deleted. * @return : ResponseCode based on the execution. * <p>/*from w ww. jav a2 s . c om*/ * Response Codes * SUCCESS : If the certificate is deleted successfully. * INTERNAL_SERVER_ERROR : If any exception occurred. * CERTIFICATE_NOT_FOUND : If the Alias is not found in the key store. */ public ResponseCode removeCertificateFromTrustStore(String alias) { boolean isExists; //Check for the existence of the certificate in trust store. try { File trustStoreFile = new File(TRUST_STORE); localTrustStoreStream = new FileInputStream(trustStoreFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD); if (trustStore.containsAlias(alias)) { trustStore.deleteEntry(alias); isExists = true; } else { isExists = false; if (log.isDebugEnabled()) { log.debug("Certificate for alias '" + alias + "' not found in the trust store."); } } fileOutputStream = new FileOutputStream(trustStoreFile); trustStore.store(fileOutputStream, TRUST_STORE_PASSWORD); responseCode = isExists ? ResponseCode.SUCCESS : ResponseCode.CERTIFICATE_NOT_FOUND; } catch (IOException e) { log.error("Error in loading the certificate.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (CertificateException e) { log.error("Error loading certificate.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (NoSuchAlgorithmException e) { log.error("Could not find the algorithm to load the certificate.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (KeyStoreException e) { log.error("Error reading certificate contents.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } finally { closeStreams(localTrustStoreStream, fileOutputStream); } return responseCode; }
From source file:org.oscarehr.sharingcenter.actions.SecurityInfrastructureServlet.java
private String deleteInfrastructure(Integer id) { InfrastructureDao dao = SpringUtils.getBean(InfrastructureDao.class); InfrastructureDataObject toDelete = dao.getInfrastructure(id); // there is a problem if the alias is null.. if (toDelete.getAlias() == null) { dao.remove(id);/*from ww w. j av a 2 s . c o m*/ return "delete"; } //Preparing for the KeyStore containsAlias() test OscarProperties oscarProperties = OscarProperties.getInstance(); String keyStoreFile = oscarProperties.getProperty("TOMCAT_KEYSTORE_FILE"); String trustStoreFile = oscarProperties.getProperty("TOMCAT_TRUSTSTORE_FILE"); String keyStorePass = oscarProperties.getProperty("TOMCAT_KEYSTORE_PASSWORD"); String trustStorePass = oscarProperties.getProperty("TOMCAT_TRUSTSTORE_PASSWORD"); String alias = toDelete.getAlias(); KeyStore ks = null; KeyStore ts = null; try { ks = SslUtility.loadKeyStore(keyStoreFile, keyStorePass.toCharArray()); ts = SslUtility.loadKeyStore(trustStoreFile, trustStorePass.toCharArray()); if (ks.containsAlias(alias)) { ks.deleteEntry(alias); ts.deleteEntry(alias); } // save the keystore ks.store(new FileOutputStream(keyStoreFile), keyStorePass.toCharArray()); // save the truststore ts.store(new FileOutputStream(trustStoreFile), trustStorePass.toCharArray()); } catch (SslException ex) { LOGGER.info(ex); } catch (KeyStoreException ex) { LOGGER.info(ex); } catch (NoSuchAlgorithmException ex) { LOGGER.info(ex); } catch (CertificateException ex) { LOGGER.info(ex); } catch (FileNotFoundException ex) { LOGGER.info(ex); } catch (IOException ex) { LOGGER.info(ex); } dao.remove(id); return "delete"; }
From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager.java
public void setEnrollmentStatus() { KeyStore keyStore; try {// w w w .jav a2s . c o m keyStore = KeyStore.getInstance(AgentConstants.DEVICE_KEYSTORE_TYPE); this.isEnrolled = (keyStore.containsAlias(AgentConstants.DEVICE_CERT_ALIAS) && keyStore.containsAlias(AgentConstants.DEVICE_PRIVATE_KEY_ALIAS) && keyStore.containsAlias(AgentConstants.SERVER_CA_CERT_ALIAS)); } catch (KeyStoreException e) { log.error(AgentConstants.LOG_APPENDER + "An error occurred whilst accessing the device KeyStore '" + AgentConstants.DEVICE_KEYSTORE + "' with keystore type [" + AgentConstants.DEVICE_KEYSTORE_TYPE + "] to ensure enrollment status."); log.error(AgentConstants.LOG_APPENDER + e); log.warn(AgentConstants.LOG_APPENDER + "Device will be re-enrolled."); return; } try { if (this.isEnrolled) { this.SCEPCertificate = (X509Certificate) keyStore.getCertificate(AgentConstants.DEVICE_CERT_ALIAS); this.privateKey = (PrivateKey) keyStore.getKey(AgentConstants.DEVICE_PRIVATE_KEY_ALIAS, AgentConstants.DEVICE_KEYSTORE_PASSWORD.toCharArray()); this.publicKey = SCEPCertificate.getPublicKey(); X509Certificate serverCACert = (X509Certificate) keyStore .getCertificate(AgentConstants.SERVER_CA_CERT_ALIAS); this.serverPublicKey = serverCACert.getPublicKey(); log.info(AgentConstants.LOG_APPENDER + "Device has already been enrolled. Hence, loaded certificate information from device" + " trust-store."); } } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e) { log.error(AgentConstants.LOG_APPENDER + "An error occurred whilst accessing the device KeyStore '" + AgentConstants.DEVICE_KEYSTORE + "' to ensure enrollment status."); log.error(AgentConstants.LOG_APPENDER + e); log.warn(AgentConstants.LOG_APPENDER + "Device will be re-enrolled."); this.isEnrolled = false; } }
From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java
/** * To validate the current certificate and alias. * * @param alias Alias of the certificate. * @param certificate Bas64 endcoded certificated. * @return response code based on the validation *//*from ww w.ja va2 s . c o m*/ public ResponseCode validateCertificate(String alias, int tenantId, String certificate) { File trustStoreFile = new File(TRUST_STORE); ResponseCode responseCode = ResponseCode.SUCCESS; ByteArrayInputStream serverCert = null; try { localTrustStoreStream = new FileInputStream(trustStoreFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD); if (StringUtils.isNotEmpty(alias) && trustStore.containsAlias(alias + "_" + tenantId)) { responseCode = ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE; } if (responseCode != ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE) { byte[] cert = (Base64.decodeBase64(certificate.getBytes(StandardCharsets.UTF_8))); serverCert = new ByteArrayInputStream(cert); if (serverCert.available() == 0) { responseCode = ResponseCode.CERTIFICATE_NOT_FOUND; } else { CertificateFactory cf = CertificateFactory.getInstance(CERTIFICATE_TYPE); while (serverCert.available() > 0) { Certificate generatedCertificate = cf.generateCertificate(serverCert); X509Certificate x509Certificate = (X509Certificate) generatedCertificate; if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) { responseCode = ResponseCode.CERTIFICATE_EXPIRED; } } } } } catch (IOException e) { log.error("I/O Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (CertificateException e) { log.error("Certificate Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (NoSuchAlgorithmException e) { log.error("No Such Algorithm Exception while trying to load trust store while trying to check whether " + "alias " + alias + " exists", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (KeyStoreException e) { log.error("KeyStore Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } finally { closeStreams(serverCert); } return responseCode; }
From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java
@Override public boolean isNodeCertificateValid(String issuerDN) throws CertificateException { KeyStore keyStore = loadKeyStore(); X509Certificate x509 = null;//from w w w . ja v a 2 s . c om try { if (keyStore == null || !keyStore.containsAlias(nodeAlias)) { return false; } Certificate cert = keyStore.getCertificate(nodeAlias); if (!(cert instanceof X509Certificate)) { return false; } x509 = (X509Certificate) cert; x509.checkValidity(); X500Principal issuer = new X500Principal(issuerDN); if (!x509.getIssuerX500Principal().equals(issuer)) { log.debug("Certificate issuer {} not same as expected {}", x509.getIssuerX500Principal().getName(), issuer.getName()); return false; } return true; } catch (KeyStoreException e) { throw new CertificateException("Error checking for node certificate", e); } catch (CertificateExpiredException e) { log.debug("Certificate {} has expired", x509.getSubjectDN().getName()); } catch (CertificateNotYetValidException e) { log.debug("Certificate {} not valid yet", x509.getSubjectDN().getName()); } return false; }
From source file:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java
private void clear(File file, KeyStore keyStore) throws SecureLocalStorageException { if (file.exists()) { if (!file.delete()) { throw new SecureLocalStorageException("Could not delete storage file"); }/*from w ww . j a v a 2 s.c om*/ } try { if (keyStore.containsAlias(SECURELOCALSTORAGEALIAS)) { keyStore.deleteEntry(SECURELOCALSTORAGEALIAS); } } catch (Exception e) { throw new SecureLocalStorageException(e.getMessage(), e); } }