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:org.adempierelbr.model.MLBRDigitalCertificate.java

/**
 * setCertificate//from w ww  .j a v  a  2  s  .c  o  m
 * Set all System.property for webservice connection
 */
public static void setCertificate(Properties ctx, MOrgInfo oi) throws Exception {

    Integer certOrg = (Integer) oi.get_Value("LBR_DC_Org_ID");
    Integer certWS = (Integer) oi.get_Value("LBR_DC_WS_ID");
    MLBRDigitalCertificate dcOrg = new MLBRDigitalCertificate(Env.getCtx(), certOrg, null);
    MLBRDigitalCertificate dcWS = new MLBRDigitalCertificate(Env.getCtx(), certWS, null);

    String orgPassword = dcOrg.getPassword();
    String certType = null;
    InputStream certFileOrg = null;

    if (MLBRDigitalCertificate.LBR_CERTTYPE_PKCS12.equals(dcOrg.getlbr_CertType())) {
        certType = "PKCS12";
        certFileOrg = dcOrg.getAttachment(true).getEntry(0).getInputStream();
        if (certFileOrg == null)
            throw new Exception("Unable to find private key attachment");
    } else if (MLBRDigitalCertificate.LBR_CERTTYPE_PKCS11.equals(dcOrg.getlbr_CertType())) {
        certType = "PKCS11";
        Provider p = new sun.security.pkcs11.SunPKCS11(dcOrg.getConfigurationFile());
        Security.addProvider(p);
    } else
        return; //   Unknown Certificate

    KeyStore ks = KeyStore.getInstance(certType);
    try {
        ks.load(certFileOrg, orgPassword.toCharArray());
    } catch (IOException e) {
        throw new Exception("Incorrect Certificate Password");
    }

    InputStream certFileWS = dcWS.getAttachment(true).getEntry(0).getInputStream();
    if (certFileWS == null) {
        throw new Exception("Unable to find webservices keystore attachment");
    }

    String alias = dcOrg.getAlias();
    if (alias != null && ks.containsAlias(alias) && ks.isKeyEntry(alias))
        ;//   Do Nothing
    else {
        Enumeration<String> aliasesEnum = ks.aliases();
        while (aliasesEnum.hasMoreElements()) {
            alias = (String) aliasesEnum.nextElement();
            if (ks.isKeyEntry(alias))
                break;
        }
    }

    //Erro NFe 3.10
    System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");

    X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
    PrivateKey privateKey = (PrivateKey) ks.getKey(alias, orgPassword.toCharArray());
    SocketFactoryDinamico socketFactoryDinamico = new SocketFactoryDinamico(certificate, privateKey);
    socketFactoryDinamico.setFileCacerts(certFileWS, dcWS.getPassword());

    Protocol protocol = new Protocol("https", socketFactoryDinamico, 443);
    Protocol.registerProtocol("https", protocol);
}

From source file:testa3.SendLote.java

