Example usage for org.w3c.dom Document getElementsByTagNameNS

List of usage examples for org.w3c.dom Document getElementsByTagNameNS

Introduction

In this page you can find the example usage for org.w3c.dom Document getElementsByTagNameNS.

Prototype

public NodeList getElementsByTagNameNS(String namespaceURI, String localName);

Source Link

Document

Returns a NodeList of all the Elements with a given local name and namespace URI in document order.

Usage

From source file:test.unit.be.fedict.eid.applet.service.signer.CoSignatureFacetTest.java

@Test
public void testCoSignatureUri() throws Exception {
    // setup/*from ww  w .  j  a  v a2  s.  co m*/
    Document document = PkiTestUtils
            .loadDocument(CoSignatureFacetTest.class.getResourceAsStream("/helloworld.xml"));
    KeyPair keyPair = PkiTestUtils.generateKeyPair();

    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    XMLSignContext signContext = new DOMSignContext(keyPair.getPrivate(), document.getDocumentElement());
    signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds");

    CoSignatureFacet testedInstance = new CoSignatureFacet(DigestAlgo.SHA1, "ref-1234");
    List<Reference> references = new LinkedList<Reference>();
    testedInstance.preSign(signatureFactory, document, "foo-bar", null, references, null);

    SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
    CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod(
            CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references);

    XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null);

    // operate
    xmlSignature.sign(signContext);

    // verify
    LOG.debug("signed document: " + PkiTestUtils.toString(document));
    NodeList signatureNodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    assertEquals(1, signatureNodeList.getLength());
    Node signatureNode = signatureNodeList.item(0);
    DOMValidateContext domValidateContext = new DOMValidateContext(keyPair.getPublic(), signatureNode);
    XMLSignature validationXmlSignature = signatureFactory.unmarshalXMLSignature(domValidateContext);
    boolean validity = validationXmlSignature.validate(domValidateContext);
    assertTrue(validity);

    document.getDocumentElement().getFirstChild().setNodeValue("test");
    LOG.debug("signed document: " + PkiTestUtils.toString(document));
    assertTrue(validationXmlSignature.validate(domValidateContext));
    // really have to re-load the XML signature object.
    validationXmlSignature = signatureFactory.unmarshalXMLSignature(domValidateContext);
    assertFalse(validationXmlSignature.validate(domValidateContext));
}

From source file:test.unit.be.fedict.eid.applet.service.signer.CoSignatureFacetTest.java

@Test
public void testMultipleCoSignatures() throws Exception {

    // setup//w w  w  .  j a  va2s  .  c o m
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.newDocument();
    Element rootElement = document.createElementNS("urn:test", "tns:root");
    rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "urn:test");
    document.appendChild(rootElement);
    Element dataElement = document.createElementNS("urn:test", "tns:data");
    rootElement.appendChild(dataElement);

    // add alot of nodes to test performance
    // when using xpath v1 in the co signature facet the c14n became really slow
    for (int i = 0; i < 80000; i++) {
        Element fooElement = document.createElementNS("urn:test", "tns:foo");
        fooElement.setTextContent("bar");
        dataElement.appendChild(fooElement);
    }

    KeyPair keyPair1 = PkiTestUtils.generateKeyPair();
    KeyPair keyPair2 = PkiTestUtils.generateKeyPair();

    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());
    List<Reference> references = new LinkedList<Reference>();

    CoSignatureFacet testedInstance = new CoSignatureFacet();
    testedInstance.preSign(signatureFactory, document, "foo-bar", null, references, null);

    // ds:SignedInfo
    SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
    CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod(
            CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references);

    XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null);
    XMLSignature xmlSignature2 = signatureFactory.newXMLSignature(signedInfo, null);

    // sign context
    XMLSignContext signContext1 = new DOMSignContext(keyPair1.getPrivate(), document.getDocumentElement());
    signContext1.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds");

    XMLSignContext signContext2 = new DOMSignContext(keyPair2.getPrivate(), document.getDocumentElement());
    signContext2.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds");

    // operate
    xmlSignature.sign(signContext1);
    xmlSignature2.sign(signContext2);

    // verify
    LOG.debug("signed document: " + PkiTestUtils.toString(document));
    NodeList signatureNodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    assertEquals(2, signatureNodeList.getLength());
    Node signature1Node = signatureNodeList.item(0);
    DOMValidateContext domValidateContext1 = new DOMValidateContext(keyPair1.getPublic(), signature1Node);
    XMLSignature validationXmlSignature1 = signatureFactory.unmarshalXMLSignature(domValidateContext1);
    boolean validity1 = validationXmlSignature1.validate(domValidateContext1);
    assertTrue(validity1);

    Node signature2Node = signatureNodeList.item(1);
    DOMValidateContext domValidateContext2 = new DOMValidateContext(keyPair2.getPublic(), signature2Node);
    XMLSignature validationXmlSignature2 = signatureFactory.unmarshalXMLSignature(domValidateContext2);
    boolean validity2 = validationXmlSignature2.validate(domValidateContext2);
    assertTrue(validity2);

    // cut out first signature should not break second one
    document.getDocumentElement().removeChild(signature1Node);
    LOG.debug("signed document: " + PkiTestUtils.toString(document));
    NodeList signatureNodeList2 = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    assertEquals(1, signatureNodeList2.getLength());

    Node signature3Node = signatureNodeList2.item(0);
    DOMValidateContext domValidateContext3 = new DOMValidateContext(keyPair2.getPublic(), signature3Node);
    XMLSignature validationXmlSignature3 = signatureFactory.unmarshalXMLSignature(domValidateContext3);
    boolean validity3 = validationXmlSignature3.validate(domValidateContext3);
    assertTrue(validity3);
}

