List of usage examples for java.security KeyStore getCertificate
public final Certificate getCertificate(String alias) throws KeyStoreException
From source file:mitm.BouncyCastleSslEngineSource.java
public static Certificate initializeKeyStoreStatic(Authority authority) throws RootCertificateException, GeneralSecurityException, OperatorCreationException, IOException { if (authority.aliasFile(KEY_STORE_FILE_EXTENSION).exists() && authority.aliasFile(".pem").exists()) { return KeyStore.getInstance(KEY_STORE_TYPE).getCertificate(authority.alias()); }//w w w . j a v a 2s . c o m MillisecondsDuration duration = new MillisecondsDuration(); KeyStore keystore = CertificateHelper.createRootCertificate(authority, KEY_STORE_TYPE); LOG.info("Created root certificate authority key store in {}ms", duration); OutputStream os = null; try { os = new FileOutputStream(authority.aliasFile(KEY_STORE_FILE_EXTENSION)); keystore.store(os, authority.password()); } finally { IOUtils.closeQuietly(os); } Certificate cert = keystore.getCertificate(authority.alias()); exportPem(authority.aliasFile(".pem"), cert); return cert; }
From source file:org.wso2.store.sso.common.util.Util.java
/** * This method validates the signature of the SAML Response. * * @param resp SAML Response//from ww w . j a va 2s. co m * @return true, if signature is valid. */ public static boolean validateSignature(Response resp, String keyStoreName, String keyStorePassword, String alias, int tenantId, String tenantDomain) { boolean isSigValid = false; try { KeyStore keyStore = null; java.security.cert.X509Certificate cert = null; if (tenantId != MultitenantConstants.SUPER_TENANT_ID) { // get an instance of the corresponding Key Store Manager instance KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId); keyStore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(tenantDomain)); // log.info(keyStore.getCertificate(tenantDomain)); cert = (java.security.cert.X509Certificate) keyStore.getCertificate(tenantDomain); // log.info(cert.getSubjectDN().getName()); } else { keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(new File(keyStoreName)), keyStorePassword.toCharArray()); cert = (java.security.cert.X509Certificate) keyStore.getCertificate(alias); } X509CredentialImpl credentialImpl = new X509CredentialImpl(cert); SignatureValidator signatureValidator = new SignatureValidator(credentialImpl); signatureValidator.validate(resp.getSignature()); isSigValid = true; return isSigValid; } catch (Exception e) { e.printStackTrace(); return isSigValid; } }
From source file:nl.nn.adapterframework.http.AuthSSLProtocolSocketFactoryBase.java
protected static KeyStore createKeyStore(final URL url, final String password, String keyStoreType, String prefix) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { if (url == null) { throw new IllegalArgumentException("Keystore url for " + prefix + " may not be null"); }/*from w ww. ja v a 2s . co m*/ log.info("Initializing keystore for " + prefix + " from " + url.toString()); KeyStore keystore = KeyStore.getInstance(keyStoreType); keystore.load(url.openStream(), password != null ? password.toCharArray() : null); if (log.isInfoEnabled()) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); log.info(prefix + " '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; log.info(" Subject DN: " + cert.getSubjectDN()); log.info(" Signature Algorithm: " + cert.getSigAlgName()); log.info(" Valid from: " + cert.getNotBefore()); log.info(" Valid until: " + cert.getNotAfter()); log.info(" Issuer: " + cert.getIssuerDN()); } } } return keystore; }
From source file:fr.inria.ucn.Helpers.java
/** * FIXME: remove once all servers have valid certificate * @return/*from w ww.j a v a 2s . c om*/ */ public static boolean isCaCertInstalledHack(String match) { boolean res = false; try { KeyStore ks = KeyStore.getInstance("AndroidCAStore"); ks.load(null, null); Enumeration<String> aliases = ks.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); X509Certificate cert = (X509Certificate) ks.getCertificate(alias); //Log.d(Constants.LOGTAG, "keystore: " + alias + "/" + cert.getIssuerDN().getName()); if (cert.getIssuerDN().getName().contains(match)) { res = true; break; } } } catch (KeyStoreException e) { Log.w(Constants.LOGTAG, "failed to check certificates", e); } catch (NoSuchAlgorithmException e) { } catch (CertificateException e) { } catch (IOException e) { } return res; }
From source file:org.wso2.carbon.identity.query.saml.util.OpenSAML3Util.java
/** * Get the X509CredentialImpl object for a particular tenant * * @param tenantDomain tenant domain of the issuer * @param alias alias of cert/*from w w w . j a va2 s . com*/ * @return X509CredentialImpl object containing the public certificate of that tenant * @throws IdentitySAML2QueryException Error when creating X509CredentialImpl object */ public static X509CredentialImpl getX509CredentialImplForTenant(String tenantDomain, String alias) throws IdentitySAML2QueryException { if (tenantDomain.trim() == null || alias.trim() == null) { log.error("Invalid parameters; domain name : " + tenantDomain + ", " + "alias : " + alias); } int tenantId; try { tenantId = SAMLQueryServiceComponent.getRealmservice().getTenantManager().getTenantId(tenantDomain); } catch (org.wso2.carbon.user.api.UserStoreException e) { String errorMsg = "Error getting the tenant ID for the tenant domain : " + tenantDomain; throw new IdentitySAML2QueryException(errorMsg, e); } KeyStoreManager keyStoreManager; // get an instance of the corresponding Key Store Manager instance keyStoreManager = KeyStoreManager.getInstance(tenantId); X509CredentialImpl credentialImpl = null; KeyStore keyStore; try { if (tenantId != -1234) {// for tenants, load private key from their generated key store keyStore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(tenantDomain)); } else { // for super tenant, load the default pub. cert using the // config. in carbon.xml keyStore = keyStoreManager.getPrimaryKeyStore(); } java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) keyStore .getCertificate(alias); credentialImpl = new X509CredentialImpl(cert); } catch (KeyStoreException e) { String errorMsg = "Error instantiating an X509CredentialImpl object for the public certificate of " + tenantDomain; log.error(errorMsg, e); throw new IdentitySAML2QueryException(errorMsg, e); } catch (Exception e) { //keyStoreManager throws Exception log.error("Unable to load key store manager for the tenant domain:" + tenantDomain, e); throw new IdentitySAML2QueryException( "Unable to load key store manager for the tenant domain:" + tenantDomain, e); } return credentialImpl; }
From source file:com.bcmcgroup.flare.client.ClientUtil.java
/** * Fetch a public key (certificate) from KeyStore * * @param keyStorePath a String containing the path to the KeyStore * @param keyStorePW a String containing the KeyStore password * @param alias a String containing the alias of targeted certificate * @return the PublicKey object containing the targeted public key * */// w w w .ja v a2s. com public static PublicKey getPublicKeyByAlias(String keyStorePath, String keyStorePW, String alias) { KeyStore ks; FileInputStream is = null; try { ks = KeyStore.getInstance("JKS"); is = new FileInputStream(keyStorePath); ks.load(is, keyStorePW.toCharArray()); Certificate certificate = ks.getCertificate(alias); if (certificate != null) { return certificate.getPublicKey(); } } catch (FileNotFoundException e) { logger.error("FileNotFoundException when attempting to extract a public key by an alias in a keystore. " + e); } catch (IOException e) { logger.error("IOException when attempting to extract a public key by an alias in a keystore. " + e); } catch (KeyStoreException e) { logger.error( "KeyStoreException when attempting to extract a public key by an alias in a keystore. " + e); } catch (NoSuchAlgorithmException e) { logger.error( "NoSuchAlgorithmException when attempting to extract a public key by an alias in a keystore. " + e); } catch (CertificateException e) { logger.error( "CertificateException when attempting to extract a public key by an alias in a keystore. " + e); } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { logger.error("IOException when attempting to close an input stream. " + ioe); } } } return null; }
From source file:br.gov.serpro.cert.AuthSSLProtocolSocketFactory.java
private static KeyStore createKeyStore(final URL[] urls, final String[] passwords) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null);/*from w w w . ja v a 2 s . c o m*/ if (urls == null) { throw new IllegalArgumentException("Keystore urls may not be null"); } if (passwords != null && passwords.length != urls.length) { throw new IllegalArgumentException("Urls and passwords arrays must have the same size"); } LOG.debug("Initializing key store"); for (int i = 0; i < urls.length; i++) { LOG.debug("Adding " + urls[i].toString() + " to internal keystore"); KeyStore ks = KeyStore.getInstance("jks"); InputStream is = null; try { is = urls[i].openStream(); if (passwords == null) { ks.load(is, null); } else { ks.load(is, passwords[i] != null ? passwords[i].toCharArray() : null); } for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) { X509Certificate cert = (X509Certificate) ks.getCertificate(e.nextElement()); keystore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert); } } catch (IOException e) { if (AuthSSLProtocolSocketFactory.setup.getParameter("debug").equalsIgnoreCase("true")) { System.out.println("Erro ao abrir URL: " + urls[i].toExternalForm()); } } finally { if (is != null) is.close(); } } return keystore; }
From source file:org.panbox.core.pairing.file.PanboxFilePairingUtils.java
public static PanboxFilePairingLoadReturnContainer loadPairingFile(File inputFile, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException, UnrecoverableKeyException, IllegalArgumentException { ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(inputFile)); try {//www .j a v a2 s . c o m byte[] buffer = new byte[1048576]; //1MB ArchiveEntry entry; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len = 0; // ENTRY 1: devicename entry = in.getNextEntry(); if (entry == null) { logger.error("PanboxClient : loadPairingFile : Could not find entry for device name."); throw new IllegalArgumentException("Could not find entry for device name."); } baos = new ByteArrayOutputStream(); len = 0; while ((len = in.read(buffer)) > 0) { baos.write(buffer, 0, len); } String devicename = new String(baos.toByteArray()); // ENTRY 2: eMail entry = in.getNextEntry(); if (entry == null) { logger.error("PanboxClient : loadPairingFile : Could not find entry for eMail."); throw new IllegalArgumentException("Could not find entry for eMail."); } baos = new ByteArrayOutputStream(); len = 0; while ((len = in.read(buffer)) > 0) { baos.write(buffer, 0, len); } String eMail = new String(baos.toByteArray()); // ENTRY 3: firstName entry = in.getNextEntry(); if (entry == null) { logger.error("PanboxClient : loadPairingFile : Could not find entry for first name."); throw new IllegalArgumentException("Could not find entry for first name."); } baos = new ByteArrayOutputStream(); len = 0; while ((len = in.read(buffer)) > 0) { baos.write(buffer, 0, len); } String firstName = new String(baos.toByteArray()); // ENTRY 4: lastName entry = in.getNextEntry(); if (entry == null) { logger.error("PanboxClient : loadPairingFile : Could not find entry for last name."); throw new IllegalArgumentException("Could not find entry for last name."); } baos = new ByteArrayOutputStream(); len = 0; while ((len = in.read(buffer)) > 0) { baos.write(buffer, 0, len); } String lastName = new String(baos.toByteArray()); // ENTRY 5: devKeyStore.p12 entry = in.getNextEntry(); if (entry == null) { logger.error("PanboxClient : loadPairingFile : Could not find entry for device key store."); throw new IllegalArgumentException("Could not find entry for device key store."); } KeyStore devKeyStore = KeyStore.getInstance("PKCS12"); devKeyStore.load(in, password); PrivateKey devPKey = (PrivateKey) devKeyStore.getKey(devicename.toLowerCase(), password); Certificate[] devCert = devKeyStore.getCertificateChain(devicename.toLowerCase()); // ENTRY 6: knownDevices.list/knownDevices.bks entry = in.getNextEntry(); // knownDevices.list if (entry == null) { logger.error("PanboxClient : loadPairingFile : Could not find entry for knownDevices.list."); throw new IllegalArgumentException("Could not find entry for knownDevices.list."); } Map<String, X509Certificate> devices = new HashMap<String, X509Certificate>(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); Map<String, String> deviceNames = new HashMap<String, String>(); String line; while ((line = br.readLine()) != null) { String[] values = line.split(DELIMITER); deviceNames.put(values[0], values[1]); } entry = in.getNextEntry(); // knownDevices.bks if (entry == null) { logger.error("PanboxClient : loadPairingFile : Could not find entry for knownDevices.bks."); throw new IllegalArgumentException("Could not find entry for knownDevices.bks."); } KeyStore devicesStore = KeyStore.getInstance("BKS"); devicesStore.load(in, password); for (Entry<String, String> device : deviceNames.entrySet()) { X509Certificate deviceCert = (X509Certificate) devicesStore.getCertificate(device.getKey()); devices.put(device.getValue(), deviceCert); } // ENTRY 7: contacts.vcard entry = in.getNextEntry(); if (entry == null) { logger.error("PanboxClient : loadPairingFile : Could not find entry for contacts."); throw new IllegalArgumentException("Could not find entry for contacts."); } File contacts = File.createTempFile("panbox" + (new Random().nextInt(65536) - 32768), null); FileOutputStream fos = new FileOutputStream(contacts); len = 0; while ((len = in.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.flush(); fos.close(); // ENTRY 8: ownerKeyStore/ownerCertStore.jks entry = in.getNextEntry(); ByteArrayOutputStream tmp = new ByteArrayOutputStream(); IOUtils.copy(in, tmp); ByteArrayInputStream buf = new ByteArrayInputStream(tmp.toByteArray()); if (entry == null) { logger.error("PanboxClient : loadPairingFile : Could not find entry for owner key store."); throw new IllegalArgumentException("Could not find entry for owner key store."); } KeyStore ownerKeyStore = null; try { // Check if pairing is MASTER ownerKeyStore = KeyStore.getInstance("PKCS12"); ownerKeyStore.load(buf, password); // At this point we know it's a PKCS11 file! PrivateKey ownerEncKey = (PrivateKey) ownerKeyStore.getKey("ownerEncKey", password); Certificate[] ownerEncCert = ownerKeyStore.getCertificateChain("ownerEncKey"); PrivateKey ownerSignKey = (PrivateKey) ownerKeyStore.getKey("ownerSignKey", password); Certificate[] ownerSignCert = ownerKeyStore.getCertificateChain("ownerSignKey"); in.close(); removeInputFile(inputFile); return new PanboxFilePairingLoadReturnContainer(eMail, firstName, lastName, password, devicename, devPKey, devCert[0], ownerSignKey, ownerSignCert[0], ownerEncKey, ownerEncCert[0], devices, contacts); } catch (Exception e) { // SLAVE try { buf = new ByteArrayInputStream(tmp.toByteArray()); ownerKeyStore = KeyStore.getInstance("BKS"); ownerKeyStore.load(buf, password); Certificate ownerEncCert = ownerKeyStore.getCertificate("ownerEncCert"); Certificate ownerSignCert = ownerKeyStore.getCertificate("ownerSignCert"); in.close(); removeInputFile(inputFile); return new PanboxFilePairingLoadReturnContainer(eMail, firstName, lastName, password, devicename, devPKey, devCert[0], null, ownerSignCert, null, ownerEncCert, devices, contacts); } catch (Exception ex) { logger.error( "PanboxClient : loadPairingFile : Could not determine if pairing file was master or slave."); throw new IllegalArgumentException("Pairing type was unknown. Broken file?"); } } } catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException | UnrecoverableKeyException | IllegalArgumentException e) { in.close(); throw e; } }
From source file:com.yodlee.sampleapps.helper.OpenSamlHelper.java
/** * Initilize the Keystore.//www . j av a2 s . c o m */ private static void initKeyStore() { InputStream fileInput = null; try { fileInput = new FileInputStream(keystoreFilename); } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } KeyStore keystore = null; try { keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(fileInput, keystorePassword.toCharArray()); privateKey = (PrivateKey) keystore.getKey(keystoreAlias, keystorePassword.toCharArray()); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } if (privateKey == null) throw new RuntimeException(keystoreAlias + " key not found in keystore " + keystoreFilename); X509Certificate cert = null; Certificate[] certificates = new Certificate[0]; try { cert = (X509Certificate) keystore.getCertificate(keystoreAlias); certificates = keystore.getCertificateChain(keystoreAlias); } catch (KeyStoreException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } if (cert == null) throw new RuntimeException(keystoreAlias + " cert not found in keystore " + keystoreFilename); if (certificates == null) throw new RuntimeException(keystoreAlias + " cert chain not found in keystore " + keystoreFilename); certs = new X509Certificate[certificates.length]; System.arraycopy(certificates, 0, certs, 0, certs.length); }
From source file:org.wso2.carbon.identity.saml.inbound.util.SAMLSSOUtil.java
/** * Get the X509CredentialImpl object for a particular tenant * * @param tenantDomain/*from w w w. j a v a2s.c o m*/ * @param alias * @return X509CredentialImpl object containing the public certificate of * that tenant * @throws IdentitySAML2SSOException Error when creating X509CredentialImpl object */ public static X509CredentialImpl getX509CredentialImplForTenant(String tenantDomain, String alias) throws IdentitySAML2SSOException { KeyStoreManager keyStoreManager; // get an instance of the corresponding Key Store Manager instance try { keyStoreManager = KeyStoreManager.getInstance(); X509CredentialImpl credentialImpl = null; KeyStore keyStore; keyStore = keyStoreManager.getKeyStore(); java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) keyStore .getCertificate(alias); credentialImpl = new X509CredentialImpl(cert); return credentialImpl; } catch (Exception e) { throw new IdentitySAML2SSOException("Error while initializing keystore"); } }