public static String sendLot(String caminhoArquivo, String certAlias, String certPass)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, XMLStreamException, JAXBException {

    KeyStore ks = KeyStore.getInstance("Windows-MY");
    ks.load(null, null);/*from   w w w.j ava 2 s  .  co m*/

    String codigoDoEstado = "26";

    /**
     * Enderecos de Homoloo do Sefaz Virtual RS para cada WebService
     * existe um endereco Diferente.
     */
    /**
     *
     * homologaao
     */
    URL NFeAutorizacao = new URL("https://nfehomolog.sefaz.pe.gov.br/nfe-service/services/NfeAutorizacao");
    //URL NFeRetAutorizacao  = new URL("https://nfehomolog.sefaz.pe.gov.br/nfe-service/services/NfeRetAutorizacao");
    //URL NfeInutilizacao  = new URL("https://nfce-homologacao.svrs.rs.gov.br/ws/nfeinutilizacao/nfeinutilizacao2.asmx");  
    //URL NfeConsultaProtocolo  = new URL("https://nfce-homologacao.svrs.rs.gov.br/ws/NfeConsulta/NfeConsulta2.asmx");  
    //URL NfeStatusServico  = new URL("https://nfehomolog.sefaz.pe.gov.br/nfe-service/services/NfeStatusServico2");  
    //URL RecepcaoEvento  = new URL("https://nfce-homologacao.svrs.rs.gov.br/ws/recepcaoevento/recepcaoevento.asmx");  

    X509Certificate certificate = (X509Certificate) ks.getCertificate(certAlias);
    PrivateKey privateKey = (PrivateKey) ks.getKey(certAlias, certPass.toCharArray());
    SocketFactoryDinamico socketFactoryDinamico = new SocketFactoryDinamico(certificate, privateKey);
    socketFactoryDinamico.setFileCacerts("NFeCacerts");

    Protocol protocol = new Protocol("https", socketFactoryDinamico, SSL_PORT);
    Protocol.registerProtocol("https", protocol);

    /**
     * Envia NF-e *
     */
    String xml = lerXML(caminhoArquivo);

    StringBuilder xmlEnv = new StringBuilder();

    xmlEnv.append(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?><enviNFe xmlns=\"http://www.portalfiscal.inf.br/nfe\" versao=\"3.10\">")
            .append("<idLote>12312322322</idLote>").append("<indSinc>1</indSinc>")
            .append(xml.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "")).append("</enviNFe>");

    OMElement ome = AXIOMUtil.stringToOM(xmlEnv.toString());

    NfeAutorizacaoStub.NfeDadosMsg dadosMsg = new NfeAutorizacaoStub.NfeDadosMsg();
    dadosMsg.setExtraElement(ome);
    NfeAutorizacaoStub.NfeCabecMsg nfeCabecMsg = new NfeAutorizacaoStub.NfeCabecMsg();
    nfeCabecMsg.setCUF(codigoDoEstado);
    nfeCabecMsg.setVersaoDados("3.10");
    NfeAutorizacaoStub.NfeCabecMsgE nfeCabecMsgE = new NfeAutorizacaoStub.NfeCabecMsgE();
    nfeCabecMsgE.setNfeCabecMsg(nfeCabecMsg);
    NfeAutorizacaoStub stub = new NfeAutorizacaoStub(NFeAutorizacao.toString());
    NfeAutorizacaoStub.NfeAutorizacaoLoteResult result = stub.nfeAutorizacaoLote(dadosMsg, nfeCabecMsgE);

    String retorno = result.getExtraElement().toString();

    //System.out.println(retorno);

    return retorno;

}

From source file:com.kixeye.kixmpp.client.KixmppClientTest.java

private SslContext createSslContext() throws Exception {
    Certificate cert;/*from w  ww  .  ja va 2s  . co m*/

    try (InputStream certStream = this.getClass().getResourceAsStream("/bogus_mina_tls.cert")) {
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(certStream, "boguspw".toCharArray());
        cert = ks.getCertificate("bogus");
    }

    File certFile = File.createTempFile(UUID.randomUUID().toString().replace("-", ""), null);
    FileOutputStream certFileOutputStream = new FileOutputStream(certFile);
    IOUtils.copy(new StringReader("-----BEGIN CERTIFICATE-----\n"), certFileOutputStream);
    IOUtils.copy(new ByteArrayInputStream(Base64.encodeBase64(cert.getEncoded())), certFileOutputStream);
    IOUtils.copy(new StringReader("\n-----END CERTIFICATE-----"), certFileOutputStream);
    certFileOutputStream.close();

    return SslContext.newClientContext(certFile);
}

From source file:org.wso2.carbon.webapp.mgt.sso.SAMLSignatureValidatorImpl.java

/**
 * @param tenantID   tenant ID value//from  www.ja  va 2 s . c o  m
 * @param domainName tenant domain name
 * @return SSOCarbonX509Credential
 * @throws SSOAgentException
 */
private SSOCarbonX509Credential getX509CredentialImplForTenant(int tenantID, String domainName)
        throws SSOAgentException {

    KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantID);
    SSOCarbonX509Credential credentialImpl;
    X509Certificate x509Certificate;
    try {
        if (tenantID != MultitenantConstants.SUPER_TENANT_ID) {
            KeyStore keystore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(domainName));
            x509Certificate = (X509Certificate) keystore.getCertificate(domainName);
        } else {
            x509Certificate = keyStoreManager.getDefaultPrimaryCertificate();
        }
        credentialImpl = new SSOCarbonX509Credential(x509Certificate);
    } catch (Exception e) {
        String errorMsg = "Error instantiating an X509CredentialImpl object for the public cert.";
        throw new SSOAgentException(errorMsg, e);
    }
    return credentialImpl;
}

From source file:org.wso2.identity.scenarios.commons.security.SSOAgentX509KeyStoreCredential.java

