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.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSignerTest.java

/**
 * teste passando apenas o hash do arquivo
 *///from   w ww  . j a v a  2s .co  m
//@Test
public void testSignWithHash() {
    try {

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

        // INFORMAR o arquivo para gerar o hash
        String fileDirName = "/home/teste.txt";

        byte[] fileToSign = readContent(fileDirName);

        // Para certificado em arquivo A1  preciso essa senha para PrivateKey
        // para token troque a senha em: getKeyStoreToken()
        char[] senha = "senha".toCharArray();

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

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

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

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

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

        // gera o hash do arquivo
        java.security.MessageDigest md = java.security.MessageDigest
                .getInstance(DigestAlgorithmEnum.SHA_512.getAlgorithm());

        // devido a uma restrio do token branco, no windws s funciona com 256
        if (org.demoiselle.signer.core.keystore.loader.configuration.Configuration.getInstance().getSO()
                .toLowerCase().indexOf("indows") > 0) {
            md = java.security.MessageDigest.getInstance(DigestAlgorithmEnum.SHA_256.getAlgorithm());
        }

        byte[] hash = md.digest(fileToSign);

        String contentEncoded = Base64.encodeBase64String(fileToSign);
        System.out.println("contentEncoded : " + contentEncoded);
        String hashEncoded = new String(Base64.encodeBase64(hash));
        System.out.println("hashEncoded: " + hashEncoded);

        // seta o algoritmo de acordo com o que foi gerado o Hash
        signer.setAlgorithm(SignerAlgorithmEnum.SHA512withRSA);
        if (org.demoiselle.signer.core.keystore.loader.configuration.Configuration.getInstance().getSO()
                .toLowerCase().indexOf("indows") > 0) {
            signer.setAlgorithm(SignerAlgorithmEnum.SHA256withRSA);
        }

        // Para certificado em arquivo A1
        // signer.setPrivateKey((PrivateKey) ks.getKey(alias,senha));

        // Para certificado em token
        signer.setPrivateKey((PrivateKey) ks.getKey(alias, null));

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

        /* Realiza a assinatura do conteudo */
        System.out.println("Efetuando a  assinatura do hash");
        byte[] signature = signer.doHashSign(hash);
        String signatureEncoded = new String(Base64.encodeBase64(signature));
        System.out.println("signatureEncoded :" + signatureEncoded);
        File file = new File(fileDirName + ".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:com.t2tierp.controller.nfe.CancelaNfe.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public Map cancelaNfe(String alias, KeyStore ks, char[] senha, String codigoUf, String ambiente,
        String chaveAcesso, String numeroProtocolo, String justificativa, String cnpj) throws Exception {
    String versaoDados = "1.00";
    String url = "";
    if (codigoUf.equals("53")) {
        if (ambiente.equals("1")) {
            url = "https://nfe.sefazvirtual.rs.gov.br/ws/recepcaoevento/recepcaoevento.asmx";
        } else if (ambiente.equals("2")) {
            url = "https://homologacao.nfe.sefazvirtual.rs.gov.br/ws/recepcaoevento/recepcaoevento.asmx";
        }/*  www . j av a2s.c o  m*/
    }
    /* fica a cargo de cada participante definir a url que ser utiizada de acordo com o cdigo da UF
     * URLs disponveis em:
     * Homologao: http://hom.nfe.fazenda.gov.br/PORTAL/WebServices.aspx
     * Produo: 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);
    }

    SimpleDateFormat formatoIso = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
    String dataHoraEvento = formatoIso.format(new Date());

    String xmlCanc = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
            + "<envEvento xmlns=\"http://www.portalfiscal.inf.br/nfe\" versao=\"" + versaoDados + "\">"
            + "<idLote>1</idLote>" + "<evento versao=\"" + versaoDados + "\">" + "<infEvento Id=\"ID" + "110111"
            + chaveAcesso + "01\">" + "<cOrgao>" + codigoUf + "</cOrgao>" + "<tpAmb>" + ambiente + "</tpAmb>"
            + "<CNPJ>" + cnpj + "</CNPJ>" + "<chNFe>" + chaveAcesso + "</chNFe>" + "<dhEvento>" + dataHoraEvento
            + "</dhEvento>" + "<tpEvento>110111</tpEvento>" + "<nSeqEvento>1</nSeqEvento>" + "<verEvento>"
            + versaoDados + "</verEvento>" + "<detEvento versao=\"" + versaoDados + "\">"
            + "<descEvento>Cancelamento</descEvento>" + "<nProt>" + numeroProtocolo + "</nProt>" + "<xJust>"
            + justificativa + "</xJust>" + "</detEvento>" + "</infEvento>" + "</evento>" + "</envEvento>";

    xmlCanc = Biblioteca.assinaXML(xmlCanc, alias, ks, senha, "#ID110111" + chaveAcesso + "01", "evento",
            "infEvento", "Id");

    X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
    PrivateKey privatekey = (PrivateKey) ks.getKey(alias, senha);
    SocketFactoryDinamico socketFactory = new SocketFactoryDinamico(certificate, privatekey);
    //arquivo que contm a cadeia de certificados do servio a ser consumido
    socketFactory.setFileCacerts(this.getClass().getResourceAsStream("/br/inf/portalfiscal/nfe/jssecacerts"));

    //define o protocolo a ser utilizado na conexo
    Protocol protocol = new Protocol("https", socketFactory, 443);
    Protocol.registerProtocol("https", protocol);

    OMElement omElement = AXIOMUtil.stringToOM(xmlCanc);

    RecepcaoEventoStub.NfeDadosMsg dadosMsg = new RecepcaoEventoStub.NfeDadosMsg();
    dadosMsg.setExtraElement(omElement);

    RecepcaoEventoStub.NfeCabecMsg cabecMsg = new RecepcaoEventoStub.NfeCabecMsg();
    cabecMsg.setCUF(codigoUf);
    cabecMsg.setVersaoDados(versaoDados);

    RecepcaoEventoStub.NfeCabecMsgE cabecMsgE = new RecepcaoEventoStub.NfeCabecMsgE();
    cabecMsgE.setNfeCabecMsg(cabecMsg);

    RecepcaoEventoStub stub = new RecepcaoEventoStub(url);

    RecepcaoEventoStub.NfeRecepcaoEventoResult result = stub.nfeRecepcaoEvento(dadosMsg, cabecMsgE);

    ByteArrayInputStream in = new ByteArrayInputStream(result.getExtraElement().toString().getBytes());

    JAXBContext jc = JAXBContext.newInstance("br.inf.portalfiscal.nfe.retevento");
    Unmarshaller unmarshaller = jc.createUnmarshaller();

    JAXBElement<br.inf.portalfiscal.nfe.retevento.TRetEnvEvento> retEvento = (JAXBElement) unmarshaller
            .unmarshal(in);

    Map map = new HashMap();
    if (retEvento.getValue().getRetEvento().get(0).getInfEvento().getCStat().equals("135")) {
        map.put("nfeCancelada", true);
        xmlCanc = xmlCancelamento(retEvento.getValue(), versaoDados, codigoUf, ambiente, chaveAcesso,
                numeroProtocolo, justificativa, cnpj, dataHoraEvento);
        xmlCanc = xmlCanc.replaceAll("xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\"", "");

        xmlCanc = Biblioteca.assinaXML(xmlCanc, alias, ks, senha, "#ID110111" + chaveAcesso + "01", "evento",
                "infEvento", "Id");
        map.put("xmlCancelamento", xmlCanc);
    } else {
        map.put("nfeCancelada", false);
    }
    map.put("motivo1", retEvento.getValue().getXMotivo());
    map.put("motivo2", retEvento.getValue().getRetEvento().get(0).getInfEvento().getXMotivo());

    return map;
}

From source file:org.lockss.util.KeyStoreUtil.java

private static void initializeKeyStore(KeyStore keyStore, String domainName, String password)
        throws IOException, CertificateException, InvalidKeyException, SignatureException,
        NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, UnrecoverableKeyException {
    String keyAlias = domainName + keySuffix;
    String certAlias = domainName + crtSuffix;
    String keyStorePassword = domainName;
    String keyStoreFileName = domainName + ".jceks";
    File keyStoreFile = new File(keyStoreFileName);
    if (keyStoreFile.exists()) {
        log.debug("Key store file " + keyStoreFileName + " exists");
        throw new IOException("Key store file " + keyStoreFileName + " exists");
    }//  w  w w  .  j  a  va 2s.com
    String keyAlgName = "RSA";
    String sigAlgName = "MD5WithRSA";
    log.debug("About to create a CertAndKeyGen: " + keyAlgName + " " + sigAlgName);
    CertAndKeyGen keypair;
    try {
        keypair = new CertAndKeyGen(keyAlgName, sigAlgName);
    } catch (NoSuchAlgorithmException e) {
        log.debug("new CertAndKeyGen(" + keyAlgName + "," + sigAlgName + ") threw " + e);
        throw e;
    }
    log.debug("About to generate a key pair");
    try {
        keypair.generate(1024);
    } catch (InvalidKeyException e) {
        log.debug("keypair.generate(1024) threw " + e);
        throw e;
    }
    log.debug("About to get a PrivateKey");
    PrivateKey privKey = keypair.getPrivateKey();
    log.debug("MyKey: " + privKey.getAlgorithm() + " " + privKey.getFormat());
    log.debug("About to get a self-signed certificate");
    X509Certificate[] chain = new X509Certificate[1];
    X500Name x500Name = new X500Name(
            "CN=" + domainName + ", " + "OU=LOCKSS Team, O=Stanford, " + "L=Stanford, S=California, C=US");
    chain[0] = keypair.getSelfCertificate(x500Name, 365 * 24 * 60 * 60);
    log.debug("Certificate: " + chain[0].toString());
    log.debug("About to keyStore.load(null)");
    try {
        keyStore.load(null, keyStorePassword.toCharArray());
    } catch (IOException e) {
        log.debug("keyStore.load() threw " + e);
        throw e;
    } catch (CertificateException e) {
        log.debug("keyStore.load() threw " + e);
        throw e;
    } catch (NoSuchAlgorithmException e) {
        log.debug("keyStore.load() threw " + e);
        throw e;
    }
    log.debug("About to store " + certAlias + " in key store");
    try {
        keyStore.setCertificateEntry(certAlias, chain[0]);
    } catch (KeyStoreException e) {
        log.debug("keyStore.setCertificateEntry() threw " + e);
        throw e;
    }
    log.debug("About to store " + keyAlias + " in key store");
    try {
        keyStore.setKeyEntry(keyAlias, privKey, password.toCharArray(), chain);
    } catch (KeyStoreException e) {
        log.debug("keyStore.setKeyEntry() threw " + e);
        throw e;
    }
    log.debug("About to getKeyEntry()");
    Key myKey = keyStore.getKey(keyAlias, password.toCharArray());
    log.debug("MyKey: " + myKey.getAlgorithm() + " " + myKey.getFormat());
    log.debug("Done storing");
}

From source file:org.lockss.protocol.BlockingStreamComm.java

private void logKeyStore(KeyStore ks, char[] privateKeyPassWord) {
    log.debug3("start of key store");
    try {//from   w  ww  .j a v  a 2  s .  co m
        for (Enumeration en = ks.aliases(); en.hasMoreElements();) {
            String alias = (String) en.nextElement();
            log.debug3("Next alias " + alias);
            if (ks.isCertificateEntry(alias)) {
                log.debug3("About to Certificate");
                java.security.cert.Certificate cert = ks.getCertificate(alias);
                if (cert == null) {
                    log.debug3(alias + " null cert chain");
                } else {
                    log.debug3("Cert for " + alias + " is " + cert.toString());
                }
            } else if (ks.isKeyEntry(alias)) {
                log.debug3("About to getKey");
                Key privateKey = ks.getKey(alias, privateKeyPassWord);
                log.debug3(alias + " key " + privateKey.getAlgorithm() + "/" + privateKey.getFormat());
            } else {
                log.debug3(alias + " neither key nor cert");
            }
        }
        log.debug3("end of key store");
    } catch (Exception ex) {
        log.error("logKeyStore() threw " + ex);
    }
}

From source file:com.ext.portlet.epsos.EpsosHelperService.java

@SuppressWarnings("deprecation")
public static void signSAMLAssertion(SignableSAMLObject as, String keyAlias, char[] keyPassword)
        throws Exception {
    //String KEY_STORE_NAME="Unknown-1";
    //String KEY_STORE_PASS="spirit";
    //String PRIVATE_KEY_PASS="spirit";
    //String KEY_ALIAS="server1";

    ConfigurationManagerService cms = ConfigurationManagerService.getInstance();

    //String KEY_STORE_NAME =GetterUtil.getString(GnPropsUtil.get("portalb", "KEYSTORE_LOCATION"),"Unknown-1");

    String KEYSTORE_LOCATION = cms.getProperty("javax.net.ssl.keyStore");
    String KEY_STORE_PASS = cms.getProperty("javax.net.ssl.keyStorePassword"); //GetterUtil.getString(GnPropsUtil.get("portalb", "KEYSTORE_PASSWORD"),"spirit");
    String KEY_ALIAS = cms.getProperty("javax.net.ssl.key.alias"); //GetterUtil.getString(GnPropsUtil.get("portalb", "PRIVATEKEY_ALIAS"),"server1");
    String PRIVATE_KEY_PASS = cms.getProperty("javax.net.ssl.privateKeyPassword"); //GetterUtil.getString(GnPropsUtil.get("portalb", "PRIVATEKEY_PASSWORD"),"spirit");
    _log.debug("-------" + KEYSTORE_LOCATION);
    _log.debug("-------" + KEY_STORE_PASS);
    _log.debug("-------" + KEY_ALIAS);
    _log.debug("-------" + PRIVATE_KEY_PASS);

    KeyStoreManager keyManager = new DefaultKeyStoreManager();
    //KeyPair kp = null;
    X509Certificate cert = null;/*from  ww w . java 2s  .  c  om*/
    //check if we must use the default key
    PrivateKey privateKey = null;
    PublicKey publicKey = null;
    if (keyAlias == null) {
        // kp = keyManager.getDefaultPrivateKey();
        cert = (X509Certificate) keyManager.getDefaultCertificate();

    } else {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        File file = new File(KEYSTORE_LOCATION);
        keyStore.load(new FileInputStream(file), KEY_STORE_PASS.toCharArray());

        privateKey = (PrivateKey) keyStore.getKey(KEY_ALIAS, PRIVATE_KEY_PASS.toCharArray());

        X509Certificate cert1 = (X509Certificate) keyStore.getCertificate(KEY_ALIAS);
        publicKey = cert1.getPublicKey();

        //kp = keyManager.getPrivateKey(keyAlias, keyPassword);
        cert = (X509Certificate) keyManager.getCertificate(keyAlias);
    }

    org.opensaml.xml.signature.Signature sig = (org.opensaml.xml.signature.Signature) Configuration
            .getBuilderFactory().getBuilder(org.opensaml.xml.signature.Signature.DEFAULT_ELEMENT_NAME)
            .buildObject(org.opensaml.xml.signature.Signature.DEFAULT_ELEMENT_NAME);

    Credential signingCredential = SecurityHelper.getSimpleCredential(cert, privateKey);

    //sig.setCanonicalizationAlgorithm(SignatureConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
    sig.setSigningCredential(signingCredential);
    // sig.setKeyInfo(SecurityHelper.getKeyInfoGenerator(signingCredential, null, null).generate(signingCredential));
    sig.setSignatureAlgorithm("http://www.w3.org/2000/09/xmldsig#rsa-sha1");
    sig.setCanonicalizationAlgorithm("http://www.w3.org/2001/10/xml-exc-c14n#");

    SecurityConfiguration secConfig = Configuration.getGlobalSecurityConfiguration();
    try {
        SecurityHelper.prepareSignatureParams(sig, signingCredential, secConfig, null);
    } catch (SecurityException e) {
        throw new SMgrException(e.getMessage(), e);
    }

    as.setSignature(sig);
    try {
        Configuration.getMarshallerFactory().getMarshaller(as).marshall(as);
    } catch (MarshallingException e) {
        throw new SMgrException(e.getMessage(), e);
    }
    try {
        org.opensaml.xml.signature.Signer.signObject(sig);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

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

private static void exportSPMetaData(Options options, CommandLine cmd, TremoloType tt, KeyStore ks)
        throws Exception, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException,
        CertificateEncodingException, MarshallingException {
    logger.info("Finding mechanism...");
    String mechanismName = loadOption(cmd, "mechanismName", options);
    MechanismType saml2Mech = loadMechanismType(mechanismName, tt);
    logger.info("...found");

    logger.info("Finding chain...");
    String chainName = loadOption(cmd, "chainName", options);

    AuthChainType act = loadChainType(chainName, tt);

    logger.info("Looking for correct mechanism on the chain...");
    AuthMechType currentMechanism = null;
    for (AuthMechType amt : act.getAuthMech()) {
        if (amt.getName().equalsIgnoreCase(mechanismName)) {
            currentMechanism = amt;// w  ww. jav a  2s . co m
            break;
        }
    }

    if (currentMechanism == null) {
        System.err.println("Unknown chain on mechanism");
        System.exit(1);
    }

    InitializationService.initialize();

    logger.info("loading url base");

    String urlBase = loadOption(cmd, "urlBase", options);

    String url = urlBase + saml2Mech.getUri();

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

    String id = "f" + Hex.encodeHexString(idBytes);

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

    SPSSODescriptorBuilder spb = new SPSSODescriptorBuilder();
    SPSSODescriptorImpl sp = (SPSSODescriptorImpl) spb.buildObject();
    ed.getRoleDescriptors().add(sp);

    HashMap<String, ParamType> params = new HashMap<String, ParamType>();
    for (ParamType pt : currentMechanism.getParams().getParam()) {
        params.put(pt.getName(), pt);
    }

    boolean assertionsSigned = params.get("assertionsSigned") != null
            && params.get("assertionsSigned").getValue().equalsIgnoreCase("true");
    sp.setWantAssertionsSigned(assertionsSigned);
    sp.addSupportedProtocol("urn:oasis:names:tc:SAML:2.0:protocol");

    SingleLogoutServiceBuilder slsb = new SingleLogoutServiceBuilder();
    SingleLogoutService sls = slsb.buildObject();
    sls.setLocation(url);
    sls.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
    sp.getSingleLogoutServices().add(sls);

    sls = slsb.buildObject();
    sls.setLocation(url);
    sls.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    sp.getSingleLogoutServices().add(sls);

    AssertionConsumerServiceBuilder acsb = new AssertionConsumerServiceBuilder();
    AssertionConsumerService acs = acsb.buildObject();
    acs.setLocation(url);
    acs.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    acs.setIndex(0);
    acs.setIsDefault(true);
    sp.getAssertionConsumerServices().add(acs);

    acs = acsb.buildObject();
    acs.setLocation(url);
    acs.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
    acs.setIndex(1);
    sp.getAssertionConsumerServices().add(acs);

    if (params.get("spSigKey") != null && !params.get("spSigKey").getValue().isEmpty()) {
        String alias = params.get("spSigKey").getValue();
        X509Certificate certFromKS = (X509Certificate) ks.getCertificate(alias);

        if (certFromKS == null) {
            throw new Exception("Certificate '" + params.get("spSigKey").getValue() + "' not found");
        }

        PrivateKey keyFromKS = (PrivateKey) ks.getKey(alias, tt.getKeyStorePassword().toCharArray());
        KeyDescriptorBuilder kdb = new KeyDescriptorBuilder();
        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(new String(Base64.encode(certFromKS.getEncoded())));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sp.getKeyDescriptors().add(kd);

    }

    if (params.get("spEncKey") != null && !params.get("spEncKey").getValue().isEmpty()) {
        String alias = params.get("spEncKey").getValue();
        X509Certificate certFromKS = (X509Certificate) ks.getCertificate(alias);

        if (certFromKS == null) {
            throw new Exception("Certificate '" + params.get("spEncKey").getValue() + "' not found");
        }

        PrivateKey keyFromKS = (PrivateKey) ks.getKey(alias, tt.getKeyStorePassword().toCharArray());
        KeyDescriptorBuilder kdb = new KeyDescriptorBuilder();
        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(new String(Base64.encode(certFromKS.getEncoded())));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sp.getKeyDescriptors().add(kd);

    }

    EntityDescriptorMarshaller marshaller = new EntityDescriptorMarshaller();

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

    String xml = net.shibboleth.utilities.java.support.xml.SerializeSupport.prettyPrintXML(assertionElement);

    logger.info(xml);
}

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

/**
 * This method will list 1. Certificate aliases 2. Private key alise 3. Private key value to a
 * given keystore./*from  w ww.jav  a2 s  . c o  m*/
 *
 * @param keyStoreName The name of the keystore
 * @return Instance of KeyStoreData
 * @throws SecurityConfigException will be thrown
 */
public KeyStoreData getKeystoreInfo(String keyStoreName) throws SecurityConfigException {
    try {

        if (keyStoreName == null) {
            throw new Exception("keystore name cannot be null");
        }

        KeyStore keyStore;
        String keyStoreType;
        String privateKeyPassowrd = null;
        if (KeyStoreUtil.isPrimaryStore(keyStoreName)) {
            KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
            keyStore = keyMan.getPrimaryKeyStore();
            ServerConfiguration serverConfig = ServerConfiguration.getInstance();
            keyStoreType = serverConfig
                    .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_TYPE);
            privateKeyPassowrd = serverConfig
                    .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD);
        } else {
            String path = SecurityConstants.KEY_STORES + "/" + keyStoreName;
            if (!registry.resourceExists(path)) {
                throw new SecurityConfigException("Key Store not found");
            }
            Resource resource = registry.get(path);
            KeyStoreManager manager = KeyStoreManager.getInstance(tenantId);
            keyStore = manager.getKeyStore(keyStoreName);
            keyStoreType = resource.getProperty(SecurityConstants.PROP_TYPE);

            String encpass = resource.getProperty(SecurityConstants.PROP_PRIVATE_KEY_PASS);
            if (encpass != null) {
                CryptoUtil util = CryptoUtil.getDefaultCryptoUtil();
                privateKeyPassowrd = new String(util.base64DecodeAndDecrypt(encpass));
            }
        }
        // Fill the information about the certificates
        Enumeration<String> aliases = keyStore.aliases();
        List<org.wso2.carbon.security.keystore.service.CertData> certDataList = new ArrayList<>();
        Format formatter = new SimpleDateFormat("dd/MM/yyyy");

        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            if (keyStore.isCertificateEntry(alias)) {
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
                certDataList.add(fillCertData(cert, alias, formatter));
            }
        }

        // Create a cert array
        CertData[] certs = certDataList.toArray(new CertData[certDataList.size()]);

        // Create a KeyStoreData bean, set the name and fill in the cert information
        KeyStoreData keyStoreData = new KeyStoreData();
        keyStoreData.setKeyStoreName(keyStoreName);
        keyStoreData.setCerts(certs);
        keyStoreData.setKeyStoreType(keyStoreType);

        aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            // There be only one entry in WSAS related keystores
            if (keyStore.isKeyEntry(alias)) {
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
                keyStoreData.setKey(fillCertData(cert, alias, formatter));

                PrivateKey key = (PrivateKey) keyStore.getKey(alias, privateKeyPassowrd.toCharArray());
                String pemKey;
                pemKey = "-----BEGIN PRIVATE KEY-----\n";
                pemKey += Base64.encode(key.getEncoded());
                pemKey += "\n-----END PRIVATE KEY-----";
                keyStoreData.setKeyValue(pemKey);
                break;

            }
        }
        return keyStoreData;
    } catch (Exception e) {
        String msg = "Error has encounted while loading the keystore to the given keystore name "
                + keyStoreName;
        log.error(msg, e);
        throw new SecurityConfigException(msg);
    }

}

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

