List of usage examples for org.w3c.dom Element setAttributeNS
public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException;
From source file:ru.codeinside.gws3572c.GMPClientSignTest.java
@Test public void testSignForEntity() throws Exception { ClientRequest request = client.createClientRequest(createContext()); InputSource is = new InputSource(new StringReader(request.appData)); Document doc = documentBuilder.parse(is); Element elementForSign = (Element) doc.getElementsByTagNameNS(null, "Charge").item(0); Node parentNode;/*www .ja va 2 s .c o m*/ Document detachedDocument; if (!elementForSign.isSameNode(doc.getDocumentElement())) { parentNode = elementForSign.getParentNode(); parentNode.removeChild(elementForSign); detachedDocument = documentBuilder.newDocument(); Node importedElementForSign = detachedDocument.importNode(elementForSign, true); detachedDocument.appendChild(importedElementForSign); } else { detachedDocument = doc; } Element nscontext = detachedDocument.createElementNS(null, "namespaceContext"); nscontext.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + "ds".trim(), "http://www.w3.org/2000/09/xmldsig#"); Element certificateElement = (Element) XPathAPI.selectSingleNode(detachedDocument, "//ds:X509Certificate[1]", nscontext); Element sigElement = (Element) certificateElement.getParentNode().getParentNode().getParentNode(); XMLSignature signature = new XMLSignature(sigElement, ""); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certKey = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.decode(certificateElement.getTextContent().trim().getBytes()))); Assert.assertNotNull("There are no information about public key. Verification couldn't be implemented", certKey); Assert.assertTrue("Signature is not valid", signature.checkSignatureValue(certKey)); }
From source file:ru.codeinside.gws3572c.GMPClientSignTest.java
/** * ? ? XML- ? 34.10-2001./*from w ww .ja v a2s.co m*/ * * @throws Exception / */ boolean signDocVer(Document doc) throws Exception { /* ? <ds:Signature> XML- */ // ? ?? Signature final Element nscontext = doc.createElementNS(null, "namespaceContext"); nscontext.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + "ds".trim(), Constants.SignatureSpecNS); // ? ?? ? <ds:Signature> final Element sigElement = (Element) XPathAPI.selectSingleNode(doc, "//ds:Signature[1]", nscontext); /* ? XML- ? , ??? XML- */ // ? ? final XMLSignature signature = new XMLSignature(sigElement, ""); // <ds:KeyInfo> final KeyInfo ki = signature.getKeyInfo(); // ? final X509Certificate certKey = ki.getX509Certificate(); // ? ? , ????? // ? ? ? if (certKey != null) { return signature.checkSignatureValue(certKey); } // ? ????? else { // final PublicKey pk = ki.getPublicKey(); // ? , ????? ? if (pk != null) { return signature.checkSignatureValue(pk); } // ? else throw new Exception( "There are no information about public key. Verification couldn't be implemented"); } }
From source file:test.integ.be.agiv.security.Axis2Test.java
private Element getNSElement(Document document) { Element nsElement = document.createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:soap", "http://schemas.xmlsoap.org/soap/envelope/"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:soap12", "http://www.w3.org/2003/05/soap-envelope"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:trust", "http://docs.oasis-open.org/ws-sx/ws-trust/200512"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); return nsElement; }
From source file:test.integ.be.e_contract.mycarenet.genins.GenericInsurabilityClientTest.java
@Test public void testInvoke() throws Exception { EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService"); Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null);/*from w w w . ja v a 2 s .co m*/ PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12"); FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path()); eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray()); Enumeration<String> aliasesEnum = eHealthKeyStore.aliases(); String alias = aliasesEnum.nextElement(); X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias); PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias, this.config.getEHealthPKCS12Password().toCharArray()); List<Attribute> attributes = new LinkedList<Attribute>(); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>(); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributeDesignators .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth", "urn:be:fgov:person:ssin:ehealth:1.0:doctor:nihii11")); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth", "urn:be:fgov:person:ssin:doctor:boolean")); Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate, eHealthPrivateKey, attributes, attributeDesignators); assertNotNull(assertion); String assertionString = client.toString(assertion); // String location = // "https://services-int.ehealth.fgov.be/GenericInsurability/v1"; String location = "https://services-acpt.ehealth.fgov.be/GenericInsurability/v1"; GenericInsurabilityClient genInsClient = new GenericInsurabilityClient(location); genInsClient.setCredentials(eHealthPrivateKey, assertionString); ObjectFactory objectFactory = new ObjectFactory(); GetInsurabilityAsXmlOrFlatRequestType body = objectFactory.createGetInsurabilityAsXmlOrFlatRequestType(); be.e_contract.mycarenet.genins.jaxb.core.ObjectFactory coreObjectFactory = new be.e_contract.mycarenet.genins.jaxb.core.ObjectFactory(); CommonInputType commonInput = coreObjectFactory.createCommonInputType(); body.setCommonInput(commonInput); RequestType request = coreObjectFactory.createRequestType(); request.setIsTest(true); commonInput.setRequest(request); OriginType origin = coreObjectFactory.createOriginType(); commonInput.setOrigin(origin); PackageType packageObject = coreObjectFactory.createPackageType(); origin.setPackage(packageObject); LicenseType license = coreObjectFactory.createLicenseType(); packageObject.setLicense(license); PackageLicenseKey packageLicenseKey = this.config.getPackageLicenseKey(); license.setUsername(packageLicenseKey.getUsername()); license.setPassword(packageLicenseKey.getPassword()); Element namespaceElement = assertion.getOwnerDocument().createElement("ns"); namespaceElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:saml", "urn:oasis:names:tc:SAML:1.0:assertion"); Node nihiiNode = XPathAPI.selectSingleNode(assertion, "saml:AttributeStatement/saml:Attribute[@AttributeName='urn:be:fgov:person:ssin:ehealth:1.0:doctor:nihii11']/saml:AttributeValue/text()", namespaceElement); String myNihii = nihiiNode.getTextContent(); LOG.debug("NIHII: " + myNihii); Node ssinNode = XPathAPI.selectSingleNode(assertion, "saml:AttributeStatement/saml:Attribute[@AttributeName='urn:be:fgov:person:ssin']/saml:AttributeValue/text()", namespaceElement); String mySsin = ssinNode.getTextContent(); CareProviderType careProvider = coreObjectFactory.createCareProviderType(); origin.setCareProvider(careProvider); NihiiType nihii = coreObjectFactory.createNihiiType(); careProvider.setNihii(nihii); nihii.setQuality("doctor"); ValueRefString nihiiValue = coreObjectFactory.createValueRefString(); nihii.setValue(nihiiValue); nihiiValue.setValue(myNihii); IdType physicalPerson = coreObjectFactory.createIdType(); careProvider.setPhysicalPerson(physicalPerson); ValueRefString ssinValue = coreObjectFactory.createValueRefString(); physicalPerson.setSsin(ssinValue); ssinValue.setValue(mySsin); commonInput.setInputReference("PRIG1234567890"); RecordCommonInputType recordCommonInput = coreObjectFactory.createRecordCommonInputType(); body.setRecordCommonInput(recordCommonInput); recordCommonInput.setInputReference(new BigDecimal("1234567890123")); SingleInsurabilityRequestType singleInsurabilityRequest = coreObjectFactory .createSingleInsurabilityRequestType(); body.setRequest(singleInsurabilityRequest); CareReceiverIdType careReceiverId = coreObjectFactory.createCareReceiverIdType(); singleInsurabilityRequest.setCareReceiverId(careReceiverId); careReceiverId.setInss(mySsin); InsurabilityRequestDetailType insurabilityRequestDetail = coreObjectFactory .createInsurabilityRequestDetailType(); singleInsurabilityRequest.setInsurabilityRequestDetail(insurabilityRequestDetail); InsurabilityRequestTypeType insurabilityRequestType = InsurabilityRequestTypeType.INFORMATION; insurabilityRequestDetail.setInsurabilityRequestType(insurabilityRequestType); PeriodType period = coreObjectFactory.createPeriodType(); insurabilityRequestDetail.setPeriod(period); DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); GregorianCalendar periodStartCal = new GregorianCalendar(); DateTime periodStartDateTime = new DateTime(); periodStartCal.setTime(periodStartDateTime.toDate()); XMLGregorianCalendar periodStart = datatypeFactory.newXMLGregorianCalendar(periodStartCal); period.setPeriodStart(periodStart); DateTime periodEndDateTime = periodStartDateTime; GregorianCalendar periodEndCal = new GregorianCalendar(); periodEndCal.setTime(periodEndDateTime.toDate()); XMLGregorianCalendar periodEnd = datatypeFactory.newXMLGregorianCalendar(periodEndCal); period.setPeriodEnd(periodEnd); insurabilityRequestDetail.setInsurabilityContactType(InsurabilityContactTypeType.HOSPITALIZED_FOR_DAY); genInsClient.getInsurability(body); }
From source file:test.integ.be.fedict.hsm.ws.WSSecurityTestSOAPHandler.java
private void handleOutboundMessage(SOAPMessageContext context) throws SOAPException, DatatypeConfigurationException, CertificateEncodingException, DOMException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, NoSuchProviderException { SOAPMessage soapMessage = context.getMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); Element soapEnvelopeElement = soapPart.getDocumentElement(); String soapPrefix = soapEnvelopeElement.getPrefix(); LOG.debug("SOAP prefix: " + soapPrefix); Element soapHeaderElement = soapPart.createElementNS(SOAP_NAMESPACE, soapPrefix + ":Header"); Element soapBodyElement = (Element) soapEnvelopeElement.getFirstChild(); soapBodyElement.setAttributeNS(XMLNS_NS, "xmlns:wsu", WSU_NAMESPACE); soapBodyElement.setAttributeNS(WSU_NAMESPACE, "wsu:Id", "Body"); soapEnvelopeElement.insertBefore(soapHeaderElement, soapBodyElement); LOG.debug("adding WS-Security SOAP header"); Element wsSecurityHeaderElement = soapPart.createElementNS(WSSE_NAMESPACE, "wsse:Security"); soapHeaderElement.appendChild(wsSecurityHeaderElement); wsSecurityHeaderElement.setAttributeNS(XMLNS_NS, "xmlns:wsse", WSSE_NAMESPACE); wsSecurityHeaderElement.setAttributeNS(XMLNS_NS, "xmlns:wsu", WSU_NAMESPACE); wsSecurityHeaderElement.setAttributeNS(SOAP_NAMESPACE, soapPrefix + ":mustUnderstand", "true"); Element tsElement = addTimestamp(wsSecurityHeaderElement); addBinarySecurityToken(wsSecurityHeaderElement); addSignature(wsSecurityHeaderElement, tsElement, soapBodyElement); }
From source file:test.integ.be.fedict.hsm.ws.WSSecurityTestSOAPHandler.java
private void addBinarySecurityToken(Element wsSecurityHeaderElement) throws SOAPException, CertificateEncodingException, DOMException { if (null == this.certificate) { return;/* w w w . ja v a2 s.co m*/ } Document document = wsSecurityHeaderElement.getOwnerDocument(); Element binarySecurityTokenElement = document.createElementNS(WSSE_NAMESPACE, "wsse:BinarySecurityToken"); binarySecurityTokenElement.setAttribute("EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"); binarySecurityTokenElement.setAttribute("ValueType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"); binarySecurityTokenElement.setAttributeNS(WSU_NAMESPACE, "wsu:Id", "X509"); binarySecurityTokenElement.setTextContent(Base64.encodeBase64String(this.certificate.getEncoded())); wsSecurityHeaderElement.appendChild(binarySecurityTokenElement); }
From source file:test.integ.be.fedict.hsm.ws.WSSecurityTestSOAPHandler.java
private Element addTimestamp(Element wsSecurityHeaderElement) throws SOAPException, DatatypeConfigurationException { if (false == this.addTimestamp) { return null; }//from w w w . j a v a 2 s . c om Document document = wsSecurityHeaderElement.getOwnerDocument(); Element timestampElement = document.createElementNS(WSU_NAMESPACE, "wsu:Timestamp"); timestampElement.setAttributeNS(WSU_NAMESPACE, "wsu:Id", "TS"); Attr idAttr = timestampElement.getAttributeNodeNS(WSU_NAMESPACE, "Id"); timestampElement.setIdAttributeNode(idAttr, true); Element createdElement = document.createElementNS(WSU_NAMESPACE, "wsu:Created"); DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); GregorianCalendar gregorianCalendar = new GregorianCalendar(); Date now = new Date(); gregorianCalendar.setTime(now); gregorianCalendar.setTimeZone(TimeZone.getTimeZone("UTC")); XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendar(gregorianCalendar); createdElement.setTextContent(xmlGregorianCalendar.toXMLFormat()); timestampElement.appendChild(createdElement); Element expiresElement = document.createElementNS(WSU_NAMESPACE, "wsu:Expires"); Date expiresDate = new Date(now.getTime() + 1000 * 60 * 5); gregorianCalendar.setTime(expiresDate); xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendar(gregorianCalendar); expiresElement.setTextContent(xmlGregorianCalendar.toXMLFormat()); timestampElement.appendChild(expiresElement); wsSecurityHeaderElement.appendChild(timestampElement); return timestampElement; }
From source file:test.integ.be.fedict.trust.WSSecurityTest.java
@Test public void testWSSecurity() throws Exception { // Setup/* w w w. j a va 2 s . co m*/ KeyPair keyPair = TestUtils.generateKeyPair(); X509Certificate certificate = TestUtils.generateSelfSignedCertificate(keyPair, "CN=Test"); KeyPair fooKeyPair = TestUtils.generateKeyPair(); X509Certificate fooCertificate = TestUtils.generateSelfSignedCertificate(fooKeyPair, "CN=F00"); this.wsSecurityClientHandler.setServerCertificate(certificate); KeyStoreType keyStoreType = KeyStoreType.PKCS12; String keyStorePassword = "secret"; String keyEntryPassword = "secret"; String alias = "alias"; File tmpP12File = File.createTempFile("keystore-", ".p12"); tmpP12File.deleteOnExit(); TestUtils.persistInKeyStore(tmpP12File, "pkcs12", keyPair.getPrivate(), certificate, keyStorePassword, keyEntryPassword, alias); String keyStorePath = tmpP12File.getAbsolutePath(); MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); InputStream testSoapMessageInputStream = WSSecurityTest.class.getResourceAsStream("/test-soap-message.xml"); assertNotNull(testSoapMessageInputStream); SOAPMessage message = messageFactory.createMessage(null, testSoapMessageInputStream); SOAPMessageContext soapMessageContext = new TestSOAPMessageContext(message, true); soapMessageContext.put(MessageContext.SERVLET_CONTEXT, this.mockServletContext); // Expectations expect(this.mockServletContext.getAttribute(TrustService.class.getName())).andReturn(mockTrustService); expect(this.mockTrustService.getWsSecurityConfig()).andReturn(new WSSecurityConfigEntity("test", true, keyStoreType, keyStorePath, keyStorePassword, keyEntryPassword, alias)); // Replay replay(this.mockObjects); // Operate : Let WSSecurityServerHandler sign the SOAP message assertTrue(this.wsSecurityServerHandler.handleMessage(soapMessageContext)); // Verify message is signed verify(this.mockObjects); SOAPMessage resultMessage = soapMessageContext.getMessage(); SOAPPart resultSoapPart = resultMessage.getSOAPPart(); LOG.debug("signed SOAP part:" + TestUtils.domToString(resultSoapPart)); Element nsElement = resultSoapPart.createElement("nsElement"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:soap", "http://schemas.xmlsoap.org/soap/envelope/"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", "http://www.w3.org/2000/09/xmldsig#"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); Node resultNode = XPathAPI.selectSingleNode(resultSoapPart, "/soap:Envelope/soap:Header/wsse:Security[@soap:mustUnderstand = '1']", nsElement); assertNotNull(resultNode); assertNotNull("missing WS-Security timestamp", XPathAPI.selectSingleNode(resultSoapPart, "/soap:Envelope/soap:Header/wsse:Security/wsu:Timestamp/wsu:Created", nsElement)); assertEquals(2.0, XPathAPI.eval(resultSoapPart, "count(//ds:Reference)", nsElement).num()); // Setup soapMessageContext.put(MessageContext.MESSAGE_OUTBOUND_PROPERTY, false); // Operate : pass on signed message to WSSecurityClientHandler for // validation assertTrue(this.wsSecurityClientHandler.handleMessage(soapMessageContext)); // Operate : pass on signed message to WSSecurityClient handler // configured with wrong server certificate this.wsSecurityClientHandler.setServerCertificate(fooCertificate); try { this.wsSecurityClientHandler.handleMessage(soapMessageContext); fail(); } catch (SOAPFaultException e) { // expected LOG.debug("SOAPFaultException: " + e.getMessage()); } }
From source file:test.unit.be.agiv.security.client.RSTSClientTest.java
private Element getNSElement(Document document) { Element nsElement = document.createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:soap12", "http://www.w3.org/2003/05/soap-envelope"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:trust", "http://docs.oasis-open.org/ws-sx/ws-trust/200512"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); return nsElement; }
From source file:test.unit.be.agiv.security.client.TestUtils.java
/** * XMLSEC 1.5 requires us to explicitly mark the Id's within a DOM document. * // ww w. j av a2 s. c om * @param document */ public static void markAllIdAttributesAsId(Document document) { Element nsElement = document.createElement("nsElement"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:wsu", WSConstants.WS_SECURITY_UTILITY_NAMESPACE); NodeList elementsWithIdNodeList; try { elementsWithIdNodeList = XPathAPI.selectNodeList(document, "//*[@Id or @wsu:Id]", nsElement); } catch (TransformerException e) { throw new RuntimeException(e); } for (int nodeIdx = 0; nodeIdx < elementsWithIdNodeList.getLength(); nodeIdx++) { Element elementWithId = (Element) elementsWithIdNodeList.item(nodeIdx); LOG.debug("element with Id: " + elementWithId.getLocalName()); Attr attributeNode = elementWithId.getAttributeNode("Id"); if (null == attributeNode) { attributeNode = elementWithId.getAttributeNodeNS(WSConstants.WS_SECURITY_UTILITY_NAMESPACE, "Id"); } elementWithId.setIdAttributeNode(attributeNode, true); } }