List of usage examples for javax.xml.crypto.dsig.dom DOMValidateContext setIdAttributeNS
public void setIdAttributeNS(Element element, String namespaceURI, String localName)
From source file:Signing.java
public static void main(String[] args) throws Exception { SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPHeader soapHeader = soapEnvelope.getHeader(); SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12")); SOAPBody soapBody = soapEnvelope.getBody(); soapBody.addAttribute(// ww w .j a va 2s .co m soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"), "Body"); Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com"); SOAPBodyElement gltp = soapBody.addBodyElement(bodyName); Source source = soapPart.getContent(); Node root = null; if (source instanceof DOMSource) { root = ((DOMSource) source).getNode(); } else if (source instanceof SAXSource) { InputSource inSource = ((SAXSource) source).getInputSource(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = null; db = dbf.newDocumentBuilder(); Document doc = db.parse(inSource); root = (Node) doc.getDocumentElement(); } dumpDocument(root); KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(1024, new SecureRandom()); KeyPair keypair = kpg.generateKeyPair(); XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance(); Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null)); SignedInfo signedInfo = sigFactory.newSignedInfo( sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); KeyInfoFactory kif = sigFactory.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(keypair.getPublic()); KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo); System.out.println("Signing the message..."); PrivateKey privateKey = keypair.getPrivate(); Element envelope = getFirstChildElement(root); Element header = getFirstChildElement(envelope); DOMSignContext sigContext = new DOMSignContext(privateKey, header); sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); sigContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); sig.sign(sigContext); dumpDocument(root); System.out.println("Validate the signature..."); Element sigElement = getFirstChildElement(header); DOMValidateContext valContext = new DOMValidateContext(keypair.getPublic(), sigElement); valContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); boolean valid = sig.validate(valContext); System.out.println("Signature valid? " + valid); }
From source file:Main.java
/** * /* www. ja v a 2 s . c om*/ * @param context * @param element */ public static void recursiveIdBrowse(DOMValidateContext context, Element element) { for (int i = 0; i < element.getChildNodes().getLength(); i++) { Node node = element.getChildNodes().item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element childEl = (Element) node; String ID_ATTRIBUTE_NAME = "Id"; if (childEl.hasAttribute(ID_ATTRIBUTE_NAME)) { context.setIdAttributeNS(childEl, null, ID_ATTRIBUTE_NAME); } recursiveIdBrowse(context, childEl); } } }
From source file:eu.europa.esig.dss.DSSXMLUtils.java
/** * If this method finds an attribute with names ID (case-insensitive) then declares it to be a user-determined ID attribute. * * @param childElement/*from w w w . jav a2s .c om*/ */ public static void setIDIdentifier(final DOMValidateContext context, final Element childElement) { final NamedNodeMap attributes = childElement.getAttributes(); for (int jj = 0; jj < attributes.getLength(); jj++) { final Node item = attributes.item(jj); final String localName = item.getNodeName(); if (localName != null) { final String id = localName.toLowerCase(); if (ID_ATTRIBUTE_NAME.equals(id)) { context.setIdAttributeNS(childElement, null, localName); break; } } } }
From source file:eu.europa.ec.markt.dss.validation.xades.XAdESSignature.java
private void recursiveIdBrowse(DOMValidateContext context, Element element) { for (int i = 0; i < element.getChildNodes().getLength(); i++) { Node node = element.getChildNodes().item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element childEl = (Element) node; if (childEl.hasAttribute("Id")) { context.setIdAttributeNS(childEl, null, "Id"); }/*www. j a va 2 s . co m*/ recursiveIdBrowse(context, childEl); } } }
From source file:eu.europa.ec.markt.dss.validation102853.xades.XAdESSignature.java
@Override public SignatureCryptographicVerification checkIntegrity(DSSDocument detachedDocument) { final SignatureCryptographicVerification scv = new SignatureCryptographicVerification(); final CertificateToken certToken = getSigningCertificate().getCertToken(); if (certToken != null) { final PublicKey publicKey = certToken.getCertificate().getPublicKey(); final KeySelector keySelector = KeySelector.singletonKeySelector(publicKey); /** * Creating a Validation Context<br> * We create an XMLValidateContext instance containing input parameters for validating the signature. Since we * are using DOM, we instantiate a DOMValidateContext instance (a subclass of XMLValidateContext), and pass it * two parameters, a KeyValueKeySelector object and a reference to the Signature element to be validated (which * is the first entry of the NodeList we generated earlier): *//*from w w w .j av a 2s . com*/ final DOMValidateContext valContext = new DOMValidateContext(keySelector, signatureElement); try { URIDereferencer dereferencer = new ExternalFileURIDereferencer(detachedDocument); valContext.setURIDereferencer(dereferencer); /** * This property controls whether or not the digested Reference objects will cache the dereferenced content * and pre-digested input for subsequent retrieval via the Reference.getDereferencedData and * Reference.getDigestInputStream methods. The default value if not specified is Boolean.FALSE. */ valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); /** * Unmarshalling the XML Signature<br> * We extract the contents of the Signature element into an XMLSignature object. This process is called * unmarshalling. The Signature element is unmarshalled using an XMLSignatureFactory object. An application * can obtain a DOM implementation of XMLSignatureFactory by calling the following line of code: */ // These providers do not support ECDSA algorithm // factory = XMLSignatureFactory.getInstance("DOM"); // factory = XMLSignatureFactory.getInstance("DOM", "XMLDSig"); // factory = XMLSignatureFactory.getInstance("DOM", new org.jcp.xml.dsig.internal.dom.XMLDSigRI()); // This provider support ECDSA signature /** * ApacheXMLDSig / Apache Santuario XMLDSig (DOM XMLSignatureFactory; DOM KeyInfoFactory; C14N 1.0, C14N * 1.1, Exclusive C14N, Base64, Enveloped, XPath, XPath2, XSLT TransformServices)<br> * If this library is used than the same library must be used for the URIDereferencer. */ final XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM", xmlProvider); /** * We then invoke the unmarshalXMLSignature method of the factory to unmarshal an XMLSignature object, and * pass it the validation context we created earlier: */ final XMLSignature signature = factory.unmarshalXMLSignature(valContext); //System.out.println("XMLSignature class: " + signature.getClass()); // Austrian specific signature //org.apache.xml.security.signature.XMLSignature signature_ = null; // try { // signature_ = new org.apache.xml.security.signature.XMLSignature(signatureElement, ""); // } catch (Exception e) { // // throw new DSSException(e); // } // signature.addResourceResolver(new XPointerResourceResolver(signatureElement)); //signature_.getSignedInfo().verifyReferences();//getVerificationResult(1); /** * In case of org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI() provider, the ID attributes need to be set * manually.<br> * The DSSXMLUtils.recursiveIdBrowse(...) method do not take into account the XML outside of the Signature * tag. It prevents some signatures to be validated.<br> * * Solution: the following lines where added: */ final Document document = signatureElement.getOwnerDocument(); final Element rootElement = document.getDocumentElement(); if (rootElement.hasAttribute(DSSXMLUtils.ID_ATTRIBUTE_NAME)) { valContext.setIdAttributeNS(rootElement, null, DSSXMLUtils.ID_ATTRIBUTE_NAME); } DSSXMLUtils.recursiveIdBrowse(valContext, rootElement); /** * Validating the XML Signature<br> * Now we are ready to validate the signature. We do this by invoking the validate method on the * XMLSignature object, and pass it the validation context as follows: */ boolean coreValidity = false; try { coreValidity = signature.validate(valContext); } catch (XMLSignatureException e) { scv.setErrorMessage("Signature validation: " + e.getMessage()); } boolean signatureValidity = coreValidity; boolean dataFound = true; boolean dataHashValid = true; /** * If the XMLSignature.validate method returns false, we can try to narrow down the cause of the failure. * There are two phases in core XML Signature validation: <br> * - Signature validation (the cryptographic verification of the signature)<br> * - Reference validation (the verification of the digest of each reference in the signature)<br> * Each phase must be successful for the signature to be valid. To check if the signature failed to * cryptographically validate, we can check the status, as follows: */ try { signatureValidity = signature.getSignatureValue().validate(valContext); } catch (XMLSignatureException e) { scv.setErrorMessage(e.getMessage()); } @SuppressWarnings("unchecked") final List<Reference> references = signature.getSignedInfo().getReferences(); for (Reference reference : references) { boolean refHashValidity = false; try { refHashValidity = reference.validate(valContext); } catch (XMLSignatureException e) { scv.setErrorMessage(reference.getURI() + ": " + e.getMessage()); } dataHashValid = dataHashValid && refHashValidity; if (LOG.isLoggable(Level.INFO)) { LOG.info("Reference hash validity checked: " + reference.getURI() + "=" + refHashValidity); } final Data data = reference.getDereferencedData(); dataFound = dataFound && (data != null); final InputStream digestInputStream = reference.getDigestInputStream(); if (data != null && digestInputStream != null) { // The references are saved for later treatment in -A level. try { IOUtils.copy(digestInputStream, referencesDigestOutputStream); } catch (IOException e) { } } } scv.setReferenceDataFound(dataFound); scv.setReferenceDataIntact(dataHashValid); scv.setSignatureIntegrity(signatureValidity); } catch (MarshalException e) { scv.setErrorMessage(e.getMessage()); } } else { scv.setErrorMessage( "Unable to proceed with the signature cryptographic verification. There is no signing certificate!"); } return scv; }
From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java
/** * ? .// ww w .ja v a 2 s. c o m */ private static void fixWsuId(final Node node, final DOMValidateContext ctx, final Set<String> ids) { if (node instanceof Element) { final NamedNodeMap attributes = node.getAttributes(); if (attributes != null) { final Node wsuId = attributes.getNamedItemNS(WSU, "Id"); if (wsuId != null) { final String id = wsuId.getNodeValue(); if (ids.contains(id)) { throw new RuntimeException( "? ? " + node + " @" + wsuId); } ids.add(id); ctx.setIdAttributeNS((Element) node, WSU, "Id"); } } } final NodeList children = node.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { fixWsuId(children.item(i), ctx, ids); } } }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java
@Test public void testSignEnvelopingDocument() throws Exception { // setup// w ww . j a v a2 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); }