List of usage examples for java.security KeyStore getCertificateChain
public final Certificate[] getCertificateChain(String alias) throws KeyStoreException
From source file:test.integ.be.fedict.trust.ECCTest.java
/** * The CRL of the Entrust Demo ECC CA does not exist online. * /* ww w . j a v a 2 s . c o m*/ * @throws Exception */ @Test public void testEntrustDemoECCPKI() throws Exception { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate rootCertificate = (X509Certificate) certificateFactory .generateCertificate(ECCTest.class.getResourceAsStream("/ecc/root.cer")); LOG.debug("Root CA: " + rootCertificate); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(ECCTest.class.getResourceAsStream("/ecc/www.e-contract.be.p12"), "EntrustSSL".toCharArray()); String alias = keyStore.aliases().nextElement(); Certificate[] certificates = keyStore.getCertificateChain(alias); for (Certificate certificate : certificates) { LOG.debug("Certificate: " + certificate); } MemoryCertificateRepository repository = new MemoryCertificateRepository(); repository.addTrustPoint(rootCertificate); TrustValidator trustValidator = new TrustValidator(repository); TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator(); trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator); trustValidator.isTrusted(certificates); }
From source file:com.thoughtworks.go.security.AuthSSLKeyManagerFactory.java
private void logKeyStore(KeyStore store) throws KeyStoreException { LOG.trace("Certificates count: " + store.size()); Enumeration aliases = store.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certs = store.getCertificateChain(alias); if (certs != null) { LOG.debug("Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; LOG.trace(" Certificate " + (c + 1) + ":"); LOG.trace(" Subject DN: " + cert.getSubjectDN()); LOG.trace(" Signature Algorithm: " + cert.getSigAlgName()); LOG.trace(" Valid from: " + cert.getNotBefore()); LOG.trace(" Valid until: " + cert.getNotAfter()); LOG.trace(" Issuer: " + cert.getIssuerDN()); }//from w ww .j a va 2s. c om } } } }
From source file:org.kse.gui.actions.ExportKeyPairAction.java
/** * Do action.//w w w . j a v a 2 s.c o m */ @Override protected void doAction() { File exportFile = null; try { KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory(); KeyStoreState currentState = history.getCurrentState(); String alias = kseFrame.getSelectedEntryAlias(); Password password = getEntryPassword(alias, currentState); if (password == null) { return; } KeyStore keyStore = currentState.getKeyStore(); PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray()); Certificate[] certificates = keyStore.getCertificateChain(alias); DExportKeyPair dExportKeyPair = new DExportKeyPair(frame, alias, applicationSettings.getPasswordQualityConfig()); dExportKeyPair.setLocationRelativeTo(frame); dExportKeyPair.setVisible(true); if (!dExportKeyPair.isExportSelected()) { return; } exportFile = dExportKeyPair.getExportFile(); Password exportPassword = dExportKeyPair.getExportPassword(); ExportFormat exportFormat = dExportKeyPair.getExportFormat(); if (exportFormat == ExportFormat.PKCS12) { exportAsPkcs12(exportFile, alias, privateKey, certificates, exportPassword); } else { exportAsPem(exportFile, privateKey, certificates, exportPassword); } JOptionPane.showMessageDialog(frame, res.getString("ExportKeyPairAction.ExportKeyPairSuccessful.message"), res.getString("ExportKeyPairAction.ExportKeyPair.Title"), JOptionPane.INFORMATION_MESSAGE); } catch (FileNotFoundException ex) { String message = MessageFormat.format(res.getString("ExportKeyPairAction.NoWriteFile.message"), exportFile); JOptionPane.showMessageDialog(frame, message, res.getString("ExportKeyPairAction.ExportKeyPair.Title"), JOptionPane.WARNING_MESSAGE); } catch (Exception ex) { DError.displayError(frame, ex); } }
From source file:org.wso2.carbon.identity.idp.metadata.saml2.SignKeyDataHolder.java
/** * Represent OpenSAML compatible certificate credential */// w ww.j a va 2 s. c om public SignKeyDataHolder() throws MetadataException { String keyAlias; KeyStoreAdmin keyAdmin; KeyStoreManager keyMan; Certificate[] certificates; int tenantID; String userTenantDomain; try { userTenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); tenantID = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); if (log.isDebugEnabled()) { log.debug("Key store used for signing is based on the tenant: " + userTenantDomain); } if (tenantID != MultitenantConstants.SUPER_TENANT_ID) { String keyStoreName = userTenantDomain.trim().replace(".", "-") + ".jks"; keyAlias = userTenantDomain; keyMan = KeyStoreManager.getInstance(tenantID); File f; KeyStore keyStore = keyMan.getKeyStore(keyStoreName); issuerPK = (PrivateKey) keyMan.getPrivateKey(keyStoreName, userTenantDomain); certificates = keyStore.getCertificateChain(keyAlias); issuerCerts = new X509Certificate[certificates.length]; int i = 0; for (Certificate certificate : certificates) { issuerCerts[i++] = (X509Certificate) certificate; } signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256; String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm(); if (pubKeyAlgo.equalsIgnoreCase("DSA")) { signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA; } } else { keyAlias = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.KeyAlias"); keyAdmin = new KeyStoreAdmin(tenantID, IDPMetadataSAMLServiceComponentHolder.getInstance() .getRegistryService().getGovernanceSystemRegistry()); keyMan = KeyStoreManager.getInstance(tenantID); issuerPK = (PrivateKey) keyAdmin.getPrivateKey(keyAlias, true); certificates = keyMan.getPrimaryKeyStore().getCertificateChain(keyAlias); issuerCerts = new X509Certificate[certificates.length]; int i = 0; for (Certificate certificate : certificates) { issuerCerts[i++] = (X509Certificate) certificate; } signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256; String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm(); if (pubKeyAlgo.equalsIgnoreCase("DSA")) { signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA; } } } catch (Exception e) { throw new MetadataException("Error occurred while creating certificate credentials", e); } }
From source file:org.ejbca.util.keystore.KeyTools.java
/** * Retrieves the certificate chain from a keystore. * * @param keyStore the keystore, which has been loaded and opened. * @param privateKeyAlias the alias of the privatekey for which the certchain belongs. * * @return array of Certificate, or null if no certificates are found. *//*w w w. java 2 s.c o m*/ public static Certificate[] getCertChain(final KeyStore keyStore, final String privateKeyAlias) throws KeyStoreException { if (log.isTraceEnabled()) { log.trace(">getCertChain: alias='" + privateKeyAlias + "'"); } final Certificate[] certchain = keyStore.getCertificateChain(privateKeyAlias); if (certchain == null) { return null; } log.debug("Certchain retrieved from alias '" + privateKeyAlias + "' has length " + certchain.length); if (certchain.length < 1) { log.error("Cannot load certificate chain with alias '" + privateKeyAlias + "' from keystore."); if (log.isTraceEnabled()) { log.trace("<getCertChain: alias='" + privateKeyAlias + "', retlength=" + certchain.length); } return certchain; } else if (certchain.length > 0) { if (CertTools.isSelfSigned((X509Certificate) certchain[certchain.length - 1])) { if (log.isDebugEnabled()) { log.debug("Issuer='" + CertTools.getIssuerDN((X509Certificate) certchain[certchain.length - 1]) + "'."); log.debug("Subject='" + CertTools.getSubjectDN((X509Certificate) certchain[certchain.length - 1]) + "'."); } if (log.isTraceEnabled()) { log.trace("<getCertChain: alias='" + privateKeyAlias + "', retlength=" + certchain.length); } return certchain; } } // If we came here, we have a cert which is not root cert in 'cert' final ArrayList<Certificate> array = new ArrayList<Certificate>(); for (int i = 0; i < certchain.length; i++) { array.add(certchain[i]); } boolean stop = false; while (!stop) { final X509Certificate cert = (X509Certificate) array.get(array.size() - 1); final String ialias = CertTools.getPartFromDN(CertTools.getIssuerDN(cert), "CN"); final Certificate[] chain1 = keyStore.getCertificateChain(ialias); if (chain1 == null) { stop = true; } else { if (log.isDebugEnabled()) { log.debug("Loaded certificate chain with length " + chain1.length + " with alias '" + ialias + "'."); } if (chain1.length == 0) { log.error("No RootCA certificate found!"); stop = true; } for (int j = 0; j < chain1.length; j++) { array.add(chain1[j]); // If one cert is slefsigned, we have found a root certificate, we don't need to go on anymore if (CertTools.isSelfSigned((X509Certificate) chain1[j])) { stop = true; } } } } final Certificate[] ret = new Certificate[array.size()]; for (int i = 0; i < ret.length; i++) { ret[i] = (X509Certificate) array.get(i); if (log.isDebugEnabled()) { log.debug("Issuer='" + CertTools.getIssuerDN((X509Certificate) ret[i]) + "'."); log.debug("Subject='" + CertTools.getSubjectDN((X509Certificate) ret[i]) + "'."); } } if (log.isTraceEnabled()) { log.trace("<getCertChain: alias='" + privateKeyAlias + "', retlength=" + ret.length); } return ret; }
From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImplIT.java
/** * @throws java.lang.Exception/*w w w .j a 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.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:org.wso2.identity.integration.common.clients.sso.saml.query.ClientSignKeyDataHolder.java
/** * Constructor method// w ww . j av a 2 s. c o m * @param keyStorePath path to the key store * @param password password of keystore * @param keyAlias key alias of keystore * @throws Exception if, Algorithm fails, input stream fails */ public ClientSignKeyDataHolder(String keyStorePath, String password, String keyAlias) throws Exception { Certificate[] certificates; InputStream is = null; try { File file = new File(keyStorePath); is = new FileInputStream(file); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(is, password.toCharArray()); privateKey = (PrivateKey) keystore.getKey(keyAlias, password.toCharArray()); certificates = keystore.getCertificateChain(keyAlias); issuerCerts = new X509Certificate[certificates.length]; int i = 0; for (Certificate certificate : certificates) { issuerCerts[i++] = (X509Certificate) certificate; } signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA; publicKey = issuerCerts[0].getPublicKey(); String pubKeyAlgo = publicKey.getAlgorithm(); if (DSA_ENCRYPTION_ALGORITHM.equalsIgnoreCase(pubKeyAlgo)) { signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA; } } catch (CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | IOException e) { String mgs = "Error while initializing credentials"; log.error(mgs, e); throw new Exception(mgs); } finally { if (is != null) { try { is.close(); } catch (IOException e) { log.error("Unable to close input stream", e); } } } }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplIT.java
/** * @throws java.lang.Exception/* w w w.j a v a 2 s . c om*/ */ @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:org.wso2.carbon.identity.sso.saml.builders.SignKeyDataHolder.java
public SignKeyDataHolder(String username) throws IdentityException { String keyAlias = null;//from w w w . j av a 2s . com KeyStoreAdmin keyAdmin; KeyStoreManager keyMan; Certificate[] certificates; int tenantID; String tenantDomain; String userTenantDomain; String spTenantDomain; try { userTenantDomain = MultitenantUtils.getTenantDomain(username); spTenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); if (!SAMLSSOUtil.isSaaSApplication() && !spTenantDomain.equalsIgnoreCase(userTenantDomain)) { throw new IdentityException("Service Provider tenant domian must be equal to user tenant domain" + " for non-SaaS applications"); } String signWithValue = IdentityUtil .getProperty(SAMLSSOConstants.FileBasedSPConfig.USE_AUTHENTICATED_USER_DOMAIN_CRYPTO); if (signWithValue != null && "true".equalsIgnoreCase(signWithValue.trim())) { tenantDomain = userTenantDomain; tenantID = SAMLSSOUtil.getRealmService().getTenantManager().getTenantId(tenantDomain); } else { tenantDomain = spTenantDomain; tenantID = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); } initializeRegistry(tenantID); if (tenantID != MultitenantConstants.SUPER_TENANT_ID) { String keyStoreName = SAMLSSOUtil.generateKSNameFromDomainName(tenantDomain); keyAlias = tenantDomain; keyMan = KeyStoreManager.getInstance(tenantID); KeyStore keyStore = keyMan.getKeyStore(keyStoreName); issuerPK = (PrivateKey) keyMan.getPrivateKey(keyStoreName, tenantDomain); certificates = keyStore.getCertificateChain(keyAlias); issuerCerts = new X509Certificate[certificates.length]; int i = 0; for (Certificate certificate : certificates) { issuerCerts[i++] = (X509Certificate) certificate; } signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA; String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm(); if (pubKeyAlgo.equalsIgnoreCase("DSA")) { signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA; } } else { keyAlias = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.KeyAlias"); keyAdmin = new KeyStoreAdmin(tenantID, SAMLSSOUtil.getRegistryService().getGovernanceSystemRegistry()); keyMan = KeyStoreManager.getInstance(tenantID); issuerPK = (PrivateKey) keyAdmin.getPrivateKey(keyAlias, true); certificates = keyMan.getPrimaryKeyStore().getCertificateChain(keyAlias); issuerCerts = new X509Certificate[certificates.length]; int i = 0; for (Certificate certificate : certificates) { issuerCerts[i++] = (X509Certificate) certificate; } signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA; String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm(); if (pubKeyAlgo.equalsIgnoreCase("DSA")) { signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA; } } } catch (Exception e) { throw new IdentityException(e.getMessage(), e); } }
From source file:org.wso2.carbon.identity.query.saml.SignKeyDataHolder.java
/** * This constructor is used to collect certificate information of the signature * * @param tenantDomain String type of tenant domain * @throws IdentitySAML2QueryException If unable connect with RealmService *///from w ww. ja v a2 s. c o m public SignKeyDataHolder(String tenantDomain) throws IdentitySAML2QueryException { String keyAlias; KeyStoreAdmin keyAdmin; KeyStoreManager keyMan; Certificate[] certificates; int tenantID; try { if (tenantDomain == null) { tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; } tenantID = SAMLSSOUtil.getRealmService().getTenantManager().getTenantId(tenantDomain); IdentityTenantUtil.initializeRegistry(tenantID, tenantDomain); if (tenantID != MultitenantConstants.SUPER_TENANT_ID) { String keyStoreName = SAMLSSOUtil.generateKSNameFromDomainName(tenantDomain); keyAlias = tenantDomain; keyMan = KeyStoreManager.getInstance(tenantID); KeyStore keyStore = keyMan.getKeyStore(keyStoreName); issuerPK = (PrivateKey) keyMan.getPrivateKey(keyStoreName, tenantDomain); certificates = keyStore.getCertificateChain(keyAlias); issuerCerts = new X509Certificate[certificates.length]; int i = 0; for (Certificate certificate : certificates) { issuerCerts[i++] = (X509Certificate) certificate; } signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA; publicKey = issuerCerts[0].getPublicKey(); String pubKeyAlgo = publicKey.getAlgorithm(); if (DSA_ENCRYPTION_ALGORITHM.equalsIgnoreCase(pubKeyAlgo)) { signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA; } } else { keyAlias = ServerConfiguration.getInstance().getFirstProperty(SECURITY_KEY_STORE_KEY_ALIAS); keyAdmin = new KeyStoreAdmin(tenantID, SAMLSSOUtil.getRegistryService().getGovernanceSystemRegistry()); keyMan = KeyStoreManager.getInstance(tenantID); issuerPK = (PrivateKey) keyAdmin.getPrivateKey(keyAlias, true); certificates = keyMan.getPrimaryKeyStore().getCertificateChain(keyAlias); issuerCerts = new X509Certificate[certificates.length]; int i = 0; for (Certificate certificate : certificates) { issuerCerts[i++] = (X509Certificate) certificate; } signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA; publicKey = issuerCerts[0].getPublicKey(); String pubKeyAlgo = publicKey.getAlgorithm(); if (DSA_ENCRYPTION_ALGORITHM.equalsIgnoreCase(pubKeyAlgo)) { signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA; } } } catch (IdentityException e) { log.error("Unable to access realm service ", e); throw new IdentitySAML2QueryException("Unable to access realm service"); } catch (KeyStoreException e) { log.error("Unable to load keystore", e); throw new IdentitySAML2QueryException("Unable to load keystore"); } catch (UserStoreException e) { log.error("Unable to load user store", e); throw new IdentitySAML2QueryException("Unable to load user store"); } catch (Exception e) { log.error("Unable to get primary keystore", e); throw new IdentitySAML2QueryException("Unable to get primary keystore"); } }