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.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

@Override
public void restoreCAKeyStore(AuthenticationToken authenticationToken, String caname, byte[] p12file,
        String keystorepass, String privkeypass, String privateSignatureKeyAlias,
        String privateEncryptionKeyAlias) {
    if (log.isTraceEnabled()) {
        log.trace(">restoreCAKeyStore");
    }/*from   w w w  . j ava 2 s. com*/
    try {
        // check authorization
        if (!accessSession.isAuthorizedNoLogging(authenticationToken, StandardRules.ROLE_ROOT.resource())) {
            final String detailsMsg = intres.getLocalizedMessage("caadmin.notauthorizedtorestorecatoken",
                    caname);
            auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    authenticationToken.toString(), null, null, null, detailsMsg);
        }
        CA thisCa = caSession.getCAForEdit(authenticationToken, caname);
        final CAToken thisCAToken = thisCa.getCAToken();
        CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(thisCAToken.getCryptoTokenId());
        if (cryptoToken != null) {
            throw new Exception("CA already has an existing CryptoToken reference: " + cryptoToken.getId());
        }
        // load keystore from input
        KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
        keystore.load(new ByteArrayInputStream(p12file), keystorepass.toCharArray());
        // Extract signature keys
        if (privateSignatureKeyAlias == null || !keystore.isKeyEntry(privateSignatureKeyAlias)) {
            throw new Exception("Alias \"" + privateSignatureKeyAlias + "\" not found.");
        }
        Certificate[] signatureCertChain = KeyTools.getCertChain(keystore, privateSignatureKeyAlias);
        if (signatureCertChain.length < 1) {
            String msg = "Cannot load certificate chain with alias " + privateSignatureKeyAlias;
            log.error(msg);
            throw new Exception(msg);
        }
        Certificate caSignatureCertificate = (Certificate) signatureCertChain[0];
        PublicKey p12PublicSignatureKey = caSignatureCertificate.getPublicKey();
        PrivateKey p12PrivateSignatureKey = null;
        p12PrivateSignatureKey = (PrivateKey) keystore.getKey(privateSignatureKeyAlias,
                privkeypass.toCharArray());

        // Extract encryption keys
        PrivateKey p12PrivateEncryptionKey = null;
        PublicKey p12PublicEncryptionKey = null;
        Certificate caEncryptionCertificate = null;
        if (privateEncryptionKeyAlias != null) {
            if (!keystore.isKeyEntry(privateEncryptionKeyAlias)) {
                throw new Exception("Alias \"" + privateEncryptionKeyAlias + "\" not found.");
            }
            Certificate[] encryptionCertChain = KeyTools.getCertChain(keystore, privateEncryptionKeyAlias);
            if (encryptionCertChain.length < 1) {
                String msg = "Cannot load certificate chain with alias " + privateEncryptionKeyAlias;
                log.error(msg);
                throw new Exception(msg);
            }
            caEncryptionCertificate = (Certificate) encryptionCertChain[0];
            p12PrivateEncryptionKey = (PrivateKey) keystore.getKey(privateEncryptionKeyAlias,
                    privkeypass.toCharArray());
            p12PublicEncryptionKey = caEncryptionCertificate.getPublicKey();
        } else {
            throw new Exception("Missing encryption key");
        }

        // Sign something to see that we are restoring the right private signature key
        String testSigAlg = (String) AlgorithmTools
                .getSignatureAlgorithms(thisCa.getCACertificate().getPublicKey()).iterator().next();
        if (testSigAlg == null) {
            testSigAlg = "SHA1WithRSA";
        }
        // Sign with imported private key
        byte[] input = "Test data...".getBytes();
        Signature signature = Signature.getInstance(testSigAlg, "BC");
        signature.initSign(p12PrivateSignatureKey);
        signature.update(input);
        byte[] signed = signature.sign();
        // Verify with public key from CA certificate
        signature = Signature.getInstance(testSigAlg, "BC");
        signature.initVerify(thisCa.getCACertificate().getPublicKey());
        signature.update(input);
        if (!signature.verify(signed)) {
            throw new Exception("Could not use private key for verification. Wrong p12-file for this CA?");
        }
        // Import the keys and save to database
        CAToken catoken = importKeysToCAToken(authenticationToken, keystorepass, thisCAToken.getProperties(),
                p12PrivateSignatureKey, p12PublicSignatureKey, p12PrivateEncryptionKey, p12PublicEncryptionKey,
                signatureCertChain, thisCa.getCAId());
        thisCa.setCAToken(catoken);
        // Finally save the CA
        caSession.editCA(authenticationToken, thisCa, true);
        // Log
        final String detailsMsg = intres.getLocalizedMessage("caadmin.restoredcakeystore",
                Integer.valueOf(thisCa.getCAId()));
        auditSession.log(EjbcaEventTypes.CA_RESTORETOKEN, EventStatus.SUCCESS, ModuleTypes.CA,
                ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(thisCa.getCAId()), null, null,
                detailsMsg);
    } catch (Exception e) {
        final String detailsMsg = intres.getLocalizedMessage("caadmin.errorrestorecakeystore", caname, "PKCS12",
                e.getMessage());
        auditSession.log(EjbcaEventTypes.CA_RESTORETOKEN, EventStatus.FAILURE, ModuleTypes.CA,
                ServiceTypes.CORE, authenticationToken.toString(), null, null, null, detailsMsg);
        throw new EJBException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<restoreCAKeyStore");
    }
}

