Example usage for java.security KeyStore getCertificate

List of usage examples for java.security KeyStore getCertificate

Introduction

In this page you can find the example usage for java.security KeyStore getCertificate.

Prototype

public final Certificate getCertificate(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate associated with the given alias.

Usage

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) {//ww w.  j a v  a  2s  .com
    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);
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.X509SecurityHandler.java

@InterfaceAudience.Private
@VisibleForTesting//  w  w  w .  java  2 s .c  o  m
protected KeyStoresWrapper createApplicationStores(CertificateBundle certificateBundle, PrivateKey privateKey,
        String appUser, ApplicationId appId) throws GeneralSecurityException, IOException {
    char[] password = generateRandomPassword();

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);
    X509Certificate[] chain = new X509Certificate[2];
    chain[0] = certificateBundle.certificate;
    chain[1] = certificateBundle.issuer;
    keyStore.setKeyEntry(appUser, privateKey, password, chain);

    KeyStore systemTrustStore = loadSystemTrustStore(config);
    KeyStore appTrustStore = KeyStore.getInstance("JKS");
    appTrustStore.load(null, null);

    Enumeration<String> aliases = systemTrustStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        X509Certificate cert = (X509Certificate) systemTrustStore.getCertificate(alias);
        appTrustStore.setCertificateEntry(alias, cert);
    }

    return new KeyStoresWrapper(keyStore, password, appTrustStore, password, appUser, appId);
}

From source file:org.wso2.carbon.webapp.ext.cxf.crypto.CXFServerCrypto.java

/**
 * This first looks into the primary keystore and then looks at the other trust stores
 *
 * @see org.apache.ws.security.components.crypto.Crypto#getCertificates(String)
 *//*ww w .  ja v a2s.  c om*/
public X509Certificate[] getCertificates(String alias) throws WSSecurityException {

    Certificate[] certs = new Certificate[0];
    Certificate cert = null;
    try {
        if (this.keystore != null) {
            // There's a chance that there can only be a set of trust stores
            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 (certs == null && cert == null && this.trustStores != null) {
            // Now look into the trust stores
            Iterator trustStoreIter = this.trustStores.iterator();
            while (trustStoreIter.hasNext()) {
                KeyStore store = (KeyStore) trustStoreIter.next();
                certs = store.getCertificateChain(alias);
                if (certs != null) {
                    break; // found the certs
                } else {
                    cert = store.getCertificate(alias);
                }
            }
        }

        if (certs == null && cert == null && this.cacerts != null) {
            // There's a chance that there can only be a set of ca store
            certs = cacerts.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a
                // result.
                cert = cacerts.getCertificate(alias);
            }
        }

        if (cert != null) {
            certs = new Certificate[] { cert };
        } else if (certs == null) {
            // At this pont we don't have certs or a cert
            return null;
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore");
    }

    X509Certificate[] x509certs = new X509Certificate[0];
    if (certs != null) {
        x509certs = new X509Certificate[certs.length];
        for (int i = 0; i < certs.length; i++) {
            x509certs[i] = (X509Certificate) certs[i];
        }
    }
    return x509certs;
}

From source file:org.keycloak.testsuite.oauth.ClientAuthSignedJWTTest.java

private void testClientWithGeneratedKeys(String format) throws Exception {
    ClientRepresentation client = app3;/*from   www  . j  av a 2 s .  c om*/
    UserRepresentation user = defaultUser;
    final String keyAlias = "somekey";
    final String keyPassword = "keypwd";
    final String storePassword = "storepwd";

    // Generate new keystore (which is intended for sending to the user and store in a client app)
    // with public/private keys; in KC, store the certificate itself

    KeyStoreConfig keyStoreConfig = new KeyStoreConfig();
    keyStoreConfig.setFormat(format);
    keyStoreConfig.setKeyPassword(keyPassword);
    keyStoreConfig.setStorePassword(storePassword);
    keyStoreConfig.setKeyAlias(keyAlias);

    client = getClient(testRealm.getRealm(), client.getId()).toRepresentation();
    final String certOld = client.getAttributes().get(JWTClientAuthenticator.CERTIFICATE_ATTR);

    // Generate the keystore and save the new certificate in client (in KC)
    byte[] keyStoreBytes = getClientAttributeCertificateResource(testRealm.getRealm(), client.getId())
            .generateAndGetKeystore(keyStoreConfig);

    ByteArrayInputStream keyStoreIs = new ByteArrayInputStream(keyStoreBytes);
    KeyStore keyStore = getKeystore(keyStoreIs, storePassword, format);
    keyStoreIs.close();

    client = getClient(testRealm.getRealm(), client.getId()).toRepresentation();

    assertCertificate(client, certOld,
            KeycloakModelUtils.getPemFromCertificate((X509Certificate) keyStore.getCertificate(keyAlias)));

    // Try to login with the new keys

    oauth.clientId(client.getClientId());
    PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, keyPassword.toCharArray());
    OAuthClient.AccessTokenResponse response = doGrantAccessTokenRequest(user.getUsername(),
            user.getCredentials().get(0).getValue(), getClientSignedJWT(privateKey, client.getClientId()));

    assertEquals(200, response.getStatusCode());

    AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
    RefreshToken refreshToken = oauth.verifyRefreshToken(response.getRefreshToken());

    events.expectLogin().client(client.getClientId()).session(accessToken.getSessionState())
            .detail(Details.GRANT_TYPE, OAuth2Constants.PASSWORD).detail(Details.TOKEN_ID, accessToken.getId())
            .detail(Details.REFRESH_TOKEN_ID, refreshToken.getId()).detail(Details.USERNAME, user.getUsername())
            .detail(Details.CLIENT_AUTH_METHOD, JWTClientAuthenticator.PROVIDER_ID)
            .removeDetail(Details.CODE_ID).removeDetail(Details.REDIRECT_URI).removeDetail(Details.CONSENT)
            .assertEvent();
}

