Example usage for javax.xml.crypto.dsig XMLSignatureFactory newTransform

List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory newTransform

Introduction

In this page you can find the example usage for javax.xml.crypto.dsig XMLSignatureFactory newTransform.

Prototype

public abstract Transform newTransform(String algorithm, XMLStructure params)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException;

Source Link

Document

Creates a Transform for the specified algorithm URI and parameters.

Usage

From source file:org.warlock.itk.distributionenvelope.Payload.java

/** 
 * Sign the payloadBody as-is. Note that this is going to be encrypted anyway
 * so we avoid any incompatibilities due to canonicalisation, and we don't
 * care if the payloadBody is text, compressed and so on. Re-writes payloadBody
 * with a serialised XML Digital Signature "Signature" element containing an
 * enveloping signature, or throws an exception to signal failure. 
 * /*from w w  w  . ja va  2s  . co m*/
 * @param pk
 * @param cert
 * @throws Exception 
 */
private void signPayload(PrivateKey pk, X509Certificate cert) throws Exception {
    if ((pk == null) || (cert == null)) {
        throw new Exception("Null signing material");
    }
    cert.checkValidity();

    XMLSignatureFactory xsf = XMLSignatureFactory.getInstance("DOM");
    Reference ref = null;
    String objectRef = "uuid" + UUID.randomUUID().toString();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = null;
    DOMStructure payloadContent = null;
    if (compressed || base64 || !mimeType.contains("xml")) {
        ref = xsf.newReference("#" + objectRef, xsf.newDigestMethod(DigestMethod.SHA1, null));
        doc = dbf.newDocumentBuilder().newDocument();
        payloadContent = new DOMStructure(doc.createTextNode(payloadBody));
    } else {
        Transform t = xsf.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#",
                (TransformParameterSpec) null);
        ref = xsf.newReference("#" + objectRef, xsf.newDigestMethod(DigestMethod.SHA1, null),
                Collections.singletonList(t), null, null);
        doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(payloadBody)));
        payloadContent = new DOMStructure(doc.getDocumentElement());
    }
    XMLObject payloadObject = xsf.newXMLObject(Collections.singletonList(payloadContent), objectRef, null,
            null);
    SignedInfo si = xsf.newSignedInfo(
            xsf.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null),
            xsf.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));

    KeyInfoFactory kif = xsf.getKeyInfoFactory();
    ArrayList<Object> x509content = new ArrayList<Object>();
    x509content.add(cert);
    X509Data xd = kif.newX509Data(x509content);

    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
    XMLSignature signature = xsf.newXMLSignature(si, ki, Collections.singletonList(payloadObject), null, null);
    DOMSignContext dsc = new DOMSignContext(pk, doc);
    signature.sign(dsc);
    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);
    Transformer tx = TransformerFactory.newInstance().newTransformer();
    tx.transform(new DOMSource(doc), sr);
    if (sw.toString().indexOf("<?xml ") == 0) {
        payloadBody = sw.toString().substring(sw.toString().indexOf("?>") + "?>".length());
    } else {
        payloadBody = sw.toString();
    }
}

From source file:test.integ.be.fedict.hsm.ws.WSSecurityTestSOAPHandler.java

private void addSignature(Element wsSecurityHeaderElement, Element tsElement, Element bodyElement)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException,
        XMLSignatureException, NoSuchProviderException, SOAPException {
    if (null == this.privateKey) {
        return;//from w w  w  .j  a v  a 2 s .  c  o m
    }
    DOMSignContext domSignContext = new DOMSignContext(this.privateKey, wsSecurityHeaderElement);
    domSignContext.setDefaultNamespacePrefix("ds");
    domSignContext.setIdAttributeNS(tsElement, WSU_NAMESPACE, "Id");
    domSignContext.setIdAttributeNS(bodyElement, WSU_NAMESPACE, "Id");
    LOG.debug("Timestamp element found: " + (null != domSignContext.getElementById("TS")));
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");

    List<Reference> references = new LinkedList<Reference>();

    List<String> tsPrefixes = new LinkedList<String>();
    tsPrefixes.add("wsse");
    tsPrefixes.add("S");
    ExcC14NParameterSpec tsTransformSpec = new ExcC14NParameterSpec(tsPrefixes);
    Reference tsReference = xmlSignatureFactory.newReference("#TS",
            xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null),
            Collections.singletonList(
                    xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, tsTransformSpec)),
            null, null);
    references.add(tsReference);

    if (this.signBody) {
        List<String> bodyPrefixes = new LinkedList<String>();
        ExcC14NParameterSpec bodyTransformSpec = new ExcC14NParameterSpec(bodyPrefixes);
        Reference bodyReference = xmlSignatureFactory.newReference("#Body",
                xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null),
                Collections.singletonList(
                        xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, bodyTransformSpec)),
                null, null);
        references.add(bodyReference);
    }

    if (this.signBinarySecurityToken) {
        Reference bstReference = xmlSignatureFactory
                .newReference("#X509", xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null),
                        Collections.singletonList(xmlSignatureFactory
                                .newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)),
                        null, null);
        references.add(bstReference);
    }

    SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(
            xmlSignatureFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
                    (C14NMethodParameterSpec) null),
            xmlSignatureFactory.newSignatureMethod(this.signatureAlgorithm, null), references);

    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    Document document = wsSecurityHeaderElement.getOwnerDocument();
    Element securityTokenReferenceElement = document.createElementNS(WSSE_NAMESPACE,
            "wsse:SecurityTokenReference");
    Element referenceElement = document.createElementNS(WSSE_NAMESPACE, "wsse:Reference");
    referenceElement.setAttribute("ValueType",
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3");
    referenceElement.setAttribute("URI", "#X509");
    securityTokenReferenceElement.appendChild(referenceElement);
    KeyInfo keyInfo = keyInfoFactory
            .newKeyInfo(Collections.singletonList(new DOMStructure(securityTokenReferenceElement)));

    XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo, null, "SIG", null);
    xmlSignature.sign(domSignContext);
}

