Example usage for java.security.cert CertificateFactory getInstance

List of usage examples for java.security.cert CertificateFactory getInstance

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory getInstance.

Prototype

public static final CertificateFactory getInstance(String type) throws CertificateException 

Source Link

Document

Returns a certificate factory object that implements the specified certificate type.

Usage

From source file:module.signature.util.XAdESValidator.java

/**
 * @author joao.antunes@tagus.ist.utl.pt adapted it from {@link #validateXMLSignature(String)}
 * @param streamWithSignature/*  w w w . j  av a2  s .c o m*/
 *            the {@link InputStream} that has the signature content
 * @return true if it's valid, false otherwise
 */
public boolean validateXMLSignature(InputStream streamWithSignature) {
    try {

        // get the  xsd schema

        Validator validator = schemaXSD.newValidator();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder parser = dbf.newDocumentBuilder();

        ErrorHandler eh = new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }
        };

        // parse the document
        parser.setErrorHandler(eh);
        Document document = parser.parse(streamWithSignature);

        // XAdES extension
        NodeList nlObject = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Object");
        // XMLDSIG
        NodeList nlSignature = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#",
                "Signature");

        if (checkSchema) {
            if (nlObject.getLength() < 1) {
                return false;
            }
            if (nlSignature.getLength() < 1) {
                return false;
            }

            // parse the XML DOM tree againts the XSD schema
            validator.validate(new DOMSource(nlSignature.item(0)));
        }

        if (checkSignature) {
            // Validate Every Signature Element (including CounterSignatures)
            for (int i = 0; i < nlSignature.getLength(); i++) {

                Element signature = (Element) nlSignature.item(i);
                //          String baseURI = fileToValidate.toURL().toString();
                XMLSignature xmlSig = new XMLSignature(signature, null);

                KeyInfo ki = xmlSig.getKeyInfo();

                // If signature contains X509Data
                if (ki.containsX509Data()) {

                    NodeList nlSigningTime = signature.getElementsByTagNameNS(xadesNS, "SigningTime");
                    Date signingDate = null;

                    if (nlSigningTime.item(0) != null) {
                        StringBuilder xmlDate = new StringBuilder(nlSigningTime.item(0).getTextContent())
                                .deleteCharAt(22);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                        signingDate = simpleDateFormat.parse(xmlDate.toString());
                    }

                    //verificao OCSP
                    //TODO FENIX-189 joantune: na realidade acho que isto no verifica mesmo a revocao.. a no ser que a keystore indicada seja actualizada regularmente.
                    if (checkRevocation) {
                        //keystore certs cc, raiz estado

                        Security.setProperty("ocsp.enable", "true");
                        //System.setProperty("com.sun.security.enableCRLDP", "true");

                        CertificateFactory cf = CertificateFactory.getInstance("X.509");

                        CertPath certPath = cf
                                .generateCertPath(Collections.singletonList(ki.getX509Certificate()));
                        //             TrustAnchor trustA = new TrustAnchor(ki.getX509Certificate(), null);
                        //             Set trustAnchors = Collections.singleton(trustA);

                        PKIXParameters params = new PKIXParameters(cartaoCidadaoKeyStore);
                        params.setRevocationEnabled(true);

                        // validar o estado na data da assinatura
                        if (nlSigningTime.item(0) != null) {
                            params.setDate(signingDate);
                        }

                        try {
                            CertPathValidator cpValidator = CertPathValidator.getInstance("PKIX");
                            CertPathValidatorResult result = cpValidator.validate(certPath, params);
                            //TODO FENIX-196 probably one would want to send a notification here
                        } catch (CertPathValidatorException ex) {
                            return false;
                        } catch (InvalidAlgorithmParameterException ex) {
                            return false;
                        }
                    }

                    // verifica a validade do certificado no momento da assinatura
                    if (checkValidity) {

                        if (nlSigningTime.item(0) != null) { // continue if there is no SigningTime, if CounterSignature isn't XAdES
                            try {
                                ki.getX509Certificate().checkValidity(signingDate);
                            } catch (CertificateExpiredException ex) {
                                return false;
                            } catch (CertificateNotYetValidException ex) {
                                return false;
                            }
                        }
                    }

                    // validate against Certificate Public Key
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getX509Certificate().getPublicKey());

                    if (!validSignature) {
                        return false;
                    }
                }

                // if signature includes KeyInfo KeyValue, also check against it
                if (ki.containsKeyValue()) {
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getPublicKey());
                    if (!validSignature) {
                        return false;
                    }
                }

                //let's check the SignatureTimeStamp(s) joantune

                NodeList signatureTimeStamps = signature.getElementsByTagNameNS("*", "SignatureTimeStamp");
                Element signatureValue = null;
                if (signatureTimeStamps.getLength() > 0) {
                    signatureValue = (Element) signature.getElementsByTagNameNS("*", "SignatureValue").item(0);
                }
                for (int j = 0; j < signatureTimeStamps.getLength(); j++) {
                    logger.debug("Found a SignatureTimeStamp");
                    Element signatureTimeStamp = (Element) signatureTimeStamps.item(j);
                    //for now we are ignoring the XMLTimeStamp element, let's iterate through all of the EncapsulatedTimeStamp that we find
                    NodeList encapsulatedTimeStamps = signatureTimeStamp.getElementsByTagNameNS("*",
                            "EncapsulatedTimeStamp");
                    for (int k = 0; k < encapsulatedTimeStamps.getLength(); k++) {
                        logger.debug("Found an EncapsulatedTimeStamp");
                        Element encapsulatedTimeStamp = (Element) encapsulatedTimeStamps.item(k);
                        //let's check it
                        // note, we have the timestamptoken, not the whole response, that is, we don't have the status field

                        ASN1Sequence signedTimeStampToken = ASN1Sequence
                                .getInstance(Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        CMSSignedData cmsSignedData = new CMSSignedData(
                                Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        TimeStampToken timeStampToken = new TimeStampToken(cmsSignedData);

                        //let's construct the Request to make sure this is a valid response

                        //let's generate the digest
                        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
                        byte[] digest = sha1.digest(signatureValue.getTextContent().getBytes("UTF-8"));

                        //let's make sure the digests are the same
                        if (!Arrays.equals(digest,
                                timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
                            //TODO probably want to send an e-mail if this happens, as it's clearly a sign of tampering
                            //FENIX-196
                            logger.debug("Found a different digest in the timestamp!");
                            return false;
                        }

                        try {
                            //TODO for now we won't use the provided certificates that came with the TST
                            //            X509Store certificateStore = (X509Store) timeStampToken.getCertificates();
                            //            JcaDigestCalculatorProviderBuilder builder = new JcaDigestCalculatorProviderBuilder();
                            //            timeStampToken.validate(tsaCert, "BC");
                            //            timeStampToken.validate(new SignerInformationVerifier(new JcaContentVerifierProviderBuilder()
                            //               .build(tsaCert), builder.build()));
                            timeStampToken.validate(new SignerInformationVerifier(
                                    new JcaContentVerifierProviderBuilder().build(tsaCert),
                                    new BcDigestCalculatorProvider()));
                            //let's just verify that the timestamp was done in the past :) - let's give a tolerance of 5 mins :)
                            Date currentDatePlus5Minutes = new Date();
                            //let's make it go 5 minutes ahead
                            currentDatePlus5Minutes.setMinutes(currentDatePlus5Minutes.getMinutes() + 5);
                            if (!timeStampToken.getTimeStampInfo().getGenTime()
                                    .before(currentDatePlus5Minutes)) {
                                //FENIX-196 probably we want to log this!
                                //what the heck, timestamp is done in the future!! (clocks might be out of sync)
                                logger.warn("Found a timestamp in the future!");
                                return false;
                            }
                            logger.debug("Found a valid TimeStamp!");
                            //as we have no other timestamp elements in this signature, this means all is ok! :) 
                            //(point 5) of g.2.2.16.1.3 on the specs

                        } catch (TSPException exception) {
                            logger.debug("TimeStamp response did not validate", exception);
                            return false;
                        }

                    }
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (SAXException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (Exception ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
    return true;
}

From source file:org.guanxi.idp.service.SSOBase.java

/**
 * Extracts the X509 cenrtificate from a KeyDescriptor
 *
 * @param keyDescriptor the KeyDescriptor containing the X509 certificate
 * @return X509Certificate//w  w w  .ja v a  2s . c  o  m
 * @throws GuanxiException if an error occurs
 */
private X509Certificate getCertFromKeyDescriptor(KeyDescriptorType keyDescriptor) throws GuanxiException {
    try {
        byte[] spCertBytes = keyDescriptor.getKeyInfo().getX509DataArray(0).getX509CertificateArray(0);
        CertificateFactory certFactory = CertificateFactory.getInstance("x.509");
        ByteArrayInputStream certByteStream = new ByteArrayInputStream(spCertBytes);
        X509Certificate metadataCert = (X509Certificate) certFactory.generateCertificate(certByteStream);
        certByteStream.close();
        return metadataCert;
    } catch (CertificateException ce) {
        logger.error("can't get x509 from KeyDescriptor");
        throw new GuanxiException(ce);
    } catch (IOException ioe) {
        logger.error("can't close cert byte stream");
        throw new GuanxiException(ioe);
    }
}

From source file:com.vmware.identity.sts.ws.SignatureValidator.java

/**
 * Decode a byte array to an Certificate object.
 *//*  w  ww .  j  a  va 2s.  co m*/
private X509Certificate decodeCertificate(byte[] certificateDer) {
    assert certificateDer != null;

    ByteArrayInputStream stream = new ByteArrayInputStream(certificateDer);
    CertificateFactory certFactory;
    try {
        certFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new IllegalStateException(
                "Internal error: X.509 Certificate " + "Factory is not available (uncompliant JRE?)", e);
    }

    X509Certificate certificate = null;
    try {
        certificate = (X509Certificate) certFactory.generateCertificate(stream);
    } catch (CertificateException e) {
        throw new WSFaultException(FaultKey.WSSE_INVALID_SECURITY_TOKEN, e);
    }

    return certificate;
}

From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java

/**
 * X509??.//from w ww.  jav a 2  s. c om
 * @param privateKeyFileName ???
 * @param certificateFileName ??
 * @param rootCertificateFileNames ??
 * @throws IOException IOException
 * @throws NoSuchAlgorithmException NoSuchAlgorithmException
 * @throws InvalidKeySpecException InvalidKeySpecException
 * @throws CertificateException CertificateException
 */
public static void configureX509(String privateKeyFileName, String certificateFileName,
        String[] rootCertificateFileNames)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {

    xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");

    // Read RootCA Certificate
    x509RootCertificateFileNames = new ArrayList<String>();
    if (rootCertificateFileNames != null) {
        for (String fileName : rootCertificateFileNames) {
            x509RootCertificateFileNames.add(fileName);
        }
    }

    // Read Private Key
    InputStream is = null;
    if (privateKeyFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_KEY_PATH);
    } else {
        is = new FileInputStream(privateKeyFileName);
    }

    PEMReader privateKeyPemReader = new PEMReader(is);
    byte[] privateKeyDerBytes = privateKeyPemReader.getDerBytes();
    PKCS1EncodedKeySpec keySpecRSAPrivateKey = new PKCS1EncodedKeySpec(privateKeyDerBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    privKey = keyFactory.generatePrivate(keySpecRSAPrivateKey.getKeySpec());

    // Read Certificate
    if (certificateFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_CRT_PATH);
    } else {
        is = new FileInputStream(certificateFileName);
    }
    PEMReader serverCertificatePemReader;
    serverCertificatePemReader = new PEMReader(is);
    byte[] serverCertificateBytesCert = serverCertificatePemReader.getDerBytes();
    CertificateFactory cf = CertificateFactory.getInstance(X509KeySelector.X509KEY_TYPE);
    x509Certificate = (X509Certificate) cf
            .generateCertificate(new ByteArrayInputStream(serverCertificateBytesCert));

    // Create the KeyInfo containing the X509Data
    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    List x509Content = new ArrayList();
    x509Content.add(x509Certificate.getSubjectX500Principal().getName());
    x509Content.add(x509Certificate);
    X509Data xd = keyInfoFactory.newX509Data(x509Content);
    keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(xd));

    // http://java.sun.com/developer/technicalArticles/xml/dig_signature_api/

}

From source file:io.personium.common.auth.token.TransCellAccessToken.java

/**
 * X509??.//from   w w  w  .ja v a  2  s .  co  m
 * @param privateKeyFileName ???
 * @param certificateFileName ??
 * @param rootCertificateFileNames ??
 * @throws IOException IOException
 * @throws NoSuchAlgorithmException NoSuchAlgorithmException
 * @throws InvalidKeySpecException InvalidKeySpecException
 * @throws CertificateException CertificateException
 * @throws InvalidNameException InvalidNameException
 */
public static void configureX509(String privateKeyFileName, String certificateFileName,
        String[] rootCertificateFileNames) throws IOException, NoSuchAlgorithmException,
        InvalidKeySpecException, CertificateException, InvalidNameException {

    xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");

    // Read RootCA Certificate
    x509RootCertificateFileNames = new ArrayList<String>();
    if (rootCertificateFileNames != null) {
        for (String fileName : rootCertificateFileNames) {
            x509RootCertificateFileNames.add(fileName);
        }
    }

    // Read Private Key
    InputStream is = null;
    if (privateKeyFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_KEY_PATH);
    } else {
        is = new FileInputStream(privateKeyFileName);
    }

    PEMReader privateKeyPemReader = new PEMReader(is);
    byte[] privateKeyDerBytes = privateKeyPemReader.getDerBytes();
    PKCS1EncodedKeySpec keySpecRSAPrivateKey = new PKCS1EncodedKeySpec(privateKeyDerBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    privKey = keyFactory.generatePrivate(keySpecRSAPrivateKey.getKeySpec());

    // Read Certificate
    if (certificateFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_CRT_PATH);
    } else {
        is = new FileInputStream(certificateFileName);
    }
    PEMReader serverCertificatePemReader;
    serverCertificatePemReader = new PEMReader(is);
    byte[] serverCertificateBytesCert = serverCertificatePemReader.getDerBytes();
    CertificateFactory cf = CertificateFactory.getInstance(X509KeySelector.X509KEY_TYPE);
    x509Certificate = (X509Certificate) cf
            .generateCertificate(new ByteArrayInputStream(serverCertificateBytesCert));

    // Create the KeyInfo containing the X509Data
    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    List x509Content = new ArrayList();
    x509Content.add(x509Certificate.getSubjectX500Principal().getName());
    x509Content.add(x509Certificate);
    X509Data xd = keyInfoFactory.newX509Data(x509Content);
    keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(xd));

    // Get FQDN from Certificate and set FQDN to PersoniumCoreUtils
    String dn = x509Certificate.getSubjectX500Principal().getName();
    LdapName ln = new LdapName(dn);
    for (Rdn rdn : ln.getRdns()) {
        if (rdn.getType().equalsIgnoreCase("CN")) {
            PersoniumCoreUtils.setFQDN(rdn.getValue().toString());
            break;
        }
    }

    // http://java.sun.com/developer/technicalArticles/xml/dig_signature_api/

}

From source file:de.sub.goobi.helper.ldap.Ldap.java

private void loadCertificates(String path, String passwd) {
    /* wenn die Zertifikate noch nicht im Keystore sind, jetzt einlesen */
    File myPfad = new File(path);
    if (!myPfad.exists()) {
        try (FileOutputStream ksos = (FileOutputStream) serviceManager.getFileService().write(myPfad.toURI());
                // TODO: Rename parameters to something more meaningful,
                // this is quite specific for the GDZ
                FileInputStream cacertFile = new FileInputStream(ConfigCore.getParameter("ldap_cert_root"));
                FileInputStream certFile2 = new FileInputStream(ConfigCore.getParameter("ldap_cert_pdc"))) {

            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cacert = (X509Certificate) cf.generateCertificate(cacertFile);
            X509Certificate servercert = (X509Certificate) cf.generateCertificate(certFile2);

            KeyStore ks = KeyStore.getInstance("jks");
            char[] password = passwd.toCharArray();

            // TODO: Let this method really load a keystore if configured
            // initialize the keystore, if file is available, load the
            // keystore
            ks.load(null);//from ww w .  j  av  a  2  s.c  o m

            ks.setCertificateEntry("ROOTCERT", cacert);
            ks.setCertificateEntry("PDC", servercert);
            ks.store(ksos, password);
        } catch (Exception e) {
            logger.error(e);
        }

    }
}

From source file:org.kitodo.services.data.LdapServerService.java

private void loadCertificates(String path, String passwd, LdapServer ldapServer) {
    /* wenn die Zertifikate noch nicht im Keystore sind, jetzt einlesen */
    File myPfad = new File(path);
    if (!myPfad.exists()) {
        try (FileOutputStream ksos = (FileOutputStream) serviceManager.getFileService().write(myPfad.toURI());
                // TODO: Rename parameters to something more meaningful,
                // this is quite specific for the GDZ
                FileInputStream cacertFile = new FileInputStream(ldapServer.getRootCertificate());
                FileInputStream certFile2 = new FileInputStream(ldapServer.getPdcCertificate())) {

            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cacert = (X509Certificate) cf.generateCertificate(cacertFile);
            X509Certificate servercert = (X509Certificate) cf.generateCertificate(certFile2);

            KeyStore ks = KeyStore.getInstance("jks");
            char[] password = passwd.toCharArray();

            // TODO: Let this method really load a keystore if configured
            // initialize the keystore, if file is available, load the
            // keystore
            ks.load(null);/*from   www .ja v  a2s.c  o  m*/

            ks.setCertificateEntry("ROOTCERT", cacert);
            ks.setCertificateEntry("PDC", servercert);
            ks.store(ksos, password);
        } catch (IOException | CertificateException | KeyStoreException | NoSuchAlgorithmException
                | RuntimeException e) {
            logger.error(e.getMessage(), e);
        }

    }
}

From source file:org.kitodo.production.services.data.LdapServerService.java

private void loadCertificates(String path, String passwd, LdapServer ldapServer) {
    /* wenn die Zertifikate noch nicht im Keystore sind, jetzt einlesen */
    File myPfad = new File(path);
    if (!myPfad.exists()) {
        try (FileOutputStream ksos = (FileOutputStream) ServiceManager.getFileService().write(myPfad.toURI());
                // TODO: Rename parameters to something more meaningful,
                // this is quite specific for the GDZ
                FileInputStream cacertFile = new FileInputStream(ldapServer.getRootCertificate());
                FileInputStream certFile2 = new FileInputStream(ldapServer.getPdcCertificate())) {

            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cacert = (X509Certificate) cf.generateCertificate(cacertFile);
            X509Certificate servercert = (X509Certificate) cf.generateCertificate(certFile2);

            KeyStore ks = KeyStore.getInstance("jks");
            char[] password = passwd.toCharArray();

            // TODO: Let this method really load a keystore if configured
            // initialize the keystore, if file is available, load the
            // keystore
            ks.load(null);//from   w ww . j a  va  2s. c o  m

            ks.setCertificateEntry("ROOTCERT", cacert);
            ks.setCertificateEntry("PDC", servercert);
            ks.store(ksos, password);
        } catch (IOException | CertificateException | KeyStoreException | NoSuchAlgorithmException
                | RuntimeException e) {
            logger.error(e.getMessage(), e);
        }

    }
}

From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java

void importPrivateKey(String keyAlias, String keyPassword, InputStream fl, InputStream certstream)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException,
        KeyStoreException {/*from  w  w  w. j a va 2 s  .  c  om*/
    KeyInfoManager keyInfoManager = null;

    writeLock.lock();
    try {
        keyInfoManager = getKeyInfoManager(getKeyMetaDataFileLocation());
        KeyStore ks = loadKeyStore(getKeyStoreParameters(), keyInfoManager);

        // loading Key
        byte[] keyBytes = new byte[fl.available()];
        KeyFactory kf = KeyFactory.getInstance("RSA");
        fl.read(keyBytes, 0, fl.available());
        fl.close();
        PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyBytes);
        PrivateKey key = kf.generatePrivate(keysp);

        // loading CertificateChain
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        @SuppressWarnings("rawtypes")
        Collection c = cf.generateCertificates(certstream);
        Certificate[] certs = new Certificate[c.toArray().length];

        certs = (Certificate[]) c.toArray(new Certificate[0]);

        // storing keystore
        ks.setKeyEntry(keyAlias, key, keyPassword.toCharArray(), certs);

        if (logger.isDebugEnabled()) {
            logger.debug("Key and certificate stored.");
            logger.debug("Alias:" + keyAlias);
        }

        ks.store(new FileOutputStream(getKeyStoreParameters().getLocation()), keyPassword.toCharArray());
    } finally {
        if (keyInfoManager != null) {
            keyInfoManager.clear();
        }

        writeLock.unlock();
    }
}

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

