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:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java

public KeyStoreObjects getKeyStoreObjects(String reserver) {
    String keyStoreId = "";
    File privateKsFile = new File(tempKeyStoreDir, reserver);
    File[] listFiles = new File(keyStoreDir).listFiles(noLeadingDot);
    int cnt = listFiles.length;
    int select = rng.nextInt(cnt);
    File selected;//from   ww  w . java 2  s  .  co  m
    boolean success = false;
    // try to claim a ks file;
    try {
        selected = listFiles[select];
        keyStoreId = selected.getName();
        selected.renameTo(privateKsFile);
        success = privateKsFile.canRead();
    } catch (Exception ex) {
    }
    // If not successful - generate a new key store
    if (!success) {
        createKeyStore(privateKsFile);
        keyStoreId = reserver;
    }

    try {
        KeyStore ks = getKeyStore(privateKsFile, keyStoreId);
        PrivateKey pk = (PrivateKey) ks.getKey(K_NAME, getKsPass(keyStoreId));
        Certificate cert = ks.getCertificate(K_NAME);
        iaik.x509.X509Certificate x509cert = CertificateUtils.getCertificate(cert.getEncoded());
        privateKsFile.delete();
        return new KeyStoreObjects(pk, x509cert);
    } catch (Exception ex) {
        LOG.log(Level.WARNING, null, ex);
        privateKsFile.delete();
        return null;
    }
}

From source file:Main.java

