List of usage examples for java.security KeyStore getCertificate
public final Certificate getCertificate(String alias) throws KeyStoreException
From source file:net.sf.keystore_explorer.crypto.keystore.KeyStoreUtil.java
/** * Is the keystore entry type supported (e.g. exclude Card Verifiable Certificates) * * @param alias//from w w w. j a v a 2 s .c om * Alias of keystore entry * @param keyStore * KeyStore that contains the key pair or certificate * @return True, if entry type is supported * @throws KeyStoreException * If there was a problem accessing the KeyStore. */ public static boolean isSupportedEntryType(String alias, KeyStore keyStore) throws KeyStoreException { Certificate certificate = keyStore.getCertificate(alias); return (certificate == null) || (certificate instanceof X509Certificate); }
From source file:com.microsoft.aad.adal4j.MSCAPIAsymmetricKeyCredential.java
/** * Static method to create KeyCredential instance. * /*from ww w .j a v a 2 s .co m*/ * @param clientId * Identifier of the client requesting the token. * @param pkcs12Certificate * PKCS12 certificate stream containing public and private key. * Caller is responsible to handling the inputstream. * @param password * certificate password * @return KeyCredential instance * @throws KeyStoreException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws FileNotFoundException * @throws IOException * @throws UnrecoverableKeyException */ public static MSCAPIAsymmetricKeyCredential create(final String clientId, final InputStream pkcs12Certificate, final String password) throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException { final KeyStore keystore = KeyStore.getInstance("PKCS12", "SunJSSE"); keystore.load(pkcs12Certificate, password.toCharArray()); final Enumeration<String> aliases = keystore.aliases(); final String alias = aliases.nextElement(); final PrivateKey key = (PrivateKey) keystore.getKey(alias, password.toCharArray()); final X509Certificate publicCertificate = (X509Certificate) keystore.getCertificate(alias); return create(clientId, key, publicCertificate); }
From source file:it.cnr.icar.eric.client.xml.registry.util.CertificateUtil.java
@SuppressWarnings("static-access") private static Certificate[] getCertificateSignedByRegistry(LifeCycleManager lcm, X509Certificate inCert) throws JAXRException { Certificate[] certChain = new Certificate[2]; try {/*from www . ja v a2s.c o m*/ // Save cert in a temporary keystore file which is sent as // repository item to server so it can be signed KeyStore tmpKeystore = KeyStore.getInstance("JKS"); tmpKeystore.load(null, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray()); tmpKeystore.setCertificateEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ, inCert); File repositoryItemFile = File.createTempFile(".eric-ca-req", ".jks"); repositoryItemFile.deleteOnExit(); FileOutputStream fos = new java.io.FileOutputStream(repositoryItemFile); tmpKeystore.store(fos, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray()); fos.flush(); fos.close(); // Now have server sign the cert using extensionRequest javax.activation.DataHandler repositoryItem = new DataHandler(new FileDataSource(repositoryItemFile)); String id = it.cnr.icar.eric.common.Utility.getInstance().createId(); HashMap<String, Object> idToRepositoryItemsMap = new HashMap<String, Object>(); idToRepositoryItemsMap.put(id, repositoryItem); HashMap<String, String> slotsMap = new HashMap<String, String>(); slotsMap.put(BindingUtility.FREEBXML_REGISTRY_PROTOCOL_SIGNCERT, "true"); RegistryRequestType req = bu.rsFac.createRegistryRequestType(); bu.addSlotsToRequest(req, slotsMap); RegistryResponseHolder respHolder = ((LifeCycleManagerImpl) lcm).extensionRequest(req, idToRepositoryItemsMap); DataHandler responseRepositoryItem = (DataHandler) respHolder.getAttachmentsMap().get(id); InputStream is = responseRepositoryItem.getInputStream(); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(is, bu.FREEBXML_REGISTRY_KS_PASS_RESP.toCharArray()); is.close(); certChain[0] = keyStore.getCertificate(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_RESP); if (certChain[0] == null) { throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CannotFindUserCert")); } certChain[1] = keyStore.getCertificate(bu.FREEBXML_REGISTRY_CACERT_ALIAS); if (certChain[1] == null) { throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CannotFindCARootCert")); } } catch (Exception e) { throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CertSignFailed"), e); } return certChain; }
From source file:net.firejack.platform.web.security.x509.KeyUtils.java
public static X500Name getInfo(File keystore) { try {//from w w w. j a v a2s . c o m KeyStore ks = KeyStore.getInstance("JKS", "SUN"); FileInputStream stream = new FileInputStream(keystore); ks.load(stream, SECRET); IOUtils.closeQuietly(stream); X509CertImpl x509Cert = (X509CertImpl) ks.getCertificate(ALIAS); return (X500Name) x509Cert.getSubjectDN(); } catch (Exception e) { return null; } }
From source file:org.socraticgrid.workbench.security.wso2.Saml2Util.java
/** * This method validates the signature of the SAML Response. * @param resp SAML Response// www. j a va 2 s. c o m * @return true, if signature is valid. */ public static boolean validateSignature(Response resp) { boolean isSigValid = false; try { KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(new File(getProperty(SSOConstants.KEY_STORE_NAME))), getProperty(SSOConstants.KEY_STORE_PASSWORD).toCharArray()); java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) keyStore .getCertificate(getProperty(SSOConstants.IDP_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:it.cnr.icar.eric.client.xml.registry.util.CertificateUtil.java
/** * Generate a self signed certificate and store it in the keystore. * // w w w . ja va 2 s .c om * @param userRegInfo * @throws JAXRException */ public static void generateRegistryIssuedCertificate(UserRegistrationInfo userRegInfo) throws JAXRException { User user = userRegInfo.getUser(); LifeCycleManager lcm = user.getLifeCycleManager(); String dname = getDNameFromUser(userRegInfo); File keystoreFile = KeystoreUtil.getKeystoreFile(); KeystoreUtil.createKeystoreDirectory(keystoreFile); String keystoreType = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.storetype", "JKS"); String storePassStr = new String(userRegInfo.getStorePassword()); String keyPassStr = new String(userRegInfo.getKeyPassword()); String alias = userRegInfo.getAlias(); String keyAlg = "RSA"; // XWSS does not support DSA which is default is // KeyTool. Hmm. Weird. String[] args = { "-genkey", "-keyAlg", keyAlg, "-alias", alias, "-keypass", keyPassStr, "-keystore", keystoreFile.getAbsolutePath(), "-storepass", storePassStr, "-storetype", keystoreType, "-dname", dname }; try { KeyTool keytool = new KeyTool(); keytool.run(args, System.out); // Now load the KeyStore and get the cert FileInputStream fis = new FileInputStream(keystoreFile); KeyStore keyStore = KeyStore.getInstance(keystoreType); keyStore.load(fis, storePassStr.toCharArray()); fis.close(); X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); Certificate[] certChain = getCertificateSignedByRegistry(lcm, cert); Key key = keyStore.getKey(alias, userRegInfo.getKeyPassword()); // Now overwrite original cert with signed cert keyStore.deleteEntry(alias); // keyStore.setCertificateEntry(alias, cert); keyStore.setKeyEntry(alias, key, userRegInfo.getKeyPassword(), certChain); FileOutputStream fos = new java.io.FileOutputStream(keystoreFile); keyStore.store(fos, storePassStr.toCharArray()); fos.flush(); fos.close(); } catch (Exception e) { throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CertGenFailed"), e); } log.debug(JAXRResourceBundle.getInstance().getString("message.StoredUserInKeyStore", new Object[] { alias, keystoreFile.getAbsolutePath() })); try { // Export registry issued cert to certFile so it can be available // for import into a web browser for SSL access to registry exportRegistryIssuedCert(userRegInfo); } catch (Exception e) { String msg = JAXRResourceBundle.getInstance().getString( "message.UnableToExportCertificateSeeNextExceptionNoteThatThisFeatureRequiresUseOfJDK5"); log.warn(msg, e); // Do not throw exception as user reg can be done despite not // exporting the p12 file for the web browser. } }
From source file:mitm.common.security.crl.GenerateTestCRLs.java
private static void loadCA() throws Exception { KeyStore caKeyStore = securityFactory.createKeyStore("PKCS12"); File file = new File("test/resources/testdata/keys/testCA.p12"); FileInputStream input = new FileInputStream(file); caKeyStore.load(input, "test".toCharArray()); caCertificate = (X509Certificate) caKeyStore.getCertificate("ca"); caPrivateKey = (PrivateKey) caKeyStore.getKey("ca", null); rootCertificate = (X509Certificate) caKeyStore.getCertificate("root"); rootPrivateKey = (PrivateKey) caKeyStore.getKey("root", null); assertNotNull(caCertificate);/*from ww w . java 2 s . com*/ assertNotNull(caPrivateKey); }
From source file:com.dbay.apns4j.tools.ApnsTools.java
public final static SocketFactory createSocketFactory(InputStream keyStore, String password, String keystoreType, String algorithm, String protocol) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException, CertificateExpiredException { char[] pwdChars = password.toCharArray(); KeyStore ks = KeyStore.getInstance(keystoreType); ks.load(keyStore, pwdChars);//from ww w. ja va2s. c o m // ?? Enumeration<String> enums = ks.aliases(); String alias = ""; if (enums.hasMoreElements()) { alias = enums.nextElement(); } if (StringUtils.isNotEmpty(alias)) { X509Certificate certificate = (X509Certificate) ks.getCertificate(alias); if (null != certificate) { String type = certificate.getType(); int ver = certificate.getVersion(); String name = certificate.getSubjectDN().getName(); String serialNumber = certificate.getSerialNumber().toString(16); String issuerDN = certificate.getIssuerDN().getName(); String sigAlgName = certificate.getSigAlgName(); String publicAlgorithm = certificate.getPublicKey().getAlgorithm(); Date before = certificate.getNotBefore(); Date after = certificate.getNotAfter(); String beforeStr = DateFormatUtils.format(before, "yyyy-MM-dd HH:mm:ss"); String afterStr = DateFormatUtils.format(after, "yyyy-MM-dd HH:mm:ss"); // ?? long expire = DateUtil.getNumberOfDaysBetween(new Date(), after); if (expire <= 0) { if (LOG.isErrorEnabled()) { LOG.error( "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]", name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr, afterStr, Math.abs(expire)); } throw new CertificateExpiredException("??[" + Math.abs(expire) + "]"); } if (LOG.isInfoEnabled()) { LOG.info( "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]?", name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr, afterStr, expire); } } } KeyManagerFactory kf = KeyManagerFactory.getInstance(algorithm); kf.init(ks, pwdChars); TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init((KeyStore) null); SSLContext context = SSLContext.getInstance(protocol); context.init(kf.getKeyManagers(), tmf.getTrustManagers(), null); return context.getSocketFactory(); }
From source file:org.apache.accumulo.test.util.CertUtils.java
static Certificate findCert(KeyStore keyStore) throws KeyStoreException { Enumeration<String> aliases = keyStore.aliases(); Certificate cert = null;//from w w w . j av a2 s. co m while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keyStore.isCertificateEntry(alias)) { if (cert == null) { cert = keyStore.getCertificate(alias); } else { log.warn("Found multiple certificates in keystore. Ignoring " + alias); } } } if (cert == null) { throw new KeyStoreException("Could not find cert in keystore"); } return cert; }
From source file:net.sf.keystore_explorer.crypto.keystore.KeyStoreUtil.java
/** * Is the key pair entry identified by alias a EC key pair? * * @param alias/*from ww w . java 2 s . co m*/ * Alias of key pair entry * @param keyStore * KeyStore that contains the key pair * @return True, if alias is a EC key pair * @throws KeyStoreException * If there was a problem accessing the KeyStore. */ public static boolean isECKeyPair(String alias, KeyStore keyStore) throws KeyStoreException { if (!isKeyPairEntry(alias, keyStore)) { return false; } Certificate certificate = keyStore.getCertificate(alias); String algorithm = certificate.getPublicKey().getAlgorithm(); return algorithm.equals(EC.jce()); }