From source file:test.unit.be.fedict.eid.applet.service.signer.OOXMLSignatureVerifierTest.java

@Test
public void testSignedOOXML2() throws Exception {
    // setup//  w w w. j  a va2  s.  c  o m
    URL url = OOXMLSignatureVerifierTest.class.getResource("/signed.docx");

    // operate
    OOXMLSignatureVerifier verifier = new OOXMLSignatureVerifier();
    List<X509Certificate> result = verifier.getSigners(url);

    // verify
    assertNotNull(result);
    assertEquals(1, result.size());
    X509Certificate signer = result.get(0);
    LOG.debug("signer: " + signer.getSubjectX500Principal());

    byte[] document = IOUtils.toByteArray(url.openStream());
    List<String> signatureResourceNames = verifier.getSignatureResourceNames(document);
    Document signatureDocument = verifier.getSignatureDocument(new ByteArrayInputStream(document),
            signatureResourceNames.get(0));
    NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");

    Element signatureElement = (Element) signatureNodeList.item(0);
    KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
    DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);
    domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE);
    OOXMLURIDereferencer dereferencer = new OOXMLURIDereferencer(document);
    domValidateContext.setURIDereferencer(dereferencer);

    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
    XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
    assertTrue(verifier.isValidOOXMLSignature(xmlSignature, document));
}

From source file:test.unit.be.fedict.eid.applet.service.signer.OOXMLSignatureVerifierTest.java

@Test
public void testSignedOOXMLOffice2010ValidOOXML() throws Exception {
    // setup/*  www .  j  a  va2s. co  m*/
    URL url = OOXMLSignatureVerifierTest.class.getResource("/hallo.docx");

    // operate
    OOXMLSignatureVerifier verifier = new OOXMLSignatureVerifier();
    List<X509Certificate> result = verifier.getSigners(url);

    // verify
    assertNotNull(result);
    assertEquals(1, result.size());
    X509Certificate signer = result.get(0);
    LOG.debug("signer: " + signer.getSubjectX500Principal());

    byte[] document = IOUtils.toByteArray(url.openStream());
    List<String> signatureResourceNames = verifier.getSignatureResourceNames(document);
    Document signatureDocument = verifier.getSignatureDocument(new ByteArrayInputStream(document),
            signatureResourceNames.get(0));
    NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");

    Element signatureElement = (Element) signatureNodeList.item(0);
    KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
    DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);
    domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE);
    OOXMLURIDereferencer dereferencer = new OOXMLURIDereferencer(document);
    domValidateContext.setURIDereferencer(dereferencer);

    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
    XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
    assertTrue(verifier.isValidOOXMLSignature(xmlSignature, document));
}

From source file:test.unit.be.fedict.eid.applet.service.signer.OOXMLSignatureVerifierTest.java

