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.lockss.util.KeyStoreUtil.java

private static void initializeKeyStore(KeyStore keyStore, Configuration config)
        throws CertificateException, IOException, InvalidKeyException, KeyStoreException,
        NoSuchAlgorithmException, NoSuchProviderException, SignatureException, UnrecoverableKeyException {
    String keyAlias = config.get(PROP_KEY_ALIAS, DEFAULT_KEY_ALIAS);
    String certAlias = config.get(PROP_CERT_ALIAS, DEFAULT_CERT_ALIAS);
    String keyAlgName = config.get(PROP_KEY_ALGORITHM, DEFAULT_KEY_ALGORITHM);
    String sigAlgName = config.get(PROP_SIG_ALGORITHM, DEFAULT_SIG_ALGORITHM);
    String keyStorePassword = config.get(PROP_KEYSTORE_PASSWORD);
    String keyPassword = config.get(PROP_KEY_PASSWORD);
    int keyBits = config.getInt(PROP_KEY_BITS, DEFAULT_KEY_BITS);
    long expireIn = config.getTimeInterval(PROP_EXPIRE_IN, DEFAULT_EXPIRE_IN);
    String x500String = config.get(PROP_X500_NAME, DEFAULT_X500_NAME);

    CertAndKeyGen keypair = new CertAndKeyGen(keyAlgName, sigAlgName);
    keypair.generate(keyBits);//from w  ww . j  av  a  2 s  .co m

    PrivateKey privKey = keypair.getPrivateKey();
    log.debug3("PrivKey: " + privKey.getAlgorithm() + " " + privKey.getFormat());

    X509Certificate[] chain = new X509Certificate[1];

    X500Name x500Name = new X500Name(x500String);
    chain[0] = keypair.getSelfCertificate(x500Name, expireIn);
    log.debug3("Certificate: " + chain[0].toString());

    keyStore.load(null, keyStorePassword.toCharArray());
    keyStore.setCertificateEntry(certAlias, chain[0]);
    keyStore.setKeyEntry(keyAlias, privKey, keyPassword.toCharArray(), chain);
    Key myKey = keyStore.getKey(keyAlias, keyPassword.toCharArray());
    log.debug("MyKey: " + myKey.getAlgorithm() + " " + myKey.getFormat());
}

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

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

