List of usage examples for java.security KeyStore aliases
public final Enumeration<String> aliases() throws KeyStoreException
From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java
@Test public void testSignPerformance() throws Exception { LOG.debug("sign"); // operate//from w ww . ja v a2 s. c o m Security.addProvider(new HSMProxyProvider()); KeyStore keyStore = KeyStore.getInstance("HSMProxy"); HSMProxyTestCredential testCredential = new HSMProxyTestCredential(); HSMProxyKeyStoreParameter keyStoreParameter = new HSMProxyKeyStoreParameter( testCredential.getCredentialPrivateKey(), testCredential.getCredentialCertificate(), "http://localhost:8080/hsm-proxy-ws/dss", new MyHSMProxyAudit()); keyStore.load(keyStoreParameter); String alias = keyStore.aliases().nextElement(); PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, null); assertNotNull(privateKey); X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias); final int TEST_COUNT = 40; int count = TEST_COUNT; long t0 = System.currentTimeMillis(); while (count > 0) { signAndVerify(certificate, privateKey, "SHA1withRSA"); count--; } long t1 = System.currentTimeMillis(); LOG.debug("dt: " + (t1 - t0) / TEST_COUNT); }
From source file:org.wso2.carbon.dataservices.core.auth.JWTAuthorizationProvider.java
/** * Get the alias for the X509 certificate thumb * @param thumb/* w ww . j a va2 s. co m*/ * @param keyStore * @return * @throws org.apache.axis2.AxisFault */ private String getAliasForX509CertThumb(byte[] thumb, KeyStore keyStore) throws AxisFault { Certificate cert = null; MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e1) { log.error("noSHA1availabe"); throw new AxisFault("noSHA1availabe"); } try { for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) { String alias = (String) e.nextElement(); Certificate[] certs = keyStore.getCertificateChain(alias); if (certs == null || certs.length == 0) { // no cert chain, so lets check if getCertificate gives us a result. cert = keyStore.getCertificate(alias); if (cert == null) { return null; } } else { cert = certs[0]; } if (!(cert instanceof X509Certificate)) { continue; } sha.reset(); try { sha.update(cert.getEncoded()); } catch (CertificateEncodingException e1) { log.error("Error encoding certificate"); throw new AxisFault("Error encoding certificate"); } byte[] data = sha.digest(); if (new String(thumb).equals(hexify(data))) { return alias; } } } catch (KeyStoreException e) { log.error("KeyStore exception while getting alias for X509CertThumb"); throw new AxisFault("KeyStore exception while getting alias for X509CertThumb"); } return null; }
From source file:test.integ.be.e_contract.mycarenet.ehbox.EHealthBoxPublicationClientTest.java
@Test public void testPublishAnnex() throws Exception { // STS//from w w w .j a v a 2s .c o m EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService"); Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null); PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12"); FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path()); eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray()); Enumeration<String> aliasesEnum = eHealthKeyStore.aliases(); String alias = aliasesEnum.nextElement(); X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias); PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias, this.config.getEHealthPKCS12Password().toCharArray()); List<Attribute> attributes = new LinkedList<Attribute>(); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>(); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributeDesignators .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth", "urn:be:fgov:person:ssin:nurse:boolean")); Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate, eHealthPrivateKey, attributes, attributeDesignators); assertNotNull(assertion); String assertionString = client.toString(assertion); // eHealthBox publication EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient( "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3"); ObjectFactory objectFactory = new ObjectFactory(); PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType(); String publicationId = UUID.randomUUID().toString().substring(1, 13); LOG.debug("publication id: " + publicationId); publicationMessage.setPublicationId(publicationId); DestinationContextType destinationContext = objectFactory.createDestinationContextType(); publicationMessage.getDestinationContext().add(destinationContext); destinationContext.setQuality("NURSE"); destinationContext.setType("INSS"); destinationContext.setId(getUserIdentifier(authnCertificate)); ContentContextType contentContext = objectFactory.createContentContextType(); publicationMessage.setContentContext(contentContext); PublicationContentType publicationContent = objectFactory.createPublicationContentType(); contentContext.setContent(publicationContent); PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType(); publicationContent.setDocument(publicationDocument); publicationDocument.setTitle("test"); publicationDocument.setMimeType("text/plain"); publicationDocument.setDownloadFileName("test.txt"); byte[] message = "hello world".getBytes(); publicationDocument.setEncryptableTextContent(message); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte[] digest = messageDigest.digest(message); publicationDocument.setDigest(Base64.encodeBase64String(digest)); List<PublicationAnnexType> publicationAnnexList = publicationContent.getAnnex(); PublicationAnnexType publicationAnnex = objectFactory.createPublicationAnnexType(); publicationAnnexList.add(publicationAnnex); publicationAnnex.setDownloadFileName("test.txt"); publicationAnnex.setEncryptableTitle("hello world".getBytes()); publicationAnnex.setMimeType("application/octet-stream"); publicationAnnex.setEncryptableTextContent(message); messageDigest.reset(); digest = messageDigest.digest(message); publicationAnnex.setDigest(Base64.encodeBase64String(digest)); ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType(); contentContext.setContentSpecification(contentSpecification); contentSpecification.setContentType("DOCUMENT"); publicationClient.setCredentials(eHealthPrivateKey, assertionString); publicationClient.publish(publicationMessage); }
From source file:org.cesecore.keys.util.KeyTools.java
/** * Convert a KeyStore to PEM format.// w w w. j a v a2 s . co m */ public static byte[] getSinglePemFromKeyStore(final KeyStore ks, final char[] password) throws KeyStoreException, CertificateEncodingException, IOException, UnrecoverableKeyException, NoSuchAlgorithmException { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); // Find the key private key entry in the keystore final Enumeration<String> e = ks.aliases(); Object o = null; String alias = ""; PrivateKey serverPrivKey = null; while (e.hasMoreElements()) { o = e.nextElement(); if (o instanceof String) { if ((ks.isKeyEntry((String) o)) && ((serverPrivKey = (PrivateKey) ks.getKey((String) o, password)) != null)) { alias = (String) o; break; } } } byte[] privKeyEncoded = "".getBytes(); if (serverPrivKey != null) { privKeyEncoded = serverPrivKey.getEncoded(); } final Certificate[] chain = KeyTools.getCertChain(ks, (String) o); final X509Certificate userX509Certificate = (X509Certificate) chain[0]; final byte[] output = userX509Certificate.getEncoded(); String sn = CertTools.getSubjectDN(userX509Certificate); String subjectdnpem = sn.replace(',', '/'); String issuerdnpem = CertTools.getIssuerDN(userX509Certificate).replace(',', '/'); buffer.write(BAG_ATTRIBUTES); buffer.write(FRIENDLY_NAME); buffer.write(alias.getBytes()); buffer.write(NL); buffer.write(BEGIN_PRIVATE_KEY); buffer.write(NL); final byte[] privKey = Base64.encode(privKeyEncoded); buffer.write(privKey); buffer.write(NL); buffer.write(END_PRIVATE_KEY); buffer.write(NL); buffer.write(BAG_ATTRIBUTES); buffer.write(FRIENDLY_NAME); buffer.write(alias.getBytes()); buffer.write(NL); buffer.write(SUBJECT_ATTRIBUTE); buffer.write(subjectdnpem.getBytes()); buffer.write(NL); buffer.write(ISSUER_ATTRIBUTE); buffer.write(issuerdnpem.getBytes()); buffer.write(NL); buffer.write(BEGIN_CERTIFICATE); buffer.write(NL); final byte[] userCertB64 = Base64.encode(output); buffer.write(userCertB64); buffer.write(NL); buffer.write(END_CERTIFICATE); buffer.write(NL); if (!CertTools.isSelfSigned(userX509Certificate)) { for (int num = 1; num < chain.length; num++) { final X509Certificate tmpX509Cert = (X509Certificate) chain[num]; sn = CertTools.getSubjectDN(tmpX509Cert); String cn = CertTools.getPartFromDN(sn, "CN"); if (StringUtils.isEmpty(cn)) { cn = "Unknown"; } subjectdnpem = sn.replace(',', '/'); issuerdnpem = CertTools.getIssuerDN(tmpX509Cert).replace(',', '/'); buffer.write(BAG_ATTRIBUTES); buffer.write(FRIENDLY_NAME); buffer.write(cn.getBytes()); buffer.write(NL); buffer.write(SUBJECT_ATTRIBUTE); buffer.write(subjectdnpem.getBytes()); buffer.write(NL); buffer.write(ISSUER_ATTRIBUTE); buffer.write(issuerdnpem.getBytes()); buffer.write(NL); final byte[] tmpOutput = tmpX509Cert.getEncoded(); buffer.write(BEGIN_CERTIFICATE); buffer.write(NL); final byte[] tmpCACertB64 = Base64.encode(tmpOutput); buffer.write(tmpCACertB64); buffer.write(NL); buffer.write(END_CERTIFICATE); buffer.write(NL); } } return buffer.toByteArray(); }
From source file:org.apache.hadoop.yarn.server.resourcemanager.security.MockX509SecurityHandler.java
private void verifyContentOfAppTrustStore(byte[] appTrustStore, char[] password, String appUser, ApplicationId appId) throws GeneralSecurityException, IOException { File trustStoreFile = Paths.get(systemTMP, appUser + "-" + appId.toString() + "_tstore.jks").toFile(); boolean certificateMissing = false; try {/*ww w .j a va2s .c o m*/ KeyStore systemTrustStore = loadSystemTrustStore(getConfig()); FileUtils.writeByteArrayToFile(trustStoreFile, appTrustStore, false); KeyStore ts = KeyStore.getInstance("JKS"); try (FileInputStream fis = new FileInputStream(trustStoreFile)) { ts.load(fis, password); } Enumeration<String> sysAliases = systemTrustStore.aliases(); while (sysAliases.hasMoreElements()) { String alias = sysAliases.nextElement(); X509Certificate appCert = (X509Certificate) ts.getCertificate(alias); if (appCert == null) { certificateMissing = true; break; } X509Certificate sysCert = (X509Certificate) systemTrustStore.getCertificate(alias); if (!Arrays.equals(sysCert.getSignature(), appCert.getSignature())) { certificateMissing = true; break; } } } finally { FileUtils.deleteQuietly(trustStoreFile); assertFalse(certificateMissing); } }
From source file:org.mule.api.security.tls.TlsConfiguration.java
protected void checkKeyStoreContainsAlias(KeyStore keyStore) throws KeyStoreException { if (StringUtils.isNotBlank(keyAlias)) { boolean keyAliasFound = false; Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (alias.equals(keyAlias)) { // if alias is found all is valid but continue processing to strip out all // other (unwanted) keys keyAliasFound = true;/*from w ww . j a v a2 s . c o m*/ } else { // if the current alias is not the one we are looking for, remove // it from the keystore keyStore.deleteEntry(alias); } } // if the alias was not found, throw an exception if (!keyAliasFound) { throw new IllegalStateException("Key with alias \"" + keyAlias + "\" was not found"); } } }
From source file:org.yawlfoundation.yawl.digitalSignature.DigitalSignature.java
private PrivateKey getPrivateKey() { KeyStore keystore = null; try {/*www. j a v a2s . c o m*/ char[] password = _Password.toCharArray(); String _alias = ""; _Password = null; keystore = KeyStore.getInstance("PKCS12"); keystore.load(new FileInputStream(_Pathway + _P12), password); Enumeration enumeration = keystore.aliases(); Vector vectaliases = new Vector(); while (enumeration.hasMoreElements()) vectaliases.add(enumeration.nextElement()); String[] aliases = (String[]) (vectaliases.toArray(new String[0])); for (int i = 0; i < aliases.length; i++) if (keystore.isKeyEntry(aliases[i])) { _alias = aliases[i]; break; } PrivateKey pk = (PrivateKey) keystore.getKey(_alias, password); password = null; return pk; } catch (Exception e) { System.out.println("Error: " + "Invalid pkcs#12 Certificate"); return null; } }
From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java
private List<Map<String, Object>> getKeyStoreInfo(KeyStore store) { List<Map<String, Object>> storeEntries = new ArrayList<>(); try {/*from w w w .jav a 2 s. c o m*/ Enumeration<String> aliases = store.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); Map<String, Object> aliasMap = new HashMap<>(); Certificate certificate = store.getCertificate(alias); boolean isKey = store.isKeyEntry(alias); aliasMap.put("alias", alias); aliasMap.put("isKey", isKey); aliasMap.put("type", certificate.getType()); aliasMap.put("format", certificate.getPublicKey().getFormat()); aliasMap.put("algorithm", certificate.getPublicKey().getAlgorithm()); storeEntries.add(aliasMap); } } catch (KeyStoreException e) { LOGGER.error("Unable to read entries from keystore.", e); } return storeEntries; }
From source file:view.CertificateManagementDialog.java
private KeyStore isValidKeystore(File file, boolean showDialog) { FileInputStream is = null;//from ww w .j av a 2 s .c o m try { is = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(is, null); if (ks.aliases().hasMoreElements()) { return ks; } else { if (showDialog) { JOptionPane.showMessageDialog(this, Bundle.getBundle().getString("emptyChain"), "", JOptionPane.INFORMATION_MESSAGE); } return ks; } } catch (java.security.cert.CertificateException | NoSuchAlgorithmException | KeyStoreException | FileNotFoundException e) { if (showDialog) { JOptionPane.showMessageDialog(this, Bundle.getBundle().getString("fileNotKeystoreOrCorrupted"), "", JOptionPane.ERROR_MESSAGE); } return null; } catch (IOException e) { if (showDialog) { JOptionPane.showMessageDialog(this, Bundle.getBundle().getString("fileNotKeystoreOrCorrupted"), "", JOptionPane.ERROR_MESSAGE); } return null; } finally { if (null != is) { try { is.close(); } catch (IOException e) { } } } }
From source file:nl.nn.adapterframework.webcontrol.action.ShowSecurityItems.java
private void addCertificateInfo(XmlBuilder certElem, final URL url, final String password, String keyStoreType, String prefix) {//from ww w. j av a2 s . c o m try { 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(); XmlBuilder infoElem = new XmlBuilder("info"); infoElem.setCdataValue(prefix + " '" + alias + "':"); certElem.addSubElement(infoElem); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; infoElem = new XmlBuilder("info"); infoElem.setCdataValue(" Subject DN: " + cert.getSubjectDN()); certElem.addSubElement(infoElem); infoElem = new XmlBuilder("info"); infoElem.setCdataValue(" Signature Algorithm: " + cert.getSigAlgName()); certElem.addSubElement(infoElem); infoElem = new XmlBuilder("info"); infoElem.setCdataValue(" Valid from: " + cert.getNotBefore()); certElem.addSubElement(infoElem); infoElem = new XmlBuilder("info"); infoElem.setCdataValue(" Valid until: " + cert.getNotAfter()); certElem.addSubElement(infoElem); infoElem = new XmlBuilder("info"); infoElem.setCdataValue(" Issuer: " + cert.getIssuerDN()); certElem.addSubElement(infoElem); } } } } catch (Exception e) { XmlBuilder infoElem = new XmlBuilder("info"); infoElem.setCdataValue("*** ERROR ***"); certElem.addSubElement(infoElem); } }