@Test
public void testVerifySignature() throws Exception {

    java.util.logging.Logger logger = java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
    logger.log(Level.FINE, "test");

    URL url = OOXMLSignatureVerifierTest.class.getResource("/hello-world-signed.docx");
    String signatureResourceName = getSignatureResourceName(url);
    LOG.debug("signature resource name: " + signatureResourceName);

    OOXMLProvider.install();/*from w  w  w  .j ava 2  s  . com*/

    ZipInputStream zipInputStream = new ZipInputStream(url.openStream());
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (false == signatureResourceName.equals(zipEntry.getName())) {
            continue;
        }
        Document signatureDocument = loadDocument(zipInputStream);
        LOG.debug("signature loaded");
        NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        assertEquals(1, signatureNodeList.getLength());
        Node signatureNode = signatureNodeList.item(0);
        KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
        DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureNode);
        domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE);

        OOXMLURIDereferencer dereferencer = new OOXMLURIDereferencer(url);
        domValidateContext.setURIDereferencer(dereferencer);

        XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
        XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
        boolean validity = xmlSignature.validate(domValidateContext);
        assertTrue(validity);
        List<?> objects = xmlSignature.getObjects();
        for (Object object : objects) {
            LOG.debug("ds:Object class type: " + object.getClass().getName());
        }
        break;
    }
}

From source file:test.unit.be.fedict.eid.applet.service.signer.XAdESSignatureFacetTest.java

