Sign SOAP message : SOAP « Web Services SOA « Java Tutorial

Java Tutorial
1. Language
2. Data Type
3. Operators
4. Statement Control
5. Class Definition
6. Development
7. Reflection
8. Regular Expressions
9. Collections
10. Thread
11. File
12. Generics
13. I18N
14. Swing
15. Swing Event
16. 2D Graphics
17. SWT
18. SWT 2D Graphics
19. Network
20. Database
21. JSP
22. JSTL
23. Servlet
24. Web Services SOA
25. Email
26. J2ME
27. J2EE Application
28. XML
29. Design Pattern
30. Log
31. Security
32. Apache Common
Java
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Tutorial » Web Services SOA » SOAP 
24. 2. 6. Sign SOAP message
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.util.Collections;

import javax.xml.crypto.dsig.CanonicalizationMethod;
import javax.xml.crypto.dsig.DigestMethod;
import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.SignatureMethod;
import javax.xml.crypto.dsig.SignedInfo;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
import javax.xml.crypto.dsig.keyinfo.KeyValue;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

public class Signing {

  public static void main(String[] argsthrows 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(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 = ((DOMSourcesource).getNode();
    else if (source instanceof SAXSource) {
      InputSource inSource = ((SAXSourcesource).getInputSource();
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      DocumentBuilder db = null;

      db = dbf.newDocumentBuilder();

      Document doc = db.parse(inSource);
      root = (Nodedoc.getDocumentElement();
    }

    dumpDocument(root);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
    kpg.initialize(1024new 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, (C14NMethodParameterSpecnull), 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);
  }

  private static void dumpDocument(Node rootthrows TransformerException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(new DOMSource(root)new StreamResult(System.out));
  }

  private static Element getFirstChildElement(Node node) {
    Node child = node.getFirstChild();
    while ((child != null&& (child.getNodeType() != Node.ELEMENT_NODE)) {
      child = child.getNextSibling();
    }
    return (Elementchild;
  }

  public static Element getNextSiblingElement(Node node) {
    Node sibling = node.getNextSibling();
    while ((sibling != null&& (sibling.getNodeType() != Node.ELEMENT_NODE)) {
      sibling = sibling.getNextSibling();
    }
    return (Elementsibling;
  }
}
/*

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header>
<SOAP-SEC:Signature xmlns:SOAP-SEC="http://schemas.xmlsoap.org/soap/security/2000-12"/>
</SOAP-ENV:Header>
<SOAP-ENV:Body xmlns:SOAP-SEC="http://schemas.xmlsoap.org/soap/security/2000-12" SOAP-SEC:id="Body">
<z:FooBar xmlns:z="http://example.com"/>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Signing the message...
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header>
<SOAP-SEC:Signature xmlns:SOAP-SEC="http://schemas.xmlsoap.org/soap/security/2000-12"/>
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"/>
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1"/>
<ds:Reference URI="#Body">
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<ds:DigestValue>9x0mZhajy9dHKuIXh7bm0khuC7M=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>CiKztXFr2HnE1ul1S5OrJpiYCV46MJ9jEiDaU7AkAiCsgkTDxAhzyA==</ds:SignatureValue>
<ds:KeyInfo>
<ds:KeyValue>
<ds:DSAKeyValue>
<ds:P>/X9TgR11EilS30qcLuzk5/YRt1I870QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuA
HTRv8mZgt2uZUKWkn5/oBHsQIsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOu
K2HXKu/yIgMZndFIAcc=</ds:P>
<ds:Q>l2BQjxUjC8yykrmCouuEC/BYHPU=</ds:Q>
<ds:G>9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3
zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKL
Zl6Ae1UlZAFMO/7PSSo=</ds:G>
<ds:Y>j9Jsiuc8WtI3LxN+wuVUHsCJ5i22tG2SBtiRzKoWrpso/Tk62TJRN7FNsWQ0lDqIqJrQt4GqzkHx
yiRtmqm0xDsAd2ojzH1OZiGen+C8dsbAA4ydwmP1iz9UyAwevrdA/rhOAqgTUFv0ar9koh0aG/Wn
iFrXoLYt5eVzpw/swT4=</ds:Y>
</ds:DSAKeyValue>
</ds:KeyValue>
</ds:KeyInfo>
</ds:Signature>
</SOAP-ENV:Header>
<SOAP-ENV:Body xmlns:SOAP-SEC="http://schemas.xmlsoap.org/soap/security/2000-12" SOAP-SEC:id="Body">
<z:FooBar xmlns:z="http://example.com"/>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Validate the signature...
Signature valid? true



*/

#Code referenced from 
#Chapter - Extensible Markup Language (XML)
#Java Platform Revealed
#by John Zukowski 
#ISBN: 1590596609
#http://www.apress.com/book/bookDisplay.html?bID=10109
24. 2. SOAP
24. 2. 1. Create SOAP message
24. 2. 2. Generate DOM with SOAP message
24. 2. 3. Output SOAP message with XML transformer
24. 2. 4. Generate DSA key pair
24. 2. 5. Use DSA key pair to generate XML Signature
24. 2. 6. Sign SOAP message
24. 2. 7. Call google web service and deal with the return with SOAPMessage
24. 2. 8. Sending a SOAP Message
24. 2. 9. Processing a SOAP Message
www.j__a__v___a___2_s_.__c___om__ | Contact Us
Copyright 2003 - 08 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.