Example usage for java.security KeyStore getKey

List of usage examples for java.security KeyStore getKey

Introduction

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

Prototype

public final Key getKey(String alias, char[] password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 

Source Link

Document

Returns the key associated with the given alias, using the given password to recover it.

Usage

From source file:org.picketbox.test.jaxrs.RESTEasyStandaloneTestCase.java

private PrivateKey getPrivateKey() throws Exception {
    InputStream is = getClass().getClassLoader().getResourceAsStream("keystore/pbox_jaxrs.keystore");
    assertNotNull(is);/*from ww  w  . j a  v  a  2  s . co  m*/
    KeyStore keystore = KeyStoreUtil.getKeyStore(is, "pass123".toCharArray());

    // Get private key
    Key key = keystore.getKey("1234", "pass123".toCharArray());
    return (PrivateKey) key;
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUnidClient.java

/**
  * @param ksfilename String Filename of PKCS#12 keystore used to authenticate TLS client authentication, or null if TLS is not used
  * @param pwd String password for the key store,or null if no keystore is used 
  * @param ocspurl String url to the OCSP server, or null if we should try to use the AIA extension from the cert; e.g. http://127.0.0.1:8080/ejbca/publicweb/status/ocsp (or https for TLS)
 * @return the client to use//ww w  . j a  v  a 2s . co  m
  * @throws Exception
 */
public static OCSPUnidClient getOCSPUnidClient(String ksfilename, String pwd, String ocspurl,
        boolean doSignRequst, boolean getfnr) throws Exception {
    if (doSignRequst && ksfilename == null) {
        throw new Exception("You got to give the path name for a keystore to use when using signing.");
    }
    final KeyStore ks;
    if (ksfilename != null) {
        ks = KeyStore.getInstance("PKCS12", "BC");
        ks.load(new FileInputStream(ksfilename), pwd.toCharArray());
        Enumeration<String> en = ks.aliases();
        String alias = null;
        // If this alias is a trusted certificate entry, we don't want to fetch that, we want the key entry
        while ((alias == null || ks.isCertificateEntry(alias)) && en.hasMoreElements()) {
            alias = en.nextElement();
        }
        final Certificate[] certs = KeyTools.getCertChain(ks, alias);
        if (certs == null) {
            throw new IOException("Can not find a certificate entry in PKCS12 keystore for alias " + alias);
        }
        final PrivateKey privateKey = doSignRequst ? (PrivateKey) ks.getKey(alias, null) : null;
        return new OCSPUnidClient(ks, pwd, ocspurl, certs, privateKey, getfnr);
    } else {
        return new OCSPUnidClient(null, null, ocspurl, null, null, getfnr);
    }
}

From source file:com.indivica.olis.Driver.java

public static String signData(String data) {
    X509Certificate cert = null;//  w  ww.j  a v  a 2  s  .  c o  m
    PrivateKey priv = null;
    KeyStore keystore = null;
    String pwd = "Olis2011";
    String result = null;
    try {
        Security.addProvider(new BouncyCastleProvider());

        keystore = KeyStore.getInstance("PKCS12", "SunJSSE");
        // Load the keystore
        keystore.load(new FileInputStream(OscarProperties.getInstance().getProperty("olis_keystore")),
                pwd.toCharArray());

        Enumeration e = keystore.aliases();
        String name = "";

        if (e != null) {
            while (e.hasMoreElements()) {
                String n = (String) e.nextElement();
                if (keystore.isKeyEntry(n)) {
                    name = n;
                }
            }
        }

        // Get the private key and the certificate
        priv = (PrivateKey) keystore.getKey(name, pwd.toCharArray());
        cert = (X509Certificate) keystore.getCertificate(name);

        // I'm not sure if this is necessary

        ArrayList<Certificate> certList = new ArrayList<Certificate>();
        certList.add(cert);

        Store certs = new JcaCertStore(certList);

        // Encrypt data
        CMSSignedDataGenerator sgen = new CMSSignedDataGenerator();

        // What digest algorithm i must use? SHA1? MD5? RSA?...
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(priv);
        sgen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
                new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert));

        // I'm not sure this is necessary
        sgen.addCertificates(certs);

        // I think that the 2nd parameter need to be false (detached form)
        CMSSignedData csd = sgen.generate(new CMSProcessableByteArray(data.getBytes()), true);

        byte[] signedData = csd.getEncoded();
        byte[] signedDataB64 = Base64.encode(signedData);

        result = new String(signedDataB64);

    } catch (Exception e) {
        MiscUtils.getLogger().error("Can't sign HL7 message for OLIS", e);
    }
    return result;
}

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

