List of usage examples for java.security KeyStore getCertificate
public final Certificate getCertificate(String alias) throws KeyStoreException
From source file:ch.cyberduck.core.ssl.CertificateStoreX509KeyManager.java
public X509Certificate getCertificate(final String alias, final String[] keyTypes, final Principal[] issuers) { try {// ww w .j a v a2 s . c o m final KeyStore store; try { store = this.getKeystore(); } catch (IOException e) { return null; } final Certificate cert = store.getCertificate(alias); if (this.matches(cert, keyTypes, issuers)) { return (X509Certificate) cert; } for (Certificate c : store.getCertificateChain(alias)) { if (c instanceof X509Certificate) { if (this.matches(c, keyTypes, issuers)) { return (X509Certificate) cert; } } } } catch (KeyStoreException e) { log.error(String.format("Keystore not loaded %s", e.getMessage())); } if (log.isInfoEnabled()) { log.info(String.format("No matching certificate found for alias %s and issuers %s", alias, Arrays.toString(issuers))); } return null; }
From source file:it.cnr.icar.eric.server.security.authentication.CertificateAuthority.java
/** * Generate a registry issued certificate signed by private key of RegistryOperator. *//* w w w.j a va 2 s . co m*/ public X509Certificate generateRegistryIssuedCertificate(String dname) throws RegistryException { X509Certificate cert = null; File ksFile = null; try { String keystoreFileName = System.getProperty("java.io.tmpdir") + "/eric-temp-ks.jks"; String keystoreType = "JKS"; String alias = "ebxmlrr"; String storePassStr = "ebxmlrr"; String keyPassStr = "ebxmlrr"; 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", keystoreFileName, "-storepass", storePassStr, "-storetype", keystoreType, "-dname", dname }; KeyTool keytool = new KeyTool(); keytool.run(args, System.out); ksFile = new File(keystoreFileName); //Now load the KeyStore and get the cert FileInputStream fis = new java.io.FileInputStream(ksFile); KeyStore keyStore = KeyStore.getInstance(keystoreType); keyStore.load(fis, storePassStr.toCharArray()); cert = (X509Certificate) keyStore.getCertificate(alias); cert = signCertificate(cert); } catch (Exception e) { throw new RegistryException(ServerResourceBundle.getInstance().getString("message.CertGenError"), e); } finally { if (ksFile != null) { try { ksFile.delete(); } catch (Exception e) { ksFile = null; } } } return cert; }
From source file:org.openhealthtools.openatna.net.MailConnection.java
public MimeBodyPart decryptMessage(Message message) throws MessagingException { try {/* w w w . j a v a2 s . c o m*/ /* Add BC */ Security.addProvider(new BouncyCastleProvider()); // Open the key store KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(new FileInputStream(getSenderKeystoreFile()), getSenderKeystorePassword().toCharArray()); // find the certificate for the private key and generate a // suitable recipient identifier. X509Certificate cert = (X509Certificate) ks.getCertificate(getSenderKeyAlias()); RecipientId recId = new RecipientId(); recId.setSerialNumber(cert.getSerialNumber()); recId.setIssuer(cert.getIssuerX500Principal().getEncoded()); SMIMEEnveloped m = new SMIMEEnveloped((MimeMessage) message); RecipientInformationStore recipients = m.getRecipientInfos(); // TODO figure out why this doesn't work... //RecipientInformation recipient = recipients.get(recId); RecipientInformation recipient = (RecipientInformation) recipients.getRecipients().iterator().next(); Key key = ks.getKey(getSenderKeyAlias(), getSenderKeystorePassword().toCharArray()); byte[] byteContent = recipient.getContent(key, "BC"); MimeBodyPart res = SMIMEUtil.toMimeBodyPart(byteContent); return res; } catch (Exception e) { log.error("Problem decrypting message: ", e); throw new MessagingException(e.getMessage()); } }
From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java
public String generateCertificateReq(final KeyStore odlKeyStore, final String keyStorePwd, final String keyAlias, final String signAlg, final boolean withTag) { try {//from w w w. ja v a 2s . c o m if (odlKeyStore.containsAlias(keyAlias)) { final X509Certificate odlCert = (X509Certificate) odlKeyStore.getCertificate(keyAlias); final PublicKey pubKey = odlCert.getPublicKey(); final PrivateKey privKey = (PrivateKey) odlKeyStore.getKey(keyAlias, keyStorePwd.toCharArray()); final String subject = odlCert.getSubjectDN().getName(); final X509Name xname = new X509Name(subject); final String signatureAlgorithm = signAlg; final PKCS10CertificationRequest csr = new PKCS10CertificationRequest(signatureAlgorithm, xname, pubKey, null, privKey); final String certReq = DatatypeConverter.printBase64Binary(csr.getEncoded()); if (withTag) { final StringBuilder sb = new StringBuilder(); sb.append(KeyStoreConstant.BEGIN_CERTIFICATE_REQUEST); sb.append("\n"); sb.append(certReq); sb.append("\n"); sb.append(KeyStoreConstant.END_CERTIFICATE_REQUEST); return sb.toString(); } return certReq; } LOG.info("KeyStore does not contain alias {}", keyAlias); return null; } catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | InvalidKeyException | NoSuchProviderException | SignatureException e) { LOG.error("Failed to generate certificate request", e); return null; } }
From source file:test.integ.be.e_contract.mycarenet.genins.GenericInsurabilityClientTest.java
@Test public void testSTSNurse() throws Exception { 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);/*from w w w .j a va 2s . c o m*/ 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); LOG.debug("SAML assertion: " + assertionString); }
From source file:test.integ.be.e_contract.mycarenet.genins.GenericInsurabilityClientTest.java
@Test public void testSTSDoctor() throws Exception { 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);/*from w w w .j ava2s .c o m*/ 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:ehealth:1.0:doctor:nihii11")); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth", "urn:be:fgov:person:ssin:doctor:boolean")); Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate, eHealthPrivateKey, attributes, attributeDesignators); assertNotNull(assertion); String assertionString = client.toString(assertion); LOG.debug("SAML assertion: " + assertionString); }
From source file:eu.europa.esig.dss.x509.KeyStoreCertificateSource.java
public List<CertificateToken> getCertificatesFromKeyStore() { List<CertificateToken> list = new ArrayList<CertificateToken>(); KeyStore keyStore = getKeyStore(); try {// ww w . ja v a2 s.com Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keyStore.isCertificateEntry(alias)) { Certificate certificate = keyStore.getCertificate(alias); CertificateToken certificateToken = DSSUtils.loadCertificate(certificate.getEncoded()); list.add(certificateToken); } } } catch (Exception e) { logger.error("Unable to retrieve certificates from the keystore : " + e.getMessage(), e); } return list; }
From source file:org.ejbca.core.model.ca.catoken.BaseCAToken.java
/** * @param keyStore/*from ww w. j av a 2 s. co m*/ * @param alias * @return * @throws Exception */ protected PublicKey readPublicKey(KeyStore keyStore, String alias) throws Exception { Certificate cert = keyStore.getCertificate(alias); PublicKey pubk = null; if (cert != null) { pubk = cert.getPublicKey(); } else { log.error(intres.getLocalizedMessage("catoken.nopublic", alias)); if (log.isDebugEnabled()) { Enumeration en = keyStore.aliases(); while (en.hasMoreElements()) { log.debug("Existing alias: " + (String) en.nextElement()); } } } return pubk; }
From source file:org.wso2.carbon.registry.security.vault.CipherInitializer.java
/** * Initializing the encryption key store which uses to encypt the given * plain text/*from www. j a va2s.c o m*/ * */ public void initEncrypt() { Properties properties = SecureVaultUtil.loadProperties(); String keyStoreFile = null; String keyType = null; String aliasName = null; String password = null; String provider = null; Cipher cipher = null; keyStoreFile = properties.getProperty("keystore.identity.location"); File keyStore = new File(keyStoreFile); if (!keyStore.exists()) { handleException("Primary Key Store Can not be found at Default location"); } keyType = properties.getProperty("keystore.identity.type"); aliasName = properties.getProperty("keystore.identity.alias"); ; // Create a KeyStore Information for private key entry KeyStore IdentityKeyStoreInformation identityInformation = KeyStoreInformationFactory .createIdentityKeyStoreInformation(properties); password = identityInformation.getKeyPasswordProvider().getResolvedSecret(); try { KeyStore primaryKeyStore = getKeyStore(keyStoreFile, password, keyType, provider); java.security.cert.Certificate certs = primaryKeyStore.getCertificate(aliasName); cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, certs); } catch (InvalidKeyException e) { handleException("Error initializing Cipher ", e); } catch (NoSuchAlgorithmException e) { handleException("Error initializing Cipher ", e); } catch (KeyStoreException e) { handleException("Error initializing Cipher ", e); } catch (NoSuchPaddingException e) { handleException("Error initializing Cipher ", e); } encryptionProvider = cipher; }
From source file:org.wso2.carbon.mediation.security.vault.CipherInitializer.java
/** * Initializing the encryption key store which uses to encrypt the given * plain text/* w ww .j a va 2s. c o m*/ * */ public void initEncrypt() { if (encryptionProvider != null) return; Properties properties = SecureVaultUtil.loadProperties(); String keyStoreFile; String keyType; String aliasName; String password; String provider = null; Cipher cipher = null; keyStoreFile = properties.getProperty("keystore.identity.location"); File keyStore = new File(keyStoreFile); if (!keyStore.exists()) { handleException("Primary Key Store Can not be found at Default location"); } keyType = properties.getProperty("keystore.identity.type"); aliasName = properties.getProperty("keystore.identity.alias"); ; // Create a KeyStore Information for private key entry KeyStore IdentityKeyStoreInformation identityInformation = KeyStoreInformationFactory .createIdentityKeyStoreInformation(properties); password = identityInformation.getKeyStorePasswordProvider().getResolvedSecret(); try { KeyStore primaryKeyStore = getKeyStore(keyStoreFile, password, keyType, provider); java.security.cert.Certificate certs = primaryKeyStore.getCertificate(aliasName); cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, certs); } catch (InvalidKeyException e) { handleException("Error initializing Cipher ", e); } catch (NoSuchAlgorithmException e) { handleException("Error initializing Cipher ", e); } catch (KeyStoreException e) { handleException("Error initializing Cipher ", e); } catch (NoSuchPaddingException e) { handleException("Error initializing Cipher ", e); } encryptionProvider = cipher; }