List of usage examples for org.w3c.dom Document getElementsByTagNameNS
public NodeList getElementsByTagNameNS(String namespaceURI, String localName);
NodeList
of all the Elements
with a given local name and namespace URI in document order. From source file:test.unit.be.agiv.security.handler.WSSecurityHandlerTest.java
@Test public void testCertificateSignature() throws Exception { // setup// w w w . j av a 2 s . co m SOAPMessageContext mockContext = EasyMock.createMock(SOAPMessageContext.class); EasyMock.expect(mockContext.get("javax.xml.ws.handler.message.outbound")).andStubReturn(Boolean.TRUE); SOAPMessage soapMessage = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(null, new ByteArrayInputStream( ("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">" + "<soap:Header>" + "<wsa:To soap:mustUnderstand=\"1\" wsu:Id=\"toId\">destination</wsa:To>" + "</soap:Header>" + "<soap:Body>test</soap:Body>" + "</soap:Envelope>") .getBytes())); EasyMock.expect(mockContext.getMessage()).andStubReturn(soapMessage); EasyMock.expect(mockContext.get(WSAddressingHandler.class.getName() + ".toId")).andStubReturn("toId"); KeyPair keyPair = generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); X509Certificate certificate = generateSelfSignedCertificate(keyPair); this.testedInstance.setCredentials(privateKey, certificate); // prepare EasyMock.replay(mockContext); // operate boolean result = this.testedInstance.handleMessage(mockContext); // verify EasyMock.verify(mockContext); assertTrue(result); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); soapMessage.writeTo(outputStream); LOG.debug("SOAP message: " + new String(outputStream.toByteArray())); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray()); Document resultDocument = documentBuilder.parse(byteArrayInputStream); TestUtils.markAllIdAttributesAsId(resultDocument); NodeList signatureNodeList = resultDocument.getElementsByTagNameNS(Constants.SignatureSpecNS, "Signature"); assertEquals(1, signatureNodeList.getLength()); Element signatureElement = (Element) signatureNodeList.item(0); XMLSignature xmlSignature = new XMLSignature(signatureElement, null); boolean signatureResult = xmlSignature.checkSignatureValue(certificate); assertTrue(signatureResult); LOG.debug("signed SOAP: " + toString(resultDocument)); }
From source file:test.unit.be.e_contract.dssp.client.SignResponseVerifierTest.java
@Test public void testMissingSignature() throws Exception { byte[] tokenKey = new byte[256 / 8]; SecureRandom secureRandom = new SecureRandom(); secureRandom.nextBytes(tokenKey);/*from w w w . ja v a2 s. co m*/ String signResponse = SignResponseFactory.createSignResponse("response-id", "destination", "in-response-to", "token-id", tokenKey); LOG.debug("SignResponse: " + signResponse); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(new ByteArrayInputStream(Base64.decode(signResponse))); Node signatureNode = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature") .item(0); signatureNode.getParentNode().removeChild(signatureNode); signResponse = Base64.encode(toString(document).getBytes()); DigitalSignatureServiceSession session = new DigitalSignatureServiceSession("response-id", "token-id", tokenKey, null); session.setDestination("destination"); session.setInResponseTo("in-response-to"); try { SignResponseVerifier.checkSignResponse(signResponse, session); fail(); } catch (SecurityException e) { LOG.debug("expected exception: " + e.getMessage()); // expected assertFalse(session.isSignResponseVerified()); } }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractODFSignatureServiceTest.java
private boolean hasOdfSignature(URL odfUrl, int signatureCount) throws IOException, ParserConfigurationException, SAXException, org.apache.xml.security.signature.XMLSignatureException, XMLSecurityException, MarshalException, XMLSignatureException { InputStream odfInputStream = odfUrl.openStream(); if (null == odfInputStream) { return false; }/* w w w. j a va 2 s .c om*/ ZipInputStream odfZipInputStream = new ZipInputStream(odfInputStream); ZipEntry zipEntry; while (null != (zipEntry = odfZipInputStream.getNextEntry())) { LOG.debug(zipEntry.getName()); if (true == "META-INF/documentsignatures.xml".equals(zipEntry.getName())) { Document documentSignatures = loadDocument(odfZipInputStream); NodeList signatureNodeList = documentSignatures.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); assertEquals(signatureCount, signatureNodeList.getLength()); for (int idx = 0; idx < signatureNodeList.getLength(); idx++) { Node signatureNode = signatureNodeList.item(idx); if (false == verifySignature(odfUrl, signatureNode)) { LOG.debug("JSR105 says invalid signature"); return false; } } return true; } } LOG.debug("no documentsignatures.xml entry present"); return false; }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java
@Test public void testSignEnvelopingDocument() throws Exception { // setup//from w ww.j a v a 2 s. co 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"); dataElement.setAttributeNS(null, "Id", "id-1234"); dataElement.setIdAttribute("Id", true); dataElement.setTextContent("data to be signed"); rootElement.appendChild(dataElement); SignatureTestFacet signatureFacet = new SignatureTestFacet(); signatureFacet.addReferenceUri("#id-1234"); XmlSignatureTestService testedInstance = new XmlSignatureTestService(signatureFacet); testedInstance.setEnvelopingDocument(document); testedInstance.setSignatureDescription("test-signature-description"); // operate DigestInfo digestInfo = testedInstance.preSign(null, null); // verify assertNotNull(digestInfo); LOG.debug("digest info description: " + digestInfo.description); assertEquals("test-signature-description", digestInfo.description); assertNotNull(digestInfo.digestValue); LOG.debug("digest algo: " + digestInfo.digestAlgo); assertEquals("SHA-1", digestInfo.digestAlgo); 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); 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. */ KeyPair keyPair = PkiTestUtils.generateKeyPair(); 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); 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)); /* * Operate: postSign */ testedInstance.postSign(signatureValue, Collections.singletonList(certificate)); 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); domValidateContext.setIdAttributeNS((Element) signedDocument.getDocumentElement().getFirstChild(), null, "Id"); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); assertTrue(validity); }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java
@Test public void testSignExternalUri() throws Exception { // setup/* w ww. j av a 2 s . c om*/ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); SignatureTestFacet signatureFacet = new SignatureTestFacet(); signatureFacet.addReferenceUri("external-uri"); XmlSignatureTestService testedInstance = new XmlSignatureTestService(signatureFacet); testedInstance.setEnvelopingDocument(document); testedInstance.setSignatureDescription("test-signature-description"); UriTestDereferencer uriDereferencer = new UriTestDereferencer(); uriDereferencer.addResource("external-uri", "hello world".getBytes()); testedInstance.setUriDereferencer(uriDereferencer); // operate DigestInfo digestInfo = testedInstance.preSign(null, null); // verify assertNotNull(digestInfo); LOG.debug("digest info description: " + digestInfo.description); assertEquals("test-signature-description", digestInfo.description); assertNotNull(digestInfo.digestValue); LOG.debug("digest algo: " + digestInfo.digestAlgo); assertEquals("SHA-1", digestInfo.digestAlgo); 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); 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. */ KeyPair keyPair = PkiTestUtils.generateKeyPair(); 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); 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)); /* * Operate: postSign */ testedInstance.postSign(signatureValue, Collections.singletonList(certificate)); 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); domValidateContext.setURIDereferencer(uriDereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); assertTrue(validity); }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java
@Test public void testSignEnvelopingDocumentWithExternalDigestInfo() throws Exception { // setup/*from ww w . j a v a 2 s .co 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); XmlSignatureTestService testedInstance = new XmlSignatureTestService(); testedInstance.setEnvelopingDocument(document); testedInstance.setSignatureDescription("test-signature-description"); byte[] refData = "hello world".getBytes(); MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); messageDigest.update(refData); byte[] digestValue = messageDigest.digest(); DigestInfo refDigestInfo = new DigestInfo(digestValue, "SHA-1", "urn:test:ref"); // operate DigestInfo digestInfo = testedInstance.preSign(Collections.singletonList(refDigestInfo), null); // verify assertNotNull(digestInfo); LOG.debug("digest info description: " + digestInfo.description); assertEquals("test-signature-description", digestInfo.description); assertNotNull(digestInfo.digestValue); LOG.debug("digest algo: " + digestInfo.digestAlgo); assertEquals("SHA-1", digestInfo.digestAlgo); 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); 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. */ KeyPair keyPair = PkiTestUtils.generateKeyPair(); 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); 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)); /* * Operate: postSign */ testedInstance.postSign(signatureValue, Collections.singletonList(certificate)); 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); URIDereferencer dereferencer = new URITest2Dereferencer(); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); assertTrue(validity); }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java
@Test public void testSignExternalDigestInfo() throws Exception { // setup/*from w w w.j a va2 s. co m*/ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); XmlSignatureTestService testedInstance = new XmlSignatureTestService(); testedInstance.setEnvelopingDocument(document); testedInstance.setSignatureDescription("test-signature-description"); byte[] refData = "hello world".getBytes(); MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); messageDigest.update(refData); byte[] digestValue = messageDigest.digest(); DigestInfo refDigestInfo = new DigestInfo(digestValue, "SHA-1", "urn:test:ref"); // operate DigestInfo digestInfo = testedInstance.preSign(Collections.singletonList(refDigestInfo), null); // verify assertNotNull(digestInfo); LOG.debug("digest info description: " + digestInfo.description); assertEquals("test-signature-description", digestInfo.description); assertNotNull(digestInfo.digestValue); LOG.debug("digest algo: " + digestInfo.digestAlgo); assertEquals("SHA-1", digestInfo.digestAlgo); 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); 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. */ KeyPair keyPair = PkiTestUtils.generateKeyPair(); 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); 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)); /* * Operate: postSign */ testedInstance.postSign(signatureValue, Collections.singletonList(certificate)); 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); URIDereferencer dereferencer = new URITest2Dereferencer(); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); assertTrue(validity); }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java
@Test public void testSignEnvelopingDocumentWithDTD() throws Exception { // setup//from www. j a v a 2 s . co m InputStream documentInputStream = AbstractXmlSignatureServiceTest.class .getResourceAsStream("/bookstore.xml"); InputSource inputSource = new InputSource(documentInputStream); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); EntityResolver entityResolver = new MyEntityResolver(); documentBuilder.setEntityResolver(entityResolver); Document document = documentBuilder.parse(inputSource); SignatureFacet signatureFacet = new EnvelopedSignatureFacet(); XmlSignatureTestService testedInstance = new XmlSignatureTestService(signatureFacet); testedInstance.setEnvelopingDocument(document); testedInstance.setSignatureDescription("test-signature-description"); // operate DigestInfo digestInfo = testedInstance.preSign(null, null); // verify assertNotNull(digestInfo); LOG.debug("digest info description: " + digestInfo.description); assertEquals("test-signature-description", digestInfo.description); assertNotNull(digestInfo.digestValue); LOG.debug("digest algo: " + digestInfo.digestAlgo); assertEquals("SHA-1", digestInfo.digestAlgo); 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); 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. */ KeyPair keyPair = PkiTestUtils.generateKeyPair(); 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); 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)); /* * Operate: postSign */ testedInstance.postSign(signatureValue, Collections.singletonList(certificate)); 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); }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java
@Test public void testSignExternalXMLDocument() throws Exception { // setup//from w w w .j a v a 2 s .c om 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); SignatureTestFacet signatureFacet = new SignatureTestFacet(); signatureFacet.addReferenceUri("/bookstore.xml"); XmlSignatureTestService testedInstance = new XmlSignatureTestService(signatureFacet); testedInstance.setUriDereferencer(new MyURIDereferencer()); testedInstance.setEnvelopingDocument(document); testedInstance.setSignatureDescription("test-signature-description"); // operate DigestInfo digestInfo = testedInstance.preSign(null, null); // verify assertNotNull(digestInfo); LOG.debug("digest info description: " + digestInfo.description); assertEquals("test-signature-description", digestInfo.description); assertNotNull(digestInfo.digestValue); LOG.debug("digest algo: " + digestInfo.digestAlgo); assertEquals("SHA-1", digestInfo.digestAlgo); 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); 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. */ KeyPair keyPair = PkiTestUtils.generateKeyPair(); 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); 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)); /* * Operate: postSign */ testedInstance.postSign(signatureValue, Collections.singletonList(certificate)); 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); /* * Required to resolve the external XML document. */ domValidateContext.setURIDereferencer(new MyURIDereferencer()); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); assertTrue(validity); }
From source file:test.unit.be.fedict.eid.applet.service.signer.CoSignatureFacetTest.java
@Test public void testCoSignature() throws Exception { // setup//w w w . ja va2 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(); 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)); }