From source file:com.vmware.identity.idm.client.TenantManagementTest.java

@TestOrderAnnotation(order = 3)
@Test//  w ww . j  a  v  a 2 s.  c om
public void testImportExportExternalIDPConfiguration() throws Exception, IDMException {
    CasIdmClient idmClient = getIdmClient();

    Properties props = getTestProperties();

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

    builderFactory.setNamespaceAware(true);

    DocumentBuilder builder = builderFactory.newDocumentBuilder();

    builder.setErrorHandler(new SamlParserErrorHandler());

    Document externalIDPDoc = builder.parse(getClass().getResourceAsStream(_impExternalIDPConfigFile));

    Document externalIDPNoSLODoc = builder
            .parse(getClass().getResourceAsStream(_impExternalIDPNoSLOConfigFile));

    IdmClientTestUtil.ensureTenantExists(idmClient, _impTenantName);

    //get the certificates in order and key to setup the tenant's credentials
    String password = props.getProperty(CFG_KEY_STS_KEYSTORE_PASSWORD);

    KeyStore ks = loadKeyStore(CFG_KEY_STS_KEYSTORE, CFG_KEY_STS_KEYSTORE_PASSWORD);
    Certificate certForPrivKeyEntry = ks.getCertificate(props.getProperty(CFG_KEY_STS_KEY_ALIAS));
    Certificate certAlias1 = ks.getCertificate(props.getProperty(CFG_KEY_STS_KEY_ALIAS1));

    PrivateKey key = (PrivateKey) ks.getKey(props.getProperty(CFG_KEY_STS_KEY_ALIAS), password.toCharArray());

    idmClient.setTenantCredentials(_impTenantName, Arrays.asList(certForPrivKeyEntry, certAlias1), key);

    String importedEntityId = null;
    try {
        //import
        importedEntityId = idmClient.importExternalIDPConfiguration(_impTenantName, externalIDPNoSLODoc);
        importedEntityId = idmClient.importExternalIDPConfiguration(_impTenantName, externalIDPDoc);
        Collection<IDPConfig> idpConfigs = idmClient.getAllExternalIdpConfig(_impTenantName);
        Assert.assertEquals(idpConfigs.size(), 1);

        //export
        // include optional data for external IDPs
        Document castleAsSPProfileDoc = idmClient.exportExternalIDPFederation(_impTenantName, true);
        persistDoc(castleAsSPProfileDoc, _expCastleAsSPProfileFile);
        loadFileAndvalidate(idmClient, _expCastleAsSPProfileFile);

        // w/o optional data
        castleAsSPProfileDoc = idmClient.exportExternalIDPFederation(_impTenantName, false);
        persistDoc(castleAsSPProfileDoc, _expCastleAsSPProfileFileNoOptionalExternalIDPData);
        loadFileAndvalidate(idmClient, _expCastleAsSPProfileFileNoOptionalExternalIDPData);
    } finally {
        //cleanup, note that any partial import has been clean up by the import API
        if (null != importedEntityId) {
            idmClient.removeExternalIdpConfig(_impTenantName, importedEntityId);
        }
    }
}

From source file:com.vmware.identity.idm.client.TenantManagementTest.java

/**
 * Place this after set testings so the properties are available
 *
 * @throws Exception//from ww  w  .j  a  v a  2s.  co  m
 * @throws IDMException
 */
