Search in sources :

Example 46 with Transforms

use of org.apache.xml.security.transforms.Transforms in project JavaClasses by genexuslabs.

the class GXXMLDsig method signElements.

public String signElements(String xml, String xPath) {
    initialize();
    if (!anyError()) {
        if (!_gxCert.hasPrivateKey()) {
            setError(5);
            return "";
        }
        try {
            Document doc = Utils.documentFromString(Canonicalizer.canonize(xml), true);
            if (doc == null) {
                setError(2);
                return "";
            }
            ArrayList<Element> list = new ArrayList<Element>();
            if (xPath.equals("")) {
                list.add(doc.getDocumentElement());
            } else {
                XPath xPathHelper = XPathFactory.newInstance().newXPath();
                NodeList nodeList = (NodeList) xPathHelper.evaluate(xPath, doc, XPathConstants.NODESET);
                for (int i = 0; i < nodeList.getLength(); i++) {
                    list.add((Element) nodeList.item(i));
                }
            }
            for (int i = 0; i < list.size(); i++) {
                Element element = (Element) list.get(i);
                // Create a DOM XMLSignatureFactory that will be used to
                // generate the enveloped signature.
                // removes signature element if present.
                NodeList nodeListSignature = element.getElementsByTagName("Signature");
                for (int j = 0; j < nodeListSignature.getLength(); j++) {
                    Node parentSignature = nodeListSignature.item(j).getParentNode();
                    parentSignature.removeChild(nodeListSignature.item(j));
                }
                DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
                Document docToBeSigned = docBuilder.newDocument();
                docToBeSigned.appendChild(docToBeSigned.importNode(element, true));
                ElementProxy.setDefaultPrefix(org.apache.xml.security.utils.Constants.SignatureSpecNS, "");
                XMLSignature signature = new XMLSignature(docToBeSigned, "", XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);
                docToBeSigned.getDocumentElement().appendChild(signature.getElement());
                Transforms transforms = new Transforms(docToBeSigned);
                transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
                if (_references.size() > 0) {
                    for (int j = 0; j < _references.size(); j++) {
                        signature.addDocument(_references.get(j), transforms, org.apache.xml.security.utils.Constants.ALGO_ID_DIGEST_SHA1);
                    }
                } else {
                    signature.addDocument("", transforms, // Signs
                    org.apache.xml.security.utils.Constants.ALGO_ID_DIGEST_SHA1);
                // the
                // whole
                // document
                }
                setKeyInfo(signature);
                signature.sign(_gxCert.getPrivateKey());
                Node p = element.getParentNode();
                p.replaceChild(doc.importNode(docToBeSigned.getDocumentElement(), true), element);
            }
            ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
            XMLUtils.outputDOMc14nWithComments(doc, byteArray);
            return new String(byteArray.toByteArray());
        } catch (NoSuchAlgorithmException e) {
            Utils.logError(e);
            setError(3);
        } catch (InvalidAlgorithmParameterException e) {
            Utils.logError(e);
        } catch (Exception e) {
            Utils.logError(e);
            setError(6, e.getMessage());
        }
    }
    return "";
}
Also used : XPath(javax.xml.xpath.XPath) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Transforms(org.apache.xml.security.transforms.Transforms) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Document(org.w3c.dom.Document) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) XMLSignatureException(org.apache.xml.security.signature.XMLSignatureException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) XMLSignature(org.apache.xml.security.signature.XMLSignature)

Example 47 with Transforms

use of org.apache.xml.security.transforms.Transforms in project esocial by tst-labs.

the class AssinaturaXmlServico method assinar.