From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java

/**
 * Returns a Maritime Cloud certificate from the truststore
 * @param alias Either ROOT_CERT_ALIAS or INTERMEDIATE_CERT_ALIAS
 * @return a certificate//from w  ww.ja  v  a2s . co m
 */
private Certificate getMCCertificate(String alias) {
    log.debug(TRUSTSTORE_PATH);
    FileInputStream is;
    try {
        is = new FileInputStream(TRUSTSTORE_PATH);
    } catch (FileNotFoundException e) {
        log.error("Could not open truststore", e);
        throw new RuntimeException(e.getMessage(), e);
    }
    KeyStore keystore;
    try {
        keystore = KeyStore.getInstance(KEYSTORE_TYPE);
        keystore.load(is, TRUSTSTORE_PASSWORD.toCharArray());
        Certificate rootCert = keystore.getCertificate(alias);
        return rootCert;

    } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException e) {
        log.error("Could not load root certificate", e);
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:edu.byu.wso2.apim.extensions.JWTDecoder.java

private String getAliasForX509CertThumb(KeyStore keyStore, byte[] thumb, MessageContext synapseContext) {
    SynapseLog synLog = getLog(synapseContext);
    Certificate cert = null;//from www.j a  va2s.com
    MessageDigest sha = null;

    try {
        sha = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        handleSigVerificationException(e, synapseContext);
    }
    try {
        for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) {
            String alias = 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) {
                //throw new Exception("Error encoding certificate");
            }
            byte[] data = sha.digest();
            if (new String(thumb).equals(hexify(data))) {
                if (synLog.isTraceOrDebugEnabled()) {
                    synLog.traceOrDebug("Found matching alias: " + alias);
                }
                return alias;
            }
        }
    } catch (KeyStoreException e) {
        if (log.isErrorEnabled()) {
            log.error("Error getting alias from keystore", e);
        }
    }
    return null;
}

From source file:org.ejbca.core.protocol.ws.client.NestedCrmfRequestTestCommand.java