/**
 * This method will list 1. Certificate aliases 2. Private key alise 3. Private key value to a
 * given keystore.//from   ww w .  jav  a 2  s .  c  o m
 *
 * @param keyStoreName The name of the keystore
 * @param pageNumber   page number
 * @return Instance of KeyStoreData
 * @throws SecurityConfigException will be thrown
 */
public PaginatedKeyStoreData getPaginatedKeystoreInfo(String keyStoreName, int pageNumber)
        throws SecurityConfigException {
    try {

        if (keyStoreName == null) {
            throw new Exception("keystore name cannot be null");
        }

        KeyStore keyStore;
        String keyStoreType;
        String privateKeyPassowrd = null;
        if (KeyStoreUtil.isPrimaryStore(keyStoreName)) {
            KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
            keyStore = keyMan.getPrimaryKeyStore();
            ServerConfiguration serverConfig = ServerConfiguration.getInstance();
            keyStoreType = serverConfig
                    .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_TYPE);
            privateKeyPassowrd = serverConfig
                    .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD);
        } else {
            String path = SecurityConstants.KEY_STORES + "/" + keyStoreName;
            if (!registry.resourceExists(path)) {
                throw new SecurityConfigException("Key Store not found");
            }
            Resource resource = registry.get(path);
            KeyStoreManager manager = KeyStoreManager.getInstance(tenantId);
            keyStore = manager.getKeyStore(keyStoreName);
            keyStoreType = resource.getProperty(SecurityConstants.PROP_TYPE);

            String encpass = resource.getProperty(SecurityConstants.PROP_PRIVATE_KEY_PASS);
            if (encpass != null) {
                CryptoUtil util = CryptoUtil.getDefaultCryptoUtil();
                privateKeyPassowrd = new String(util.base64DecodeAndDecrypt(encpass));
            }
        }
        // Fill the information about the certificates
        Enumeration<String> aliases = keyStore.aliases();
        List<org.wso2.carbon.security.keystore.service.CertData> certDataList = new ArrayList<>();
        Format formatter = new SimpleDateFormat("dd/MM/yyyy");

        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            if (keyStore.isCertificateEntry(alias)) {
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
                certDataList.add(fillCertData(cert, alias, formatter));
            }
        }

        // Create a cert array
        CertData[] certs = certDataList.toArray(new CertData[certDataList.size()]);

        // Create a KeyStoreData bean, set the name and fill in the cert information
        PaginatedKeyStoreData keyStoreData = new PaginatedKeyStoreData();
        keyStoreData.setKeyStoreName(keyStoreName);
        keyStoreData.setPaginatedCertData(doPaging(pageNumber, certs));
        keyStoreData.setKeyStoreType(keyStoreType);

        aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            // There be only one entry in WSAS related keystores
            if (keyStore.isKeyEntry(alias)) {
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
                keyStoreData.setKey(fillCertData(cert, alias, formatter));

                PrivateKey key = (PrivateKey) keyStore.getKey(alias, privateKeyPassowrd.toCharArray());
                String pemKey;
                pemKey = "-----BEGIN PRIVATE KEY-----\n";
                pemKey += Base64.encode(key.getEncoded());
                pemKey += "\n-----END PRIVATE KEY-----";
                keyStoreData.setKeyValue(pemKey);
                break;

            }
        }
        return keyStoreData;
    } catch (Exception e) {
        String msg = "Error has encounted while loading the keystore to the given keystore name "
                + keyStoreName;
        log.error(msg, e);
        throw new SecurityConfigException(msg);
    }

}

