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.wso2.carbon.certificate.mgt.core.impl.KeyStoreReader.java

PrivateKey getCAPrivateKey() throws KeystoreException {
    KeyStore keyStore = loadCertificateKeyStore();
    PrivateKey caPrivateKey;/*  w  w w . java2 s.  co  m*/
    try {
        CertificateKeystoreConfig certificateKeystoreConfig = CertificateConfigurationManager.getInstance()
                .getCertificateKeyStoreConfig();
        caPrivateKey = (PrivateKey) keyStore.getKey(certificateKeystoreConfig.getCACertAlias(),
                certificateKeystoreConfig.getCAPrivateKeyPassword().toCharArray());
    } catch (UnrecoverableKeyException e) {
        String errorMsg = "Key is unrecoverable when retrieving CA private key";
        throw new KeystoreException(errorMsg, e);
    } catch (KeyStoreException e) {
        String errorMsg = "KeyStore issue occurred when retrieving CA private key";
        throw new KeystoreException(errorMsg, e);
    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Algorithm not found when retrieving CA private key";
        throw new KeystoreException(errorMsg, e);
    } catch (CertificateManagementException e) {
        String errorMsg = "Unable to find KeyStore configuration in certificate-mgt.config file.";
        throw new KeystoreException(errorMsg, e);
    }

    if (caPrivateKey == null) {
        throw new KeystoreException("CA private key not found in KeyStore");
    }

    return caPrivateKey;
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.KeyStoreReader.java

public PrivateKey getRAPrivateKey() throws KeystoreException {
    KeyStore keystore = loadCertificateKeyStore();
    PrivateKey raPrivateKey;//from  w  w  w .  j  a  v a2 s. co  m
    try {
        CertificateKeystoreConfig certificateKeystoreConfig = CertificateConfigurationManager.getInstance()
                .getCertificateKeyStoreConfig();
        raPrivateKey = (PrivateKey) keystore.getKey(certificateKeystoreConfig.getRACertAlias(),
                certificateKeystoreConfig.getRAPrivateKeyPassword().toCharArray());
    } catch (UnrecoverableKeyException e) {
        String errorMsg = "Key is unrecoverable when retrieving RA private key";
        throw new KeystoreException(errorMsg, e);
    } catch (KeyStoreException e) {
        String errorMsg = "KeyStore issue occurred when retrieving RA private key";
        throw new KeystoreException(errorMsg, e);
    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Algorithm not found when retrieving RA private key";
        throw new KeystoreException(errorMsg, e);
    } catch (CertificateManagementException e) {
        String errorMsg = "Unable to find KeyStore configuration in certificate-mgt.config file.";
        throw new KeystoreException(errorMsg, e);
    }

    if (raPrivateKey == null) {
        throw new KeystoreException("RA private key not found in KeyStore");
    }

    return raPrivateKey;
}

From source file:org.votingsystem.web.ejb.SignatureBean.java

public KeyStoreInfo getKeyStoreInfo(byte[] keyStoreBytes, String keyAlias) throws Exception {
    KeyStore keyStore = KeyStoreUtil.getKeyStoreFromBytes(keyStoreBytes, password.toCharArray());
    PrivateKey privateKeySigner = (PrivateKey) keyStore.getKey(keyAlias, password.toCharArray());
    X509Certificate certSigner = (X509Certificate) keyStore.getCertificate(keyAlias);
    return new KeyStoreInfo(keyStore, privateKeySigner, certSigner);
}

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 {/* ww  w  .  j a 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:org.lockss.util.TestKeyStoreUtil.java

void assertPrivateKs(File file, String pass, String alias) throws Exception {
    KeyStore ks = loadKeyStore("jceks", file, alias);
    List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases()));
    assertEquals(2, aliases.size());// w  ww  .  j  a  v  a 2s  . c  o  m
    Certificate cert = ks.getCertificate(alias + ".crt");
    assertNotNull(cert);
    assertEquals("X.509", cert.getType());
    assertTrue(ks.isKeyEntry(alias + ".key"));
    assertTrue(ks.isCertificateEntry(alias + ".crt"));
    Key key = ks.getKey(alias + ".key", pass.toCharArray());
    assertNotNull(key);
    assertEquals("RSA", key.getAlgorithm());
}

From source file:org.atricore.idbus.capabilities.sso.support.test.XmlDsigTest.java

/**
 * Sign a SAMLR2 Assertion using the configured JSR 105 Provider
 *///  w w w .  j  a va2s . com
@Test
public void assertionSign() throws Exception {
    //All the parameters for the keystore
    String keystoreType = "JKS";
    String keystoreFile = "src/test/resources/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File assertionFile = new File("src/test/resources/assertion-001.xml");
    File signatureFile = new File("target/assertion-signed-001.xml");

    JAXBContext context = JAXBContext.newInstance("oasis.names.tc.saml._2_0.assertion");
    Unmarshaller um = context.createUnmarshaller();

    JAXBElement jaxbElement = (JAXBElement) um.unmarshal(assertionFile);

    AssertionType assertion = (AssertionType) jaxbElement.getValue();

    // Unmarshall the assertion
    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    //load the keystore
    ks.load(fis, keystorePass.toCharArray());

    //get the private key for signing.
    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());

    X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);
    PublicKey publicKey = cert.getPublicKey();

    // Create a DOM XMLSignatureFactory that will be used to generate the
    // enveloped signature
    String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",
            (Provider) Class.forName(providerName).newInstance());

    // Create a Reference to the enveloped document (in this case we are
    // signing the whole document, so a URI of "" signifies that) and
    // also specify the SHA1 digest algorithm and the ENVELOPED Transform.
    Reference ref = fac.newReference("#" + assertion.getID(), fac.newDigestMethod(DigestMethod.SHA1, null),
            Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
            null, null);

    // Create the SignedInfo
    SignedInfo si = fac.newSignedInfo(
            fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null),
            fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));

    // Instantiate the document to be signed
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    //XML Signature needs to be namespace aware
    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();

    Marshaller m = context.createMarshaller();
    m.marshal(jaxbElement, doc);

    // Create a DOMSignContext and specify the DSA PrivateKey and
    // location of the resulting XMLSignature's parent element
    DOMSignContext dsc = new DOMSignContext(privateKey, doc.getDocumentElement(),
            doc.getDocumentElement().getFirstChild());

    // Create the XMLSignature (but don't sign it yet)
    KeyInfoFactory kif = fac.getKeyInfoFactory();

    X509Data kv = kif.newX509Data(Collections.singletonList(cert));

    // Create a KeyInfo and add the KeyValue to it
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));

    javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki);

    signature.sign(dsc);
    // output the resulting document

    FileOutputStream f = new FileOutputStream(signatureFile);
    XMLUtils.outputDOMc14nWithComments(doc, f);
    f.close();
}