@TestOrderAnnotation(order = 31)
@Test
public void testExportTenantConfiguration() throws Exception, IDMException {
    CasIdmClient idmClient = getIdmClient();

    Properties props = getTestProperties();

    String tenantName = _expTenantName;

    Tenant tenant = IdmClientTestUtil.ensureTenantExists(idmClient, tenantName);

    Assert.assertNotNull(tenant);

    List<Certificate> certList = new ArrayList<Certificate>();

    KeyStore ks = loadKeyStore(CFG_KEY_STS_KEYSTORE, CFG_KEY_STS_KEYSTORE_PASSWORD);

    String alias = props.getProperty(CFG_KEY_STS_KEY_ALIAS);

    Assert.assertNotNull(alias);

    certList.add(ks.getCertificate(alias));

    String alias1 = props.getProperty(CFG_KEY_STS_KEY_ALIAS1);

    Assert.assertNotNull(alias1);

    certList.add(ks.getCertificate(alias1));

    String password = props.getProperty(CFG_KEY_STS_KEYSTORE_PASSWORD);

    PrivateKey key = (PrivateKey) ks.getKey(alias, password.toCharArray());

    idmClient.setTenantCredentials(tenantName, certList, key);

    try {
        exportTest(idmClient, true);
        exportTest(idmClient, false);

    } catch (Exception e) {
        throw new AssertionError(e);
    }

}

From source file:com.vmware.identity.idm.client.TenantManagementTest.java

@TestOrderAnnotation(order = 13)
@Test// w w  w. j  a  va2 s.c o  m
public void testSetTenantCredentials() throws Exception, IDMException {
    CasIdmClient idmClient = getIdmClient();

    Properties props = getTestProperties();

    String tenantName = props.getProperty(CFG_KEY_IDM_TENANT_1_NAME);

    Assert.assertNotNull(tenantName);

    Tenant tenant = IdmClientTestUtil.ensureTenantExists(idmClient, tenantName);

    Assert.assertNotNull(tenant);

    List<Certificate> certList = new ArrayList<Certificate>();

    KeyStore ks = loadKeyStore(CFG_KEY_STS_KEYSTORE, CFG_KEY_STS_KEYSTORE_PASSWORD);

    String alias = props.getProperty(CFG_KEY_STS_KEY_ALIAS);

    Assert.assertNotNull(alias);

    certList.add(ks.getCertificate(alias));

    String alias1 = props.getProperty(CFG_KEY_STS_KEY_ALIAS1);

    Assert.assertNotNull(alias1);

    Certificate trustedRootCert = ks.getCertificate(alias1);
    certList.add(trustedRootCert);

    String password = props.getProperty(CFG_KEY_STS_KEYSTORE_PASSWORD);

    PrivateKey key = (PrivateKey) ks.getKey(alias, password.toCharArray());

    idmClient.setTenantCredentials(tenantName, certList, key);

    List<Certificate> certList2 = idmClient.getTenantCertificate(tenantName);

    Assert.assertNotNull(certList2);
    Assert.assertEquals(2, certList2.size());

    PrivateKey key2 = idmClient.getTenantPrivateKey(tenantName);

    Assert.assertNotNull(key2);

    // Attempt to delete trusted Root certificate that is the active signerIdentity
    try {
        idmClient.deleteCertificate(tenantName,
                CertificateUtil.generateFingerprint((X509Certificate) trustedRootCert),
                CertificateType.STS_TRUST_CERT);
    } catch (CertificateInUseException e) {
        //Expect to reach here
        try {
            idmClient.deleteCertificate(tenantName,
                    CertificateUtil.generateFingerprint((X509Certificate) trustedRootCert),
                    CertificateType.LDAP_TRUSTED_CERT);
        } catch (NoSuchCertificateException e1) {
            //Expect to reach here
            return;
        }

        Assert.fail("Should not reach here, "
                + "attempting to remove an in-existing trusted Root Certificate should fail.");
    }

    Assert.fail("Should not reach here, "
            + "attempting to remove a trusted Root Certificate that is the root of active signerIdentity should be denied.");
}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