private void testClientWithGeneratedKeys(String format) throws Exception {
    ClientRepresentation client = app3;//www .  ja v a 2  s . co  m
    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:eu.eidas.auth.engine.core.impl.AbstractSigner.java

public Credential getSigningCredential(KeyStore keystore, String target) throws SAMLEngineException {
    try {//from  ww w  . j ava 2s .  c o m
        String propPrefix = PROPERTY_PREFIX_DEFAULT;
        if (StringUtils.isNotEmpty(target)) {
            propPrefix = target + PROPERTY_PREFIX_SEPARATOR;
        }
        String serialNumber = getProperties().getProperty(propPrefix + CONF_SERIAL_NUMBER);
        serialNumber = serialNumber == null ? getProperties().getProperty(CONF_SERIAL_NUMBER) : serialNumber;
        String issuer = getProperties().getProperty(propPrefix + CONF_ISSUER);
        issuer = issuer == null ? getProperties().getProperty(CONF_ISSUER) : issuer;
        CertificateAliasPair certificatePair = SAMLEngineUtils.getCertificatePair(keystore, serialNumber,
                issuer);
        checkCertificateValidityPeriod(certificatePair.getCertificate());
        checkCertificateIssuer(certificatePair.getCertificate());
        String password = getProperties().getProperty(propPrefix + CONF_PASSWORD);
        password = password == null ? getProperties().getProperty(CONF_PASSWORD) : password;

        final PrivateKey privateKey = (PrivateKey) keystore.getKey(certificatePair.getAlias(),
                password.toCharArray());

        LOG.debug("Recover BasicX509Credential.");
        final BasicX509Credential credential = new BasicX509Credential();

        LOG.debug("Load certificate");
        credential.setEntityCertificate(certificatePair.getCertificate());

        LOG.debug("Load privateKey");
        credential.setPrivateKey(privateKey);
        return credential;
    } catch (NoSuchAlgorithmException e) {
        LOG.info(
                "ERROR : A 'xmldsig#rsa-sha1' cryptographic algorithm is requested but is not available in the environment.");
        throw new SAMLEngineException(e);
    } catch (KeyStoreException e) {
        LOG.warn("ERROR : Generic KeyStore exception.");
        throw new SAMLEngineException(e);
    } catch (UnrecoverableKeyException e) {
        LOG.warn("ERROR : UnrecoverableKey exception.");
        throw new SAMLEngineException(e);
    }
}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSignerTest.java

/**
 * Teste de coassinatura desanexada com envio do contedo
 *///  ww w . j  a v a2s  .co m
//@Test
public void testSignCoDetached() {
    try {

        System.out.println("******** TESTANDO COM CONTEDO *****************");

        // INFORMAR o arquivo
        String fileDirName = "caminha do arquivo do conteudo";
        String fileSignatureDirName = "caminho do arquivo com a(s) assinatura(s) .p7s";

        byte[] fileToSign = readContent(fileDirName);
        byte[] signatureFile = readContent(fileSignatureDirName);

        // quando certificado em arquivo, precisa informar a senha
        char[] senha = "senha".toCharArray();

        // Para certificado em Neo Id e windows
        KeyStore ks = getKeyStoreTokenBySigner();

        // Para certificado em Token
        // KeyStore ks = getKeyStoreToken();

        // Para certificado em arquivo A1
        // KeyStore ks = getKeyStoreFile();

        // Para certificados no so windows (mascapi)
        // KeyStore ks = getKeyStoreOnWindows();

        String alias = getAlias(ks);

        /* Parametrizando o objeto doSign */
        PKCS7Signer signer = PKCS7Factory.getInstance().factoryDefault();
        signer.setCertificates(ks.getCertificateChain(alias));

        // para token
        signer.setPrivateKey((PrivateKey) ks.getKey(alias, null));

        // para arquivo
        // signer.setPrivateKey((PrivateKey) ks.getKey(alias, senha));
        // politica sem carimbo de tempo
        signer.setSignaturePolicy(PolicyFactory.Policies.AD_RB_CADES_2_3);
        // com carimbo de tempo
        //signer.setSignaturePolicy(PolicyFactory.Policies.AD_RT_CADES_2_3);

        // para mudar o algoritimo
        signer.setAlgorithm(SignerAlgorithmEnum.SHA512withRSA);
        if (org.demoiselle.signer.core.keystore.loader.configuration.Configuration.getInstance().getSO()
                .toLowerCase().indexOf("indows") > 0) {
            signer.setAlgorithm(SignerAlgorithmEnum.SHA256withRSA);
        }

        /* Realiza a assinatura do conteudo */
        System.out.println("Efetuando a  assinatura do conteudo");
        // Assinatura desatachada
        byte[] signature = signer.doDetachedSign(fileToSign, signatureFile);
        File file = new File(fileDirName + "-co_detached.p7s");
        FileOutputStream os = new FileOutputStream(file);
        os.write(signature);
        os.flush();
        os.close();
        System.out.println("------------------ ok --------------------------");
        assertTrue(true);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | IOException ex) {
        ex.printStackTrace();
        assertTrue(false);
    }
}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSignerTest.java

/**
 * Teste com envio do contedo// w ww .j  a v  a2 s . c o  m
 */
//@Test
public void testSignAttached() {
    try {

        System.out.println("******** TESTANDO COM CONTEDO ATACHADO*****************");

        // INFORMAR o arquivo
        String fileDirName = "/home/arquivo.txt";

        byte[] fileToSign = readContent(fileDirName);

        // quando certificado em arquivo, precisa informar a senha
        char[] senha = "senha".toCharArray();

        // Para certificado em Token
        KeyStore ks = getKeyStoreToken();

        // Para certificado NeoID e windows token
        //KeyStore ks = getKeyStoreTokenBySigner();

        // Para certificado em arquivo A1
        //KeyStore ks = getKeyStoreFile();

        // Para certificados no so windows (mascapi)
        // KeyStore ks = getKeyStoreOnWindows();

        String alias = getAlias(ks);
        /* Parametrizando o objeto doSign */
        PKCS7Signer signer = PKCS7Factory.getInstance().factoryDefault();
        signer.setCertificates(ks.getCertificateChain(alias));

        // para token
        signer.setPrivateKey((PrivateKey) ks.getKey(alias, null));

        // para arquivo
        // signer.setPrivateKey((PrivateKey) ks.getKey(alias, senha));
        // politica sem carimbo de tempo
        signer.setSignaturePolicy(PolicyFactory.Policies.AD_RB_CADES_2_3);
        // com carimbo de tempo
        //signer.setSignaturePolicy(PolicyFactory.Policies.AD_RT_CADES_2_3);

        // Referencia de validao
        //signer.setSignaturePolicy(PolicyFactory.Policies.AD_RA_CADES_2_4);

        // para mudar o algoritimo
        signer.setAlgorithm(SignerAlgorithmEnum.SHA512withRSA);
        if (org.demoiselle.signer.core.keystore.loader.configuration.Configuration.getInstance().getSO()
                .toLowerCase().indexOf("indows") > 0) {
            signer.setAlgorithm(SignerAlgorithmEnum.SHA256withRSA);
        }

        /* Realiza a assinatura do conteudo */
        System.out.println("Efetuando a  assinatura do conteudo");
        // Com conteudo atachado
        byte[] signature = signer.doAttachedSign(fileToSign);
        File file = new File(fileDirName + "_atached.p7s");
        FileOutputStream os = new FileOutputStream(file);
        os.write(signature);
        os.flush();
        os.close();
        assertTrue(true);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | IOException ex) {
        ex.printStackTrace();
        assertTrue(false);
    }
}

From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java

public Key getPrivateKey(String alias, boolean isSuperTenant) throws SecurityConfigException {
    KeyStoreData[] keystores = getKeyStores(isSuperTenant);
    KeyStore keyStore = null;
    String privateKeyPassowrd = null;

    try {//w  w  w .jav a2s. c  o m

        for (int i = 0; i < keystores.length; i++) {
            if (KeyStoreUtil.isPrimaryStore(keystores[i].getKeyStoreName())) {
                KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
                keyStore = keyMan.getPrimaryKeyStore();
                ServerConfiguration serverConfig = ServerConfiguration.getInstance();
                privateKeyPassowrd = serverConfig
                        .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD);
                return keyStore.getKey(alias, privateKeyPassowrd.toCharArray());
            }
        }
    } catch (Exception e) {
        String msg = "Error has encounted while loading the key for the given alias " + alias;
        log.error(msg, e);
        throw new SecurityConfigException(msg);
    }
    return null;
}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSignerTest.java