public String assinar(String xml) {
    String signedXML = null;
    try {
        Init.init();
        ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, "");
        final Document doc = getDocumentBuilder().parse(new InputSource(new StringReader(xml)));
        XMLSignature sig = new XMLSignature(doc, null, signatureMethod);
        doc.getDocumentElement().appendChild(sig.getElement());
        final Transforms transforms = criarTransformacoes(transformList, doc);
        sig.addDocument("", transforms, digestMethod);
        sig.addKeyInfo(certificado.getX509Certificate());
        sig.sign(certificado.getPrivateKey());
        signedXML = getDocString(doc);
    } catch (XMLSecurityException | SAXException | IOException | ParserConfigurationException | TransformerFactoryConfigurationError | TransformerException ex) {
        LOGGER.error("Erro ao assinar", ex);
    }
    return signedXML;
}
Also used : TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) InputSource(org.xml.sax.InputSource) Transforms(org.apache.xml.security.transforms.Transforms) IOException(java.io.IOException) Document(org.w3c.dom.Document) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) SAXException(org.xml.sax.SAXException) XMLSignature(org.apache.xml.security.signature.XMLSignature) StringReader(java.io.StringReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerException(javax.xml.transform.TransformerException)

Example 48 with Transforms

use of org.apache.xml.security.transforms.Transforms in project cxf by apache.

the class XmlSigOutInterceptor method prepareEnvelopedSignature.

private XMLSignature prepareEnvelopedSignature(Document doc, String id, String referenceURI, String sigAlgo, String digestAlgo) throws Exception {
    doc.getDocumentElement().setAttributeNS(null, "Id", id);
    doc.getDocumentElement().setIdAttributeNS(null, "Id", true);
    XMLSignature sig = new XMLSignature(doc, "", sigAlgo);
    doc.getDocumentElement().appendChild(sig.getElement());
    Transforms transforms = new Transforms(doc);
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
    transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
    sig.addDocument(referenceURI, transforms, digestAlgo);
    return sig;
}
Also used : XMLSignature(org.apache.xml.security.signature.XMLSignature) Transforms(org.apache.xml.security.transforms.Transforms)

Example 49 with Transforms

use of org.apache.xml.security.transforms.Transforms in project cxf by apache.

the class XmlSigOutInterceptor method prepareEnvelopingSignature.

private XMLSignature prepareEnvelopingSignature(Document doc, String id, String referenceId, String sigAlgo, String digestAlgo) throws Exception {
    Element docEl = doc.getDocumentElement();
    Document newDoc = DOMUtils.createDocument();
    doc.removeChild(docEl);
    newDoc.adoptNode(docEl);
    Element object = newDoc.createElementNS(Constants.SignatureSpecNS, "ds:Object");
    object.appendChild(docEl);
    docEl.setAttributeNS(null, "Id", id);
    docEl.setIdAttributeNS(null, "Id", true);
    XMLSignature sig = new XMLSignature(newDoc, "", sigAlgo);
    newDoc.appendChild(sig.getElement());
    sig.getElement().appendChild(object);
    Transforms transforms = new Transforms(newDoc);
    transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
    sig.addDocument(referenceId, transforms, digestAlgo);
    return sig;
}
Also used : XMLSignature(org.apache.xml.security.signature.XMLSignature) Element(org.w3c.dom.Element) Transforms(org.apache.xml.security.transforms.Transforms) Document(org.w3c.dom.Document)

Example 50 with Transforms

use of org.apache.xml.security.transforms.Transforms in project cxf by apache.

the class AbstractXmlSigInHandler method validateReference.

protected Element validateReference(Element root, Reference ref) {
    boolean enveloped = false;
    String refId = ref.getURI();
    if (!refId.startsWith("#") || refId.length() <= 1) {
        throwFault("Only local Signature References are supported", null);
    }
    Element signedEl = getSignedElement(root, ref);
    if (signedEl != null) {
        enveloped = signedEl == root;
    } else {
        throwFault("Signature Reference ID is invalid", null);
    }
    Transforms transforms = null;
    try {
        transforms = ref.getTransforms();
    } catch (XMLSecurityException ex) {
        throwFault("Signature transforms can not be obtained", ex);
    }
    boolean c14TransformConfirmed = false;
    String c14TransformExpected = sigProps != null ? sigProps.getSignatureC14nTransform() : null;
    boolean envelopedConfirmed = false;
    for (int i = 0; i < transforms.getLength(); i++) {
        try {
            Transform tr = transforms.item(i);
            if (Transforms.TRANSFORM_ENVELOPED_SIGNATURE.equals(tr.getURI())) {
                envelopedConfirmed = true;
            } else if (c14TransformExpected != null && c14TransformExpected.equals(tr.getURI())) {
                c14TransformConfirmed = true;
            }
        } catch (Exception ex) {
            throwFault("Problem accessing Transform instance", ex);
        }
    }
    if (enveloped && !envelopedConfirmed) {
        throwFault("Only enveloped signatures are currently supported", null);
    }
    if (c14TransformExpected != null && !c14TransformConfirmed) {
        throwFault("Transform Canonicalization is not supported", null);
    }
    if (sigProps != null && sigProps.getSignatureDigestAlgo() != null) {
        Element dm = DOMUtils.getFirstChildWithName(ref.getElement(), Constants.SignatureSpecNS, "DigestMethod");
        if (dm != null && !dm.getAttribute("Algorithm").equals(sigProps.getSignatureDigestAlgo())) {
            throwFault("Signature Digest Algorithm is not supported", null);
        }
    }
    return signedEl;
}
Also used : Element(org.w3c.dom.Element) Transforms(org.apache.xml.security.transforms.Transforms) Transform(org.apache.xml.security.transforms.Transform) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) PatternSyntaxException(java.util.regex.PatternSyntaxException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Aggregations

Transforms (org.apache.xml.security.transforms.Transforms)94 XMLSignature (org.apache.xml.security.signature.XMLSignature)66 Element (org.w3c.dom.Element)57 Document (org.w3c.dom.Document)45 XPath (javax.xml.xpath.XPath)24 XPathFactory (javax.xml.xpath.XPathFactory)23 ByteArrayOutputStream (java.io.ByteArrayOutputStream)22 DSNamespaceContext (org.apache.xml.security.test.dom.DSNamespaceContext)22 PrivateKey (java.security.PrivateKey)20 InputStream (java.io.InputStream)17 ByteArrayInputStream (java.io.ByteArrayInputStream)16 XMLSecurityException (org.apache.xml.security.exceptions.XMLSecurityException)15 NodeList (org.w3c.dom.NodeList)14 SignatureAlgorithm (org.apache.xml.security.algorithms.SignatureAlgorithm)13 ObjectContainer (org.apache.xml.security.signature.ObjectContainer)13 FileInputStream (java.io.FileInputStream)12 XMLSignatureException (org.apache.xml.security.signature.XMLSignatureException)10 XPathContainer (org.apache.xml.security.transforms.params.XPathContainer)10 KeyStore (java.security.KeyStore)9 X509Certificate (java.security.cert.X509Certificate)8