List of usage examples for java.security KeyStore aliases
public final Enumeration<String> aliases() throws KeyStoreException
From source file:org.adempierelbr.model.MLBRDigitalCertificate.java
/** * setCertificate//from w ww.j av a 2 s.c o m * Set all System.property for webservice connection */ public static void setCertificate(Properties ctx, MOrgInfo oi) throws Exception { Integer certOrg = (Integer) oi.get_Value("LBR_DC_Org_ID"); Integer certWS = (Integer) oi.get_Value("LBR_DC_WS_ID"); MLBRDigitalCertificate dcOrg = new MLBRDigitalCertificate(Env.getCtx(), certOrg, null); MLBRDigitalCertificate dcWS = new MLBRDigitalCertificate(Env.getCtx(), certWS, null); String orgPassword = dcOrg.getPassword(); String certType = null; InputStream certFileOrg = null; if (MLBRDigitalCertificate.LBR_CERTTYPE_PKCS12.equals(dcOrg.getlbr_CertType())) { certType = "PKCS12"; certFileOrg = dcOrg.getAttachment(true).getEntry(0).getInputStream(); if (certFileOrg == null) throw new Exception("Unable to find private key attachment"); } else if (MLBRDigitalCertificate.LBR_CERTTYPE_PKCS11.equals(dcOrg.getlbr_CertType())) { certType = "PKCS11"; Provider p = new sun.security.pkcs11.SunPKCS11(dcOrg.getConfigurationFile()); Security.addProvider(p); } else return; // Unknown Certificate KeyStore ks = KeyStore.getInstance(certType); try { ks.load(certFileOrg, orgPassword.toCharArray()); } catch (IOException e) { throw new Exception("Incorrect Certificate Password"); } InputStream certFileWS = dcWS.getAttachment(true).getEntry(0).getInputStream(); if (certFileWS == null) { throw new Exception("Unable to find webservices keystore attachment"); } String alias = dcOrg.getAlias(); if (alias != null && ks.containsAlias(alias) && ks.isKeyEntry(alias)) ;// Do Nothing else { Enumeration<String> aliasesEnum = ks.aliases(); while (aliasesEnum.hasMoreElements()) { alias = (String) aliasesEnum.nextElement(); if (ks.isKeyEntry(alias)) break; } } //Erro NFe 3.10 System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true"); X509Certificate certificate = (X509Certificate) ks.getCertificate(alias); PrivateKey privateKey = (PrivateKey) ks.getKey(alias, orgPassword.toCharArray()); SocketFactoryDinamico socketFactoryDinamico = new SocketFactoryDinamico(certificate, privateKey); socketFactoryDinamico.setFileCacerts(certFileWS, dcWS.getPassword()); Protocol protocol = new Protocol("https", socketFactoryDinamico, 443); Protocol.registerProtocol("https", protocol); }
From source file:org.kse.crypto.x509.X509CertUtil.java
/** * Check whether or not a trusted certificate in the supplied KeyStore * matches the supplied X.509 certificate. * * @param cert/*from w w w .j a v a 2s.co m*/ * The certificate * @param keyStore * The KeyStore * @return The alias of the matching certificate in the KeyStore or null if * there is no match * @throws CryptoException * If there is a problem establishing trust */ public static String matchCertificate(KeyStore keyStore, X509Certificate cert) throws CryptoException { try { for (Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements();) { String alias = aliases.nextElement(); if (keyStore.isCertificateEntry(alias)) { X509Certificate compCert = X509CertUtil.convertCertificate(keyStore.getCertificate(alias)); if (cert.equals(compCert)) { return alias; } } } return null; } catch (KeyStoreException ex) { throw new CryptoException(res.getString("NoMatchCertificate.exception.message"), ex); } }
From source file:Main.java
public static boolean isCACertificateInstalled(File fileCA, String type, char[] password) throws KeyStoreException { KeyStore keyStoreCA = null; try {/*from w w w. j a va 2s . c o m*/ keyStoreCA = KeyStore.getInstance(type/*, "BC"*/); } catch (Exception e) { e.printStackTrace(); } if (fileCA.exists() && fileCA.canRead()) { try { FileInputStream fileCert = new FileInputStream(fileCA); keyStoreCA.load(fileCert, password); fileCert.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (java.security.cert.CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Enumeration ex = keyStoreCA.aliases(); Date exportFilename = null; String caAliasValue = ""; while (ex.hasMoreElements()) { String is = (String) ex.nextElement(); Date lastStoredDate = keyStoreCA.getCreationDate(is); if (exportFilename == null || lastStoredDate.after(exportFilename)) { exportFilename = lastStoredDate; caAliasValue = is; } } try { return keyStoreCA.getKey(caAliasValue, password) != null; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } } return false; }
From source file:com.indivica.olis.Driver.java
public static String signData(String data) { X509Certificate cert = null;/*from www .j a v a 2 s. c om*/ PrivateKey priv = null; KeyStore keystore = null; String pwd = "Olis2011"; String result = null; try { Security.addProvider(new BouncyCastleProvider()); keystore = KeyStore.getInstance("PKCS12", "SunJSSE"); // Load the keystore keystore.load(new FileInputStream(OscarProperties.getInstance().getProperty("olis_keystore")), pwd.toCharArray()); Enumeration e = keystore.aliases(); String name = ""; if (e != null) { while (e.hasMoreElements()) { String n = (String) e.nextElement(); if (keystore.isKeyEntry(n)) { name = n; } } } // Get the private key and the certificate priv = (PrivateKey) keystore.getKey(name, pwd.toCharArray()); cert = (X509Certificate) keystore.getCertificate(name); // I'm not sure if this is necessary ArrayList<Certificate> certList = new ArrayList<Certificate>(); certList.add(cert); Store certs = new JcaCertStore(certList); // Encrypt data CMSSignedDataGenerator sgen = new CMSSignedDataGenerator(); // What digest algorithm i must use? SHA1? MD5? RSA?... ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(priv); sgen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert)); // I'm not sure this is necessary sgen.addCertificates(certs); // I think that the 2nd parameter need to be false (detached form) CMSSignedData csd = sgen.generate(new CMSProcessableByteArray(data.getBytes()), true); byte[] signedData = csd.getEncoded(); byte[] signedDataB64 = Base64.encode(signedData); result = new String(signedDataB64); } catch (Exception e) { MiscUtils.getLogger().error("Can't sign HL7 message for OLIS", e); } return result; }
From source file:nu.yona.app.utils.AppUtils.java
public static boolean checkCACertificate() { boolean isCertExist = false; try {//w w w.j a v a 2 s . com KeyStore ks = KeyStore.getInstance("AndroidCAStore"); if (ks != null) { ks.load(null, null); Enumeration aliases = ks.aliases(); if (YonaApplication.getEventChangeManager().getDataState().getUser() != null && YonaApplication .getEventChangeManager().getDataState().getUser().getSslRootCertCN() != null) { String caCertName = YonaApplication.getEventChangeManager().getDataState().getUser() .getSslRootCertCN(); if (!TextUtils.isEmpty(caCertName)) { while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) ks .getCertificate(alias); if (cert.getIssuerDN().getName().contains(caCertName)) { isCertExist = true; break; } } } } } } catch (Exception e) { reportException(AppUtils.class.getSimpleName(), e, Thread.currentThread()); } return isCertExist; }
From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java
/** * Check whether or not a trusted certificate in the supplied KeyStore * matches the supplied X.509 certificate. * * @param cert//from w w w.jav a 2 s . c o m * The certificate * @param keyStore * The KeyStore * @return The alias of the matching certificate in the KeyStore or null if * there is no match * @throws CryptoException * If there is a problem establishing trust */ public static String matchCertificate(KeyStore keyStore, X509Certificate cert) throws CryptoException { try { for (Enumeration aliases = keyStore.aliases(); aliases.hasMoreElements();) { String alias = (String) aliases.nextElement(); if (keyStore.isCertificateEntry(alias)) { X509Certificate compCert = X509CertUtil.convertCertificate(keyStore.getCertificate(alias)); if (cert.equals(compCert)) { return alias; } } } return null; } catch (KeyStoreException ex) { throw new CryptoException(res.getString("NoMatchCertificate.exception.message"), ex); } }
From source file:org.kse.crypto.x509.X509CertUtil.java
private static List<X509Certificate> extractCertificates(KeyStore keyStore) throws CryptoException { try {// w w w . ja v a2 s .co m List<X509Certificate> certs = new ArrayList<X509Certificate>(); for (Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements();) { String alias = aliases.nextElement(); if (keyStore.isCertificateEntry(alias)) { certs.add(X509CertUtil.convertCertificate(keyStore.getCertificate(alias))); } } return certs; } catch (KeyStoreException ex) { throw new CryptoException(res.getString("NoExtractCertificates.exception.message"), ex); } }
From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImplIT.java
/** * @throws java.lang.Exception//from w w w.j a v a 2 s . co m */ @BeforeClass @Ignore public static void setUpBeforeCLass() throws Exception { Security.addProvider(new BouncyCastleProvider()); // Create some test username and passwords for services serviceURI = new URI("http://someservice"); usernamePassword = new UsernamePassword("testuser", "testpasswd"); serviceURI2 = new URI("http://someservice2"); usernamePassword2 = new UsernamePassword("testuser2", "testpasswd2"); serviceURI3 = new URI("http://someservice3"); usernamePassword3 = new UsernamePassword("testuser3", "testpasswd3"); // Load the test private key and its certificate File privateKeyCertFile = new File(privateKeyFileURL.getPath()); KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!! FileInputStream inStream = new FileInputStream(privateKeyCertFile); pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray()); // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword); Enumeration<String> aliases = pkcs12Keystore.aliases(); while (aliases.hasMoreElements()) { // The test-private-key-cert.p12 file contains only one private key // and corresponding certificate entry String alias = aliases.nextElement(); if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry? privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray()); privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias); break; } } inStream.close(); // Load the test trusted certificate (belonging to *.Google.com) File trustedCertFile = new File(trustedCertficateGoogleFileURL.getPath()); inStream = new FileInputStream(trustedCertFile); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); trustedCertficateGoogle = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } // Load the test trusted certificate (belonging to heater.cs.man.ac.uk) File trustedCertFile2 = new File(trustedCertficateHeaterFileURL.getPath()); inStream = new FileInputStream(trustedCertFile2); trustedCertficateHeater = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } credentialManager = new CredentialManagerImpl(); // // The code below sets up the Keystore and Truststore files and loads some data into them // // and saves them into a temp directory. These files can later be used for testing the Credential // // Manager with non-empty keystores. // Random randomGenerator = new Random(); // String credentialManagerDirectoryPath = System // .getProperty("java.io.tmpdir") // + System.getProperty("file.separator") // + "taverna-security-" // + randomGenerator.nextInt(1000000); // System.out.println("Credential Manager's directory path: " // + credentialManagerDirectoryPath); // credentialManagerDirectory = new File(credentialManagerDirectoryPath); // credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory); // // // Create the dummy master password provider // masterPasswordProvider = new DummyMasterPasswordProvider(); // masterPasswordProvider.setMasterPassword(masterPassword); // List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>(); // masterPasswordProviders.add(masterPasswordProvider); // credentialManager.setMasterPasswordProviders(masterPasswordProviders); // // // Add some stuff into Credential Manager // credentialManager.addUsernameAndPasswordForService(usernamePassword, serviceURI); // credentialManager.addUsernameAndPasswordForService(usernamePassword2, serviceURI2); // credentialManager.addUsernameAndPasswordForService(usernamePassword3, serviceURI3); // credentialManager.addKeyPair(privateKey, privateKeyCertChain); // credentialManager.addTrustedCertificate(trustedCertficate); // Set up a random temp directory and copy the test keystore files // from resources/security Random randomGenerator = new Random(); String credentialManagerDirectoryPath = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "taverna-security-" + randomGenerator.nextInt(1000000); System.out.println("Credential Manager's directory path: " + credentialManagerDirectoryPath); credentialManagerDirectory = new File(credentialManagerDirectoryPath); if (!credentialManagerDirectory.exists()) { credentialManagerDirectory.mkdir(); } URL keystoreFileURL = CredentialManagerImplIT.class.getResource("/security/t2keystore.ubr"); File keystoreFile = new File(keystoreFileURL.getPath()); File keystoreDestFile = new File(credentialManagerDirectory, "taverna-keystore.ubr"); URL truststroreFileURL = CredentialManagerImplIT.class.getResource("/security/t2truststore.ubr"); File truststoreFile = new File(truststroreFileURL.getPath()); File truststoreDestFile = new File(credentialManagerDirectory, "taverna-truststore.ubr"); FileUtils.copyFile(keystoreFile, keystoreDestFile); FileUtils.copyFile(truststoreFile, truststoreDestFile); credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory.toPath()); // Create the dummy master password provider masterPasswordProvider = new DummyMasterPasswordProvider(); masterPasswordProvider.setMasterPassword(masterPassword); List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>(); masterPasswordProviders.add(masterPasswordProvider); credentialManager.setMasterPasswordProviders(masterPasswordProviders); // Set an empty list for trust confirmation providers credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>()); keystoreChangedObserver = new Observer<KeystoreChangedEvent>() { @Override public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message) throws Exception { // TODO Auto-generated method stub } }; credentialManager.addObserver(keystoreChangedObserver); }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplIT.java
/** * @throws java.lang.Exception//ww w.ja v a 2 s . c o m */ @BeforeClass @Ignore public static void setUpBeforeCLass() throws Exception { Security.addProvider(new BouncyCastleProvider()); // Create some test username and passwords for services serviceURI = new URI("http://someservice"); usernamePassword = new UsernamePassword("testuser", "testpasswd"); serviceURI2 = new URI("http://someservice2"); usernamePassword2 = new UsernamePassword("testuser2", "testpasswd2"); serviceURI3 = new URI("http://someservice3"); usernamePassword3 = new UsernamePassword("testuser3", "testpasswd3"); // Load the test private key and its certificate File privateKeyCertFile = new File(privateKeyFileURL.getPath()); KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!! FileInputStream inStream = new FileInputStream(privateKeyCertFile); pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray()); // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword); Enumeration<String> aliases = pkcs12Keystore.aliases(); while (aliases.hasMoreElements()) { // The test-private-key-cert.p12 file contains only one private key // and corresponding certificate entry String alias = aliases.nextElement(); if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry? privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray()); privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias); break; } } inStream.close(); // Load the test trusted certificate (belonging to *.Google.com) File trustedCertFile = new File(trustedCertficateGoogleFileURL.getPath()); inStream = new FileInputStream(trustedCertFile); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); trustedCertficateGoogle = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } // Load the test trusted certificate (belonging to heater.cs.man.ac.uk) File trustedCertFile2 = new File(trustedCertficateHeaterFileURL.getPath()); inStream = new FileInputStream(trustedCertFile2); trustedCertficateHeater = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } credentialManager = new CredentialManagerImpl(); // // The code below sets up the Keystore and Truststore files and loads some data into them // // and saves them into a temp directory. These files can later be used for testing the Credential // // Manager with non-empty keystores. // Random randomGenerator = new Random(); // String credentialManagerDirectoryPath = System // .getProperty("java.io.tmpdir") // + System.getProperty("file.separator") // + "taverna-security-" // + randomGenerator.nextInt(1000000); // System.out.println("Credential Manager's directory path: " // + credentialManagerDirectoryPath); // credentialManagerDirectory = new File(credentialManagerDirectoryPath); // credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory); // // // Create the dummy master password provider // masterPasswordProvider = new DummyMasterPasswordProvider(); // masterPasswordProvider.setMasterPassword(masterPassword); // List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>(); // masterPasswordProviders.add(masterPasswordProvider); // credentialManager.setMasterPasswordProviders(masterPasswordProviders); // // // Add some stuff into Credential Manager // credentialManager.addUsernameAndPasswordForService(usernamePassword, serviceURI); // credentialManager.addUsernameAndPasswordForService(usernamePassword2, serviceURI2); // credentialManager.addUsernameAndPasswordForService(usernamePassword3, serviceURI3); // credentialManager.addKeyPair(privateKey, privateKeyCertChain); // credentialManager.addTrustedCertificate(trustedCertficate); // Set up a random temp directory and copy the test keystore files // from resources/security Random randomGenerator = new Random(); String credentialManagerDirectoryPath = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "taverna-security-" + randomGenerator.nextInt(1000000); System.out.println("Credential Manager's directory path: " + credentialManagerDirectoryPath); credentialManagerDirectory = new File(credentialManagerDirectoryPath); if (!credentialManagerDirectory.exists()) { credentialManagerDirectory.mkdir(); } URL keystoreFileURL = CredentialManagerImplIT.class.getResource("/security/t2keystore.ubr"); File keystoreFile = new File(keystoreFileURL.getPath()); File keystoreDestFile = new File(credentialManagerDirectory, "taverna-keystore.ubr"); URL truststroreFileURL = CredentialManagerImplIT.class.getResource("/security/t2truststore.ubr"); File truststoreFile = new File(truststroreFileURL.getPath()); File truststoreDestFile = new File(credentialManagerDirectory, "taverna-truststore.ubr"); FileUtils.copyFile(keystoreFile, keystoreDestFile); FileUtils.copyFile(truststoreFile, truststoreDestFile); credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory); // Create the dummy master password provider masterPasswordProvider = new DummyMasterPasswordProvider(); masterPasswordProvider.setMasterPassword(masterPassword); List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>(); masterPasswordProviders.add(masterPasswordProvider); credentialManager.setMasterPasswordProviders(masterPasswordProviders); // Set an empty list for trust confirmation providers credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>()); keystoreChangedObserver = new Observer<KeystoreChangedEvent>() { @Override public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message) throws Exception { // TODO Auto-generated method stub } }; credentialManager.addObserver(keystoreChangedObserver); }
From source file:com.ah.ui.actions.home.clientManagement.service.CertificateGenSV.java
public static X509Certificate ananysisP12(InputStream in, char[] keyStorePassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(in, keyStorePassword); in.close();/*from w ww .ja v a2s . c o m*/ Enumeration<String> enums = keyStore.aliases(); if (enums.hasMoreElements()) { String keyAlis = enums.nextElement(); X509Certificate certificate = (X509Certificate) keyStore.getCertificate(keyAlis); return certificate; } return null; }