Wednesday, March 05, 2014

Signing SOAP Messages - Generation of Enveloped XML Signatures

Digital signing is a widely used mechanism to make digital contents authentic. By producing a digital signature for some content, we can let another party capable of validating that content. It can provide a guarantee that, is not altered after we signed it, with this validation. With this sample I am to share how to generate the a signature for SOAP envelope. But of course this is valid for any other content signing as well.

Here, I will sign
  • The SOAP envelope itself
  • An attachment 
  • Place the signature inside SOAP header 
With the placement of signature inside the SOAP header which is also signed by the signature, this becomes a demonstration of enveloped signature.

I am using Apache Santuario library for signing. Following is the code segment I used. I have shared the complete sample here to to be downloaded.

public static void main(String unused[]) throws Exception {

        String keystoreType = "JKS";
        String keystoreFile = "src/main/resources/PushpalankaKeystore.jks";
        String keystorePass = "pushpalanka";
        String privateKeyAlias = "pushpalanka";
        String privateKeyPass = "pushpalanka";
        String certificateAlias = "pushpalanka";
        File signatureFile = new File("src/main/resources/signature.xml");
        Element element = null;
        String BaseURI = signatureFile.toURI().toURL().toString();
        //SOAP envelope to be signed
        File attachmentFile = new File("src/main/resources/sample.xml");

        //get the private key used to sign, from the keystore
        KeyStore ks = KeyStore.getInstance(keystoreType);
        FileInputStream fis = new FileInputStream(keystoreFile);
        ks.load(fis, keystorePass.toCharArray());
        PrivateKey privateKey =

                (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());
        //create basic structure of signature
        javax.xml.parsers.DocumentBuilderFactory dbf =
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(attachmentFile);
        XMLSignature sig =
                new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);

        //optional, but better
        element = doc.getDocumentElement();

            Transforms transforms = new Transforms(doc);
            //Sign the content of SOAP Envelope
            sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);

            //Adding the attachment to be signed
            sig.addDocument("../resources/attachment.xml", transforms, Constants.ALGO_ID_DIGEST_SHA1);


        //Signing procedure
            X509Certificate cert =
                    (X509Certificate) ks.getCertificate(certificateAlias);

        //write signature to file
        FileOutputStream f = new FileOutputStream(signatureFile);
        XMLUtils.outputDOMc14nWithComments(doc, f);

At first it reads in the private key which is to be used in signing. To create a key pair for your own, this post  will be helpful. Then it has created the signature and added the SOAP message and the attachment as the documents to be signed. Finally it performs signing  and write the signed document to a file.

The signed SOAP message looks as follows.

<soap:Envelope xmlns:dsig="" xmlns:pj=""
        <pj:MessageHeader pj:version="1.0" soap:mustUnderstand="1">
                <pj:PartyId pj:type="ABCDE">FUN</pj:PartyId>
                <pj:PartyId pj:type="ABCDE">PARTY</pj:PartyId>
            <pj:ConversationId>FUN PARTY FUN 59c64t0087fg3kfs000003n9</pj:ConversationId>
                <pj:MessageId>FUN 59c64t0087fg3kfs000003n9</pj:MessageId>
        <pj:Via pj:id="59c64t0087fg3ki6000003na" pj:syncReply="False" pj:version="1.0"
                soap:actor="" soap:mustUnderstand="1">
        <ds:Signature xmlns:ds="">
                <ds:SignatureMethod Algorithm=""></ds:SignatureMethod>
                <ds:Reference URI="">
                    <ds:DigestMethod Algorithm=""></ds:DigestMethod>
                <ds:Reference URI="../resources/attachment.xml">
                        <ds:Transform Algorithm=""></ds:Transform>
                    <ds:DigestMethod Algorithm=""></ds:DigestMethod>
            <ds:SignatureValue>d0hBQLIvZ4fwUZlrsDLDZojvwK2DVaznrvSoA/JTjnS7XZ5oMplN9  THX4xzZap3+WhXwI2xMr3GKO................x7u+PQz1UepcbKY3BsO8jB3dxWN6r+F4qTyWa+xwOFxqLj546WX35f8zT4GLdiJI5oiYeo1YPLFFqTrwg==
   <ds:X509Certificate>                MIIDjTCCAnWgAwIBAgIEeotzFjANBgkqhkiG9w0BAQsFADB3MQswCQYDVQQGEwJMSzEQMA4GA1UE...............qXfD/eY+XeIDyMQocRqTpcJIm8OneZ8vbMNQrxsRInxq+DsG+C92b
        <pr:GetPriceResponse xmlns:pr="">