From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java

@Test
public void testJsr105SignatureExternalXML() throws Exception {
    KeyPair keyPair = PkiTestUtils.generateKeyPair();

    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);/*from   w w  w  .  ja  va  2s.co  m*/
    Element dataElement = document.createElementNS("urn:test", "tns:data");
    dataElement.setAttributeNS(null, "Id", "id-1234");
    dataElement.setTextContent("data to be signed");
    rootElement.appendChild(dataElement);

    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    XMLSignContext signContext = new DOMSignContext(keyPair.getPrivate(), document.getDocumentElement());
    signContext.setURIDereferencer(new MyURIDereferencer());
    signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds");

    DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null);

    List<Transform> transforms = new LinkedList<Transform>();
    Transform transform = signatureFactory.newTransform(CanonicalizationMethod.INCLUSIVE,
            (TransformParameterSpec) null);
    transforms.add(transform);
    Reference reference = signatureFactory.newReference("/helloworld.xml", digestMethod, transforms, null,
            null);

    DOMReference domReference = (DOMReference) reference;
    assertNull(domReference.getCalculatedDigestValue());
    assertNull(domReference.getDigestValue());

    SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
    CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod(
            CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod,
            Collections.singletonList(reference));

    javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null);

    DOMXMLSignature domXmlSignature = (DOMXMLSignature) xmlSignature;
    domXmlSignature.marshal(document.getDocumentElement(), "ds", (DOMCryptoContext) signContext);
    domReference.digest(signContext);
    // xmlSignature.sign(signContext);
    // LOG.debug("signed document: " + toString(document));

    Element nsElement = document.createElement("ns");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS);
    Node digestValueNode = XPathAPI.selectSingleNode(document, "//ds:DigestValue", nsElement);
    assertNotNull(digestValueNode);
    String digestValueTextContent = digestValueNode.getTextContent();
    LOG.debug("digest value text content: " + digestValueTextContent);
    assertFalse(digestValueTextContent.isEmpty());
}

From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java

@Test
public void testJsr105SignatureExternalXMLWithDTD() throws Exception {
    KeyPair keyPair = PkiTestUtils.generateKeyPair();

    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);// w ww  .j a v a 2  s  .com
    Element dataElement = document.createElementNS("urn:test", "tns:data");
    dataElement.setAttributeNS(null, "Id", "id-1234");
    dataElement.setTextContent("data to be signed");
    rootElement.appendChild(dataElement);

    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    XMLSignContext signContext = new DOMSignContext(keyPair.getPrivate(), document.getDocumentElement());
    signContext.setURIDereferencer(new MyURIDereferencer());
    signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds");

    DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null);

    List<Transform> transforms = new LinkedList<Transform>();
    Transform transform = signatureFactory.newTransform(CanonicalizationMethod.INCLUSIVE,
            (TransformParameterSpec) null);
    LOG.debug("transform type: " + transform.getClass().getName());
    transforms.add(transform);
    Reference reference = signatureFactory.newReference("/bookstore.xml", digestMethod, transforms, null, null);

    DOMReference domReference = (DOMReference) reference;
    assertNull(domReference.getCalculatedDigestValue());
    assertNull(domReference.getDigestValue());

    SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
    CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod(
            CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod,
            Collections.singletonList(reference));

    javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null);

    DOMXMLSignature domXmlSignature = (DOMXMLSignature) xmlSignature;
    domXmlSignature.marshal(document.getDocumentElement(), "ds", (DOMCryptoContext) signContext);
    domReference.digest(signContext);
    // xmlSignature.sign(signContext);
    // LOG.debug("signed document: " + toString(document));

    Element nsElement = document.createElement("ns");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS);
    Node digestValueNode = XPathAPI.selectSingleNode(document, "//ds:DigestValue", nsElement);
    assertNotNull(digestValueNode);
    String digestValueTextContent = digestValueNode.getTextContent();
    LOG.debug("digest value text content: " + digestValueTextContent);
    assertFalse(digestValueTextContent.isEmpty());
}