/**
 * Do action.// w w  w  .  j  a v a2s  .  c om
 */
@Override
protected void doAction() {
    File csrFile = null;
    FileOutputStream fos = null;

    try {
        KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
        KeyStoreState currentState = history.getCurrentState();
        Provider provider = history.getExplicitProvider();

        String alias = kseFrame.getSelectedEntryAlias();

        Password password = getEntryPassword(alias, currentState);

        if (password == null) {
            return;
        }

        KeyStore keyStore = currentState.getKeyStore();

        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());

        String keyPairAlg = privateKey.getAlgorithm();
        KeyPairType keyPairType = KeyPairUtil.getKeyPairType(privateKey);

        if (keyPairType == null) {
            throw new CryptoException(MessageFormat
                    .format(res.getString("GenerateCsrAction.NoCsrForKeyPairAlg.message"), keyPairAlg));
        }

        // determine dir of current keystore as proposal for CSR file location
        String path = CurrentDirectory.get().getAbsolutePath();
        File keyStoreFile = history.getFile();
        if (keyStoreFile != null) {
            path = keyStoreFile.getAbsoluteFile().getParent();
        }

        DGenerateCsr dGenerateCsr = new DGenerateCsr(frame, alias, privateKey, keyPairType, path, provider);
        dGenerateCsr.setLocationRelativeTo(frame);
        dGenerateCsr.setVisible(true);

        if (!dGenerateCsr.generateSelected()) {
            return;
        }

        CsrType format = dGenerateCsr.getFormat();
        SignatureType signatureType = dGenerateCsr.getSignatureType();
        String challenge = dGenerateCsr.getChallenge();
        String unstructuredName = dGenerateCsr.getUnstructuredName();
        boolean useCertificateExtensions = dGenerateCsr.isAddExtensionsWanted();
        csrFile = dGenerateCsr.getCsrFile();

        X509Certificate firstCertInChain = X509CertUtil
                .orderX509CertChain(X509CertUtil.convertCertificates(keyStore.getCertificateChain(alias)))[0];

        fos = new FileOutputStream(csrFile);

        if (format == CsrType.PKCS10) {
            String csr = Pkcs10Util.getCsrEncodedDerPem(Pkcs10Util.generateCsr(firstCertInChain, privateKey,
                    signatureType, challenge, unstructuredName, useCertificateExtensions, provider));

            fos.write(csr.getBytes());
        } else {
            SpkacSubject subject = new SpkacSubject(
                    X500NameUtils.x500PrincipalToX500Name(firstCertInChain.getSubjectX500Principal()));
            PublicKey publicKey = firstCertInChain.getPublicKey();

            // TODO handle other providers (PKCS11 etc)
            Spkac spkac = new Spkac(challenge, signatureType, subject, publicKey, privateKey);

            spkac.output(fos);
        }
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(frame,
                MessageFormat.format(res.getString("GenerateCsrAction.NoWriteFile.message"), csrFile),
                res.getString("GenerateCsrAction.GenerateCsr.Title"), JOptionPane.WARNING_MESSAGE);
        return;
    } catch (Exception ex) {
        DError.displayError(frame, ex);
        return;
    } finally {
        IOUtils.closeQuietly(fos);
    }

    JOptionPane.showMessageDialog(frame, res.getString("GenerateCsrAction.CsrGenerationSuccessful.message"),
            res.getString("GenerateCsrAction.GenerateCsr.Title"), JOptionPane.INFORMATION_MESSAGE);
}

From source file:com.piusvelte.taplock.server.TapLockServer.java

protected static SecretKey getSecretKey(KeyStore ks) {
    SecretKey sk = null;//from   www  . j a  v  a2  s. co  m
    if (ks != null) {
        boolean ksLoaded = false;
        try {
            ks.load(new FileInputStream(sKeystore), sPassphrase.toCharArray());
            ksLoaded = true;
        } catch (NoSuchAlgorithmException e) {
            writeLog("getSecretKey: " + e.getMessage());
        } catch (CertificateException e) {
            writeLog("getSecretKey: " + e.getMessage());
        } catch (FileNotFoundException e) {
            writeLog("getSecretKey: " + e.getMessage());
        } catch (IOException e) {
            writeLog("getSecretKey: " + e.getMessage());
        }
        if (ksLoaded) {
            try {
                sk = (SecretKey) ks.getKey(TAP_LOCK, sPassphrase.toCharArray());
            } catch (UnrecoverableKeyException e) {
                writeLog("getSecretKey: " + e.getMessage());
            } catch (KeyStoreException e) {
                writeLog("getSecretKey: " + e.getMessage());
            } catch (NoSuchAlgorithmException e) {
                writeLog("getSecretKey: " + e.getMessage());
            }
        }
    }
    return sk;
}