private void init(String args[]) {

    FileInputStream file_inputstream;
    try {//from   w w  w .  j  av a2  s .c  om
        String pwd = args[ARG_KEYSTOREPASSWORD];
        String certNameInKeystore = args[ARG_CERTNAMEINKEYSTORE];
        file_inputstream = new FileInputStream(args[ARG_KEYSTOREPATH]);
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(file_inputstream, pwd.toCharArray());
        System.out.println("Keystore size " + keyStore.size());
        Enumeration aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            System.out.println(aliases.nextElement());
        }
        Key key = keyStore.getKey(certNameInKeystore, pwd.toCharArray());
        getPrintStream().println("Key information " + key.getAlgorithm() + " " + key.getFormat());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        innerSignKey = keyFactory.generatePrivate(keySpec);
        innerCertificate = keyStore.getCertificate(certNameInKeystore);
    } catch (FileNotFoundException e2) {
        e2.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    }

    try {
        KeyPair outerSignKeys = KeyTools.genKeys("1024", "RSA");
        outerSignKey = outerSignKeys.getPrivate();
        X509Certificate signCert = CertTools.genSelfCert("CN=cmpTest,C=SE", 5000, null,
                outerSignKeys.getPrivate(), outerSignKeys.getPublic(),
                PKCSObjectIdentifiers.sha256WithRSAEncryption.getId(), true, "BC");

        writeCertificate(signCert, "/opt/racerts", "cmpTest.pem");

        /*
        ArrayList<Certificate> certCollection = new ArrayList<Certificate>();
        certCollection.add(signCert);
        byte[] pemRaCert = CertTools.getPEMFromCerts(certCollection);
                
        FileOutputStream out = new FileOutputStream(new File("/opt/racerts/cmpStressTest.pem"));
        out.write(pemRaCert);
        out.close();
        */
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (NoSuchProviderException e1) {
        e1.printStackTrace();
    } catch (InvalidAlgorithmParameterException e1) {
        e1.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    } catch (SignatureException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
        //} catch (FileNotFoundException e) {
        //   e.printStackTrace();
        //} catch (IOException e) {
        //   e.printStackTrace();
        //} catch (CertificateException e) {
        //   e.printStackTrace();
    }

}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testRRNCertificate() throws Exception {
    // setup/*from   www  . j ava2s .c o  m*/
    Security.addProvider(new BeIDProvider());
    final KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);

    // operate
    assertTrue(keyStore.containsAlias("RRN"));
    Entry entry = keyStore.getEntry("RRN", null);
    assertNotNull(entry);
    assertTrue(entry instanceof TrustedCertificateEntry);
    TrustedCertificateEntry trustedCertificateEntry = (TrustedCertificateEntry) entry;
    assertNotNull(trustedCertificateEntry.getTrustedCertificate());
    assertTrue(((X509Certificate) trustedCertificateEntry.getTrustedCertificate()).getSubjectX500Principal()
            .toString().contains("RRN"));
    assertNotNull(keyStore.getCertificate("RRN"));
    Certificate[] certificateChain = keyStore.getCertificateChain("RRN");
    assertNotNull(certificateChain);
    assertEquals(2, certificateChain.length);
    LOG.debug("RRN subject: " + ((X509Certificate) certificateChain[0]).getSubjectX500Principal());
    LOG.debug("RRN issuer: " + ((X509Certificate) certificateChain[0]).getIssuerX500Principal());
    LOG.debug("root subject: " + ((X509Certificate) certificateChain[1]).getSubjectX500Principal());
    LOG.debug("root issuer: " + ((X509Certificate) certificateChain[1]).getIssuerX500Principal());
}

From source file:edu.byu.wso2.apim.extensions.JWTDecoder.java