From source file:de.conterra.suite.security.portal.gpx.EmbeddedSAMLTokenIntegrationContext.java

private void initKeyStore(StringAttributeMap stringAttributeMap) {
    LOGGER.entering("EmbeddedSAMLTokenIntegrationContext", "initKeyStore");
    String type = getValFromConfig(CONFIG_PARAM_KEYSTORE_TYPE, "JKS");
    String keystoreLoc = getValFromConfig(CONFIG_PARAM_KEYSTORE_LOC, "/gpt/config/keystore.jks");
    String keystorePw = getValFromConfig(CONFIG_PARAM_KEYSTORE_PW, "changeit");
    String keyAlias = getValFromConfig(CONFIG_PARAM_KEYSTORE_KEY_ALIAS, "gpt-security");
    String keyPw = getValFromConfig(CONFIG_PARAM_KEYSTORE_KEY_PW, "changeit");

    LOGGER.finest(MessageFormat.format("Instantiating keystore from: {0}", keystoreLoc));
    LOGGER.finest(MessageFormat.format("Using certificate alias: {0}", keyAlias));
    if ("true".equalsIgnoreCase(getValFromConfig(CONFIG_PARAM_KEYSTORE_PWS_ENCRYPTED, "false"))) {
        // TODO: test this stuff
        keystorePw = PC1_Encryptor.decrypt(keystorePw);
        keyPw = PC1_Encryptor.decrypt(keyPw);
    }/*from   w  w  w .  j a va2  s .com*/

    try {
        KeyStore keystore = KeyStore.getInstance(type);
        InputStream in = findInputStream(keystoreLoc);
        try {
            keystore.load(in, keystorePw.toCharArray());
            Certificate cert = keystore.getCertificate(keyAlias);
            Key key = keystore.getKey(keyAlias, keyPw.toCharArray());
            m_applicationCertificate = cert;
            m_applicationPrivateKey = key;
            if (cert == null || key == null) {
                throw new IllegalArgumentException("key alias '" + keyAlias + "> not found!");
            }
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                // ignore
            }
        }
    } catch (Exception e) {
        throw new IllegalStateException("Can't load certificate and key with alias '" + keyAlias
                + "' from keystore '" + keystoreLoc + "'! Msg" + e, e);
    }
}

