List of usage examples for java.security KeyStore aliases
public final Enumeration<String> aliases() throws KeyStoreException
From source file:org.wso2.carbon.security.util.ServerCrypto.java
private String getAliasForX509Cert(String issuer, BigInteger serialNumber, boolean useSerialNumber, KeyStore ks) throws WSSecurityException { Vector issuerRDN = splitAndTrim(issuer); X509Certificate x509cert;/*from w ww .j a va 2s .com*/ Vector certRDN; Certificate cert; try { for (Enumeration e = ks.aliases(); e.hasMoreElements();) { String alias = (String) e.nextElement(); Certificate[] certs = this.getCertificates(alias); if (certs == null || certs.length == 0) { return null; } else { cert = certs[0]; } if (!(cert instanceof X509Certificate)) { continue; } x509cert = (X509Certificate) cert; if (useSerialNumber && x509cert.getSerialNumber().compareTo(serialNumber) == 0) { certRDN = splitAndTrim(x509cert.getIssuerDN().getName()); if (certRDN.equals(issuerRDN)) { return alias; } } } } catch (KeyStoreException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "keystore"); } return null; }
From source file:be.fedict.eid.dss.model.bean.IdentityServiceSingletonBean.java
/** * Load identity keystore//from w ww .j av a 2s . c o m * * @param dssIdentityConfig * identity configuration * @return private key entry of identity * @throws KeyStoreLoadException * failed to load keystore */ public PrivateKeyEntry loadIdentity(DSSIdentityConfig dssIdentityConfig) throws KeyStoreLoadException { try { if (null == dssIdentityConfig) { throw new KeyStoreLoadException("Identity config is empty!"); } FileInputStream keyStoreInputStream = null; if (dssIdentityConfig.getKeyStoreType().equals(KeyStoreType.PKCS11)) { Security.addProvider(new SunPKCS11(dssIdentityConfig.getKeyStorePath())); } else { try { keyStoreInputStream = new FileInputStream(dssIdentityConfig.getKeyStorePath()); } catch (FileNotFoundException e) { throw new KeyStoreLoadException("Can't load keystore from config-specified location: " + dssIdentityConfig.getKeyStorePath(), e); } } // load keystore KeyStore keyStore = KeyStore.getInstance(dssIdentityConfig.getKeyStoreType().getJavaKeyStoreType()); char[] password; if (null != dssIdentityConfig.getKeyStorePassword() && !dssIdentityConfig.getKeyStorePassword().isEmpty()) { password = dssIdentityConfig.getKeyStorePassword().toCharArray(); } else { password = null; } keyStore.load(keyStoreInputStream, password); // find entry alias Enumeration<String> aliases = keyStore.aliases(); if (!aliases.hasMoreElements()) { throw new KeyStoreLoadException("no keystore aliases present"); } String alias; if (null != dssIdentityConfig.getKeyEntryAlias() && !dssIdentityConfig.getKeyEntryAlias().trim().isEmpty()) { boolean found = false; while (aliases.hasMoreElements()) { if (aliases.nextElement().equals(dssIdentityConfig.getKeyEntryAlias())) { found = true; break; } } if (!found) { throw new KeyStoreLoadException( "no keystore entry with alias \"" + dssIdentityConfig.getKeyEntryAlias() + "\""); } alias = dssIdentityConfig.getKeyEntryAlias(); } else { alias = aliases.nextElement(); } LOG.debug("keystore alias: " + alias); // get keystore entry char[] entryPassword; if (null != dssIdentityConfig.getKeyEntryPassword() && !dssIdentityConfig.getKeyEntryPassword().isEmpty()) { entryPassword = dssIdentityConfig.getKeyEntryPassword().toCharArray(); } else { entryPassword = null; } KeyStore.Entry entry = keyStore.getEntry(alias, new KeyStore.PasswordProtection(entryPassword)); if (!(entry instanceof PrivateKeyEntry)) { throw new KeyStoreLoadException("private key entry expected"); } return (PrivateKeyEntry) entry; } catch (KeyStoreException e) { throw new KeyStoreLoadException(e); } catch (CertificateException e) { throw new KeyStoreLoadException(e); } catch (NoSuchAlgorithmException e) { throw new KeyStoreLoadException(e); } catch (UnrecoverableEntryException e) { throw new KeyStoreLoadException(e); } catch (IOException e) { throw new KeyStoreLoadException(e); } }
From source file:org.aselect.server.request.handler.xsaml20.Saml20_Metadata.java
/** * Read meta data public key cert./*ww w .jav a2s . c om*/ * * @param sWorkingDir * the s working dir * @throws ASelectException * the a select exception */ private void readMetaDataPublicKeyCert(String sWorkingDir) throws ASelectException { String sMethod = "readMetaDataPublicKeyCert"; try { StringBuffer sbKeystoreLocation = new StringBuffer(sWorkingDir); sbKeystoreLocation.append(File.separator); sbKeystoreLocation.append("aselectserver"); sbKeystoreLocation.append(File.separator); sbKeystoreLocation.append("keystores"); sbKeystoreLocation.append(File.separator); sbKeystoreLocation.append(PUBLIC_KEYSTORE_NAME); _systemLogger.log(Level.INFO, MODULE, sMethod, "Read:" + sbKeystoreLocation); File fKeystore = new File(sbKeystoreLocation.toString()); if (!fKeystore.exists()) { StringBuffer sbError = new StringBuffer("Keystore cannot be found: "); sbError.append(sbKeystoreLocation.toString()); _systemLogger.log(Level.WARNING, MODULE, sMethod, sbError.toString()); throw new ASelectException(Errors.ERROR_ASELECT_NOT_FOUND); } KeyStore ksASelect = KeyStore.getInstance("JKS"); ksASelect.load(new FileInputStream(sbKeystoreLocation.toString()), null); Enumeration<?> enumAliases = ksASelect.aliases(); while (enumAliases.hasMoreElements()) { String sAlias = (String) enumAliases.nextElement(); sAlias = sAlias.toLowerCase(); if (sAlias.equals(getPublicKeyAlias())) { // server_id A-Select IdP java.security.cert.X509Certificate x509Cert = (java.security.cert.X509Certificate) ksASelect .getCertificate(sAlias); String encodedCert = new String(Base64.encodeBase64(x509Cert.getEncoded())); _systemLogger.log(Level.INFO, MODULE, sMethod, "Found public key alias for : " + getPublicKeyAlias() + " retrieved encoded signing certificate"); setSigningCertificate(encodedCert); } } if (getSigningCertificate() == null) { _systemLogger.log(Level.WARNING, MODULE, sMethod, "No alias found for idp public key with name : " + getPublicKeyAlias()); throw new ASelectException(Errors.ERROR_ASELECT_CONFIG_ERROR); } } catch (Exception e) { StringBuffer sbError = new StringBuffer(" Error loading public keys from directory: '"); sbError.append(sWorkingDir); sbError.append("'"); _systemLogger.log(Level.WARNING, MODULE, sMethod, sbError.toString(), e); throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR, e); } }
From source file:mitm.djigzo.web.pages.certificate.CertificateImportKey.java
private void importPfx() throws KeyStoreException, NoSuchProviderException, SecurityFactoryFactoryException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableEntryException, WebServiceCheckedException {/*from w w w. j ava2s . c o m*/ /* * To prevent timeouts on the SOAP connection we should upload the PFX file in batches if the PFX file * contains a large number of entries. The PFX file should therefore be opened. */ KeyStore allKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); if (password == null) { password = ""; } allKeys.load(file.getStream(), password.toCharArray()); KeyAndCertificateWorkflow.MissingKey missingKey = ignoreMissingKey ? KeyAndCertificateWorkflow.MissingKey.SKIP_CERTIFICATE : KeyAndCertificateWorkflow.MissingKey.ADD_CERTIFICATE; int imported = 0; KeyStore batchKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); batchKeys.load(null, password.toCharArray()); Enumeration<String> aliases = allKeys.aliases(); KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(password.toCharArray()); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (allKeys.isKeyEntry(alias)) { KeyStore.Entry entry = allKeys.getEntry(alias, passwordProtection); batchKeys.setEntry(alias, entry, passwordProtection); } else { Certificate certificate = allKeys.getCertificate(alias); batchKeys.setCertificateEntry(alias, certificate); } if (batchKeys.size() >= maxBatchSize) { imported += uploadKeyStore(batchKeys, missingKey, password); batchKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); batchKeys.load(null, password.toCharArray()); } } /* * Check if there are still some entries left to add (happens when the number * of entries is not a multiple of maxBatchSize) */ if (batchKeys.size() > 0) { imported += uploadKeyStore(batchKeys, missingKey, password); } this.importCount = imported; }
From source file:org.apache.ws.security.components.crypto.CryptoBase.java
/** * The subjectRDN argument is either an X500Principal or a BouncyCastle X509Name instance. *///from w w w .j a va2 s . c o m private Vector getAlias(Object subjectRDN, KeyStore store) throws WSSecurityException { // Store the aliases found Vector aliases = new Vector(); Certificate cert = null; try { for (Enumeration e = store.aliases(); e.hasMoreElements();) { String alias = (String) e.nextElement(); Certificate[] certs = store.getCertificateChain(alias); if (certs == null || certs.length == 0) { // no cert chain, so lets check if getCertificate gives us a result. cert = store.getCertificate(alias); if (cert == null) { continue; } certs = new Certificate[] { cert }; } else { cert = certs[0]; } if (cert instanceof X509Certificate) { X500Principal foundRDN = ((X509Certificate) cert).getSubjectX500Principal(); Object certName = createBCX509Name(foundRDN.getName()); if (subjectRDN.equals(certName)) { aliases.add(alias); } } } } catch (KeyStoreException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e); } return aliases; }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplTest.java
/** * Test method for {@link net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl#exportKeyPair(java.lang.String, java.io.File, java.lang.String)}. * @throws CMException /*from w ww. j a v a 2 s . c o m*/ * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws UnrecoverableKeyException */ @Test public void testExportKeyPair() throws CMException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException { String alias = credentialManager.addKeyPair(privateKey, privateKeyCertChain); File fileToExportTo = new File(credentialManagerDirectory, "test-export-key.p12"); credentialManager.exportKeyPair(alias, fileToExportTo, privateKeyAndPKCS12KeystorePassword); assertTrue(fileToExportTo.exists()); // Load it back from the file we just saved KeyStore ks = credentialManager.loadPKCS12Keystore(fileToExportTo, privateKeyAndPKCS12KeystorePassword); Enumeration<String> aliases = ks.aliases(); Key newPrivateKey = null; Certificate[] newPrivateKeyCerts = null; while (aliases.hasMoreElements()) { // The test-private-key-cert.p12 file contains only one private key // and corresponding certificate entry alias = aliases.nextElement(); if (ks.isKeyEntry(alias)) { // is it a (private) key entry? newPrivateKey = ks.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray()); newPrivateKeyCerts = ks.getCertificateChain(alias); break; } } assertNotNull(newPrivateKey); assertNotNull(newPrivateKeyCerts); //assertTrue(Arrays.equals(newPrivateKey.getEncoded(), privateKey.getEncoded())); assertTrue(newPrivateKey.equals(privateKey)); assertTrue(Arrays.equals(newPrivateKeyCerts, privateKeyCertChain)); }
From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java
public void addKeyStore(byte[] content, String filename, String password, String provider, String type, String pvtkeyPass) throws SecurityConfigException { if (filename == null) { throw new SecurityConfigException("Key Store name can't be null"); }/*w w w .j ava2 s .c om*/ try { if (KeyStoreUtil.isPrimaryStore(filename)) { throw new SecurityConfigException("Key store " + filename + " already available"); } String path = SecurityConstants.KEY_STORES + "/" + filename; if (registry.resourceExists(path)) { throw new SecurityConfigException("Key store " + filename + " already available"); } KeyStore keyStore = KeyStore.getInstance(type); keyStore.load(new ByteArrayInputStream(content), password.toCharArray()); // check for more private keys Enumeration enumeration = keyStore.aliases(); String pvtKeyAlias = null; while (enumeration.hasMoreElements()) { String alias = (String) enumeration.nextElement(); if (keyStore.isKeyEntry(alias)) { if (pvtKeyAlias == null) { pvtKeyAlias = alias; } else { // more than one private key throw new SecurityConfigException("more than one private key"); } } } // just to test weather pvt key password is correct. keyStore.getKey(pvtKeyAlias, pvtkeyPass.toCharArray()); CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil(); Resource resource = registry.newResource(); resource.addProperty(SecurityConstants.PROP_PASSWORD, cryptoUtil.encryptAndBase64Encode(password.getBytes())); resource.addProperty(SecurityConstants.PROP_PROVIDER, provider); resource.addProperty(SecurityConstants.PROP_TYPE, type); if (pvtKeyAlias != null) { resource.addProperty(SecurityConstants.PROP_PRIVATE_KEY_ALIAS, pvtKeyAlias); resource.addProperty(SecurityConstants.PROP_PRIVATE_KEY_PASS, cryptoUtil.encryptAndBase64Encode(pvtkeyPass.getBytes())); } resource.setContent(content); registry.put(path, resource); } catch (SecurityConfigException e) { throw e; } catch (Exception e) { String msg = "Error when adding a keyStore"; log.error(msg, e); throw new SecurityConfigException(msg, e); } }
From source file:psiprobe.controllers.certificates.ListCertificatesController.java
/** * Gets the certificates./*from w ww. j a v a 2 s . c o m*/ * * @param storeType the store type * @param storeFile the store file * @param storePassword the store password * @return the certificates * @throws Exception the exception */ public List<Cert> getCertificates(String storeType, String storeFile, String storePassword) throws Exception { KeyStore keyStore; // Get key store if (storeType != null) { keyStore = KeyStore.getInstance(storeType); } else { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); } // Get password char[] password = null; if (storePassword != null) { password = storePassword.toCharArray(); } // Load key store from file try (InputStream storeInput = getStoreInputStream(storeFile)) { keyStore.load(storeInput, password); } catch (IOException e) { logger.error("Error loading store file {}", storeFile, e); return null; } List<Cert> certs = new ArrayList<>(); for (String alias : Collections.list(keyStore.aliases())) { Certificate[] certificateChains = keyStore.getCertificateChain(alias); if (certificateChains != null) { for (Certificate certificateChain : certificateChains) { X509Certificate x509Cert = (X509Certificate) certificateChain; addToStore(certs, alias, x509Cert); } } else { X509Certificate x509Cert = (X509Certificate) keyStore.getCertificate(alias); addToStore(certs, alias, x509Cert); } } return certs; }
From source file:be.agiv.security.demo.Main.java
private void ipStsIssueToken() { GridBagLayout gridBagLayout = new GridBagLayout(); GridBagConstraints gridBagConstraints = new GridBagConstraints(); JPanel contentPanel = new JPanel(gridBagLayout); JLabel urlLabel = new JLabel("URL:"); gridBagConstraints.gridx = 0;// w w w. jav a2s. c o m gridBagConstraints.gridy = 0; gridBagConstraints.anchor = GridBagConstraints.WEST; gridBagConstraints.ipadx = 5; gridBagLayout.setConstraints(urlLabel, gridBagConstraints); contentPanel.add(urlLabel); JTextField urlTextField = new JTextField( "https://auth.beta.agiv.be/ipsts/Services/DaliSecurityTokenServiceConfiguration.svc/IWSTrust13", 60); gridBagConstraints.gridx++; gridBagLayout.setConstraints(urlTextField, gridBagConstraints); contentPanel.add(urlTextField); JLabel realmLabel = new JLabel("Realm:"); gridBagConstraints.gridx = 0; gridBagConstraints.gridy++; gridBagLayout.setConstraints(realmLabel, gridBagConstraints); contentPanel.add(realmLabel); JTextField realmTextField = new JTextField(AGIVSecurity.BETA_REALM, 30); gridBagConstraints.gridx++; gridBagLayout.setConstraints(realmTextField, gridBagConstraints); contentPanel.add(realmTextField); CredentialPanel credentialPanel = new CredentialPanel(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy++; gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER; gridBagLayout.setConstraints(credentialPanel, gridBagConstraints); contentPanel.add(credentialPanel); int result = JOptionPane.showConfirmDialog(this, contentPanel, "IP-STS Issue Token", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.CANCEL_OPTION) { return; } String location = urlTextField.getText(); String username = credentialPanel.getUsername(); String password = credentialPanel.getPassword(); File pkcs12File = credentialPanel.getPKCS12File(); String realm = realmTextField.getText(); IPSTSClient ipStsClient = new IPSTSClient(location, realm); try { if (null != username) { this.ipStsSecurityToken = ipStsClient.getSecurityToken(username, password); } else { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(new FileInputStream(pkcs12File), password.toCharArray()); String alias = keyStore.aliases().nextElement(); X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias); PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray()); this.ipStsSecurityToken = ipStsClient.getSecuritytoken(certificate, privateKey); } this.ipStsViewMenuItem.setEnabled(true); this.rStsIssueMenuItem.setEnabled(true); ipStsViewToken(); } catch (Exception e) { showException(e); } }
From source file:org.texai.x509.X509Utils.java
/** Copies the given keystore from the .uber format to the .jceks format. * * @param uberKeyStorePath the .uber keystore path * @param uberKeyStorePassword the .uber keystore password * @param jceksKeyStorePath the .jceks keystore path * @param jceksKeyStorePassword the .jceks keystore password * @throws KeyStoreException if no Provider supports a KeyStoreSpi implementation for the specified type * @throws IOException if there is an I/O or format problem with the keystore data, * if a password is required but not given, or if the given password was incorrect * @throws NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found * @throws CertificateException if any of the certificates in the keystore could not be loaded * @throws NoSuchProviderException if the cryptography provider cannot be found * @throws UnrecoverableEntryException if the keystore entry cannot be recovered with the provided password and alias */// w w w . j a v a 2 s .c o m public static synchronized void copyKeyStoreUberToJceks(final String uberKeyStorePath, final char[] uberKeyStorePassword, final String jceksKeyStorePath, final char[] jceksKeyStorePassword) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, UnrecoverableEntryException { //Preconditions assert uberKeyStorePath != null : "uberKeyStorePath must not be null"; assert !uberKeyStorePath.isEmpty() : "uberKeyStorePath must not be empty"; assert uberKeyStorePath.endsWith(".uber") : "uber keystore file extension must be .uber"; assert uberKeyStorePassword != null : "uberKeyStorePassword must not be null"; assert jceksKeyStorePath != null : "jceksKeyStorePath must not be null"; assert !jceksKeyStorePath.isEmpty() : "jceksKeyStorePath must not be empty"; assert jceksKeyStorePath.endsWith(".jceks") : "jceks keystore file extension must be .jceks"; assert uberKeyStorePassword != null : "uberKeyStorePassword must not be null"; LOGGER.info("copying keystore contents of " + uberKeyStorePath + " to " + jceksKeyStorePath); final KeyStore uberKeyStore = findOrCreateUberKeyStore(uberKeyStorePath, uberKeyStorePassword); final KeyStore jceksKeyStore = findOrCreateJceksKeyStore(jceksKeyStorePath, jceksKeyStorePassword); final Enumeration<String> aliases_enumeration = uberKeyStore.aliases(); final PasswordProtection uberPasswordProtection = new PasswordProtection(uberKeyStorePassword); final PasswordProtection jceksPasswordProtection = new PasswordProtection(jceksKeyStorePassword); while (aliases_enumeration.hasMoreElements()) { final String alias = aliases_enumeration.nextElement(); final KeyStore.Entry entry = uberKeyStore.getEntry(alias, uberPasswordProtection); assert entry != null; jceksKeyStore.setEntry(alias, entry, jceksPasswordProtection); LOGGER.info(" copied entry: " + alias); } jceksKeyStore.store(new FileOutputStream(jceksKeyStorePath), jceksKeyStorePassword); }