/**
 * Teste com envio do contedo/*from   ww  w  .ja va  2 s . com*/
 */
//@Test
public void testSignDetached() {
    try {

        System.out.println("******** TESTANDO COM CONTEDO *****************");

        // INFORMAR o arquivo

        //
        //String fileDirName = "C:\\Users\\{usuario}\\arquivo_assinar";
        String fileDirName = "";

        byte[] fileToSign = readContent(fileDirName);

        // quando certificado em arquivo, precisa informar a senha
        char[] senha = "senha".toCharArray();

        // MSCAPI off
        //org.demoiselle.signer.core.keystore.loader.configuration.Configuration.setMSCAPI_ON(false);

        // Setar Proxy
        // Proxy.setProxyEndereco("localhost");
        //Proxy.setProxyPorta("3128");
        //Proxy.setProxySenha("senha");
        //Proxy.setProxyUsuario("usuario");
        //Proxy.setProxy();

        // Para certificado NeoID e windows token
        //KeyStore ks = getKeyStoreTokenBySigner();

        // Para certificado em arquivo A1
        KeyStore ks = getKeyStoreFileBySigner();
        // Para certificado token Linux
        //KeyStore ks = getKeyStoreToken();

        // Para certificados no so windows (mascapi)
        // KeyStore ks = getKeyStoreOnWindows();

        String alias = getAlias(ks);
        /* Parametrizando o objeto doSign */
        PKCS7Signer signer = PKCS7Factory.getInstance().factoryDefault();
        signer.setCertificates(ks.getCertificateChain(alias));

        // para token
        //signer.setPrivateKey((PrivateKey) ks.getKey(alias, null));

        // para arquivo
        signer.setPrivateKey((PrivateKey) ks.getKey(alias, senha));
        // politica referencia bsica sem carimbo de tempo
        signer.setSignaturePolicy(PolicyFactory.Policies.AD_RB_CADES_2_3);
        // com carimbo de tempo
        //signer.setSignaturePolicy(PolicyFactory.Policies.AD_RT_CADES_2_3);

        // referencia de validao
        //signer.setSignaturePolicy(PolicyFactory.Policies.AD_RV_CADES_2_3);
        // para mudar o algoritimo
        signer.setAlgorithm(SignerAlgorithmEnum.SHA512withRSA);
        if (org.demoiselle.signer.core.keystore.loader.configuration.Configuration.getInstance().getSO()
                .toLowerCase().indexOf("indows") > 0) {
            signer.setAlgorithm(SignerAlgorithmEnum.SHA256withRSA);
        }

        /* Realiza a assinatura do conteudo */
        System.out.println("Efetuando a  assinatura do conteudo");
        // Assinatura desatachada

        // Cache de cadeia
        //CAManagerConfiguration config = CAManagerConfiguration.getInstance();
        //config.setCached(true);
        //org.demoiselle.signer.core.ca.manager.CAManagerConfiguration.getInstance().setCached(true);

        // Cache LCR
        //Configuration config = Configuration.getInstance();
        //config.setCrlIndex(".crl_index");
        //config.setCrlPath("/home/{usuario}/lcr_cache/");
        //config.setOnline(false);

        // Diretorio LPA
        //Configuration config = Configuration.getInstance();
        //config.setLpaPath("/home/{usuario}/.signer");

        byte[] signature = signer.doDetachedSign(fileToSign);
        File file = new File(fileDirName + "_detached_rb.p7s");
        FileOutputStream os = new FileOutputStream(file);
        os.write(signature);
        os.flush();
        os.close();
        assertTrue(true);

    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | IOException ex) {
        ex.printStackTrace();
        assertTrue(false);
    }
}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

