Git init
[external/xmlsec1.git] / docs / api / xmlsec-examples-sign-dynamimc-template.html
1 <html>
2 <head>
3 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
4 <title>Signing a dynamicaly created template.</title>
5 <meta name="GENERATOR" content="Modular DocBook HTML Stylesheet Version 1.79">
6 <link rel="HOME" title="XML Security Library Reference Manual" href="index.html">
7 <link rel="UP" title="Examples." href="xmlsec-examples.html">
8 <link rel="PREVIOUS" title="Signing a template file." href="xmlsec-examples-sign-template-file.html">
9 <link rel="NEXT" title="Signing with X509 certificate." href="xmlsec-examples-sign-x509.html">
10 <style type="text/css">.synopsis, .classsynopsis {
11     background: #eeeeee;
12     border: solid 1px #aaaaaa;
13     padding: 0.5em;
14 }
15 .programlisting {
16     background: #eeeeff;
17     border: solid 1px #aaaaff;
18     padding: 0.5em;
19 }
20 .variablelist {
21     padding: 4px;
22     margin-left: 3em;
23 }
24 .navigation {
25     background: #ffeeee;
26     border: solid 1px #ffaaaa;
27     margin-top: 0.5em;
28     margin-bottom: 0.5em;
29 }
30 .navigation a {
31     color: #770000;
32 }
33 .navigation a:visited {
34     color: #550000;
35 }
36 .navigation .title {
37     font-size: 200%;
38 }</style>
39 </head>
40 <body><table witdh="100%" valign="top"><tr valign="top">
41 <td valign="top" align="left" width="210">
42 <img src="../images/logo.gif" alt="XML Security Library" border="0"><p></p>
43 <ul>
44 <li><a href="../index.html">Home</a></li>
45 <li><a href="../download.html">Download</a></li>
46 <li><a href="../news.html">News</a></li>
47 <li><a href="../documentation.html">Documentation</a></li>
48 <ul>
49 <li><a href="../faq.html">FAQ</a></li>
50 <li><a href="../api/xmlsec-notes.html">Tutorial</a></li>
51 <li><a href="../api/xmlsec-reference.html">API reference</a></li>
52 <li><a href="../api/xmlsec-examples.html">Examples</a></li>
53 </ul>
54 <li><a href="../xmldsig.html">XML Digital Signature</a></li>
55 <ul><li><a href="http://www.aleksey.com/xmlsec/xmldsig-verifier.html">Online Verifier</a></li></ul>
56 <li><a href="../xmlenc.html">XML Encryption</a></li>
57 <li><a href="../c14n.html">XML Canonicalization</a></li>
58 <li><a href="../bugs.html">Reporting Bugs</a></li>
59 <li><a href="http://www.aleksey.com/pipermail/xmlsec">Mailing list</a></li>
60 <li><a href="../related.html">Related</a></li>
61 <li><a href="../authors.html">Authors</a></li>
62 </ul>
63 <table width="100%">
64 <tr>
65 <td width="15"></td>
66 <td><a href="http://xmlsoft.org/"><img src="../images/libxml2-logo.png" alt="LibXML2" border="0"></a></td>
67 </tr>
68 <tr>
69 <td width="15"></td>
70 <td><a href="http://xmlsoft.org/XSLT"><img src="../images/libxslt-logo.png" alt="LibXSLT" border="0"></a></td>
71 </tr>
72 <tr>
73 <td width="15"></td>
74 <td><a href="http://www.openssl.org/"><img src="../images/openssl-logo.png" alt="OpenSSL" border="0"></a></td>
75 </tr>
76 <!--Links - start--><!--Links - end-->
77 </table>
78 </td>
79 <td valign="top"><table width="100%" valign="top"><tr><td valign="top" align="left" id="xmlsecContent">
80 <table width="100%" class="navigation" summary="Navigation header" cellpadding="2" cellspacing="2"><tr valign="middle">
81 <td><a accesskey="p" href="xmlsec-examples-sign-template-file.html"><img src="left.png" width="24" height="24" border="0" alt="Prev"></a></td>
82 <td><a accesskey="u" href="xmlsec-examples.html"><img src="up.png" width="24" height="24" border="0" alt="Up"></a></td>
83 <td><a accesskey="h" href="index.html"><img src="home.png" width="24" height="24" border="0" alt="Home"></a></td>
84 <th width="100%" align="center">XML Security Library Reference Manual</th>
85 <td><a accesskey="n" href="xmlsec-examples-sign-x509.html"><img src="right.png" width="24" height="24" border="0" alt="Next"></a></td>
86 </tr></table>
87 <br clear="all"><div class="SECT1">
88 <h1 class="SECT1"><a name="XMLSEC-EXAMPLES-SIGN-DYNAMIMC-TEMPLATE">Signing a dynamicaly created template.</a></h1>
89 <br clear="all"><div class="SECT2">
90 <h2 class="SECT2"><a name="XMLSEC-EXAMPLE-SIGN2">sign2.c</a></h2>
91 <p></p>
92 <div class="INFORMALEXAMPLE">
93 <p></p>
94 <a name="AEN667"></a><pre class="PROGRAMLISTING">/** 
95  * XML Security Library example: Signing a file with a dynamicaly created template.
96  * 
97  * Signs a file using a dynamicaly created template and key from PEM file.
98  * The signature has one reference with one enveloped transform to sign
99  * the whole document except the &lt;dsig:Signature/&gt; node itself.
100  * 
101  * Usage: 
102  *      sign2 &lt;xml-doc&gt; &lt;pem-key&gt; 
103  *
104  * Example:
105  *      ./sign2 sign2-doc.xml rsakey.pem &gt; sign2-res.xml
106  *
107  * The result signature could be validated using verify1 example:
108  *      ./verify1 sign2-res.xml rsapub.pem
109  *
110  * This is free software; see Copyright file in the source
111  * distribution for preciese wording.
112  * 
113  * Copyright (C) 2002-2003 Aleksey Sanin &lt;aleksey@aleksey.com&gt;
114  */
115 #include &lt;stdlib.h&gt;
116 #include &lt;string.h&gt;
117 #include &lt;assert.h&gt;
118
119 #include &lt;libxml/tree.h&gt;
120 #include &lt;libxml/xmlmemory.h&gt;
121 #include &lt;libxml/parser.h&gt;
122
123 #ifndef XMLSEC_NO_XSLT
124 #include &lt;libxslt/xslt.h&gt;
125 #endif /* XMLSEC_NO_XSLT */
126
127 #include &lt;xmlsec/xmlsec.h&gt;
128 #include &lt;xmlsec/xmltree.h&gt;
129 #include &lt;xmlsec/xmldsig.h&gt;
130 #include &lt;xmlsec/templates.h&gt;
131 #include &lt;xmlsec/crypto.h&gt;
132
133 int sign_file(const char* xml_file, const char* key_file);
134
135 int 
136 main(int argc, char **argv) {
137     assert(argv);
138
139     if(argc != 3) {
140         fprintf(stderr, "Error: wrong number of arguments.\n");
141         fprintf(stderr, "Usage: %s &lt;xml-file&gt; &lt;key-file&gt;\n", argv[0]);
142         return(1);
143     }
144
145     /* Init libxml and libxslt libraries */
146     xmlInitParser();
147     LIBXML_TEST_VERSION
148     xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
149     xmlSubstituteEntitiesDefault(1);
150 #ifndef XMLSEC_NO_XSLT
151     xmlIndentTreeOutput = 1; 
152 #endif /* XMLSEC_NO_XSLT */
153                 
154     /* Init xmlsec library */
155     if(xmlSecInit() &lt; 0) {
156         fprintf(stderr, "Error: xmlsec initialization failed.\n");
157         return(-1);
158     }
159
160     /* Check loaded library version */
161     if(xmlSecCheckVersion() != 1) {
162         fprintf(stderr, "Error: loaded xmlsec library version is not compatible.\n");
163         return(-1);
164     }
165
166     /* Load default crypto engine if we are supporting dynamic
167      * loading for xmlsec-crypto libraries. Use the crypto library
168      * name ("openssl", "nss", etc.) to load corresponding 
169      * xmlsec-crypto library.
170      */
171 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
172     if(xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) &lt; 0) {
173         fprintf(stderr, "Error: unable to load default xmlsec-crypto library. Make sure\n"
174                         "that you have it installed and check shared libraries path\n"
175                         "(LD_LIBRARY_PATH) envornment variable.\n");
176         return(-1);     
177     }
178 #endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */
179
180     /* Init crypto library */
181     if(xmlSecCryptoAppInit(NULL) &lt; 0) {
182         fprintf(stderr, "Error: crypto initialization failed.\n");
183         return(-1);
184     }
185
186     /* Init xmlsec-crypto library */
187     if(xmlSecCryptoInit() &lt; 0) {
188         fprintf(stderr, "Error: xmlsec-crypto initialization failed.\n");
189         return(-1);
190     }
191
192     if(sign_file(argv[1], argv[2]) &lt; 0) {
193         return(-1);
194     }    
195     
196     /* Shutdown xmlsec-crypto library */
197     xmlSecCryptoShutdown();
198     
199     /* Shutdown crypto library */
200     xmlSecCryptoAppShutdown();
201     
202     /* Shutdown xmlsec library */
203     xmlSecShutdown();
204
205     /* Shutdown libxslt/libxml */
206 #ifndef XMLSEC_NO_XSLT
207     xsltCleanupGlobals();            
208 #endif /* XMLSEC_NO_XSLT */
209     xmlCleanupParser();
210     
211     return(0);
212 }
213
214 /** 
215  * sign_file:
216  * @xml_file:           the XML file name.
217  * @key_file:           the PEM private key file name.
218  *
219  * Signs the #xml_file using private key from #key_file and dynamicaly
220  * created enveloped signature template.
221  *
222  * Returns 0 on success or a negative value if an error occurs.
223  */
224 int 
225 sign_file(const char* xml_file, const char* key_file) {
226     xmlDocPtr doc = NULL;
227     xmlNodePtr signNode = NULL;
228     xmlNodePtr refNode = NULL;
229     xmlNodePtr keyInfoNode = NULL;
230     xmlSecDSigCtxPtr dsigCtx = NULL;
231     int res = -1;
232     
233     assert(xml_file);
234     assert(key_file);
235
236     /* load doc file */
237     doc = xmlParseFile(xml_file);
238     if ((doc == NULL) || (xmlDocGetRootElement(doc) == NULL)){
239         fprintf(stderr, "Error: unable to parse file \"%s\"\n", xml_file);
240         goto done;      
241     }
242     
243     /* create signature template for RSA-SHA1 enveloped signature */
244     signNode = xmlSecTmplSignatureCreate(doc, xmlSecTransformExclC14NId,
245                                          xmlSecTransformRsaSha1Id, NULL);
246     if(signNode == NULL) {
247         fprintf(stderr, "Error: failed to create signature template\n");
248         goto done;              
249     }
250
251     /* add &lt;dsig:Signature/&gt; node to the doc */
252     xmlAddChild(xmlDocGetRootElement(doc), signNode);
253     
254     /* add reference */
255     refNode = xmlSecTmplSignatureAddReference(signNode, xmlSecTransformSha1Id,
256                                         NULL, NULL, NULL);
257     if(refNode == NULL) {
258         fprintf(stderr, "Error: failed to add reference to signature template\n");
259         goto done;              
260     }
261
262     /* add enveloped transform */
263     if(xmlSecTmplReferenceAddTransform(refNode, xmlSecTransformEnvelopedId) == NULL) {
264         fprintf(stderr, "Error: failed to add enveloped transform to reference\n");
265         goto done;              
266     }
267     
268     /* add &lt;dsig:KeyInfo/&gt; and &lt;dsig:KeyName/&gt; nodes to put key name in the signed document */
269     keyInfoNode = xmlSecTmplSignatureEnsureKeyInfo(signNode, NULL);
270     if(keyInfoNode == NULL) {
271         fprintf(stderr, "Error: failed to add key info\n");
272         goto done;              
273     }
274
275     if(xmlSecTmplKeyInfoAddKeyName(keyInfoNode, NULL) == NULL) {
276         fprintf(stderr, "Error: failed to add key name\n");
277         goto done;              
278     }
279
280     /* create signature context, we don't need keys manager in this example */
281     dsigCtx = xmlSecDSigCtxCreate(NULL);
282     if(dsigCtx == NULL) {
283         fprintf(stderr,"Error: failed to create signature context\n");
284         goto done;
285     }
286
287     /* load private key, assuming that there is not password */
288     dsigCtx-&gt;signKey = xmlSecCryptoAppKeyLoad(key_file, xmlSecKeyDataFormatPem, NULL, NULL, NULL);
289     if(dsigCtx-&gt;signKey == NULL) {
290         fprintf(stderr,"Error: failed to load private pem key from \"%s\"\n", key_file);
291         goto done;
292     }
293
294     /* set key name to the file name, this is just an example! */
295     if(xmlSecKeySetName(dsigCtx-&gt;signKey, key_file) &lt; 0) {
296         fprintf(stderr,"Error: failed to set key name for key from \"%s\"\n", key_file);
297         goto done;
298     }
299
300     /* sign the template */
301     if(xmlSecDSigCtxSign(dsigCtx, signNode) &lt; 0) {
302         fprintf(stderr,"Error: signature failed\n");
303         goto done;
304     }
305         
306     /* print signed document to stdout */
307     xmlDocDump(stdout, doc);
308     
309     /* success */
310     res = 0;
311
312 done:    
313     /* cleanup */
314     if(dsigCtx != NULL) {
315         xmlSecDSigCtxDestroy(dsigCtx);
316     }
317     
318     if(doc != NULL) {
319         xmlFreeDoc(doc); 
320     }
321     return(res);
322 }\r</pre>
323 <p></p>
324 </div>
325 </div>
326 <br clear="all"><div class="SECT2">
327 <h2 class="SECT2"><a name="XMLSEC-EXAMPLE-SIGN2-DOC">sign2-doc.xml</a></h2>
328 <p></p>
329 <div class="INFORMALEXAMPLE">
330 <p></p>
331 <a name="AEN672"></a><pre class="PROGRAMLISTING">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
332 &lt;!-- 
333 XML Security Library example: Original XML doc file for sign2 example. 
334 --&gt;
335 &lt;Envelope xmlns="urn:envelope"&gt;
336   &lt;Data&gt;
337         Hello, World!
338   &lt;/Data&gt;
339 &lt;/Envelope&gt;</pre>
340 <p></p>
341 </div>
342 </div>
343 <br clear="all"><div class="SECT2">
344 <h2 class="SECT2"><a name="XMLSEC-EXAMPLE-SIGN2-RES">sign2-res.xml</a></h2>
345 <p></p>
346 <div class="INFORMALEXAMPLE">
347 <p></p>
348 <a name="AEN677"></a><pre class="PROGRAMLISTING">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
349 &lt;!-- 
350 XML Security Library example: Signed XML doc file (sign2 example). 
351 --&gt;
352 &lt;Envelope xmlns="urn:envelope"&gt;
353   &lt;Data&gt;
354         Hello, World!
355   &lt;/Data&gt;
356 &lt;Signature xmlns="http://www.w3.org/2000/09/xmldsig#"&gt;
357 &lt;SignedInfo&gt;
358 &lt;CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/&gt;
359 &lt;SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/&gt;
360 &lt;Reference&gt;
361 &lt;Transforms&gt;
362 &lt;Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/&gt;
363 &lt;/Transforms&gt;
364 &lt;DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/&gt;
365 &lt;DigestValue&gt;HjY8ilZAIEM2tBbPn5mYO1ieIX4=&lt;/DigestValue&gt;
366 &lt;/Reference&gt;
367 &lt;/SignedInfo&gt;
368 &lt;SignatureValue&gt;SIaj/6KY3C1SmDXU2++Gm31U1xTadFp04WhBgfsJFbxrL+q7GKSKN9kfQ+UpN9+i
369 D5fWmuavXEHe4Gw6RMaMEkq2URQo7F68+d5J/ajq8/l4n+xE6/reGScVwT6L4dEP
370 XXVJcAi2ZnQ3O7GTNvNGCPibL9mUcyCWBFZ92Uemtc/vJFCQ7ZyKMdMfACgxOwyN
371 T/9971oog241/2doudhonc0I/3mgPYWkZdX6yvr62mEjnG+oUZkhWYJ4ewZJ4hM4
372 JjbFqZO+OEzDRSbw3DkmuBA/mtlx+3t13SESfEub5hqoMdVmtth/eTb64dsPdl9r
373 3k1ACVX9f8aHfQQdJOmLFQ==&lt;/SignatureValue&gt;
374 &lt;KeyInfo&gt;
375 &lt;KeyName&gt;rsakey.pem&lt;/KeyName&gt;
376 &lt;/KeyInfo&gt;
377 &lt;/Signature&gt;&lt;/Envelope&gt;</pre>
378 <p></p>
379 </div>
380 </div>
381 </div>
382 <table class="navigation" width="100%" summary="Navigation footer" cellpadding="2" cellspacing="2"><tr valign="middle">
383 <td align="left"><a accesskey="p" href="xmlsec-examples-sign-template-file.html"><b>&lt;&lt;&lt; Signing a template file.</b></a></td>
384 <td align="right"><a accesskey="n" href="xmlsec-examples-sign-x509.html"><b>Signing with X509 certificate. &gt;&gt;&gt;</b></a></td>
385 </tr></table>
386 </td></tr></table></td>
387 </tr></table></body>
388 </html>