From source file:org.renci.ahab.ndllib.transport.OrcaSMXMLRPCProxy.java

/**
 * Set the identity for the communications to the XMLRPC controller. Eventually
 * we may talk to several controller with different identities. For now only
 * one is configured./*from  w w w. j a  v a  2  s . co m*/
 */
private void setSSLIdentity() throws Exception {

    //if (sslIdentitySet)
    //   return;

    //System.out.println("In setSSLIdentity()");

    try {
        // create multikeymanager
        mkm = new MultiKeyManager();
        //TODO
        //URL ctrlrUrl = new URL(GUI.getInstance().getSelectedController());
        URL ctrlrUrl = new URL(CONTROLLER_URL);
        // TODO

        // register a new protocol
        ContextualSSLProtocolSocketFactory regSslFact = new ContextualSSLProtocolSocketFactory();

        // add this multikey context factory for the controller host/port
        regSslFact.addHostContextFactory(new MultiKeySSLContextFactory(mkm, trustAllCerts), ctrlrUrl.getHost(),
                ctrlrUrl.getPort());

        if (rmProperties == null) {
            System.out.println("ERROR ... Property File with user credentials not supplied...");
            return;
        }

        KeyStore ks = null;

        //File keyStorePath = loadUserFile("/Users/anirban/Misc/tmp/renci-openvpn/flukes.jks");
        //File certFilePath = loadUserFile("/Users/anirban/.ssl/geni-anirban.pem");
        //File certKeyFilePath = loadUserFile("/Users/anirban/.ssl/geni-anirban.pem");
        File keyStorePath = null;
        File certFilePath = null;
        File certKeyFilePath = null;

        if (rmProperties.getProperty(USER_KEYSTORE_PATH_PROP) != null) {
            keyStorePath = loadUserFile(rmProperties.getProperty(USER_KEYSTORE_PATH_PROP));
        }
        if (rmProperties.getProperty(USER_CERTFILE_PATH_PROP) != null) {
            certFilePath = loadUserFile(rmProperties.getProperty(USER_CERTFILE_PATH_PROP));
        }
        if (rmProperties.getProperty(USER_CERTKEYFILE_PATH_PROP) != null) {
            certKeyFilePath = loadUserFile(rmProperties.getProperty(USER_CERTKEYFILE_PATH_PROP));
        }

        String keyAlias = null, keyPassword = null;
        if (keyStorePath != null && keyStorePath.exists()) {
            // load keystore and get the right cert from it
            System.out.println("Reading auth details from keystore");
            //TODO
            keyAlias = rmProperties.getProperty(USER_KEYSTORE_KEYALIAS_PROP);
            keyPassword = rmProperties.getProperty(USER_KEYSTORE_KEYPASS_PROP);
            //TODO
            FileInputStream jksIS = new FileInputStream(keyStorePath);
            ks = loadJKSData(jksIS, keyAlias, keyPassword);
            jksIS.close();
        } else if (certFilePath != null && certKeyFilePath != null && certFilePath.exists()
                && certKeyFilePath.exists()) {
            System.out.println("Reading auth details from cert file and certkeyfile");
            FileInputStream certIS = new FileInputStream(certFilePath);
            FileInputStream keyIS = new FileInputStream(certKeyFilePath);
            keyAlias = "x509convert";
            //TODO
            keyPassword = rmProperties.getProperty(USER_KEYPASS_PROP);
            //TODO
            ks = loadX509Data(certIS, keyIS, keyAlias, keyPassword);
            certIS.close();
            keyIS.close();
        }

        if (ks == null)
            throw new Exception("Was unable to find either: " + keyStorePath.getCanonicalPath()
                    + " or the pair of: " + certFilePath.getCanonicalPath() + " and "
                    + certKeyFilePath.getCanonicalPath() + " as specified.");

        // check that the spelling of key alias is proper
        Enumeration<String> as = ks.aliases();
        while (as.hasMoreElements()) {
            String a = as.nextElement();
            if (keyAlias.toLowerCase().equals(a.toLowerCase())) {
                keyAlias = a;
                break;
            }
        }

        // alias has to exist and have a key and cert present
        if (!ks.containsAlias(keyAlias)) {
            throw new Exception("Alias " + keyAlias + " does not exist in keystore " + keyStorePath + ".");
        }

        if (ks.getKey(keyAlias, keyPassword.toCharArray()) == null)
            throw new Exception(
                    "Key with alias " + keyAlias + " does not exist in keystore " + keyStorePath + ".");

        if (ks.getCertificate(keyAlias) == null) {
            throw new Exception(
                    "Certificate with alias " + keyAlias + " does not exist in keystore " + keyStorePath + ".");
        }

        if (ks.getCertificate(keyAlias).getType().equals("X.509")) {
            X509Certificate x509Cert = (X509Certificate) ks.getCertificate(keyAlias);
            try {
                x509Cert.checkValidity();
            } catch (Exception e) {
                throw new Exception("Certificate with alias " + keyAlias + " is not yet valid or has expired.");
            }
        }

        // add the identity into it
        mkm.addPrivateKey(keyAlias, (PrivateKey) ks.getKey(keyAlias, keyPassword.toCharArray()),
                ks.getCertificate(keyAlias));

        // before we do SSL to this controller, set our identity
        mkm.setCurrentGuid(keyAlias);

        // register the protocol (Note: All xmlrpc clients must use XmlRpcCommonsTransportFactory
        // for this to work). See ContextualSSLProtocolSocketFactory.
        Protocol reghhttps = new Protocol("https", (ProtocolSocketFactory) regSslFact, 443);
        Protocol.registerProtocol("https", reghhttps);

        sslIdentitySet = true;
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Unable to load user private key and certificate from the keystore: " + e);
    }

    //System.out.println("Exiting setSSLIdentity");

}

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

@Override
public void importCAFromKeyStore(AuthenticationToken admin, String caname, byte[] p12file, String keystorepass,
        String privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) {
    try {/*from   w ww  .  j a v a 2 s  .  c o m*/
        // check authorization
        if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) {
            String msg = intres.getLocalizedMessage("caadmin.notauthorizedtocreateca", caname);
            Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", msg);
            auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    admin.toString(), null, null, null, details);
        }
        // load keystore
        java.security.KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
        keystore.load(new java.io.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());
        log.debug("ImportSignatureKeyAlgorithm=" + p12PrivateSignatureKey.getAlgorithm());

        // 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();
        }
        importCAFromKeys(admin, caname, keystorepass, signatureCertChain, p12PublicSignatureKey,
                p12PrivateSignatureKey, p12PrivateEncryptionKey, p12PublicEncryptionKey);
    } catch (Exception e) {
        String detailsMsg = intres.getLocalizedMessage("caadmin.errorimportca", caname, "PKCS12",
                e.getMessage());
        auditSession.log(EjbcaEventTypes.CA_IMPORT, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), null, null, null, detailsMsg);
        throw new EJBException(e);
    }
}