From source file:org.atricore.idbus.capabilities.sso.support.test.XmlDsigTest.java

/**
 * Sign a simple DOM document using the configured JSR 105 Provider
 *//*from  www.j a  v  a2 s. c o m*/
@Test
public void simpleDocumentSign() throws Exception {

    //All the parameters for the keystore
    String keystoreType = "JKS";
    String keystoreFile = "src/test/resources/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File signatureFile = new File("target/signature.xml");

    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    //load the keystore
    ks.load(fis, keystorePass.toCharArray());

    //get the private key for signing.
    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());

    X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);
    PublicKey publicKey = cert.getPublicKey();

    // Create a DOM XMLSignatureFactory that will be used to generate the
    // enveloped signature
    String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",
            (Provider) Class.forName(providerName).newInstance());

    // Create a Reference to the enveloped document (in this case we are
    // signing the whole document, so a URI of "" signifies that) and
    // also specify the SHA1 digest algorithm and the ENVELOPED Transform.
    Reference ref = fac.newReference("#12345", fac.newDigestMethod(DigestMethod.SHA1, null),
            Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
            null, null);

    // Create the SignedInfo
    SignedInfo si = fac.newSignedInfo(
            fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null),
            fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));

    // Instantiate the document to be signed
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    //XML Signature needs to be namespace aware
    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();

    //Build a sample document. It will look something like:
    //<!-- Comment before -->
    //<apache:RootElement xmlns:apache="http://www.apache.org/ns/#app1" ID="12345">Some simple text
    //</apache:RootElement>
    //<!-- Comment after -->
    doc.appendChild(doc.createComment(" Comment before "));

    Element root = doc.createElementNS("http://www.apache.org/ns/#app1", "apache:RootElement");

    root.setAttributeNS(null, "ID", "12345");

    root.setAttributeNS(null, "attr1", "test1");
    root.setAttributeNS(null, "attr2", "test2");
    root.setAttributeNS(org.apache.xml.security.utils.Constants.NamespaceSpecNS, "xmlns:foo",
            "http://example.org/#foo");
    root.setAttributeNS("http://example.org/#foo", "foo:attr1", "foo's test");

    root.setAttributeNS(org.apache.xml.security.utils.Constants.NamespaceSpecNS, "xmlns:apache",
            "http://www.apache.org/ns/#app1");
    doc.appendChild(root);
    root.appendChild(doc.createTextNode("Some simple text\n"));

    // Create a DOMSignContext and specify the DSA PrivateKey and
    // location of the resulting XMLSignature's parent element
    DOMSignContext dsc = new DOMSignContext(privateKey, doc.getDocumentElement());

    // Create the XMLSignature (but don't sign it yet)
    KeyInfoFactory kif = fac.getKeyInfoFactory();

    X509Data kv = kif.newX509Data(Collections.singletonList(cert));

    // Create a KeyInfo and add the KeyValue to it
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
    javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki);

    signature.sign(dsc);

    // TODO : Verify signature ?

    // output the resulting document
    FileOutputStream f = new FileOutputStream(signatureFile);
    XMLUtils.outputDOMc14nWithComments(doc, f);
    f.close();

}

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

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

@Test
public void testNonRepudiationSignature() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//w w  w.java  2s .  com
    PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null);
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(signPrivateKey);
    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();
    assertNotNull(signatureValue);

    Certificate[] signCertificateChain = keyStore.getCertificateChain("Signature");
    assertNotNull(signCertificateChain);
}