@Test
public void testSignEnvelopingDocument() throws Exception {
    // setup//from w  w  w.  j  a  v a 2s  . co m
    EnvelopedSignatureFacet envelopedSignatureFacet = new EnvelopedSignatureFacet();
    KeyInfoSignatureFacet keyInfoSignatureFacet = new KeyInfoSignatureFacet(true, false, false);
    SignaturePolicyService signaturePolicyService = null;
    //SignaturePolicyService signaturePolicyService = new ExplicitSignaturePolicyService(
    //      "urn:test", "hello world".getBytes(), "description",
    //      "http://here.com");
    XAdESSignatureFacet xadesSignatureFacet = new XAdESSignatureFacet(signaturePolicyService);
    TimeStampService mockTimeStampService = EasyMock.createMock(TimeStampService.class);
    RevocationDataService mockRevocationDataService = EasyMock.createMock(RevocationDataService.class);
    XAdESXLSignatureFacet xadesXLSignatureFacet = new XAdESXLSignatureFacet(mockTimeStampService,
            mockRevocationDataService);
    XmlSignatureTestService testedInstance = new XmlSignatureTestService(envelopedSignatureFacet,
            keyInfoSignatureFacet, xadesSignatureFacet, xadesXLSignatureFacet);

    KeyPair keyPair = PkiTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    X509Certificate certificate = PkiTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test", notBefore,
            notAfter, null, keyPair.getPrivate(), true, 0, null, null, new KeyUsage(KeyUsage.nonRepudiation));
    List<X509Certificate> certificateChain = new LinkedList<X509Certificate>();
    /*
     * We need at least 2 certificates for the XAdES-C complete certificate
     * refs construction.
     */
    certificateChain.add(certificate);
    certificateChain.add(certificate);

    RevocationData revocationData = new RevocationData();
    final X509CRL crl = PkiTestUtils.generateCrl(certificate, keyPair.getPrivate());
    revocationData.addCRL(crl);
    OCSPResp ocspResp = PkiTestUtils.createOcspResp(certificate, false, certificate, certificate,
            keyPair.getPrivate(), "SHA1withRSA");
    revocationData.addOCSP(ocspResp.getEncoded());

    // expectations
    EasyMock.expect(mockTimeStampService.timeStamp(EasyMock.anyObject(byte[].class),
            EasyMock.anyObject(RevocationData.class))).andStubAnswer(new IAnswer<byte[]>() {
                public byte[] answer() throws Throwable {
                    Object[] arguments = EasyMock.getCurrentArguments();
                    RevocationData revocationData = (RevocationData) arguments[1];
                    revocationData.addCRL(crl);
                    return "time-stamp-token".getBytes();
                }
            });
    EasyMock.expect(mockRevocationDataService.getRevocationData(EasyMock.eq(certificateChain)))
            .andStubReturn(revocationData);

    // prepare
    EasyMock.replay(mockTimeStampService, mockRevocationDataService);

    // operate
    DigestInfo digestInfo = testedInstance.preSign(null, certificateChain);

    // verify
    assertNotNull(digestInfo);
    assertEquals("SHA-1", digestInfo.digestAlgo);
    assertNotNull(digestInfo.digestValue);

    TemporaryTestDataStorage temporaryDataStorage = (TemporaryTestDataStorage) testedInstance
            .getTemporaryDataStorage();
    assertNotNull(temporaryDataStorage);
    InputStream tempInputStream = temporaryDataStorage.getTempInputStream();
    assertNotNull(tempInputStream);
    Document tmpDocument = PkiTestUtils.loadDocument(tempInputStream);

    LOG.debug("tmp document: " + PkiTestUtils.toString(tmpDocument));
    Element nsElement = tmpDocument.createElement("ns");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS);
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:xades", "http://uri.etsi.org/01903/v1.3.2#");
    Node digestValueNode = XPathAPI.selectSingleNode(tmpDocument, "//ds:DigestValue", nsElement);
    assertNotNull(digestValueNode);
    String digestValueTextContent = digestValueNode.getTextContent();
    LOG.debug("digest value text content: " + digestValueTextContent);
    assertFalse(digestValueTextContent.isEmpty());

    /*
     * Sign the received XML signature digest value.
     */
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());
    byte[] digestInfoValue = ArrayUtils.addAll(PkiTestUtils.SHA1_DIGEST_INFO_PREFIX, digestInfo.digestValue);
    byte[] signatureValue = cipher.doFinal(digestInfoValue);

    /*
     * Operate: postSign
     */
    testedInstance.postSign(signatureValue, certificateChain);

    // verify
    EasyMock.verify(mockTimeStampService, mockRevocationDataService);
    byte[] signedDocumentData = testedInstance.getSignedDocumentData();
    assertNotNull(signedDocumentData);
    Document signedDocument = PkiTestUtils.loadDocument(new ByteArrayInputStream(signedDocumentData));
    LOG.debug("signed document: " + PkiTestUtils.toString(signedDocument));

    NodeList signatureNodeList = signedDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    assertEquals(1, signatureNodeList.getLength());
    Node signatureNode = signatureNodeList.item(0);

    DOMValidateContext domValidateContext = new DOMValidateContext(
            KeySelector.singletonKeySelector(keyPair.getPublic()), signatureNode);
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
    XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
    boolean validity = xmlSignature.validate(domValidateContext);
    assertTrue(validity);

    File tmpFile = File.createTempFile("xades-x-l-", ".xml");
    FileUtils.writeStringToFile(tmpFile, PkiTestUtils.toString(signedDocument));
    LOG.debug("tmp file: " + tmpFile.getAbsolutePath());

    Node resultNode = XPathAPI.selectSingleNode(signedDocument,
            "ds:Signature/ds:Object/xades:QualifyingProperties/xades:SignedProperties/xades:SignedSignatureProperties/xades:SigningCertificate/xades:Cert/xades:CertDigest/ds:DigestValue",
            nsElement);
    assertNotNull(resultNode);

    // also test whether the XAdES extension is in line with the XAdES XML
    // Schema.

    // stax-api 1.0.1 prevents us from using
    // "XMLConstants.W3C_XML_SCHEMA_NS_URI"
    Node qualifyingPropertiesNode = XPathAPI.selectSingleNode(signedDocument,
            "ds:Signature/ds:Object/xades:QualifyingProperties", nsElement);
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    LSResourceResolver xadesResourceResolver = new XAdESLSResourceResolver();
    factory.setResourceResolver(xadesResourceResolver);
    InputStream schemaInputStream = XAdESSignatureFacetTest.class.getResourceAsStream("/XAdESv141.xsd");
    Source schemaSource = new StreamSource(schemaInputStream);
    Schema schema = factory.newSchema(schemaSource);
    Validator validator = schema.newValidator();
    // DOMResult gives some DOMException...
    validator.validate(new DOMSource(qualifyingPropertiesNode));

    StreamSource streamSource = new StreamSource(tmpFile.toURI().toString());
    ByteArrayOutputStream resultOutputStream = new ByteArrayOutputStream();
    StreamResult streamResult = new StreamResult(resultOutputStream);
    // validator.validate(streamSource, streamResult);
    LOG.debug("result: " + resultOutputStream);
}

From source file:test.unit.be.fedict.eid.applet.service.signer.XAdESSignatureFacetTest.java