/**
 * Load the private key of the server. This method is not thread safe.
 *///  ww  w  .j  ava2  s.c o m
public static void initPrivateKey(Properties props) throws Exception {

    String privateKeyFilePath = props.getProperty(PRIVATE_KEY_FILE_PROP);
    privateKeyAlias = "";
    privateKeyEncrypt = null;
    if (privateKeyFilePath != null && privateKeyFilePath.length() > 0) {
        KeyStore ks = KeyStore.getInstance("PKCS12");
        privateKeyAlias = props.getProperty(PRIVATE_KEY_ALIAS_PROP);
        if (privateKeyAlias == null) {
            privateKeyAlias = "";
        }
        String keyStorePass = props.getProperty(PRIVATE_KEY_PASSWD_PROP);
        char[] passPhrase = (keyStorePass != null ? keyStorePass.toCharArray() : null);
        FileInputStream privateKeyFile = new FileInputStream(privateKeyFilePath);
        try {
            ks.load(privateKeyFile, passPhrase);
        } finally {
            privateKeyFile.close();
        }
        Key key = ks.getKey(privateKeyAlias, passPhrase);
        Certificate keyCert = ks.getCertificate(privateKeyAlias);
        if (key instanceof PrivateKey && keyCert instanceof X509Certificate) {
            privateKeyEncrypt = (PrivateKey) key;
            privateKeySignAlgo = ((X509Certificate) keyCert).getSigAlgName();
            privateKeySubject = ((X509Certificate) keyCert).getSubjectDN().getName();
        }
    }
}