In a next post we will see how to verify this signature, so that we can guarantee signed documents are not changed (in other words guarantee that the integrity of the content is preserved) .



  1. This comment has been removed by a blog administrator.

  2. Hi,

    I was looking out for such example to digital sign a soap request to access a webservice. Thanks for the nice example.
    My query is webserver administrator has provided us a .Keystore file (probably a jks file). I would like to know whether privatekeyalias, privatekeypass and certificatealias values would be there in that keystore file or they are to be any values which we would like to set. What is command to see contain of .keystore. Please advise as this is the first time I am trying to sign an XML document.


    Sudhir Kulkarni

    Mumbai - India

    1. Hi,

      The alias values are there in the keystore. But the keystore password, you should know from the administrator.

      Following command will list the certificates in the key store. If you know the alias you are looking at use the second command.

      keytool -list -v -keystore .jks

      keytool -list -v -keystore .jks -alias

  3. Digital Signature in ASP.Net: Super Signature You can Download Supersignature Integration demo project
    electronic signature pad

  4. Please check your sample. Ubuntuone is deleting the file on 31.7.2014 but it is already unavailable for visitors. Is it possible to attach it to your blog ?

    1. Thanks for the heads up.. I will updating the posts hosting them in a new location.

  5. sample program is not available for downloading. could you please attach it to your blog or provide its new loaction?


    1. Hi,

      You can download it from this link ''.

    2. Thanks.

      Actually I need soap request in below format.



      I tried it using wss4j but I am facing issue while configuring security header. any pointer would help,


  6. Hello, My name is Juan Carrillo, I am from Ecuador South America. Thank you for you sample. I am wondering if you can give me some advice: I need to add and "Object" node in my "Signature" node, and I do not know where I can find information to modify my code. Any help I will appreciate. This "Object" is used to meet the requirements of the European Community (

  7. I need to access a web service . I was given a jks file , its alias and password . So I need to build a soap message and sign with this jks file ( Not my own jks file ). How do I do that ? I believe jks file I got is the public key as nobody would share one's private key.. So I need a method to sign SOAP message with public key. I would request you to help on this.

    1. We can encrypt the SOAP message using public key, but not to sign. For signing purposes we should use private key. This convention is made depending on the particular needs each is satisfying.

      Encrypt with public key - Only the party with the relevant private key can read the information. This preserves confidentiality.
      Sign with private key - Any party can get the publicly available public key, generate the signature and compare. This can satisfy, integrity of the information and non-repudiation.

      Considering the above information(which explains the general use), you should decide what you should do.

  8. Hi there! glad to drop by your page and found these very interesting and informative stuff. Thanks for sharing, keep it up!

  9. Just a quick question, why is the sig.addDocument line not referencing the actual content being signed (ie Body)? Shouldn't an identifier be provided to achieve such thing?

  10. This comment has been removed by the author.

  11. hi,

    Thanks for your tutorial, i need to have SOAP message to be digitally signed and added WSSE Securuty Header with keystore , which i want it runnable in SOAP UI.

    Can you please help me to sort this..


  12. Replies
    1. No Jais. I usually do not delete these posts except for advertising stuff. I have replied you question above. If there is another question, please post, I will see if there is anything I can do for you.

  13. Hi,
    Excellent post

    Could you please post - how to verify this signature


  14. Hi,

    Please provide link for how to verify signature and sample code of response.


  15. Hi,

    I need to digitally sign my soap xml request. I have read your code. In your case, it is kept in some file and you pick it up and sign it. But, in my case the request xml is created by some code written in java. How to do it if request is not contained in a file, rather created dynamically. Can anyone help me?



    1. modify the inputstream to be byte array instead of file.

  16. Hi,
    Can you provide idea how to verify Digital Signature

    1. This comment has been removed by the author.

  17. Watch theorem is that a person has a table, you can know rolex replica what is now a few hours, and when he has two tables but can not be determined. Two watches are not to be told V. a person more accurate time, but will let the table to lose confidence in the accuracy of swiss replica watches time. Watch theorem in the enterprise management to give us a very straight The idea of inspiration, that is, to the same person or the same organization management can not be used at the same time two different methods, can not be set at the same time two different goals, and even Every man cannot by two people at the same time command, otherwise it will make the enterprise or the person at a loss. Another layer of swiss rolex meaning is that each person is Can not choose two different values at the same time, otherwise, his behavior will be in chaos.