@Test
public void testSignEnvelopingDocumentOffice2010() throws Exception {
    // setup/*  w  ww  . j ava2  s.  c o  m*/
    EnvelopedSignatureFacet envelopedSignatureFacet = new EnvelopedSignatureFacet();
    KeyInfoSignatureFacet keyInfoSignatureFacet = new KeyInfoSignatureFacet(true, false, false);
    SignaturePolicyService signaturePolicyService = new ExplicitSignaturePolicyService("urn:test",
            "hello world".getBytes(), "description", "http://here.com");
    XAdESSignatureFacet xadesSignatureFacet = new XAdESSignatureFacet(signaturePolicyService);
    TimeStampService mockTimeStampService = EasyMock.createMock(TimeStampService.class);
    RevocationDataService mockRevocationDataService = EasyMock.createMock(RevocationDataService.class);
    XAdESXLSignatureFacet xadesXLSignatureFacet = new XAdESXLSignatureFacet(mockTimeStampService,
            mockRevocationDataService);
    XmlSignatureTestService testedInstance = new XmlSignatureTestService(envelopedSignatureFacet,
            keyInfoSignatureFacet, xadesSignatureFacet, new Office2010SignatureFacet(), xadesXLSignatureFacet);

    KeyPair keyPair = PkiTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    X509Certificate certificate = PkiTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test", notBefore,
            notAfter, null, keyPair.getPrivate(), true, 0, null, null, new KeyUsage(KeyUsage.nonRepudiation));
    List<X509Certificate> certificateChain = new LinkedList<X509Certificate>();
    /*
     * We need at least 2 certificates for the XAdES-C complete certificate
     * refs construction.
     */
    certificateChain.add(certificate);
    certificateChain.add(certificate);

    RevocationData revocationData = new RevocationData();
    final X509CRL crl = PkiTestUtils.generateCrl(certificate, keyPair.getPrivate());
    revocationData.addCRL(crl);
    OCSPResp ocspResp = PkiTestUtils.createOcspResp(certificate, false, certificate, certificate,
            keyPair.getPrivate(), "SHA1withRSA");
    revocationData.addOCSP(ocspResp.getEncoded());

    // expectations
    EasyMock.expect(mockTimeStampService.timeStamp(EasyMock.anyObject(byte[].class),
            EasyMock.anyObject(RevocationData.class))).andStubAnswer(new IAnswer<byte[]>() {
                public byte[] answer() throws Throwable {
                    Object[] arguments = EasyMock.getCurrentArguments();
                    RevocationData revocationData = (RevocationData) arguments[1];
                    revocationData.addCRL(crl);
                    return "time-stamp-token".getBytes();
                }
            });
    EasyMock.expect(mockRevocationDataService.getRevocationData(EasyMock.eq(certificateChain)))
            .andStubReturn(revocationData);

    // prepare
    EasyMock.replay(mockTimeStampService, mockRevocationDataService);

    // operate
    DigestInfo digestInfo = testedInstance.preSign(null, certificateChain);

    // verify
    assertNotNull(digestInfo);
    assertEquals("SHA-1", digestInfo.digestAlgo);
    assertNotNull(digestInfo.digestValue);

    TemporaryTestDataStorage temporaryDataStorage = (TemporaryTestDataStorage) testedInstance
            .getTemporaryDataStorage();
    assertNotNull(temporaryDataStorage);
    InputStream tempInputStream = temporaryDataStorage.getTempInputStream();
    assertNotNull(tempInputStream);
    Document tmpDocument = PkiTestUtils.loadDocument(tempInputStream);

    LOG.debug("tmp document: " + PkiTestUtils.toString(tmpDocument));
    Element nsElement = tmpDocument.createElement("ns");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS);
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:xades", "http://uri.etsi.org/01903/v1.3.2#");
    Node digestValueNode = XPathAPI.selectSingleNode(tmpDocument, "//ds:DigestValue", nsElement);
    assertNotNull(digestValueNode);
    String digestValueTextContent = digestValueNode.getTextContent();
    LOG.debug("digest value text content: " + digestValueTextContent);
    assertFalse(digestValueTextContent.isEmpty());

    /*
     * Sign the received XML signature digest value.
     */
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());
    byte[] digestInfoValue = ArrayUtils.addAll(PkiTestUtils.SHA1_DIGEST_INFO_PREFIX, digestInfo.digestValue);
    byte[] signatureValue = cipher.doFinal(digestInfoValue);

    /*
     * Operate: postSign
     */
    testedInstance.postSign(signatureValue, certificateChain);

    // verify
    EasyMock.verify(mockTimeStampService, mockRevocationDataService);
    byte[] signedDocumentData = testedInstance.getSignedDocumentData();
    assertNotNull(signedDocumentData);
    Document signedDocument = PkiTestUtils.loadDocument(new ByteArrayInputStream(signedDocumentData));
    LOG.debug("signed document: " + PkiTestUtils.toString(signedDocument));

    NodeList signatureNodeList = signedDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    assertEquals(1, signatureNodeList.getLength());
    Node signatureNode = signatureNodeList.item(0);

    DOMValidateContext domValidateContext = new DOMValidateContext(
            KeySelector.singletonKeySelector(keyPair.getPublic()), signatureNode);
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
    XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
    boolean validity = xmlSignature.validate(domValidateContext);
    assertTrue(validity);

    File tmpFile = File.createTempFile("xades-bes-", ".xml");
    FileUtils.writeStringToFile(tmpFile, PkiTestUtils.toString(signedDocument));
    LOG.debug("tmp file: " + tmpFile.getAbsolutePath());

    Node resultNode = XPathAPI.selectSingleNode(signedDocument,
            "ds:Signature/ds:Object/xades:QualifyingProperties/xades:SignedProperties/xades:SignedSignatureProperties/xades:SigningCertificate/xades:Cert/xades:CertDigest/ds:DigestValue",
            nsElement);
    assertNotNull(resultNode);

    // also test whether the XAdES extension is in line with the XAdES XML
    // Schema.

    // stax-api 1.0.1 prevents us from using
    // "XMLConstants.W3C_XML_SCHEMA_NS_URI"
    Node qualifyingPropertiesNode = XPathAPI.selectSingleNode(signedDocument,
            "ds:Signature/ds:Object/xades:QualifyingProperties", nsElement);
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    LSResourceResolver xadesResourceResolver = new XAdESLSResourceResolver();
    factory.setResourceResolver(xadesResourceResolver);
    InputStream schemaInputStream = XAdESSignatureFacetTest.class.getResourceAsStream("/XAdESv141.xsd");
    Source schemaSource = new StreamSource(schemaInputStream);
    Schema schema = factory.newSchema(schemaSource);
    Validator validator = schema.newValidator();
    // DOMResult gives some DOMException...
    validator.validate(new DOMSource(qualifyingPropertiesNode));

    StreamSource streamSource = new StreamSource(tmpFile.toURI().toString());
    ByteArrayOutputStream resultOutputStream = new ByteArrayOutputStream();
    StreamResult streamResult = new StreamResult(resultOutputStream);
    // validator.validate(streamSource, streamResult);
    LOG.debug("result: " + resultOutputStream);
}