private static void exportIdPMetadata(Options options, CommandLine cmd, TremoloType tt, KeyStore ks)
        throws Exception, KeyStoreException, CertificateEncodingException, NoSuchAlgorithmException,
        UnrecoverableKeyException, SecurityException, MarshallingException, SignatureException {

    InitializationService.initialize();//ww  w  . j  ava 2  s.c o  m

    logger.info("Finding IdP...");
    String idpName = loadOption(cmd, "idpName", options);

    ApplicationType idp = null;

    for (ApplicationType app : tt.getApplications().getApplication()) {
        if (app.getName().equalsIgnoreCase(idpName)) {
            idp = app;
        }
    }

    if (idp == null) {
        throw new Exception("IdP '" + idpName + "' not found");
    }

    logger.info("Loading the base URL");
    String baseURL = loadOption(cmd, "urlBase", options);

    String url = baseURL + idp.getUrls().getUrl().get(0).getUri();

    SecureRandom random = new SecureRandom();
    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);

    StringBuffer b = new StringBuffer();
    b.append('f').append(Hex.encodeHexString(idBytes));
    String id = b.toString();

    EntityDescriptorBuilder edb = new EntityDescriptorBuilder();
    EntityDescriptor ed = edb.buildObject();
    ed.setID(id);
    ed.setEntityID(url);

    IDPSSODescriptorBuilder idpssdb = new IDPSSODescriptorBuilder();
    IDPSSODescriptor sd = idpssdb.buildObject();//ed.getSPSSODescriptor("urn:oasis:names:tc:SAML:2.0:protocol");
    sd.addSupportedProtocol("urn:oasis:names:tc:SAML:2.0:protocol");
    ed.getRoleDescriptors().add(sd);

    HashMap<String, List<String>> params = new HashMap<String, List<String>>();
    for (ParamType pt : idp.getUrls().getUrl().get(0).getIdp().getParams()) {
        List<String> vals = params.get(pt.getName());
        if (vals == null) {
            vals = new ArrayList<String>();
            params.put(pt.getName(), vals);
        }
        vals.add(pt.getValue());
    }

    sd.setWantAuthnRequestsSigned(params.containsKey("requireSignedAuthn")
            && params.get("requireSignedAuthn").get(0).equalsIgnoreCase("true"));

    KeyDescriptorBuilder kdb = new KeyDescriptorBuilder();

    if (params.get("encKey") != null && !params.get("encKey").isEmpty()
            && (ks.getCertificate(params.get("encKey").get(0)) != null)) {
        KeyDescriptor kd = kdb.buildObject();
        kd.setUse(UsageType.ENCRYPTION);
        KeyInfoBuilder kib = new KeyInfoBuilder();
        KeyInfo ki = kib.buildObject();

        X509DataBuilder x509b = new X509DataBuilder();
        X509Data x509 = x509b.buildObject();
        X509CertificateBuilder certb = new X509CertificateBuilder();
        org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
        cert.setValue(Base64.encode(ks.getCertificate(params.get("encKey").get(0)).getEncoded()));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sd.getKeyDescriptors().add(kd);

    }

    if (params.get("sigKey") != null && !params.get("sigKey").isEmpty()
            && (ks.getCertificate(params.get("sigKey").get(0)) != null)) {
        KeyDescriptor kd = kdb.buildObject();
        kd.setUse(UsageType.SIGNING);
        KeyInfoBuilder kib = new KeyInfoBuilder();
        KeyInfo ki = kib.buildObject();

        X509DataBuilder x509b = new X509DataBuilder();
        X509Data x509 = x509b.buildObject();
        X509CertificateBuilder certb = new X509CertificateBuilder();
        org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
        cert.setValue(Base64.encode(ks.getCertificate(params.get("sigKey").get(0)).getEncoded()));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sd.getKeyDescriptors().add(kd);

    }

    HashSet<String> nameids = new HashSet<String>();

    for (TrustType trustType : idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust()) {
        for (ParamType pt : trustType.getParam()) {
            if (pt.getName().equalsIgnoreCase("nameIdMap")) {
                String val = pt.getValue().substring(0, pt.getValue().indexOf('='));
                if (!nameids.contains(val)) {
                    nameids.add(val);
                }
            }
        }
    }

    NameIDFormatBuilder nifb = new NameIDFormatBuilder();

    for (String nidf : nameids) {
        NameIDFormat nif = nifb.buildObject();
        nif.setFormat(nidf);
        sd.getNameIDFormats().add(nif);
    }

    SingleSignOnServiceBuilder ssosb = new SingleSignOnServiceBuilder();
    SingleSignOnService sso = ssosb.buildObject();
    sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    sso.setLocation(url + "/httpPost");
    sd.getSingleSignOnServices().add(sso);

    sso = ssosb.buildObject();
    sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
    sso.setLocation(url + "/httpRedirect");
    sd.getSingleSignOnServices().add(sso);

    String signingKey = loadOptional(cmd, "signMetadataWithKey", options);

    if (signingKey != null && ks.getCertificate(signingKey) != null) {
        BasicX509Credential signingCredential = new BasicX509Credential(
                (X509Certificate) ks.getCertificate(signingKey),
                (PrivateKey) ks.getKey(signingKey, tt.getKeyStorePassword().toCharArray()));

        Signature signature = OpenSAMLUtils.buildSAMLObject(Signature.class);

        signature.setSigningCredential(signingCredential);
        signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
        signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

        ed.setSignature(signature);
        try {
            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(ed).marshall(ed);
        } catch (MarshallingException e) {
            throw new RuntimeException(e);
        }
        Signer.signObject(signature);
    }

    // Get the Subject marshaller
    EntityDescriptorMarshaller marshaller = new EntityDescriptorMarshaller();

    // Marshall the Subject
    Element assertionElement = marshaller.marshall(ed);

    logger.info(net.shibboleth.utilities.java.support.xml.SerializeSupport.nodeToString(assertionElement));
}