From source file:org.adempierelbr.model.MLBRDigitalCertificate.java

/**
 * setCertificate/*from  w ww.j a v  a2  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:test.integ.be.e_contract.mycarenet.cxf.CXFTest.java

@Test
public void testEcho() throws Exception {
    // setup/* w  ww.  j  a  va 2  s  . c o m*/
    String xkms2Location = "https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms2";
    XKMS2Client xkms2Client = new XKMS2Client(xkms2Location);
    SessionKey sessionKey = new SessionKey();

    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");

    // operate
    xkms2Client.registerSessionKey(sessionKey, authnPrivateKey, authnCertificate);

    // verify
    assertTrue(sessionKey.isValid());

    try {
        // setup
        Config config = new Config();
        PackageLicenseKey packageLicenseKey = config.getPackageLicenseKey();
        LOG.debug("package license key username: " + packageLicenseKey.getUsername());
        LOG.debug("package license key password: " + packageLicenseKey.getPassword());
        AsyncClient asyncClient = new AsyncClient("https://pilot.mycarenet.be/mycarenet-ws/care-provider/async",
                sessionKey, packageLicenseKey);

        BindingProvider bindingProvider = asyncClient.getBindingProvider();
        Client client = ClientProxy.getClient(bindingProvider);
        HTTPConduit http = (HTTPConduit) client.getConduit();
        HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
        httpClientPolicy.setConnectionTimeout(36000); // ms
        httpClientPolicy.setReceiveTimeout(36000); // ms
        http.setClient(httpClientPolicy);

        String message = "hello world";

        // operate
        String result;
        try {
            result = asyncClient.echo(message);
        } finally {
            LOG.debug("payload: " + asyncClient.getPayload());
        }

        // verify
        assertEquals(result, message);
    } finally {
        // operate
        XKMSClient xkmsClient = new XKMSClient("https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms");
        xkmsClient.revokeSessionKey(sessionKey);

        // verify
        assertFalse(sessionKey.isValid());
    }
}

From source file:com.vmware.identity.idm.server.ClientCertTestUtils.java

public PrivateKey getTenantCredentialPrivateKey(String keyAlias) throws Exception {
    Properties props = getTestProperties();

    KeyStore ks = loadKeyStore(props.getProperty(STS_STORE_JKS), props.getProperty(STS_STORE_PASS));
    return (PrivateKey) ks.getKey(keyAlias, props.getProperty(STS_STORE_PASS).toCharArray());
}

From source file:org.wso2.tools.ksexplorer.action.ShowPEMPrivateKeyAction.java

public String execute() throws Exception {

    HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
            .get(StrutsStatics.HTTP_REQUEST);
    HttpSession session = request.getSession();
    List keyStoreDescriptions = (List) session.getAttribute(KSExplorerConstants.SESSION_KEY_KS);

    String ksId = request.getParameter("ksId");
    KeyStoreDescription ksDesc = null;/*from  ww  w .  j  a  v a 2 s. c o  m*/
    for (Iterator iterator = keyStoreDescriptions.iterator(); iterator.hasNext();) {
        KeyStoreDescription desc = (KeyStoreDescription) iterator.next();
        if (desc.getUuid().equals(ksId)) {
            ksDesc = desc;
        }
    }

    KeyStore store = ksDesc.getKeyStore();
    this.storeName = ksDesc.getName();
    this.alias = request.getParameter("alias");
    String keyPasswd = request.getParameter("keyPasswd");
    PrivateKey key = (PrivateKey) store.getKey(alias, keyPasswd.toCharArray());

    log.info("[WSO2KSE] : Showing key : " + alias + " in keystore : " + this.storeName + " (store id :" + ksId
            + ")");

    BASE64Encoder encoder = new BASE64Encoder();
    pemKey = "-----BEGIN PRIVATE KEY-----\n";
    pemKey += encoder.encode(key.getEncoded());
    pemKey += "\n-----END PRIVATE KEY-----";

    return SUCCESS;
}

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);// www.  j  a v  a2  s.  com

    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;

}