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 =
javax.xml.parsers.DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
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();
element.normalize();
element.getElementsByTagName("soap:Header").item(0).appendChild(sig.getElement());
{
Transforms transforms = new Transforms(doc);
transforms.addTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS);
//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);
sig.addKeyInfo(cert);
sig.addKeyInfo(cert.getPublicKey());
sig.sign(privateKey);
}
//write signature to file
FileOutputStream f = new FileOutputStream(signatureFile);
XMLUtils.outputDOMc14nWithComments(doc, f);
f.close();
}
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="http://www.w3.org/2000/09/xmldsig#" xmlns:pj="http://www.pjxml.org/namespaces/messageHeader"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance">
<soap:Header>
<pj:MessageHeader pj:version="1.0" soap:mustUnderstand="1">
<pj:From>
<pj:PartyId pj:type="ABCDE">FUN</pj:PartyId>
</pj:From>
<pj:To>
<pj:PartyId pj:type="ABCDE">PARTY</pj:PartyId>
</pj:To>
<pj:CPAId>uri:www.pjxml.org/socialService/Ping</pj:CPAId>
<pj:ConversationId>FUN PARTY FUN 59c64t0087fg3kfs000003n9</pj:ConversationId>
<pj:Service>uri:www.pjxml.org/socialService/</pj:Service>
<pj:Action>Ping</pj:Action>
<pj:MessageData>
<pj:MessageId>FUN 59c64t0087fg3kfs000003n9</pj:MessageId>
<pj:Timestamp>2013-10-22T17:12:20</pj:Timestamp>
</pj:MessageData>
</pj:MessageHeader>
<pj:Via pj:id="59c64t0087fg3ki6000003na" pj:syncReply="False" pj:version="1.0"
soap:actor="http://schemas.xmlsoap.org/soap/actor/next" soap:mustUnderstand="1">
<pj:Service>uri:www.pjxml.org/socialService/</pj:Service>
<pj:Action>Ping</pj:Action>
</pj:Via>
<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"></ds:CanonicalizationMethod>
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></ds:SignatureMethod>
<ds:Reference URI="">
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod>
<ds:DigestValue>9RXY9kp/Klx36gd4BULvST4qffI=</ds:DigestValue>
</ds:Reference>
<ds:Reference URI="../resources/attachment.xml">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"></ds:Transform>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod>
<ds:DigestValue>3JcccO8+0bCUUR3EJxGJKJ+Wrbc=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>d0hBQLIvZ4fwUZlrsDLDZojvwK2DVaznrvSoA/JTjnS7XZ5oMplN9 THX4xzZap3+WhXwI2xMr3GKO................x7u+PQz1UepcbKY3BsO8jB3dxWN6r+F4qTyWa+xwOFxqLj546WX35f8zT4GLdiJI5oiYeo1YPLFFqTrwg==
</ds:SignatureValue>
<ds:KeyInfo>
<ds:X509Data>
<ds:X509Certificate> MIIDjTCCAnWgAwIBAgIEeotzFjANBgkqhkiG9w0BAQsFADB3MQswCQYDVQQGEwJMSzEQMA4GA1UE...............qXfD/eY+XeIDyMQocRqTpcJIm8OneZ8vbMNQrxsRInxq+DsG+C92b
</ds:X509Certificate>
</ds:X509Data>
<ds:KeyValue>
<ds:RSAKeyValue>
<ds:Modulus>
k5y0amGgOQ2O/St0Kc2/xye80tX2fDEKs2YOlM/zCknL8VgK0CbAKVAwvJoycQL9mGRkPDmbitHe............StGofmsoKURzo8hofYEn41rGsq5wCuqJhhHYGDrPpFcuJiuI3SeXgcMtBnMwsIaKv2uHaPRbNX31WEuabuv6Q==
</ds:Modulus>
<ds:Exponent>AQAB</ds:Exponent>
</ds:RSAKeyValue>
</ds:KeyValue>
</ds:KeyInfo>
</ds:Signature>
</soap:Header>
<soap:Body>
<pr:GetPriceResponse xmlns:pr="http://www.pushpalankajaya.com/prices">
<pr:Price>1.90</pr:Price>
</pr:GetPriceResponse>
</soap:Body>
</soap:Envelope>
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) .
Cheers!
This comment has been removed by a blog administrator.
ReplyDeleteHi,
ReplyDeleteI 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.
Regards
Sudhir Kulkarni
Mumbai - India
Hi,
DeleteThe 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
Digital Signature in ASP.Net: Super Signature You can Download Supersignature Integration demo project
ReplyDeleteelectronic signature pad
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 ?
ReplyDeleteThanks for the heads up.. I will updating the posts hosting them in a new location.
Deletesample program is not available for downloading. could you please attach it to your blog or provide its new loaction?
ReplyDeleteThanks
Hi,
DeleteYou can download it from this link 'https://drive.google.com/file/d/0B1njqfOEx3g8dHVaSHh6Mml5NU0/view?usp=sharing'.
Thanks.
DeleteActually I need soap request in below format.
MIIPOzCCA7cwggKfoAMCAQICEAz..............sfsafsafsag=RrJ63VcKP5Mm4kiLSjryxsSywl3...........
12432
I tried it using wss4j but I am facing issue while configuring security header. any pointer would help,
Thanks
Hi Pushpalanka,
DeleteStill I am unable to download from the link given by you. Could you please attach to your blog or provide some working location ?
Thank you.
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 (etsi.org/01903/v1.3.2)
ReplyDeleteI 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.
ReplyDeleteWe 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.
DeleteEncrypt 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.
Hi there! glad to drop by your page and found these very interesting and informative stuff. Thanks for sharing, keep it up!
ReplyDeleteJust 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?
ReplyDeleteThis comment has been removed by the author.
ReplyDeletehi,
ReplyDeleteThanks 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..
Thanks
deleted my post?
ReplyDeleteNo 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.
DeleteHi,
ReplyDeleteExcellent post
Could you please post - how to verify this signature
Thanks
Ramesh
Hi,
ReplyDeletePlease provide link for how to verify signature and sample code of response.
Thanks,
Gahininath
Hi,
ReplyDeleteI 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?
Thanks,
Roy
modify the inputstream to be byte array instead of file.
DeleteI have the same problem.Can anyone help out with the solution. I am using Spring-WS that would automatically generate XML request. Wanted to know how can I integrate this signed signature with the XML. Any suggestions/sample code with something like interceptors..etc please?
DeleteHi,
ReplyDeleteCan you provide idea how to verify Digital Signature
This comment has been removed by the author.
Deletehi pushpa we are facing an issue in acessing a web service that needs to digitally signed SOAP request we are not getting an idea how to send that request please can you help us for resolving this issue
ReplyDeleteHi Pushpalanka,
ReplyDeleteThis blog post was very helpful! Thank you so much.
Your blog is great. Keep up the good work!
This comment has been removed by a blog administrator.
ReplyDeleteHi Pushpalanka,
ReplyDeleteI'm currently working on a program where I will be sending a SOAP request to a third party. I'm currently having issues with the WSSE:BinarySecurityToken.
The third party has provided me with a cert and cert password to test with, I am able to export the cert but storing it into the WSSE:BinarySecurityToken element ends when SOAP is sending request as "authentication issues". I posted a question at c sharp corner if you could help me that would be great!
http://www.c-sharpcorner.com/Forums/signing-xml-document-for-soap
This comment has been removed by a blog administrator.
ReplyDeletegood post!.
ReplyDeleteThanks!
Hi ,
ReplyDeleteI have a requirement to have the X509Data element inside SecurityTokenReference element.
Any views on how to do it with apache santuario / org apache xml security signature is much appreciated.
I have added a question in stackoverflow on the same:
https://stackoverflow.com/questions/49568675/apache-santuario-for-signing-does-not-add-securitytokenreference-under-keyinfo
It is our need that you put it here in your post as much useful that all can take it as a good thing from your site. Thank you.
ReplyDeletedigital marketing company in india
In the last few months we've seen a lot of Health Care Reform rules and regulations being introduced by the Health and Human Services Department. Every time that happens, the media gets hold of it and all kinds of articles are written in the Wall Street Journal, the New York Times, and the TV network news programs talk about it. All the analysts start talking about the pros and cons, and what it means to businesses and individuals. Health is God
ReplyDeleteI think this is a real great article post.Really looking forward to read more. Visit at
ReplyDeleteCrazy Video Hub
Nutra Trials defines personal characteristics of different health products including skincare, weight loss, muscle and male enhancement. The study presented here is briefly described for reader convenience and to deliver them assurance with health standards. The best possible answers are given here regarding the selection of an ideal supplement or cream or serum that possibly remains to be safe for health and do not cause any side effects.
ReplyDeleteIt is a great job, I like your posts and wish you all the best. and I hope you continue this job well.
ReplyDeleteNutraT line
This is a great post ! it was very informative. I look forward in reading more of your work. Also, I made sure to bookmark your website so I can come back later. I enjoyed every moment of reading it..
ReplyDeletekim kardashian sex tape
porn sex video hd
mia khalifa sex video
sunny leone sexy movie
It is nice blog Thank you provide important information and I am searching for the same information to save my time Big Data Hadoop Online Training
ReplyDeleteHello, I am thomus jons thank you for this informative post. That is a great job. Wish you more success.Thank you so much and for you all the best. Takes Down
ReplyDelete123movies
Times For Health is Online Health & Wellness Program! Your post is so informative and i got everything from it. Thanks again! https://www.timesforhealth.com/
ReplyDeleteTecSmash is your ultimate source of Technology news and Make Money Online product reviews. We research and review all Tech, MMO, Biz Opp and IM products.TecSmash
ReplyDeleteBest softwares for Internet Marketers and legitimate make money online opportunities cxyrc
ReplyDeleteHealRun is a health news blog we provide the latest news about health, Drugs and latest Diseases and conditions. We update our users with health tips and health products reviews. If you want to know any information about health or health product (Side Effects & Benefits) Feel Free To ask HealRun Support Team.
ReplyDeleteWe are here to give you a complete review on the Parallel Profit project by Steve Clayton and Aidan Booth. If you are someone from the field you would already be familiar with these two names, for those of who are new. Parallel Profits Price
ReplyDeleteSupplements For Fitness While we have discovered some applications for vitamins and plant compounds isolated ... and although sometimes I suggest that my patients use certain extracts or isolated vitamins ... when it comes to this, nothing better than the complex chemistry of food to give your body The best nutrition.
ReplyDeletePilpedia is supplying 100 percent original and accurate information at each moment of time around our site and merchandise, and the intent is to improve the usage of good and pure health supplement. For More Info please visit Pilpedia online store.
ReplyDeleteKeto 180 Shark Tank : Nutrients vegetarians might try out a replacement vegan menu created of six food teams alone. How sometimes do folks start working out solely to prevent after a few days, weeks or months. However, considering that the diet lasts solely three days, these don't seem to be dispositive. Many superfoods like green tea, acai berry, and other berries are thought-about as superfoods due to the quantity of antioxidants present in them.
ReplyDeletehttp://180keto.net/
https://www.smore.com/yktvg-keto-180
This comment has been removed by the author.
ReplyDeleteHigh profile Bangalore Escorts
ReplyDeleteHigh profile Bangalore Escorts
High profile Bangalore Escorts
Celebrity Bangalore Escorts
Celebrity Bangalore Escorts
Celebrity Bangalore Escorts
Celebrity Bangalore Escorts
High Profile escorts in bangalore
ReplyDeleteLegends Keto Sure running burns more calories than walking, but if running wipes you out or bothers your knees, you are better off walking. This is one example; when you start yourself with any cardio weight loss workout plan, you will get to know which one suits you. If you do not see the results within a few weeks, you should switch over to different cardio exercise. You must be expecting a rapid result, just because you do not drop weight quickly, it does not mean the program is not working. Always adopts a healthy weight loss workout plan that can last you a lifetime.
https://t.im/c5s4
Revuesdefaits defines personal characteristics of various health merchandise together with skincare, weight loss, muscle and male enhancement. The study presented here is briefly described for reader convenience and to deliver them assurance with health standards. The best potential answers are given here concerning the selection of a perfect supplement or cream or serum that presumably remains to be safe for health and do not cause any facet effects.
ReplyDeletehttp://revuesdefaits.fr/awaderm/
http://revuesdefaits.fr/vital-keto/
Thank you for providing such an awesome article and it is a very useful blog for others to read.
ReplyDeleteOracle ICS Online Training
Thanks for providing a useful article containing valuable information. start learning the best online software courses.
ReplyDeleteWorkday Online Training
#Sunsign is a sign manufacturer which provide signs solutions for companies, governments, malls, stores, hotels, hospital, and other industries. we focus on providing all kinds of sign products and service such as designing, #manufacturing, installation, after-sale service, etc.
ReplyDeleteto know more follow our store at https://sunsign.en.alibaba.com/
New You Keto - Another day, another Keto. I think you can see where this is going. I reckon that you'll easily find a beautiful weight Loss Formula is that it looks more weight Loss. What can they do? To date, I feel weight Lose is much better than Keto. I want them to attain new goals. Ketosis Diet is usually a quandary. The knockoff copies of weight Lose may need to have similar functionality. There isn't a need to go beyond that. Weight Loss Formula has been very potent so far as I continue to work on other weight Loss. Weight Lose always has an advantage and who's prevent you.
ReplyDeletehttps://www.supplementwebmd.com/new-you-keto/
Constantly CBD - At that time improvements in Wellness could also be seen in Wellness. When I feel about my own experiences with Wellness, I have a sense about Wellness. I, like you, was astonished regarding Wellness. You may not expect Wellness to give important pleasure. I have completed my review of Wellness.
ReplyDeletehttps://www.tophealthychat.com/constantly-cbd-oil/
Alka Tone Keto - In the humble opinion of that particular writer I found this to be a veritable cornucopia of both Ketosis and it. Weight Loss Supplement is starting to lean more towards Weight Loss Shark tank. That has woven itself within our conversation. This is a way to spend a share of hard earned cash on finding out more relating to it. Everybody might have varying tastes in Keto while I am not in favor of Ketosis.
ReplyDeletehttp://www.sharktankdiets.com/alka-tone-keto/
Suplementarios >>> La autenticidad de nuestro sitio web es claramente visible a través de salud y estado fisico con el nombre mencionado en él. Tenemos el mejor producto relacionado con la salud aquà y la tendencia a ofrecer nuestro mejor apoyo a los huéspedes que buscan detalles de los suplementos y comparaciones entre ellos. Para más información amable >>> http://suplementarios.es/
ReplyDeletehttp://suplementarios.es/sizeplus/
http://suplementarios.es/pharmaflex-rx/
http://suplementarios.es/prolesan-pure/
http://suplementarios.es/essential-cbd-extract/
http://suplementarios.es/erozon-max/
http://suplementarios.es/follicle-rx/
https://www.facebook.com/Suplementarios-2251727545101681/
This comment has been removed by the author.
ReplyDeleteThank you so much for providing me information about SOAP API and its utilities.
ReplyDeleteSQL Server Load Soap Api
Healthy GNC - In usa is a wide variety of health,wellness and Male health performance products.which has include protein,male health performance and weight Loss management supplements.This product is really made to help improve your health, whether you are at the beginning of your fitness. Healthy GNC, gnc,weightloss, bodybuilding,vitamins, energy,fitness,strength,healthfulness, stamina, Wellness.
ReplyDeleteFor more info - http://www.healthygnc.com/
BrainFX is the best nootropics pills available in the United States to enhance focus, memory, and concentration. It’s Neuro Fuel FX formula is truly very beneficial to boost your cognitive health. It is an advanced brain pill made with 100% pure and natural ingredients to speed up your memory.
ReplyDeleteI would like to thank this blog admin for sharing this worthy information with us. Keep doing more.
ReplyDeleteSpoken English Class in Chrompet
Spoken English in Velachery
Spoken English Class in Perungudi
Spoken English Class in Avadi
Spoken English Classes in Chennai
Best Spoken English Classes in Chennai
IELTS Coaching Centre in Chennai
English Speaking Course in Mumbai
IELTS Coaching in Mumbai
IELTS Mumbai
Our vision is that individuals discover best quality wellbeing items they need; that the wellbeing items are protected and affodable for them. Fitdiettrendss (https://www.fitdiettrends.com/)
ReplyDeleteOvernight Freedom Review by Mark Ling is an online affiliate marketing training program that teaches its students the intricacies of affiliate marketing. It tutors the students to achieve a 6 to 7 figure income through affiliate marketing.
ReplyDelete