public static boolean isCACertificateInstalled(File fileCA, String type, char[] password)
        throws KeyStoreException {

    KeyStore keyStoreCA = null;
    try {//from w ww  . j av a2  s . c  o m
        keyStoreCA = KeyStore.getInstance(type/*, "BC"*/);
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (fileCA.exists() && fileCA.canRead()) {
        try {
            FileInputStream fileCert = new FileInputStream(fileCA);
            keyStoreCA.load(fileCert, password);
            fileCert.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (java.security.cert.CertificateException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Enumeration ex = keyStoreCA.aliases();
        Date exportFilename = null;
        String caAliasValue = "";

        while (ex.hasMoreElements()) {
            String is = (String) ex.nextElement();
            Date lastStoredDate = keyStoreCA.getCreationDate(is);
            if (exportFilename == null || lastStoredDate.after(exportFilename)) {
                exportFilename = lastStoredDate;
                caAliasValue = is;
            }
        }

        try {
            return keyStoreCA.getKey(caAliasValue, password) != null;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        }
    }
    return false;
}

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. ja v a  2  s  . c om
    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   www. j  av a 2 s.  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:org.apache.xml.security.test.signature.XmlSecTest.java

private void checkXmlSignatureSoftwareStack(boolean cert) throws Exception {
    Init.init();/*from www . j  a  v  a  2  s  .  co  m*/
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document testDocument = documentBuilder.newDocument();

    Element rootElement = testDocument.createElementNS("urn:namespace", "tns:document");
    rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "urn:namespace");
    testDocument.appendChild(rootElement);
    Element childElement = testDocument.createElementNS("urn:childnamespace", "t:child");
    childElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:t", "urn:childnamespace");
    childElement.appendChild(testDocument.createTextNode("hello world"));
    rootElement.appendChild(childElement);

    PrivateKey privateKey = null;
    PublicKey publicKey = null;
    X509Certificate signingCert = null;
    if (cert) {
        // get key & self-signed certificate from keystore
        String fs = System.getProperty("file.separator");
        FileInputStream fis = new FileInputStream(BASEDIR + fs + "data" + fs + "test.jks");
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(fis, "changeit".toCharArray());
        signingCert = (X509Certificate) ks.getCertificate("mullan");
        publicKey = signingCert.getPublicKey();
        privateKey = (PrivateKey) ks.getKey("mullan", "changeit".toCharArray());
    } else {
        KeyPair keyPair = KeyPairGenerator.getInstance("DSA").generateKeyPair();
        publicKey = keyPair.getPublic();
        privateKey = keyPair.getPrivate();
    }

    XMLSignature signature = new XMLSignature(testDocument, "", XMLSignature.ALGO_ID_SIGNATURE_DSA,
            Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);

    Element signatureElement = signature.getElement();
    rootElement.appendChild(signatureElement);

    Transforms transforms = new Transforms(testDocument);
    XPathContainer xpath = new XPathContainer(testDocument);
    xpath.setXPathNamespaceContext("ds", Constants.SignatureSpecNS);
    xpath.setXPath("not(ancestor-or-self::ds:Signature)");
    transforms.addTransform(Transforms.TRANSFORM_XPATH, xpath.getElementPlusReturns());
    transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
    signature.addDocument("", transforms, MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1);

    if (cert) {
        signature.addKeyInfo(signingCert);
    } else {
        signature.addKeyInfo(publicKey);
    }

    Element nsElement = testDocument.createElementNS(null, "nsElement");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS);

    signature.sign(privateKey);

    // TransformerFactory tf = TransformerFactory.newInstance();
    // Transformer t = tf.newTransformer();
    // t.transform(new DOMSource(testDocument), new StreamResult(System.out));

    NodeList signatureElems = XPathAPI.selectNodeList(testDocument, "//ds:Signature", nsElement);
    signatureElement = (Element) signatureElems.item(0);
    XMLSignature signatureToVerify = new XMLSignature(signatureElement, "");

    boolean signResult = signatureToVerify.checkSignatureValue(publicKey);

    assertTrue(signResult);
}

From source file:net.wasdev.gameon.concierge.PlayerClient.java

/**
 * Obtain the key we'll use to sign the jwts we use to talk to Player endpoints.
 *
 * @throws IOException/*from  w w w. j ava  2  s.  c  o  m*/
 *             if there are any issues with the keystore processing.
 */
private synchronized void getKeyStoreInfo() throws IOException {
    try {
        // load up the keystore..
        FileInputStream is = new FileInputStream(keyStore);
        KeyStore signingKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
        signingKeystore.load(is, keyStorePW.toCharArray());

        // grab the key we'll use to sign
        signingKey = signingKeystore.getKey(keyStoreAlias, keyStorePW.toCharArray());

    } catch (KeyStoreException e) {
        throw new IOException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    } catch (CertificateException e) {
        throw new IOException(e);
    } catch (UnrecoverableKeyException e) {
        throw new IOException(e);
    }

}

From source file:com.streamsets.datacollector.credential.javakeystore.JavaKeyStoreCredentialStore.java

public void deleteCredential(String name) {
    Utils.checkNotNull(name, "name cannot be NULL");

    try {//from ww  w.  jav  a  2  s  . c o  m
        KeyStore keyStore = loadKeyStore();
        if (keyStore == null) {
            keyStore = createKeyStore();
        }
        if (keyStore.getKey(name, getKeystorePassword().toCharArray()) != null) {
            keyStore.deleteEntry(name);
            persistStore(keyStore);
        } else {
            throw new IOException(
                    Utils.format("Credential Store '{}', alias '{}' not found", getContext().getId(), name));
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java

@Test
public void testAliasesAuthnCertCredential() throws Exception {
    LOG.debug("sign");
    // operate/*from  w w  w .  j a  v a  2 s  . c  o  m*/
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    Security.addProvider(new HSMProxyProvider());
    KeyStore hsmProxyKeyStore = KeyStore.getInstance("HSMProxy");

    HSMProxyKeyStoreParameter keyStoreParameter = new HSMProxyKeyStoreParameter(authnPrivateKey, authnCert,
            // "https://www.e-contract.be/hsm-proxy-ws/dss",
            "http://localhost/hsm-proxy-ws/dss", new MyHSMProxyAudit());
    hsmProxyKeyStore.load(keyStoreParameter);

    Enumeration<String> aliasesEnum = hsmProxyKeyStore.aliases();
    assertNotNull(aliasesEnum);
    while (aliasesEnum.hasMoreElements()) {
        LOG.debug("alias: " + aliasesEnum.nextElement());
    }
}

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

/**
 * Do action./*from   w  ww. ja  v a2s .  co  m*/
 */
@Override
protected void doAction() {
    FileOutputStream fos = null;
    File caReplyFile = null;

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

        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());
        Certificate[] certs = keyStore.getCertificateChain(alias);

        KeyPairType keyPairType = KeyPairUtil.getKeyPairType(privateKey);

        File csrFile = chooseCsrFile();
        if (csrFile == null) {
            return;
        }

        PKCS10CertificationRequest pkcs10Csr = null;
        Spkac spkacCsr = null;

        try {
            CryptoFileType fileType = CryptoFileUtil.detectFileType(new FileInputStream(csrFile));
            if (fileType == CryptoFileType.PKCS10_CSR) {
                pkcs10Csr = Pkcs10Util.loadCsr(new FileInputStream(csrFile));

                if (!Pkcs10Util.verifyCsr(pkcs10Csr)) {
                    JOptionPane.showMessageDialog(frame,
                            res.getString("SignCsrAction.NoVerifyPkcs10Csr.message"),
                            res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE);
                    return;
                }
            } else if (fileType == CryptoFileType.SPKAC_CSR) {
                spkacCsr = new Spkac(new FileInputStream(csrFile));

                if (!spkacCsr.verify()) {
                    JOptionPane.showMessageDialog(frame,
                            res.getString("SignCsrAction.NoVerifySpkacCsr.message"),
                            res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE);
                    return;
                }
            } else {
                JOptionPane.showMessageDialog(frame,
                        MessageFormat.format(res.getString("SignCsrAction.FileNotRecognisedType.message"),
                                csrFile),
                        res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE);
                return;
            }
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(frame,
                    MessageFormat.format(res.getString("SignCsrAction.NotFile.message"), csrFile),
                    res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE);
            return;
        } catch (Exception ex) {
            String problemStr = MessageFormat.format(res.getString("SignCsrAction.NoOpenCsr.Problem"),
                    csrFile.getName());

            String[] causes = new String[] { res.getString("SignCsrAction.NotCsr.Cause"),
                    res.getString("SignCsrAction.CorruptedCsr.Cause") };

            Problem problem = new Problem(problemStr, causes, ex);

            DProblem dProblem = new DProblem(frame, res.getString("SignCsrAction.ProblemOpeningCsr.Title"),
                    problem);
            dProblem.setLocationRelativeTo(frame);
            dProblem.setVisible(true);

            return;
        }

        X509Certificate[] signingChain = X509CertUtil
                .orderX509CertChain(X509CertUtil.convertCertificates(certs));
        X509Certificate signingCert = signingChain[0];

        PublicKey publicKey = null;
        X500Name subject = null;
        DSignCsr dSignCsr = null;
        Provider provider = history.getExplicitProvider();

        if (pkcs10Csr != null) {
            publicKey = new JcaPKCS10CertificationRequest(pkcs10Csr).getPublicKey();
            subject = pkcs10Csr.getSubject();

            dSignCsr = new DSignCsr(frame, pkcs10Csr, csrFile, privateKey, keyPairType, signingCert, provider);
        } else {
            publicKey = spkacCsr.getPublicKey();
            subject = spkacCsr.getSubject().getName();

            dSignCsr = new DSignCsr(frame, spkacCsr, csrFile, privateKey, keyPairType, signingCert, provider);
        }

        dSignCsr.setLocationRelativeTo(frame);
        dSignCsr.setVisible(true);

        X509CertificateVersion version = dSignCsr.getVersion();
        SignatureType signatureType = dSignCsr.getSignatureType();
        long validityPeriod = dSignCsr.getValidityPeriod();
        BigInteger serialNumber = dSignCsr.getSerialNumber();
        caReplyFile = dSignCsr.getCaReplyFile();
        X509ExtensionSet extensions = dSignCsr.getExtensions();

        if (version == null) {
            return;
        }

        X500Name issuer = X500NameUtils.x500PrincipalToX500Name(signingCert.getSubjectX500Principal());

        // CA Reply is a cert with subject from CSR and issuer from signing cert's subject
        X509CertificateGenerator generator = new X509CertificateGenerator(version);
        X509Certificate caReplyCert = generator.generate(subject, issuer, validityPeriod, publicKey, privateKey,
                signatureType, serialNumber, extensions, provider);

        X509Certificate[] caReplyChain = new X509Certificate[signingChain.length + 1];

        caReplyChain[0] = caReplyCert;

        // Add all of the signing chain to the reply
        System.arraycopy(signingChain, 0, caReplyChain, 1, signingChain.length);

        byte[] caCertEncoded = X509CertUtil.getCertsEncodedPkcs7(caReplyChain);

        fos = new FileOutputStream(caReplyFile);
        fos.write(caCertEncoded);
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(frame,
                MessageFormat.format(res.getString("SignJarAction.NoWriteFile.message"), caReplyFile),
                res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE);
        return;
    } catch (Exception ex) {
        DError.displayError(frame, ex);
        return;
    } finally {
        IOUtils.closeQuietly(fos);
    }

    JOptionPane.showMessageDialog(frame, res.getString("SignCsrAction.SignCsrSuccessful.message"),
            res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.INFORMATION_MESSAGE);
}

From source file:test.integ.be.agiv.security.Config.java

public Config() throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, NoSuchProviderException {
    Properties properties = new Properties();
    properties.load(Config.class.getResourceAsStream("/agiv.properties"));
    this.username = properties.getProperty("username");
    this.password = properties.getProperty("password");
    this.pkcs12Path = properties.getProperty("pkcs12.path");
    this.pkcs12Password = properties.getProperty("pkcs12.password");
    Provider[] providers = Security.getProviders();
    for (Provider provider : providers) {
        LOG.debug("security provider: " + provider.getName());
    }//w ww.j  a  va2s.co m
    if (null != this.pkcs12Path) {
        InputStream pkcs12InputStream = new FileInputStream(pkcs12Path);
        KeyStore keyStore = KeyStore.getInstance("PKCS12", "SunJSSE");
        keyStore.load(pkcs12InputStream, pkcs12Password.toCharArray());
        Enumeration<String> aliases = keyStore.aliases();
        String alias = aliases.nextElement();
        this.certificate = (X509Certificate) keyStore.getCertificate(alias);
        this.privateKey = (PrivateKey) keyStore.getKey(alias, this.pkcs12Password.toCharArray());
    } else {
        this.certificate = null;
        this.privateKey = null;
    }
}