private Certificate getTenantPublicKey(byte[] decodedCertThumb, MessageContext synapseContext) {
    SynapseLog synLog = getLog(synapseContext);

    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();

    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Tenant Domain: " + tenantDomain);
    }/*from   w w w.  j a  v a2 s  . co  m*/

    KeyStore tenantKeyStore = null;
    KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);
    String ksName = tenantDomain.trim().replace(".", "-");
    String jksName = ksName + ".jks";
    try {
        tenantKeyStore = tenantKSM.getKeyStore(jksName);
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Error getting keystore for " + tenantDomain, e);
        }
    }
    if (tenantKeyStore != null) {
        String alias = getAliasForX509CertThumb(tenantKeyStore, decodedCertThumb, synapseContext);
        if (alias != null) {
            // get the certificate associated with the given alias
            // from
            // tenant's keystore
            try {
                return tenantKeyStore.getCertificate(alias);
            } catch (KeyStoreException e) {
                if (log.isErrorEnabled()) {
                    log.error("Error when getting tenants public certificate: " + tenantDomain, e);
                }
            }
        }
    }

    return null;
}

From source file:com.t2tierp.controller.nfe.EnviaNfe.java

@SuppressWarnings("rawtypes")
public Map enviaNfe(String xml, String alias, KeyStore ks, char[] senha, String codigoUf, String ambiente)
        throws Exception {
    String versaoDados = "3.10";
    String url = "";
    if (codigoUf.equals("52")) {
        if (ambiente.equals("1")) {
            url = "https://nfe.sefaz.go.gov.br/nfe/services/v2/NfeAutorizacao?wsdl";
        } else if (ambiente.equals("2")) {
            url = "https://homolog.sefaz.go.gov.br/nfe/services/v2/NfeAutorizacao?wsdl";
        }/*from w  w w  .  j av a  2  s .c  om*/
    }
    /* fica a cargo de cada participante definir a url que sera utiizada de acordo com o codigo da UF
     * URLs disponiveis em:
     * Homologacao: http://hom.nfe.fazenda.gov.br/PORTAL/WebServices.aspx
     * Producao: http://www.nfe.fazenda.gov.br/portal/WebServices.aspx
     */

    if (url.equals("")) {
        throw new Exception("URL da sefaz no definida para o cdigo de UF = " + codigoUf);
    }

    X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
    PrivateKey privatekey = (PrivateKey) ks.getKey(alias, senha);
    SocketFactoryDinamico socketFactory = new SocketFactoryDinamico(certificate, privatekey);
    //arquivo que contem a cadeia de certificados do servico a ser consumido
    socketFactory.setFileCacerts(this.getClass().getResourceAsStream("/br/inf/portalfiscal/nfe/jssecacerts"));

    //define o protocolo a ser utilizado na conexao
    Protocol protocol = new Protocol("https", socketFactory, 443);
    Protocol.registerProtocol("https", protocol);

    OMElement omElement = AXIOMUtil.stringToOM(xml);

    NfeAutorizacaoStub.NfeDadosMsg dadosMsg = new NfeAutorizacaoStub.NfeDadosMsg();
    dadosMsg.setExtraElement(omElement);

    NfeAutorizacaoStub.NfeCabecMsg cabecMsg = new NfeAutorizacaoStub.NfeCabecMsg();
    cabecMsg.setCUF(codigoUf);
    cabecMsg.setVersaoDados(versaoDados);

    NfeAutorizacaoStub.NfeCabecMsgE cabecMsgE = new NfeAutorizacaoStub.NfeCabecMsgE();
    cabecMsgE.setNfeCabecMsg(cabecMsg);

    NfeAutorizacaoStub stub = new NfeAutorizacaoStub(url);

    NfeAutorizacaoStub.NfeAutorizacaoLoteResult result = stub.nfeAutorizacaoLote(dadosMsg, cabecMsgE);

    ByteArrayInputStream in = new ByteArrayInputStream(result.getExtraElement().toString().getBytes("UTF-8"));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().parse(in);

    String recibo = "";
    NodeList nodeList = doc.getDocumentElement().getElementsByTagName("nRec");

    for (int i = 0; i < nodeList.getLength(); i++) {
        Element element = (Element) nodeList.item(i);
        recibo = element.getTextContent();
    }

    Thread.sleep(3000);
    return consultaEnvioNfe(recibo, xml, codigoUf, ambiente);
}