List of usage examples for java.security KeyStore getCertificate
public final Certificate getCertificate(String alias) throws KeyStoreException
From source file:org.lockss.protocol.BlockingStreamComm.java
private void logKeyStore(KeyStore ks, char[] privateKeyPassWord) { log.debug3("start of key store"); try {/*from w w w. ja v a2 s. com*/ for (Enumeration en = ks.aliases(); en.hasMoreElements();) { String alias = (String) en.nextElement(); log.debug3("Next alias " + alias); if (ks.isCertificateEntry(alias)) { log.debug3("About to Certificate"); java.security.cert.Certificate cert = ks.getCertificate(alias); if (cert == null) { log.debug3(alias + " null cert chain"); } else { log.debug3("Cert for " + alias + " is " + cert.toString()); } } else if (ks.isKeyEntry(alias)) { log.debug3("About to getKey"); Key privateKey = ks.getKey(alias, privateKeyPassWord); log.debug3(alias + " key " + privateKey.getAlgorithm() + "/" + privateKey.getFormat()); } else { log.debug3(alias + " neither key nor cert"); } } log.debug3("end of key store"); } catch (Exception ex) { log.error("logKeyStore() threw " + ex); } }
From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java
/** * This method will list 1. Certificate aliases 2. Private key alise 3. Private key value to a * given keystore.// ww w.j av a 2 s. co m * * @param keyStoreName The name of the keystore * @return Instance of KeyStoreData * @throws SecurityConfigException will be thrown */ public KeyStoreData getKeystoreInfo(String keyStoreName) throws SecurityConfigException { try { if (keyStoreName == null) { throw new Exception("keystore name cannot be null"); } KeyStore keyStore; String keyStoreType; String privateKeyPassowrd = null; if (KeyStoreUtil.isPrimaryStore(keyStoreName)) { KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId); keyStore = keyMan.getPrimaryKeyStore(); ServerConfiguration serverConfig = ServerConfiguration.getInstance(); keyStoreType = serverConfig .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_TYPE); privateKeyPassowrd = serverConfig .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD); } else { String path = SecurityConstants.KEY_STORES + "/" + keyStoreName; if (!registry.resourceExists(path)) { throw new SecurityConfigException("Key Store not found"); } Resource resource = registry.get(path); KeyStoreManager manager = KeyStoreManager.getInstance(tenantId); keyStore = manager.getKeyStore(keyStoreName); keyStoreType = resource.getProperty(SecurityConstants.PROP_TYPE); String encpass = resource.getProperty(SecurityConstants.PROP_PRIVATE_KEY_PASS); if (encpass != null) { CryptoUtil util = CryptoUtil.getDefaultCryptoUtil(); privateKeyPassowrd = new String(util.base64DecodeAndDecrypt(encpass)); } } // Fill the information about the certificates Enumeration<String> aliases = keyStore.aliases(); List<org.wso2.carbon.security.keystore.service.CertData> certDataList = new ArrayList<>(); Format formatter = new SimpleDateFormat("dd/MM/yyyy"); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keyStore.isCertificateEntry(alias)) { X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); certDataList.add(fillCertData(cert, alias, formatter)); } } // Create a cert array CertData[] certs = certDataList.toArray(new CertData[certDataList.size()]); // Create a KeyStoreData bean, set the name and fill in the cert information KeyStoreData keyStoreData = new KeyStoreData(); keyStoreData.setKeyStoreName(keyStoreName); keyStoreData.setCerts(certs); keyStoreData.setKeyStoreType(keyStoreType); aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); // There be only one entry in WSAS related keystores if (keyStore.isKeyEntry(alias)) { X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); keyStoreData.setKey(fillCertData(cert, alias, formatter)); PrivateKey key = (PrivateKey) keyStore.getKey(alias, privateKeyPassowrd.toCharArray()); String pemKey; pemKey = "-----BEGIN PRIVATE KEY-----\n"; pemKey += Base64.encode(key.getEncoded()); pemKey += "\n-----END PRIVATE KEY-----"; keyStoreData.setKeyValue(pemKey); break; } } return keyStoreData; } catch (Exception e) { String msg = "Error has encounted while loading the keystore to the given keystore name " + keyStoreName; log.error(msg, e); throw new SecurityConfigException(msg); } }
From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java
/** * This method will list 1. Certificate aliases 2. Private key alise 3. Private key value to a * given keystore.//from w ww . j a v a 2 s .c om * * @param keyStoreName The name of the keystore * @param pageNumber page number * @return Instance of KeyStoreData * @throws SecurityConfigException will be thrown */ public PaginatedKeyStoreData getPaginatedKeystoreInfo(String keyStoreName, int pageNumber) throws SecurityConfigException { try { if (keyStoreName == null) { throw new Exception("keystore name cannot be null"); } KeyStore keyStore; String keyStoreType; String privateKeyPassowrd = null; if (KeyStoreUtil.isPrimaryStore(keyStoreName)) { KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId); keyStore = keyMan.getPrimaryKeyStore(); ServerConfiguration serverConfig = ServerConfiguration.getInstance(); keyStoreType = serverConfig .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_TYPE); privateKeyPassowrd = serverConfig .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD); } else { String path = SecurityConstants.KEY_STORES + "/" + keyStoreName; if (!registry.resourceExists(path)) { throw new SecurityConfigException("Key Store not found"); } Resource resource = registry.get(path); KeyStoreManager manager = KeyStoreManager.getInstance(tenantId); keyStore = manager.getKeyStore(keyStoreName); keyStoreType = resource.getProperty(SecurityConstants.PROP_TYPE); String encpass = resource.getProperty(SecurityConstants.PROP_PRIVATE_KEY_PASS); if (encpass != null) { CryptoUtil util = CryptoUtil.getDefaultCryptoUtil(); privateKeyPassowrd = new String(util.base64DecodeAndDecrypt(encpass)); } } // Fill the information about the certificates Enumeration<String> aliases = keyStore.aliases(); List<org.wso2.carbon.security.keystore.service.CertData> certDataList = new ArrayList<>(); Format formatter = new SimpleDateFormat("dd/MM/yyyy"); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keyStore.isCertificateEntry(alias)) { X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); certDataList.add(fillCertData(cert, alias, formatter)); } } // Create a cert array CertData[] certs = certDataList.toArray(new CertData[certDataList.size()]); // Create a KeyStoreData bean, set the name and fill in the cert information PaginatedKeyStoreData keyStoreData = new PaginatedKeyStoreData(); keyStoreData.setKeyStoreName(keyStoreName); keyStoreData.setPaginatedCertData(doPaging(pageNumber, certs)); keyStoreData.setKeyStoreType(keyStoreType); aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); // There be only one entry in WSAS related keystores if (keyStore.isKeyEntry(alias)) { X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); keyStoreData.setKey(fillCertData(cert, alias, formatter)); PrivateKey key = (PrivateKey) keyStore.getKey(alias, privateKeyPassowrd.toCharArray()); String pemKey; pemKey = "-----BEGIN PRIVATE KEY-----\n"; pemKey += Base64.encode(key.getEncoded()); pemKey += "\n-----END PRIVATE KEY-----"; keyStoreData.setKeyValue(pemKey); break; } } return keyStoreData; } catch (Exception e) { String msg = "Error has encounted while loading the keystore to the given keystore name " + keyStoreName; log.error(msg, e); throw new SecurityConfigException(msg); } }
From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java
public static TokenSearchResults searchTokenEntries(final KeyStore keyStore, final int startIndex, final int max, final QueryCriteria qc, final boolean includeData) throws CryptoTokenOfflineException, QueryException { final TokenSearchResults result; try {/*w ww . j a va 2 s .com*/ final ArrayList<TokenEntry> tokenEntries = new ArrayList<TokenEntry>(); final Enumeration<String> e = keyStore.aliases(); // We assume the order is the same for every call unless entries has been added or removed final long maxIndex = (long) startIndex + max; for (int i = 0; i < maxIndex && e.hasMoreElements();) { final String keyAlias = e.nextElement(); final String type; if (keyStore.entryInstanceOf(keyAlias, KeyStore.PrivateKeyEntry.class)) { type = TokenEntry.TYPE_PRIVATEKEY_ENTRY; } else if (keyStore.entryInstanceOf(keyAlias, KeyStore.SecretKeyEntry.class)) { type = TokenEntry.TYPE_SECRETKEY_ENTRY; } else if (keyStore.entryInstanceOf(keyAlias, KeyStore.TrustedCertificateEntry.class)) { type = TokenEntry.TYPE_TRUSTED_ENTRY; } else { type = null; } TokenEntry entry = new TokenEntry(keyAlias, type); if (shouldBeIncluded(entry, qc)) { if (i < startIndex) { i++; continue; } if (LOG.isDebugEnabled()) { LOG.debug("checking keyAlias: " + keyAlias); } // Add additional data if (includeData) { Map<String, String> info = new HashMap<String, String>(); try { Date creationDate = keyStore.getCreationDate(keyAlias); entry.setCreationDate(creationDate); } catch (ProviderException ex) { } // NOPMD: We ignore if it is not supported if (TokenEntry.TYPE_PRIVATEKEY_ENTRY.equals(type)) { final Certificate[] chain = keyStore.getCertificateChain(keyAlias); if (chain.length > 0) { info.put(INFO_KEY_ALGORITHM, AlgorithmTools.getKeyAlgorithm(chain[0].getPublicKey())); info.put(INFO_KEY_SPECIFICATION, AlgorithmTools.getKeySpecification(chain[0].getPublicKey())); } try { entry.setParsedChain(chain); } catch (CertificateEncodingException ex) { info.put("Error", ex.getMessage()); LOG.error("Certificate could not be encoded for alias: " + keyAlias, ex); } } else if (TokenEntry.TYPE_TRUSTED_ENTRY.equals(type)) { Certificate certificate = keyStore.getCertificate(keyAlias); try { entry.setParsedTrustedCertificate(certificate); } catch (CertificateEncodingException ex) { info.put("Error", ex.getMessage()); LOG.error("Certificate could not be encoded for alias: " + keyAlias, ex); } } else if (TokenEntry.TYPE_SECRETKEY_ENTRY.equals(type)) { try { KeyStore.Entry entry1 = keyStore.getEntry(keyAlias, null); SecretKey secretKey = ((KeyStore.SecretKeyEntry) entry1).getSecretKey(); info.put(INFO_KEY_ALGORITHM, secretKey.getAlgorithm()); //info.put(INFO_KEY_SPECIFICATION, AlgorithmTools.getKeySpecification(chain[0].getPublicKey())); // TODO: Key specification support for secret keys } catch (NoSuchAlgorithmException ex) { info.put("Error", ex.getMessage()); LOG.error("Unable to get secret key for alias: " + keyAlias, ex); } catch (UnrecoverableEntryException ex) { info.put("Error", ex.getMessage()); LOG.error("Unable to get secret key for alias: " + keyAlias, ex); } } entry.setInfo(info); } tokenEntries.add(entry); // Increase index i++; } } result = new TokenSearchResults(tokenEntries, e.hasMoreElements()); } catch (KeyStoreException ex) { throw new CryptoTokenOfflineException(ex); } return result; }
From source file:com.stargame.ad.util.http.ssl.AuthSSLProtocolSocketFactory.java
private SSLContext createSSLContext() { try {/*from w w w. j av a2 s . c om*/ KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keystoreUrl != null) { KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); if (LogUtil.D) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { LogUtil.d(AuthSSLProtocolSocketFactory.class, "Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; LogUtil.d(AuthSSLProtocolSocketFactory.class, " Certificate " + (c + 1) + ":"); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Subject DN: " + cert.getSubjectDN()); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Signature Algorithm: " + cert.getSigAlgName()); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid from: " + cert.getNotBefore()); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid until: " + cert.getNotAfter()); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Issuer: " + cert.getIssuerDN()); } } } } } keymanagers = createKeyManagers(keystore, this.keystorePassword); } if (this.truststoreUrl != null) { KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword); if (LogUtil.D) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); LogUtil.d(AuthSSLProtocolSocketFactory.class, "Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; LogUtil.d(AuthSSLProtocolSocketFactory.class, " Subject DN: " + cert.getSubjectDN()); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Signature Algorithm: " + cert.getSigAlgName()); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid from: " + cert.getNotBefore()); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid until: " + cert.getNotAfter()); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Issuer: " + cert.getIssuerDN()); } } } trustmanagers = createTrustManagers(keystore); } SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(keymanagers, trustmanagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("Key management exception: " + e.getMessage()); } catch (IOException e) { LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage()); } }
From source file:cn.org.eshow.framwork.http.ssl.AuthSSLProtocolSocketFactory.java
private SSLContext createSSLContext() { try {/*from ww w.ja va 2 s. c o m*/ KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keystoreUrl != null) { KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); if (AbLogUtil.D) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Certificate " + (c + 1) + ":"); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Subject DN: " + cert.getSubjectDN()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Signature Algorithm: " + cert.getSigAlgName()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid from: " + cert.getNotBefore()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid until: " + cert.getNotAfter()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Issuer: " + cert.getIssuerDN()); } } } } } keymanagers = createKeyManagers(keystore, this.keystorePassword); } if (this.truststoreUrl != null) { KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword); if (AbLogUtil.D) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Subject DN: " + cert.getSubjectDN()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Signature Algorithm: " + cert.getSigAlgName()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid from: " + cert.getNotBefore()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid until: " + cert.getNotAfter()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Issuer: " + cert.getIssuerDN()); } } } trustmanagers = createTrustManagers(keystore); } SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(keymanagers, trustmanagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("Key management exception: " + e.getMessage()); } catch (IOException e) { AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage()); } }
From source file:com.mhise.util.MHISEUtil.java
public static boolean saveImportedCertificateToDevice(String certificate, String password, Context ctx, String certName) {//from ww w. j ava 2 s .c o m boolean isPasswordCorrect = false; byte[] certificatebytes = null; try { certificatebytes = Base64.decode(certificate, Base64.DEFAULT); } catch (IllegalArgumentException e) { // TODO: handle exception Logger.debug("MHISEUtil-->saveImportedCertificateToDevice", "" + e); } KeyStore localTrustStore = null; try { localTrustStore = KeyStore.getInstance("PKCS12"); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } InputStream is = new ByteArrayInputStream(certificatebytes); try { localTrustStore.load(is, password.toCharArray()); isPasswordCorrect = true; } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } OutputStream fos = null; try { //<<<<<<< .mine //SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.PREFS_NAME,Context.MODE_PRIVATE); //String storeName =sharedPreferences.getString(Constants.KEY_CERT_NAME, null); File _mobiusDirectory = new File(Constants.defaultP12StorePath); if (!_mobiusDirectory.exists()) { _mobiusDirectory.mkdir(); } File file = new File(Constants.defaultP12StorePath + certName); fos = new FileOutputStream(file); //fos = ctx.openFileOutput(Constants.defaultP12StoreName, Context.MODE_PRIVATE); localTrustStore.store(fos, MHISEUtil.getStrongPassword(certName).toCharArray()); /*//======= //SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.PREFS_NAME,Context.MODE_PRIVATE); //String storeName =sharedPreferences.getString(Constants.KEY_CERT_NAME, null); File file = new File(Constants.defaultP12StorePath+certName); fos = new FileOutputStream(file); //fos = ctx.openFileOutput(Constants.defaultP12StoreName, Context.MODE_PRIVATE); localTrustStore.store(fos,MHISEUtil.getStrongPassword(certName).toCharArray()); >>>>>>> .r4477*/ fos.close(); Enumeration<String> aliases = null; try { aliases = localTrustStore.aliases(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } //boolean isInstalledCertificateValid = false; while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); java.security.cert.X509Certificate cert = null; try { cert = (X509Certificate) localTrustStore.getCertificate(alias); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } SharedPreferences sharedPreferences1 = ctx.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences1.edit(); Log.i("Imported certificate serial number", "" + cert.getSerialNumber().toString(16)); editor.putString(Constants.KEY_SERIAL_NUMBER, "" + cert.getSerialNumber().toString(16)); editor.commit(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return isPasswordCorrect; }
From source file:eu.eidas.auth.engine.EIDASSAMLEngine.java
/** * Gets the alias from X.509 Certificate at keystore. * /*w ww . j a v a 2 s .c om*/ * @param keyInfo the key info * @param ownKeyStore * @param ownKeyStore * * @return the alias */ private String getAlias(final KeyInfo keyInfo, KeyStore ownKeyStore) { LOG.trace("Recover alias information"); String alias = null; try { final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0) .getX509Certificates().get(0); // Transform the KeyInfo to X509Certificate. CertificateFactory certFact; certFact = CertificateFactory.getInstance("X.509"); final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue())); final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis); final String tokenSerialNumber = cert.getSerialNumber().toString(HEXA); final X500Name tokenIssuerDN = new X500Name(cert.getIssuerDN().getName()); String aliasCert; X509Certificate certificate; boolean find = false; for (final Enumeration<String> e = ownKeyStore.aliases(); e.hasMoreElements() && !find;) { aliasCert = e.nextElement(); certificate = (X509Certificate) ownKeyStore.getCertificate(aliasCert); final String serialNum = certificate.getSerialNumber().toString(HEXA); X500Name issuerDN = new X500Name(certificate.getIssuerDN().getName()); if (serialNum.equalsIgnoreCase(tokenSerialNumber) && X500PrincipalUtil.principalEquals(issuerDN, tokenIssuerDN)) { alias = aliasCert; find = true; } } } catch (KeyStoreException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e); } catch (CertificateException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e); } catch (RuntimeException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e); } return alias; }
From source file:com.ext.portlet.epsos.EpsosHelperService.java
@SuppressWarnings("deprecation") public static void signSAMLAssertion(SignableSAMLObject as, String keyAlias, char[] keyPassword) throws Exception { //String KEY_STORE_NAME="Unknown-1"; //String KEY_STORE_PASS="spirit"; //String PRIVATE_KEY_PASS="spirit"; //String KEY_ALIAS="server1"; ConfigurationManagerService cms = ConfigurationManagerService.getInstance(); //String KEY_STORE_NAME =GetterUtil.getString(GnPropsUtil.get("portalb", "KEYSTORE_LOCATION"),"Unknown-1"); String KEYSTORE_LOCATION = cms.getProperty("javax.net.ssl.keyStore"); String KEY_STORE_PASS = cms.getProperty("javax.net.ssl.keyStorePassword"); //GetterUtil.getString(GnPropsUtil.get("portalb", "KEYSTORE_PASSWORD"),"spirit"); String KEY_ALIAS = cms.getProperty("javax.net.ssl.key.alias"); //GetterUtil.getString(GnPropsUtil.get("portalb", "PRIVATEKEY_ALIAS"),"server1"); String PRIVATE_KEY_PASS = cms.getProperty("javax.net.ssl.privateKeyPassword"); //GetterUtil.getString(GnPropsUtil.get("portalb", "PRIVATEKEY_PASSWORD"),"spirit"); _log.debug("-------" + KEYSTORE_LOCATION); _log.debug("-------" + KEY_STORE_PASS); _log.debug("-------" + KEY_ALIAS); _log.debug("-------" + PRIVATE_KEY_PASS); KeyStoreManager keyManager = new DefaultKeyStoreManager(); //KeyPair kp = null; X509Certificate cert = null;//from w w w .jav a 2 s . c o m //check if we must use the default key PrivateKey privateKey = null; PublicKey publicKey = null; if (keyAlias == null) { // kp = keyManager.getDefaultPrivateKey(); cert = (X509Certificate) keyManager.getDefaultCertificate(); } else { KeyStore keyStore = KeyStore.getInstance("JKS"); ClassLoader cl = Thread.currentThread().getContextClassLoader(); File file = new File(KEYSTORE_LOCATION); keyStore.load(new FileInputStream(file), KEY_STORE_PASS.toCharArray()); privateKey = (PrivateKey) keyStore.getKey(KEY_ALIAS, PRIVATE_KEY_PASS.toCharArray()); X509Certificate cert1 = (X509Certificate) keyStore.getCertificate(KEY_ALIAS); publicKey = cert1.getPublicKey(); //kp = keyManager.getPrivateKey(keyAlias, keyPassword); cert = (X509Certificate) keyManager.getCertificate(keyAlias); } org.opensaml.xml.signature.Signature sig = (org.opensaml.xml.signature.Signature) Configuration .getBuilderFactory().getBuilder(org.opensaml.xml.signature.Signature.DEFAULT_ELEMENT_NAME) .buildObject(org.opensaml.xml.signature.Signature.DEFAULT_ELEMENT_NAME); Credential signingCredential = SecurityHelper.getSimpleCredential(cert, privateKey); //sig.setCanonicalizationAlgorithm(SignatureConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); sig.setSigningCredential(signingCredential); // sig.setKeyInfo(SecurityHelper.getKeyInfoGenerator(signingCredential, null, null).generate(signingCredential)); sig.setSignatureAlgorithm("http://www.w3.org/2000/09/xmldsig#rsa-sha1"); sig.setCanonicalizationAlgorithm("http://www.w3.org/2001/10/xml-exc-c14n#"); SecurityConfiguration secConfig = Configuration.getGlobalSecurityConfiguration(); try { SecurityHelper.prepareSignatureParams(sig, signingCredential, secConfig, null); } catch (SecurityException e) { throw new SMgrException(e.getMessage(), e); } as.setSignature(sig); try { Configuration.getMarshallerFactory().getMarshaller(as).marshall(as); } catch (MarshallingException e) { throw new SMgrException(e.getMessage(), e); } try { org.opensaml.xml.signature.Signer.signObject(sig); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java
private static void exportSPMetaData(Options options, CommandLine cmd, TremoloType tt, KeyStore ks) throws Exception, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, CertificateEncodingException, MarshallingException { logger.info("Finding mechanism..."); String mechanismName = loadOption(cmd, "mechanismName", options); MechanismType saml2Mech = loadMechanismType(mechanismName, tt); logger.info("...found"); logger.info("Finding chain..."); String chainName = loadOption(cmd, "chainName", options); AuthChainType act = loadChainType(chainName, tt); logger.info("Looking for correct mechanism on the chain..."); AuthMechType currentMechanism = null; for (AuthMechType amt : act.getAuthMech()) { if (amt.getName().equalsIgnoreCase(mechanismName)) { currentMechanism = amt;/*w ww.ja v a 2 s . c o m*/ break; } } if (currentMechanism == null) { System.err.println("Unknown chain on mechanism"); System.exit(1); } InitializationService.initialize(); logger.info("loading url base"); String urlBase = loadOption(cmd, "urlBase", options); String url = urlBase + saml2Mech.getUri(); SecureRandom random = new SecureRandom(); byte[] idBytes = new byte[20]; random.nextBytes(idBytes); String id = "f" + Hex.encodeHexString(idBytes); EntityDescriptorBuilder edb = new EntityDescriptorBuilder(); EntityDescriptorImpl ed = (EntityDescriptorImpl) edb.buildObject(); ed.setID(id); ed.setEntityID(url); SPSSODescriptorBuilder spb = new SPSSODescriptorBuilder(); SPSSODescriptorImpl sp = (SPSSODescriptorImpl) spb.buildObject(); ed.getRoleDescriptors().add(sp); HashMap<String, ParamType> params = new HashMap<String, ParamType>(); for (ParamType pt : currentMechanism.getParams().getParam()) { params.put(pt.getName(), pt); } boolean assertionsSigned = params.get("assertionsSigned") != null && params.get("assertionsSigned").getValue().equalsIgnoreCase("true"); sp.setWantAssertionsSigned(assertionsSigned); sp.addSupportedProtocol("urn:oasis:names:tc:SAML:2.0:protocol"); SingleLogoutServiceBuilder slsb = new SingleLogoutServiceBuilder(); SingleLogoutService sls = slsb.buildObject(); sls.setLocation(url); sls.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"); sp.getSingleLogoutServices().add(sls); sls = slsb.buildObject(); sls.setLocation(url); sls.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"); sp.getSingleLogoutServices().add(sls); AssertionConsumerServiceBuilder acsb = new AssertionConsumerServiceBuilder(); AssertionConsumerService acs = acsb.buildObject(); acs.setLocation(url); acs.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"); acs.setIndex(0); acs.setIsDefault(true); sp.getAssertionConsumerServices().add(acs); acs = acsb.buildObject(); acs.setLocation(url); acs.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"); acs.setIndex(1); sp.getAssertionConsumerServices().add(acs); if (params.get("spSigKey") != null && !params.get("spSigKey").getValue().isEmpty()) { String alias = params.get("spSigKey").getValue(); X509Certificate certFromKS = (X509Certificate) ks.getCertificate(alias); if (certFromKS == null) { throw new Exception("Certificate '" + params.get("spSigKey").getValue() + "' not found"); } PrivateKey keyFromKS = (PrivateKey) ks.getKey(alias, tt.getKeyStorePassword().toCharArray()); KeyDescriptorBuilder kdb = new KeyDescriptorBuilder(); KeyDescriptor kd = kdb.buildObject(); kd.setUse(UsageType.SIGNING); KeyInfoBuilder kib = new KeyInfoBuilder(); KeyInfo ki = kib.buildObject(); X509DataBuilder x509b = new X509DataBuilder(); X509Data x509 = x509b.buildObject(); X509CertificateBuilder certb = new X509CertificateBuilder(); org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject(); cert.setValue(new String(Base64.encode(certFromKS.getEncoded()))); x509.getX509Certificates().add(cert); ki.getX509Datas().add(x509); kd.setKeyInfo(ki); sp.getKeyDescriptors().add(kd); } if (params.get("spEncKey") != null && !params.get("spEncKey").getValue().isEmpty()) { String alias = params.get("spEncKey").getValue(); X509Certificate certFromKS = (X509Certificate) ks.getCertificate(alias); if (certFromKS == null) { throw new Exception("Certificate '" + params.get("spEncKey").getValue() + "' not found"); } PrivateKey keyFromKS = (PrivateKey) ks.getKey(alias, tt.getKeyStorePassword().toCharArray()); KeyDescriptorBuilder kdb = new KeyDescriptorBuilder(); KeyDescriptor kd = kdb.buildObject(); kd.setUse(UsageType.ENCRYPTION); KeyInfoBuilder kib = new KeyInfoBuilder(); KeyInfo ki = kib.buildObject(); X509DataBuilder x509b = new X509DataBuilder(); X509Data x509 = x509b.buildObject(); X509CertificateBuilder certb = new X509CertificateBuilder(); org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject(); cert.setValue(new String(Base64.encode(certFromKS.getEncoded()))); x509.getX509Certificates().add(cert); ki.getX509Datas().add(x509); kd.setKeyInfo(ki); sp.getKeyDescriptors().add(kd); } EntityDescriptorMarshaller marshaller = new EntityDescriptorMarshaller(); // Marshall the Subject Element assertionElement = marshaller.marshall(ed); String xml = net.shibboleth.utilities.java.support.xml.SerializeSupport.prettyPrintXML(assertionElement); logger.info(xml); }