protected void readX509Credentials(KeyStore keyStore, String publicCertAlias, String privateKeyAlias,
        char[] privateKeyPassword) throws Exception {

    try {/*from   w  w w.ja v a 2s  .  c  o  m*/
        entityCertificate = (X509Certificate) keyStore.getCertificate(publicCertAlias);
    } catch (KeyStoreException e) {
        throw new Exception("Error occurred while retrieving public certificate for alias " + publicCertAlias,
                e);
    }
    publicKey = entityCertificate.getPublicKey();
    try {
        privateKey = (PrivateKey) keyStore.getKey(privateKeyAlias, privateKeyPassword);
    } catch (KeyStoreException e) {
        throw new Exception("Error occurred while retrieving private key for alias " + privateKeyAlias, e);
    }
}

From source file:net.sf.keystore_explorer.gui.actions.ExportTrustedCertificateAction.java

private X509Certificate getCertificate(String alias) throws CryptoException {
    try {//from   w  w  w . ja v a2s .c  om
        KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
        KeyStore keyStore = history.getCurrentState().getKeyStore();

        X509Certificate cert = X509CertUtil.convertCertificate(keyStore.getCertificate(alias));

        return cert;
    } catch (KeyStoreException ex) {
        String message = MessageFormat
                .format(res.getString("ExportTrustedCertificateAction.NoAccessEntry.message"), alias);
        throw new CryptoException(message, ex);
    }
}

From source file:test.integ.be.fedict.hsm.client.HSMProxyClientTest.java

@Test
public void testGetAliases() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);// ww w.  j  ava  2 s .  c  om
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    HSMProxyClient client = new HSMProxyClient("http://localhost:8080/hsm-proxy-ws/dss", authnPrivateKey,
            authnCert);

    Set<String> aliases = client.getAliases();
    assertNotNull(aliases);
    LOG.debug("aliases: " + aliases);
    assertFalse(aliases.isEmpty());
}

From source file:test.integ.be.fedict.hsm.client.HSMProxyClientTest.java

@Test
public void testGetCertificateChain() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);/* ww  w  .  jav  a 2s.  c  o m*/
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    HSMProxyClient client = new HSMProxyClient("http://localhost:8080/hsm-proxy-ws/dss", authnPrivateKey,
            authnCert);

    Set<String> aliases = client.getAliases();
    assertNotNull(aliases);
    LOG.debug("aliases: " + aliases);
    String alias = aliases.iterator().next();

    List<X509Certificate> certificateChain = client.getCertificateChain(alias);
    assertNotNull(certificateChain);
    for (X509Certificate certificate : certificateChain) {
        LOG.debug("certificate: " + certificate);
    }
    assertFalse(certificateChain.isEmpty());
}

From source file:test.integ.be.fedict.hsm.client.HSMProxyClientTest.java

@Test
public void testSign() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);/*from  w w w  . jav a2  s  . com*/
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    String location = "http://localhost:8080/hsm-proxy-ws/dss";
    // String location = "https://www.e-contract.be/hsm-proxy-ws/dss";
    HSMProxyClient client = new HSMProxyClient(location, authnPrivateKey, authnCert);
    // client.setProxy("proxy.yourict.net", 8080);

    byte[] toBeSigned = "hello world".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    messageDigest.update(toBeSigned);
    byte[] digestValue = messageDigest.digest();

    String keyAlias = "alias";

    byte[] signatureValue = client.sign(digestValue, "SHA1", keyAlias);
    assertNotNull(signatureValue);
    LOG.debug("signature value length: " + signatureValue.length);

    X509Certificate certificate = client.getCertificateChain(keyAlias).get(0);
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(certificate.getPublicKey());
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

From source file:org.wso2.carbon.identity.sso.agent.saml.SSOAgentX509KeyStoreCredential.java

protected void readX509Credentials(KeyStore keyStore, String publicCertAlias, String privateKeyAlias,
        char[] privateKeyPassword) throws SSOAgentException {

    try {//from w w  w  .j  ava2  s  .co m
        entityCertificate = (X509Certificate) keyStore.getCertificate(publicCertAlias);
    } catch (KeyStoreException e) {
        throw new SSOAgentException(
                "Error occurred while retrieving public certificate for alias " + publicCertAlias, e);
    }
    publicKey = entityCertificate.getPublicKey();
    try {
        privateKey = (PrivateKey) keyStore.getKey(privateKeyAlias, privateKeyPassword);
    } catch (KeyStoreException e) {
        throw new SSOAgentException("Error occurred while retrieving private key for alias " + privateKeyAlias,
                e);
    } catch (NoSuchAlgorithmException e) {
        throw new SSOAgentException("Error occurred while retrieving private key for alias " + privateKeyAlias,
                e);
    } catch (UnrecoverableKeyException e) {
        throw new SSOAgentException("Error occurred while retrieving private key for alias " + privateKeyAlias,
                e);
    }
}