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.fedict.eid.idp.protocol.ws_federation.WSFederationProtocolServiceTest.java
public void testSignatureVerification() throws Exception { // setup/* ww w . j a v a2 s . c om*/ InputStream documentInputStream = WSFederationProtocolServiceTest.class .getResourceAsStream("/sts-response-message.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); SAMLURIDereferencer dereferencer = new SAMLURIDereferencer(document); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); // operate boolean validity = xmlSignature.validate(domValidateContext); // verify assertTrue(validity); }
From source file:test.unit.be.fedict.eid.tsl.BelgianTrustServiceListFactoryTest.java
@Test public void testBelgianTrustList() throws Exception { // setup/*from ww w . jav a 2 s . co m*/ TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2014, Trimester.FIRST); assertNotNull(trustServiceList.getType()); File unsignedTslFile = File.createTempFile("tsl-be-2014-T1-candidatetest", ".xml"); trustServiceList.saveAs(unsignedTslFile); // sign trust list KeyPair keyPair = TrustTestUtils.generateKeyPair(2048); PrivateKey privateKey = keyPair.getPrivate(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(5); X509Certificate certificate = TrustTestUtils.generateSelfSignedCertificate(keyPair, "C=BE, CN=Belgium Trust List Scheme Operator", notBefore, notAfter); trustServiceList.sign(privateKey, certificate); // operate File tmpTslFile = File.createTempFile("tsl-be-", ".xml"); // tmpTslFile.deleteOnExit(); trustServiceList.saveAs(tmpTslFile); // --------------- VERIFY TRUST LIST -------------------- LOG.debug("TSL: " + FileUtils.readFileToString(tmpTslFile)); Document document = TrustTestUtils.loadDocument(tmpTslFile); // XML schema validation SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); LSResourceResolver resourceResolver = new TSLLSResourceResolver(); factory.setResourceResolver(resourceResolver); InputStream tslSchemaInputStream = BelgianTrustServiceListFactoryTest.class .getResourceAsStream("/ts_119612v010101_xsd.xsd"); Source tslSchemaSource = new StreamSource(tslSchemaInputStream); Schema tslSchema = factory.newSchema(tslSchemaSource); Validator tslValidator = tslSchema.newValidator(); LOG.debug("Starting validate"); tslValidator.validate(new DOMSource(document)); Validator eccValidator = factory .newSchema(BelgianTrustServiceListFactoryTest.class.getResource("/ts_119612v010101_sie_xsd.xsd")) .newValidator(); NodeList eccQualificationsNodeList = document.getElementsByTagNameNS( "http://uri.etsi.org/TrstSvc/SvcInfoExt/eSigDir-1999-93-EC-TrustedList/#", "Qualifications"); for (int idx = 0; idx < eccQualificationsNodeList.getLength(); idx++) { Node eccQualificationsNode = eccQualificationsNodeList.item(idx); eccValidator.validate(new DOMSource(eccQualificationsNode)); } Validator xadesValidator = factory .newSchema(BelgianTrustServiceListFactoryTest.class.getResource("/XAdES.xsd")).newValidator(); NodeList xadesQualifyingPropertiesNodeList = document .getElementsByTagNameNS("http://uri.etsi.org/01903/v1.3.2#", "QualifyingProperties"); for (int idx = 0; idx < xadesQualifyingPropertiesNodeList.getLength(); idx++) { Node xadesQualifyingPropertiesNode = xadesQualifyingPropertiesNodeList.item(idx); xadesValidator.validate(new DOMSource(xadesQualifyingPropertiesNode)); } // signature trustServiceList = TrustServiceListFactory.newInstance(tmpTslFile); X509Certificate resultCertificate = trustServiceList.verifySignature(); assertEquals(certificate, resultCertificate); File pdfExportFile = File.createTempFile("tsl-be-", ".pdf"); trustServiceList.humanReadableExport(pdfExportFile); // scheme operator name String schemeOperatorNameEn = trustServiceList.getSchemeOperatorName(Locale.ENGLISH); assertEquals("FPS Economy, SMEs, Self-employed and Energy - Quality and Safety", schemeOperatorNameEn); LOG.debug("Locale.ENGLISH: " + Locale.ENGLISH.getLanguage()); assertEquals("SPF Economie, PME, Classes moyennes et Energie - Qualit et Scurit", trustServiceList.getSchemeOperatorName(Locale.FRENCH)); Node schemeOperatorNameEnNode = XPathAPI.selectSingleNode(document, "tsl:TrustServiceStatusList/tsl:SchemeInformation/tsl:SchemeOperatorName/tsl:Name[@xml:lang='en']"); assertNotNull(schemeOperatorNameEnNode); assertEquals("FPS Economy, SMEs, Self-employed and Energy - Quality and Safety", schemeOperatorNameEnNode.getTextContent()); // scheme operator postal address PostalAddressType resultPostalAddress = trustServiceList.getSchemeOperatorPostalAddress(Locale.ENGLISH); assertNotNull(resultPostalAddress); assertEquals("NG III - Koning Albert II-laan 16", resultPostalAddress.getStreetAddress()); assertEquals("Brussels", resultPostalAddress.getLocality()); assertEquals("Brussel", trustServiceList.getSchemeOperatorPostalAddress(new Locale("nl")).getLocality()); // scheme operator electronic address assertEquals(2, trustServiceList.getSchemeOperatorElectronicAddresses().size()); LOG.debug("electronic addresses: " + trustServiceList.getSchemeOperatorElectronicAddresses()); // scheme name assertTrue(trustServiceList.getSchemeName(Locale.ENGLISH).startsWith("BE:")); // scheme information uri List<String> schemeInformationUris = trustServiceList.getSchemeInformationUris(); assertNotNull(schemeInformationUris); // assertEquals(3, schemeInformationUris.size()); assertEquals("http://tsl.belgium.be/", schemeInformationUris.get(0)); // status determination approach assertEquals("http://uri.etsi.org/TrstSvc/TrustedList/TSLType/StatusDetn/EUappropriate", trustServiceList.getStatusDeterminationApproach()); // scheme types /*List<String> schemeTypes = trustServiceList.getSchemeTypes(); assertNotNull(schemeTypes); assertEquals(2, schemeTypes.size()); */ // scheme territory assertEquals("BE", trustServiceList.getSchemeTerritory()); // legal notice String resultLegalNotice = trustServiceList.getLegalNotice(Locale.ENGLISH); assertNotNull(resultLegalNotice); assertTrue(resultLegalNotice.indexOf("1999/93/EC") != -1); assertTrue(resultLegalNotice.indexOf("Belgium") != -1); // historical information period assertEquals(new Integer(21845 * 3), trustServiceList.getHistoricalInformationPeriod()); // list issue date time DateTime resultListIssueDateTime = trustServiceList.getListIssueDateTime(); assertNotNull(resultListIssueDateTime); // next update DateTime resultNextUpdateDateTime = trustServiceList.getNextUpdate(); assertNotNull(resultNextUpdateDateTime); // trust service provider list List<TrustServiceProvider> trustServiceProviders = trustServiceList.getTrustServiceProviders(); assertEquals(2, trustServiceProviders.size()); TrustServiceProvider certipostTrustServiceProvider = trustServiceProviders.get(0); assertEquals("Certipost n.v./s.a.", certipostTrustServiceProvider.getName(Locale.ENGLISH)); // postal address PostalAddressType certipostPostalAddress = certipostTrustServiceProvider.getPostalAddress(Locale.ENGLISH); assertNotNull(certipostPostalAddress); assertEquals("Muntcentrum", certipostPostalAddress.getStreetAddress()); assertEquals("BE", certipostPostalAddress.getCountryName()); // electronic address /* List<String> resultElectronicAddress = certipostTrustServiceProvider .getElectronicAddress(); assertEquals(2, resultElectronicAddress.size()); */ // information uri /* List<String> resultInformationUris = certipostTrustServiceProvider .getInformationUris(Locale.ENGLISH); assertEquals(2, resultInformationUris.size()); assertEquals("http://repository.eid.belgium.be/EN/Index.htm", resultInformationUris.get(0)); */ LOG.debug("unsigned TSL: " + unsignedTslFile.getAbsolutePath()); LOG.debug("TSL: " + tmpTslFile.getAbsolutePath()); LOG.debug("PDF: " + pdfExportFile.getAbsolutePath()); }
From source file:test.unit.org.owasp.webscarab.plugin.saml.SamlTest.java
@Test public void testEncryptedXML() throws Exception { // setup/* w ww . ja v a2 s .c o m*/ DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document document = builder .parse(SamlTest.class.getResourceAsStream("/test-saml-response-encrypted-attribute.xml")); NodeList nodeList = document.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "EncryptedAttribute"); assertEquals(1, nodeList.getLength()); Element encryptedAttributeElement = (Element) nodeList.item(0); NodeList encryptedDataNodeList = encryptedAttributeElement .getElementsByTagNameNS("http://www.w3.org/2001/04/xmlenc#", "EncryptedData"); assertEquals(1, encryptedDataNodeList.getLength()); Element encryptedDataElement = (Element) encryptedDataNodeList.item(0); Init.init(); XMLCipher xmlCipher = XMLCipher.getInstance(XMLCipher.AES_128); String aes128HexStr = "2a1e3d83f475ec3c007f487c5150a5f2"; byte[] aes128Bytes = Hex.decode(aes128HexStr); SecretKeySpec secretKeySpec = new SecretKeySpec(aes128Bytes, "AES"); xmlCipher.init(XMLCipher.DECRYPT_MODE, secretKeySpec); xmlCipher.doFinal(document, encryptedDataElement); LOG.debug("decrypted attribute: " + toString(encryptedAttributeElement)); NodeList attributeNodeList = encryptedAttributeElement .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Attribute"); assertEquals(1, attributeNodeList.getLength()); }
From source file:test.unit.test.be.fedict.eid.applet.model.XmlSignatureServiceBeanTest.java
@Test public void testJsr105Signature() throws Exception { KeyPair keyPair = generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); X509Certificate certificate = generateCertificate(keyPair.getPublic(), "CN=Test", notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, new KeyUsage(KeyUsage.nonRepudiation)); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI()); XMLSignContext signContext = new DOMSignContext(keyPair.getPrivate(), document); signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds"); byte[] externalDocument = "hello world".getBytes(); MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(externalDocument); byte[] documentDigestValue = messageDigest.digest(); DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null); Reference reference = signatureFactory.newReference("some-uri", digestMethod, null, null, null, documentDigestValue);/*from www . j av a2s . c o m*/ SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod( CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); javax.xml.crypto.dsig.SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference)); KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory(); X509Data x509Data = keyInfoFactory.newX509Data(Collections.singletonList(certificate)); KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data)); javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo); DOMXMLSignature domXmlSignature = (DOMXMLSignature) xmlSignature; domXmlSignature.marshal(document, "ds", (DOMCryptoContext) signContext); DOMSignedInfo domSignedInfo = (DOMSignedInfo) signedInfo; ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); domSignedInfo.canonicalize(signContext, dataStream); byte[] octets = dataStream.toByteArray(); MessageDigest jcaMessageDigest = MessageDigest.getInstance("SHA1"); byte[] digestValue = jcaMessageDigest.digest(octets); byte[] digestInfoValue = ArrayUtils.addAll(SHA1_DIGEST_INFO_PREFIX, digestValue); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate()); byte[] signatureValue = cipher.doFinal(digestInfoValue); NodeList signatureValueNodeList = document.getElementsByTagNameNS(javax.xml.crypto.dsig.XMLSignature.XMLNS, "SignatureValue"); assertEquals(1, signatureValueNodeList.getLength()); Element signatureValueElement = (Element) signatureValueNodeList.item(0); signatureValueElement.setTextContent(Base64.encode(signatureValue)); Source source = new DOMSource(document); StringWriter stringWriter = new StringWriter(); Result result = new StreamResult(stringWriter); Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); xformer.transform(source, result); String signedDocumentStr = stringWriter.getBuffer().toString(); LOG.debug("signed document: " + signedDocumentStr); File tmpFile = File.createTempFile("xml-signature-", ".xml"); FileUtils.writeStringToFile(tmpFile, signedDocumentStr); StringReader stringReader = new StringReader(signedDocumentStr); InputSource inputSource = new InputSource(stringReader); Document signedDocument = documentBuilder.parse(inputSource); Element signatureElement = (Element) XPathAPI.selectSingleNode(signedDocument, "ds:Signature"); assertNotNull(signatureElement); XMLSignature apacheXmlSignature = new XMLSignature(signatureElement, null); ResourceTestResolver resourceResolver = new ResourceTestResolver(); resourceResolver.addResource("some-uri", "hello world".getBytes()); apacheXmlSignature.addResourceResolver(resourceResolver); boolean signatureResult = apacheXmlSignature.checkSignatureValue(keyPair.getPublic()); assertTrue(signatureResult); LOG.debug("file: " + tmpFile.getAbsolutePath()); }