private static void importIdpMetadata(Options options, CommandLine cmd, String unisonXMLFile,
        TremoloType ttRead, TremoloType ttWrite, String ksPath, KeyStore ks)
        throws ParserConfigurationException, SAXException, IOException, FileNotFoundException,
        UnmarshallingException, Exception, Base64DecodingException, CertificateException, KeyStoreException,
        NoSuchAlgorithmException, JAXBException, PropertyException {
    logger.info("Import SP Metadata into the IdP");

    logger.info("Loading Metadata...");
    String metadataFile = loadOption(cmd, "pathToMetaData", options);

    InitializationService.initialize();//from   w  w  w.  j av  a2  s.  c  om

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);

    DocumentBuilder builder = factory.newDocumentBuilder();

    Element root = builder.parse(new InputSource(new InputStreamReader(new FileInputStream(metadataFile))))
            .getDocumentElement();

    EntityDescriptor ed = (EntityDescriptor) XMLObjectSupport.getUnmarshaller(root).unmarshall(root);

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

    ApplicationType idp = null;

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

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

    SPSSODescriptor sp = ed.getSPSSODescriptor("urn:oasis:names:tc:SAML:2.0:protocol");

    TrustType trust = null;

    trust = new TrustType();

    if (sp.getID() == null) {
        trust.setName(ed.getEntityID());
    } else {
        trust.setName(sp.getID());
    }

    for (AssertionConsumerService svc : sp.getAssertionConsumerServices()) {
        if (svc.getBinding().equalsIgnoreCase("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST")) {
            ParamType pt = new ParamType();
            pt.setName("httpPostRespURL");
            pt.setValue(svc.getLocation());
            trust.getParam().add(pt);
        }
    }

    ParamType pt = new ParamType();
    pt.setName("signAssertion");
    pt.setValue(Boolean.toString(sp.getWantAssertionsSigned().booleanValue()));
    trust.getParam().add(pt);

    if (pt.getValue().equalsIgnoreCase("false")) {

        pt = new ParamType();
        pt.setName("signResponse");
        pt.setValue("true");
        trust.getParam().add(pt);
    } else {
        pt = new ParamType();
        pt.setName("signResponse");
        pt.setValue("false");
        trust.getParam().add(pt);
    }

    boolean first = true;
    for (NameIDFormat nameid : sp.getNameIDFormats()) {
        if (first) {

            pt = new ParamType();
            pt.setName("defaultNameId");
            pt.setValue(nameid.getFormat());
            trust.getParam().add(pt);

            first = false;
        }

        pt = new ParamType();
        pt.setName("nameIdMap");
        pt.setValue(nameid.getFormat() + "=");
        trust.getParam().add(pt);
    }

    boolean encryptAssertion = false;
    boolean signAssertion = false;
    for (KeyDescriptor kd : sp.getKeyDescriptors()) {

        if (kd.getUse().equals(UsageType.SIGNING)) {
            String base64 = kd.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0).getValue();
            String name = "verify-" + ed.getEntityID() + "-sp-sig";

            ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(base64));
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            Collection<? extends Certificate> c = cf.generateCertificates(bais);

            if (c.size() > 1) {
                int j = 0;
                Iterator<? extends Certificate> i = c.iterator();
                while (i.hasNext()) {
                    Certificate certificate = (Certificate) i.next();
                    ks.setCertificateEntry(name + "-" + j, certificate);
                }
            } else {
                ks.setCertificateEntry(name, c.iterator().next());
            }

            pt = new ParamType();
            pt.setName("spSigKey");
            pt.setValue(name);
            trust.getParam().add(pt);

            signAssertion = true;
        }

        if (kd.getUse().equals(UsageType.ENCRYPTION)) {
            String base64 = kd.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0).getValue();
            String name = "verify-" + ed.getEntityID() + "-sp-enc";

            ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(base64));
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            Collection<? extends Certificate> c = cf.generateCertificates(bais);

            if (c.size() > 1) {
                int j = 0;
                Iterator<? extends Certificate> i = c.iterator();
                while (i.hasNext()) {
                    Certificate certificate = (Certificate) i.next();
                    ks.setCertificateEntry(name + "-" + j, certificate);
                }
            } else {
                ks.setCertificateEntry(name, c.iterator().next());
            }

            pt = new ParamType();
            pt.setName("spEncKey");
            pt.setValue(name);
            trust.getParam().add(pt);

            encryptAssertion = true;
        }
    }

    pt = new ParamType();
    pt.setName("encAssertion");
    pt.setValue(encryptAssertion ? "true" : "false");
    trust.getParam().add(pt);

    if (!signAssertion) {
        pt = new ParamType();
        pt.setName("spSigKey");
        pt.setValue("");
        trust.getParam().add(pt);
    }

    if (!encryptAssertion) {
        pt = new ParamType();
        pt.setName("spEncKey");
        pt.setValue("");
        trust.getParam().add(pt);
    }

    pt = new ParamType();
    pt.setName("defaultAuthCtx");
    pt.setValue("");
    trust.getParam().add(pt);

    TrustType cur = null;
    for (TrustType trustType : idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust()) {
        if (trustType.getName().equals(trust.getName())) {
            cur = trustType;
            break;
        }
    }

    if (cur != null) {
        idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust().remove(cur);
    }

    idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust().add(trust);

    OpenUnisonUtils.storeMethod(unisonXMLFile, ttWrite, ksPath, ks);
}