List of usage examples for java.security KeyStore getCertificateChain
public final Certificate[] getCertificateChain(String alias) throws KeyStoreException
From source file:io.kodokojo.config.module.SecurityModule.java
@Provides @Singleton/* w ww . j av a 2 s.c o m*/ SSLKeyPair provideSSLKeyPair(SecurityConfig securityConfig) { if (securityConfig == null) { throw new IllegalArgumentException("securityConfig must be defined."); } if (StringUtils.isNotBlank(securityConfig.wildcardPemPath())) { File pemFile = new File(securityConfig.wildcardPemPath()); try { String content = IOUtils.toString(new FileReader(pemFile)); String contentPrivate = RSAUtils.extractPrivateKey(content); String contentPublic = RSAUtils.extractPublic(content); RSAPrivateKey rsaPrivateKey = RSAUtils.readRsaPrivateKey(new StringReader(contentPrivate)); X509Certificate certificate = RSAUtils.readRsaPublicKey(new StringReader(contentPublic)); RSAPublicKey rsaPublicKey = (RSAPublicKey) certificate.getPublicKey(); X509Certificate[] certificates = new X509Certificate[1]; certificates[0] = certificate; LOGGER.info( "Using Wildcard SSL certificat {} from path {}to provide Certificat to all instances of Kodo Kojo. ", certificate.getSubjectDN().toString(), securityConfig.wildcardPemPath()); return new SSLKeyPair(rsaPrivateKey, rsaPublicKey, certificates); } catch (IOException e) { throw new IllegalArgumentException("Unable to read pem file " + pemFile.getAbsolutePath() + ".", e); } } else { try { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")), System.getProperty("javax.net.ssl.keyStorePassword", "").toCharArray()); RSAPrivateCrtKey key = (RSAPrivateCrtKey) ks.getKey(securityConfig.sslRootCaKsAlias(), securityConfig.sslRootCaKsPassword().toCharArray()); if (key == null) { return null; } RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec); Certificate[] certificateChain = ks.getCertificateChain(securityConfig.sslRootCaKsAlias()); List<X509Certificate> x509Certificates = Arrays.asList(certificateChain).stream() .map(c -> (X509Certificate) c).collect(Collectors.toList()); LOGGER.info( "Using a CA SSL certificat {} from keystore to provide Certificat to all instances of Kodo Kojo. ", securityConfig.sslRootCaKsAlias(), System.getProperty("javax.net.ssl.keyStore")); return new SSLKeyPair(key, publicKey, x509Certificates.toArray(new X509Certificate[x509Certificates.size()])); } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | InvalidKeySpecException | CertificateException | IOException e) { throw new RuntimeException("Unable to open default Keystore", e); } } }
From source file:psiprobe.controllers.certificates.ListCertificatesController.java
/** * Gets the certificates./*from w w w . j a v a 2s . co m*/ * * @param storeType the store type * @param storeFile the store file * @param storePassword the store password * @return the certificates * @throws Exception the exception */ public List<Cert> getCertificates(String storeType, String storeFile, String storePassword) throws Exception { KeyStore keyStore; // Get key store if (storeType != null) { keyStore = KeyStore.getInstance(storeType); } else { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); } // Get password char[] password = null; if (storePassword != null) { password = storePassword.toCharArray(); } // Load key store from file try (InputStream storeInput = getStoreInputStream(storeFile)) { keyStore.load(storeInput, password); } catch (IOException e) { logger.error("Error loading store file {}", storeFile, e); return null; } List<Cert> certs = new ArrayList<>(); for (String alias : Collections.list(keyStore.aliases())) { Certificate[] certificateChains = keyStore.getCertificateChain(alias); if (certificateChains != null) { for (Certificate certificateChain : certificateChains) { X509Certificate x509Cert = (X509Certificate) certificateChain; addToStore(certs, alias, x509Cert); } } else { X509Certificate x509Cert = (X509Certificate) keyStore.getCertificate(alias); addToStore(certs, alias, x509Cert); } } return certs; }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSignerTest.java
/** * teste passando apenas o hash do arquivo */// w w w . ja v a 2 s . c o m //@Test public void testSignWithHash() { try { System.out.println("******** TESTANDO COM HASH *****************"); // INFORMAR o arquivo para gerar o hash String fileDirName = "/home/teste.txt"; byte[] fileToSign = readContent(fileDirName); // Para certificado em arquivo A1 preciso essa senha para PrivateKey // para token troque a senha em: getKeyStoreToken() char[] senha = "senha".toCharArray(); // Para certificado em arquivo A1 // KeyStore ks = getKeyStoreFile(); // Para certificados no so windows (mascapi) // KeyStore ks = getKeyStoreOnWindows(); // Para certificado em token KeyStore ks = getKeyStoreToken(); // Para certificado NeoID e windows token //KeyStore ks = getKeyStoreTokenBySigner(); String alias = getAlias(ks); /* Parametrizando o objeto doSign */ PKCS7Signer signer = PKCS7Factory.getInstance().factoryDefault(); signer.setCertificates(ks.getCertificateChain(alias)); // gera o hash do arquivo java.security.MessageDigest md = java.security.MessageDigest .getInstance(DigestAlgorithmEnum.SHA_512.getAlgorithm()); // devido a uma restrio do token branco, no windws s funciona com 256 if (org.demoiselle.signer.core.keystore.loader.configuration.Configuration.getInstance().getSO() .toLowerCase().indexOf("indows") > 0) { md = java.security.MessageDigest.getInstance(DigestAlgorithmEnum.SHA_256.getAlgorithm()); } byte[] hash = md.digest(fileToSign); String contentEncoded = Base64.encodeBase64String(fileToSign); System.out.println("contentEncoded : " + contentEncoded); String hashEncoded = new String(Base64.encodeBase64(hash)); System.out.println("hashEncoded: " + hashEncoded); // seta o algoritmo de acordo com o que foi gerado o Hash signer.setAlgorithm(SignerAlgorithmEnum.SHA512withRSA); if (org.demoiselle.signer.core.keystore.loader.configuration.Configuration.getInstance().getSO() .toLowerCase().indexOf("indows") > 0) { signer.setAlgorithm(SignerAlgorithmEnum.SHA256withRSA); } // Para certificado em arquivo A1 // signer.setPrivateKey((PrivateKey) ks.getKey(alias,senha)); // Para certificado em token signer.setPrivateKey((PrivateKey) ks.getKey(alias, null)); // Sem carimbo de tempo signer.setSignaturePolicy(PolicyFactory.Policies.AD_RB_CADES_2_3); // com carimbo de tempo // signer.setSignaturePolicy(PolicyFactory.Policies.AD_RT_CADES_2_3); /* Realiza a assinatura do conteudo */ System.out.println("Efetuando a assinatura do hash"); byte[] signature = signer.doHashSign(hash); String signatureEncoded = new String(Base64.encodeBase64(signature)); System.out.println("signatureEncoded :" + signatureEncoded); File file = new File(fileDirName + ".p7s"); FileOutputStream os = new FileOutputStream(file); os.write(signature); os.flush(); os.close(); assertTrue(true); } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | IOException ex) { ex.printStackTrace(); assertTrue(false); } }
From source file:org.kse.gui.actions.ImportCaReplyFromFileAction.java
/** * Do action./*from www .j a v a 2 s.c o m*/ */ @Override protected void doAction() { try { KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory(); KeyStoreState currentState = history.getCurrentState(); String alias = kseFrame.getSelectedEntryAlias(); Password password = getEntryPassword(alias, currentState); if (password == null) { return; } KeyStoreState newState = currentState.createBasisForNextState(this); KeyStore keyStore = newState.getKeyStore(); KeyStoreType keyStoreType = KeyStoreType.resolveJce(keyStore.getType()); Key privateKey = keyStore.getKey(alias, password.toCharArray()); File caReplyFile = chooseCaFile(); if (caReplyFile == null) { return; } X509Certificate[] certs = openCaReply(caReplyFile); if ((certs == null) || (certs.length == 0)) { return; } certs = X509CertUtil.orderX509CertChain(certs); X509Certificate[] exitingEntryCerts = X509CertUtil .orderX509CertChain(X509CertUtil.convertCertificates(keyStore.getCertificateChain(alias))); if (!exitingEntryCerts[0].getPublicKey().equals(certs[0].getPublicKey())) { JOptionPane.showMessageDialog(frame, res.getString("ImportCaReplyFromFileAction.NoMatchPubKeyCaReply.message"), res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"), JOptionPane.WARNING_MESSAGE); return; } // Holds the new certificate chain for the entry should the import succeed X509Certificate[] newCertChain = null; if (!applicationSettings.getEnableImportCaReplyTrustCheck()) { newCertChain = certs; } else { KeyStore caCertificates = getCaCertificates(); KeyStore windowsTrustedRootCertificates = getWindowsTrustedRootCertificates(); // PKCS #7 reply - try and match the self-signed root with any // of the certificates in the CA Certificates or current KeyStore if (certs.length > 1) { X509Certificate rootCert = certs[certs.length - 1]; String matchAlias = null; if (caCertificates != null) // Match against CA Certificates KeyStore { matchAlias = X509CertUtil.matchCertificate(caCertificates, rootCert); } // Match against Windows Trusted Root Certificates KeyStore if ((windowsTrustedRootCertificates != null) && (matchAlias == null)) { matchAlias = X509CertUtil.matchCertificate(windowsTrustedRootCertificates, rootCert); } if (matchAlias == null) // Match against current KeyStore { matchAlias = X509CertUtil.matchCertificate(keyStore, rootCert); } if (matchAlias == null) { // No match for the root certificate - display the certificate to the user for confirmation JOptionPane.showMessageDialog(frame, res.getString("ImportCaReplyFromFileAction.NoMatchRootCertCaReplyConfirm.message"), res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"), JOptionPane.INFORMATION_MESSAGE); DViewCertificate dViewCertificate = new DViewCertificate(frame, MessageFormat.format( res.getString("ImportCaReplyFromFileAction.CertDetailsFile.Title"), caReplyFile.getName()), new X509Certificate[] { rootCert }, null, DViewCertificate.NONE); dViewCertificate.setLocationRelativeTo(frame); dViewCertificate.setVisible(true); int selected = JOptionPane.showConfirmDialog(frame, res.getString("ImportCaReplyFromFileAction.AcceptCaReply.message"), res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"), JOptionPane.YES_NO_OPTION); if (selected != JOptionPane.YES_OPTION) { return; } newCertChain = certs; } else { newCertChain = certs; } } // Single X.509 certificate reply - try and establish a chain of // trust from the certificate and ending with a root CA self-signed certificate else { // Establish trust against current KeyStore ArrayList<KeyStore> compKeyStores = new ArrayList<>(); compKeyStores.add(keyStore); if (caCertificates != null) { // Establish trust against CA Certificates KeyStore compKeyStores.add(caCertificates); } if (windowsTrustedRootCertificates != null) { // Establish trust against Windows Trusted Root Certificates KeyStore compKeyStores.add(windowsTrustedRootCertificates); } X509Certificate[] trustChain = X509CertUtil.establishTrust(certs[0], compKeyStores.toArray(new KeyStore[compKeyStores.size()])); if (trustChain != null) { newCertChain = trustChain; } else { // Cannot establish trust for the certificate - fail JOptionPane.showMessageDialog(frame, res.getString("ImportCaReplyFromFileAction.NoTrustCaReply.message"), res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"), JOptionPane.WARNING_MESSAGE); return; } } } if (keyStoreType.isFileBased()) { // TODO: why or when is delete actually necessary??? keyStore.deleteEntry(alias); keyStore.setKeyEntry(alias, privateKey, password.toCharArray(), newCertChain); } else { keyStore.setKeyEntry(alias, privateKey, password.toCharArray(), newCertChain); } currentState.append(newState); kseFrame.updateControls(true); JOptionPane.showMessageDialog(frame, res.getString("ImportCaReplyFromFileAction.ImportCaReplySuccessful.message"), res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"), JOptionPane.INFORMATION_MESSAGE); } catch (Exception ex) { DError.displayError(frame, ex); } }
From source file:com.adito.boot.KeyStoreManager.java
boolean doIsCertificateTrused(String alias, KeyStore keyStore) throws Exception { Certificate[] certs = keyStore.getCertificateChain(alias); // try { // ((CustomSSLSocketFactory)CustomSSLSocketFactory.getDefault()).checkServerTrusted((X509Certificate[])certs, ""); // return true; // } catch(CertificateException ex) { if (certs == null) { if (log.isInfoEnabled()) log.info("No certs for " + alias + ", untrusted."); } else if (certs.length > 1) { X509Certificate x509cert = (X509Certificate) certs[certs.length - 1]; TrustedCACertStore store = new TrustedCACertStore(); ByteArrayInputStream bin = new ByteArrayInputStream(x509cert.getEncoded()); DERInputStream der = null;/* ww w .j a v a2s . c o m*/ try { der = new DERInputStream(bin); ASN1Sequence certificate = (ASN1Sequence) der.readObject(); com.maverick.crypto.asn1.x509.X509Certificate x509 = new com.maverick.crypto.asn1.x509.X509Certificate( X509CertificateStructure.getInstance(certificate)); return store.isTrustedCertificate(x509, false, false); } finally { Util.closeStream(der); } } // } return false; }
From source file:org.apache.ws.security.components.crypto.CryptoBase.java
/** * The subjectRDN argument is either an X500Principal or a BouncyCastle X509Name instance. *///from w w w. jav a 2s. c o m private Vector getAlias(Object subjectRDN, KeyStore store) throws WSSecurityException { // Store the aliases found Vector aliases = new Vector(); Certificate cert = null; try { for (Enumeration e = store.aliases(); e.hasMoreElements();) { String alias = (String) e.nextElement(); Certificate[] certs = store.getCertificateChain(alias); if (certs == null || certs.length == 0) { // no cert chain, so lets check if getCertificate gives us a result. cert = store.getCertificate(alias); if (cert == null) { continue; } certs = new Certificate[] { cert }; } else { cert = certs[0]; } if (cert instanceof X509Certificate) { X500Principal foundRDN = ((X509Certificate) cert).getSubjectX500Principal(); Object certName = createBCX509Name(foundRDN.getName()); if (subjectRDN.equals(certName)) { aliases.add(alias); } } } } catch (KeyStoreException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e); } return aliases; }
From source file:org.wso2.identity.integration.test.oauth2.OAuth2IDTokenEncryptionTestCase.java
/** * Initiate service provider keys required for the tests. * * @throws Exception// w w w . jav a2s . com */ private void initServiceProviderKeys() throws Exception { KeyStore keyStore = KeyStore.getInstance("JKS"); String jksPath = TestConfigurationProvider.getResourceLocation("IS") + File.separator + "sp" + File.separator + "keystores" + File.separator + "sp1KeyStore.jks"; String jksPassword = "wso2carbon"; keyStore.load(new FileInputStream(jksPath), jksPassword.toCharArray()); String alias = "wso2carbon"; KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(jksPassword.toCharArray())); spPrivateKey = (RSAPrivateKey) pkEntry.getPrivateKey(); // Load certificate chain Certificate[] chain = keyStore.getCertificateChain(alias); spX509PublicCert = (X509Certificate) chain[0]; }
From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java
@Test public void testGetCertificateAuthnCertCredential() throws Exception { LOG.debug("sign"); // operate//w w w. j a v a 2s . c om Security.addProvider(new BeIDProvider()); KeyStore beidKeyStore = KeyStore.getInstance("BeID"); beidKeyStore.load(null); X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication"); PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null); Security.addProvider(new HSMProxyProvider()); KeyStore hsmProxyKeyStore = KeyStore.getInstance("HSMProxy"); HSMProxyKeyStoreParameter keyStoreParameter = new HSMProxyKeyStoreParameter(authnPrivateKey, authnCert, // "https://www.e-contract.be/hsm-proxy-ws/dss", "http://localhost/hsm-proxy-ws/dss", new MyHSMProxyAudit()); hsmProxyKeyStore.load(keyStoreParameter); Enumeration<String> aliasesEnum = hsmProxyKeyStore.aliases(); assertNotNull(aliasesEnum); while (aliasesEnum.hasMoreElements()) { String alias = aliasesEnum.nextElement(); LOG.debug("alias: " + alias); X509Certificate certificate = (X509Certificate) hsmProxyKeyStore.getCertificate(alias); assertNotNull(certificate); LOG.debug("certificate: " + certificate); assertTrue(hsmProxyKeyStore.containsAlias(alias)); Certificate[] certificateChain = hsmProxyKeyStore.getCertificateChain(alias); assertNotNull(certificateChain); PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) hsmProxyKeyStore.getEntry(alias, null); assertNotNull(privateKeyEntry); } }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSignerTest.java
/** * Teste de coassinatura anexada//from w ww .java2 s . com */ //@Test public void testSignCoAtached() { try { System.out.println("******** TESTANDO COM CONTEDO *****************"); // INFORMAR o arquivo String fileDirName = ""; String fileSignatureDirName = ""; byte[] fileToSign = readContent(fileDirName); byte[] signatureFile = readContent(fileSignatureDirName); // quando certificado em arquivo, precisa informar a senha char[] senha = "senha".toCharArray(); // Para certificado em Neo Id e windows //KeyStore ks = getKeyStoreTokenBySigner(); // Para certificado em Token KeyStore ks = getKeyStoreToken(); // Para certificado em arquivo A1 // KeyStore ks = getKeyStoreFile(); // Para certificados no so windows (mascapi) // KeyStore ks = getKeyStoreOnWindows(); String alias = getAlias(ks); /* Parametrizando o objeto doSign */ PKCS7Signer signer = PKCS7Factory.getInstance().factoryDefault(); signer.setCertificates(ks.getCertificateChain(alias)); // para token signer.setPrivateKey((PrivateKey) ks.getKey(alias, null)); // para arquivo // signer.setPrivateKey((PrivateKey) ks.getKey(alias, senha)); // politica sem carimbo de tempo signer.setSignaturePolicy(PolicyFactory.Policies.AD_RB_CADES_2_3); // com carimbo de tempo //signer.setSignaturePolicy(PolicyFactory.Policies.AD_RT_CADES_2_3); // para mudar o algoritimo signer.setAlgorithm(SignerAlgorithmEnum.SHA512withRSA); if (org.demoiselle.signer.core.keystore.loader.configuration.Configuration.getInstance().getSO() .toLowerCase().indexOf("indows") > 0) { signer.setAlgorithm(SignerAlgorithmEnum.SHA256withRSA); } /* Realiza a assinatura do conteudo */ System.out.println("Efetuando a assinatura do conteudo"); // Assinatura desatachada byte[] signature = signer.doAttachedSign(fileToSign, signatureFile); File file = new File(fileDirName + "-co_atached.p7s"); FileOutputStream os = new FileOutputStream(file); os.write(signature); os.flush(); os.close(); System.out.println("------------------ ok --------------------------"); assertTrue(true); } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | IOException ex) { ex.printStackTrace(); assertTrue(false); } }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSignerTest.java
private String getAlias(KeyStore ks) { Certificate[] certificates = null; String alias = ""; Enumeration<String> e; try {/*from w w w.j av a 2 s. com*/ e = ks.aliases(); while (e.hasMoreElements()) { alias = e.nextElement(); System.out.println("alias..............: " + alias); System.out.println("iskeyEntry" + ks.isKeyEntry(alias)); System.out.println("containsAlias" + ks.containsAlias(alias)); certificates = ks.getCertificateChain(alias); } } catch (Exception ex) { ex.printStackTrace(); } return alias; }