From source file:test.unit.be.fedict.eid.dss.spi.utils.XAdESValidationTest.java

private Node getSignatureNode(Document signedDocument) {

    NodeList signatureNodeList = signedDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    assertEquals(1, signatureNodeList.getLength());
    return signatureNodeList.item(0);
}

From source file:test.unit.be.fedict.eid.idp.protocol.ws_federation.sts.SecurityTokenServicePortImplTest.java

@Test
public void testValidation() throws Exception {
    // setup//  w  w w  .j  ava  2s.c o m
    InputStream requestInputStream = SecurityTokenServicePortImplTest.class
            .getResourceAsStream("/sts-validation-request.xml");
    assertNotNull(requestInputStream);

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(requestInputStream);

    Element requestSecurityTokenElement = (Element) document
            .getElementsByTagNameNS("http://docs.oasis-open.org/ws-sx/ws-trust/200512", "RequestSecurityToken")
            .item(0);

    Element x509Certificate = (Element) document
            .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "X509Certificate").item(0);
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(x509Certificate.getFirstChild().getNodeValue())));
    List<X509Certificate> certificateChain = Collections.singletonList(certificate);

    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class,
            be.fedict.eid.idp.wstrust.jaxb.wspolicy.ObjectFactory.class,
            be.fedict.eid.idp.wstrust.jaxb.wsaddr.ObjectFactory.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

    JAXBElement<RequestSecurityTokenType> resultElement = (JAXBElement<RequestSecurityTokenType>) unmarshaller
            .unmarshal(requestSecurityTokenElement);
    RequestSecurityTokenType requestSecurityToken = resultElement.getValue();

    SecurityTokenServicePortImpl testedInstance = new SecurityTokenServicePortImpl();

    WebServiceContext mockWebServiceContext = EasyMock.createMock(WebServiceContext.class);
    injectResource(mockWebServiceContext, testedInstance);

    MessageContext mockMessageContext = EasyMock.createMock(MessageContext.class);

    EasyMock.expect(mockWebServiceContext.getMessageContext()).andStubReturn(mockMessageContext);

    ServletContext mockServletContext = EasyMock.createMock(ServletContext.class);

    EasyMock.expect(mockMessageContext.get(MessageContext.SERVLET_CONTEXT)).andReturn(mockServletContext);

    IdentityProviderConfiguration mockIdentityProviderConfiguration = EasyMock
            .createMock(IdentityProviderConfiguration.class);

    EasyMock.expect(mockServletContext.getAttribute(
            IdentityProviderConfigurationFactory.IDENTITY_PROVIDER_CONFIGURATION_CONTEXT_ATTRIBUTE))
            .andReturn(mockIdentityProviderConfiguration);

    EasyMock.expect(mockIdentityProviderConfiguration.getIdentityCertificateChain())
            .andReturn(certificateChain);

    EasyMock.expect(mockIdentityProviderConfiguration.getDefaultIssuer()).andReturn("e-contract-2012");

    Element samlElement = (Element) document
            .getElementsByTagNameNS(WSTrustConstants.SAML2_NAMESPACE, "Assertion").item(0);
    EasyMock.expect(mockMessageContext.get(WSSecuritySoapHandler.class.getName() + ".samlToken"))
            .andStubReturn(samlElement);

    // prepare
    EasyMock.replay(mockWebServiceContext, mockMessageContext, mockServletContext,
            mockIdentityProviderConfiguration);

    // operate
    RequestSecurityTokenResponseCollectionType result = testedInstance
            .requestSecurityToken(requestSecurityToken);

    // verify
    EasyMock.verify(mockWebServiceContext, mockMessageContext, mockServletContext,
            mockIdentityProviderConfiguration);
    assertNotNull(result);

    List<RequestSecurityTokenResponseType> resultList = result.getRequestSecurityTokenResponse();
    assertEquals(1, resultList.size());
    RequestSecurityTokenResponseType requestSecurityTokenResponse = resultList.get(0);
    List<Object> responseObjects = requestSecurityTokenResponse.getAny();
    boolean valid = false;
    String reason = null;
    for (Object responseObject : responseObjects) {
        LOG.debug("response object type: " + responseObject);
        if (responseObject instanceof JAXBElement) {
            JAXBElement jaxbElement = (JAXBElement) responseObject;
            QName qname = jaxbElement.getName();
            LOG.debug("qname: " + qname);
            if (new QName(WSTrustConstants.WS_TRUST_NAMESPACE, "Status").equals(qname)) {
                StatusType status = (StatusType) jaxbElement.getValue();
                String code = status.getCode();
                LOG.debug("status code: " + code);
                if (WSTrustConstants.VALID_STATUS_CODE.equals(code)) {
                    valid = true;
                }
                reason = status.getReason();
            }
        }
    }
    LOG.debug("status reason: " + reason);
    assertTrue(reason.indexOf("policy") != -1);
}

From source file:test.unit.be.fedict.eid.idp.protocol.ws_federation.WSFederationMetadataHttpServletTest.java

public void testSignatureVerification() throws Exception {
    // setup/*  w ww. j  a  v  a 2 s .  c  o m*/
    InputStream documentInputStream = WSFederationProtocolServiceTest.class
            .getResourceAsStream("/FederationMetadata.xml");
    assertNotNull(documentInputStream);

    Document document = loadDocument(documentInputStream);

    NodeList signatureNodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    assertEquals(1, signatureNodeList.getLength());
    Node signatureNode = signatureNodeList.item(0);

    KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
    DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureNode);

    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
    XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);

    // operate
    boolean validity = xmlSignature.validate(domValidateContext);

    // verify
    assertTrue(validity);
}