Git init
[external/xmlsec1.git] / docs / api / xmlsec-examples-sign-x509.html
1 <html>
2 <head>
3 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
4 <title>Signing with X509 certificate.</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 dynamicaly created template." href="xmlsec-examples-sign-dynamimc-template.html">
9 <link rel="NEXT" title="Verifying a signature with a single key." href="xmlsec-verify-with-key.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-dynamimc-template.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-verify-with-key.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-X509">Signing with X509 certificate.</a></h1>
89 <br clear="all"><div class="SECT2">
90 <h2 class="SECT2"><a name="XMLSEC-EXAMPLE-SIGN3">sign3.c</a></h2>
91 <p></p>
92 <div class="INFORMALEXAMPLE">
93 <p></p>
94 <a name="AEN684"></a><pre class="PROGRAMLISTING">/** 
95  * XML Security Library example: Signing a file with a dynamicaly created template and an X509 certificate.
96  * 
97  * Signs a file using a dynamicaly created template, key from PEM file and
98  * an X509 certificate. The signature has one reference with one enveloped 
99  * transform to sign the whole document except the &lt;dsig:Signature/&gt; node 
100  * itself. The key certificate is written in the &lt;dsig:X509Data/&gt; node.
101  * 
102  * This example was developed and tested with OpenSSL crypto library. The 
103  * certificates management policies for another crypto library may break it.
104  * 
105  * Usage: 
106  *      sign3 &lt;xml-doc&gt; &lt;pem-key&gt; 
107  *
108  * Example:
109  *      ./sign3 sign3-doc.xml rsakey.pem rsacert.pem &gt; sign3-res.xml
110  *
111  * The result signature could be validated using verify3 example:
112  *      ./verify3 sign3-res.xml rootcert.pem
113  *
114  * This is free software; see Copyright file in the source
115  * distribution for preciese wording.
116  * 
117  * Copyright (C) 2002-2003 Aleksey Sanin &lt;aleksey@aleksey.com&gt;
118  */
119 #include &lt;stdlib.h&gt;
120 #include &lt;string.h&gt;
121 #include &lt;assert.h&gt;
122
123 #include &lt;libxml/tree.h&gt;
124 #include &lt;libxml/xmlmemory.h&gt;
125 #include &lt;libxml/parser.h&gt;
126
127 #ifndef XMLSEC_NO_XSLT
128 #include &lt;libxslt/xslt.h&gt;
129 #endif /* XMLSEC_NO_XSLT */
130
131 #include &lt;xmlsec/xmlsec.h&gt;
132 #include &lt;xmlsec/xmltree.h&gt;
133 #include &lt;xmlsec/xmldsig.h&gt;
134 #include &lt;xmlsec/templates.h&gt;
135 #include &lt;xmlsec/crypto.h&gt;
136
137 int sign_file(const char* xml_file, const char* key_file, const char* cert_file);
138
139 int 
140 main(int argc, char **argv) {
141     assert(argv);
142
143     if(argc != 4) {
144         fprintf(stderr, "Error: wrong number of arguments.\n");
145         fprintf(stderr, "Usage: %s &lt;xml-file&gt; &lt;key-file&gt; &lt;cert-file&gt;\n", argv[0]);
146         return(1);
147     }
148
149     /* Init libxml and libxslt libraries */
150     xmlInitParser();
151     LIBXML_TEST_VERSION
152     xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
153     xmlSubstituteEntitiesDefault(1);
154 #ifndef XMLSEC_NO_XSLT
155     xmlIndentTreeOutput = 1; 
156 #endif /* XMLSEC_NO_XSLT */
157                 
158     /* Init xmlsec library */
159     if(xmlSecInit() &lt; 0) {
160         fprintf(stderr, "Error: xmlsec initialization failed.\n");
161         return(-1);
162     }
163
164     /* Check loaded library version */
165     if(xmlSecCheckVersion() != 1) {
166         fprintf(stderr, "Error: loaded xmlsec library version is not compatible.\n");
167         return(-1);
168     }
169
170     /* Load default crypto engine if we are supporting dynamic
171      * loading for xmlsec-crypto libraries. Use the crypto library
172      * name ("openssl", "nss", etc.) to load corresponding 
173      * xmlsec-crypto library.
174      */
175 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
176     if(xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) &lt; 0) {
177         fprintf(stderr, "Error: unable to load default xmlsec-crypto library. Make sure\n"
178                         "that you have it installed and check shared libraries path\n"
179                         "(LD_LIBRARY_PATH) envornment variable.\n");
180         return(-1);     
181     }
182 #endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */
183
184     /* Init crypto library */
185     if(xmlSecCryptoAppInit(NULL) &lt; 0) {
186         fprintf(stderr, "Error: crypto initialization failed.\n");
187         return(-1);
188     }
189
190     /* Init xmlsec-crypto library */
191     if(xmlSecCryptoInit() &lt; 0) {
192         fprintf(stderr, "Error: xmlsec-crypto initialization failed.\n");
193         return(-1);
194     }
195
196     if(sign_file(argv[1], argv[2], argv[3]) &lt; 0) {
197         return(-1);
198     }    
199     
200     /* Shutdown xmlsec-crypto library */
201     xmlSecCryptoShutdown();
202     
203     /* Shutdown crypto library */
204     xmlSecCryptoAppShutdown();
205     
206     /* Shutdown xmlsec library */
207     xmlSecShutdown();
208
209     /* Shutdown libxslt/libxml */
210 #ifndef XMLSEC_NO_XSLT
211     xsltCleanupGlobals();            
212 #endif /* XMLSEC_NO_XSLT */
213     xmlCleanupParser();
214     
215     return(0);
216 }
217
218 /** 
219  * sign_file:
220  * @xml_file:           the XML file name.
221  * @key_file:           the PEM private key file name.
222  * @cert_file:          the x509 certificate PEM file.
223  *
224  * Signs the @xml_file using private key from @key_file and dynamicaly
225  * created enveloped signature template. The certificate from @cert_file
226  * is placed in the &lt;dsig:X509Data/&gt; node.
227  *
228  * Returns 0 on success or a negative value if an error occurs.
229  */
230 int 
231 sign_file(const char* xml_file, const char* key_file, const char* cert_file) {
232     xmlDocPtr doc = NULL;
233     xmlNodePtr signNode = NULL;
234     xmlNodePtr refNode = NULL;
235     xmlNodePtr keyInfoNode = NULL;
236     xmlSecDSigCtxPtr dsigCtx = NULL;
237     int res = -1;
238     
239     assert(xml_file);
240     assert(key_file);
241     assert(cert_file);
242
243     /* load doc file */
244     doc = xmlParseFile(xml_file);
245     if ((doc == NULL) || (xmlDocGetRootElement(doc) == NULL)){
246         fprintf(stderr, "Error: unable to parse file \"%s\"\n", xml_file);
247         goto done;      
248     }
249     
250     /* create signature template for RSA-SHA1 enveloped signature */
251     signNode = xmlSecTmplSignatureCreate(doc, xmlSecTransformExclC14NId,
252                                          xmlSecTransformRsaSha1Id, NULL);
253     if(signNode == NULL) {
254         fprintf(stderr, "Error: failed to create signature template\n");
255         goto done;              
256     }
257
258     /* add &lt;dsig:Signature/&gt; node to the doc */
259     xmlAddChild(xmlDocGetRootElement(doc), signNode);
260     
261     /* add reference */
262     refNode = xmlSecTmplSignatureAddReference(signNode, xmlSecTransformSha1Id,
263                                         NULL, NULL, NULL);
264     if(refNode == NULL) {
265         fprintf(stderr, "Error: failed to add reference to signature template\n");
266         goto done;              
267     }
268
269     /* add enveloped transform */
270     if(xmlSecTmplReferenceAddTransform(refNode, xmlSecTransformEnvelopedId) == NULL) {
271         fprintf(stderr, "Error: failed to add enveloped transform to reference\n");
272         goto done;              
273     }
274     
275     /* add &lt;dsig:KeyInfo/&gt; and &lt;dsig:X509Data/&gt; */
276     keyInfoNode = xmlSecTmplSignatureEnsureKeyInfo(signNode, NULL);
277     if(keyInfoNode == NULL) {
278         fprintf(stderr, "Error: failed to add key info\n");
279         goto done;              
280     }
281     
282     if(xmlSecTmplKeyInfoAddX509Data(keyInfoNode) == NULL) {
283         fprintf(stderr, "Error: failed to add X509Data node\n");
284         goto done;              
285     }
286
287     /* create signature context, we don't need keys manager in this example */
288     dsigCtx = xmlSecDSigCtxCreate(NULL);
289     if(dsigCtx == NULL) {
290         fprintf(stderr,"Error: failed to create signature context\n");
291         goto done;
292     }
293
294     /* load private key, assuming that there is not password */
295     dsigCtx-&gt;signKey = xmlSecCryptoAppKeyLoad(key_file, xmlSecKeyDataFormatPem, NULL, NULL, NULL);
296     if(dsigCtx-&gt;signKey == NULL) {
297         fprintf(stderr,"Error: failed to load private pem key from \"%s\"\n", key_file);
298         goto done;
299     }
300     
301     /* load certificate and add to the key */
302     if(xmlSecCryptoAppKeyCertLoad(dsigCtx-&gt;signKey, cert_file, xmlSecKeyDataFormatPem) &lt; 0) {
303         fprintf(stderr,"Error: failed to load pem certificate \"%s\"\n", cert_file);
304         goto done;
305     }
306
307     /* set key name to the file name, this is just an example! */
308     if(xmlSecKeySetName(dsigCtx-&gt;signKey, key_file) &lt; 0) {
309         fprintf(stderr,"Error: failed to set key name for key from \"%s\"\n", key_file);
310         goto done;
311     }
312
313     /* sign the template */
314     if(xmlSecDSigCtxSign(dsigCtx, signNode) &lt; 0) {
315         fprintf(stderr,"Error: signature failed\n");
316         goto done;
317     }
318         
319     /* print signed document to stdout */
320     xmlDocDump(stdout, doc);
321     
322     /* success */
323     res = 0;
324
325 done:    
326     /* cleanup */
327     if(dsigCtx != NULL) {
328         xmlSecDSigCtxDestroy(dsigCtx);
329     }
330     
331     if(doc != NULL) {
332         xmlFreeDoc(doc); 
333     }
334     return(res);
335 }\r</pre>
336 <p></p>
337 </div>
338 </div>
339 <br clear="all"><div class="SECT2">
340 <h2 class="SECT2"><a name="XMLSEC-EXAMPLE-SIGN3-DOC">sign3-doc.xml</a></h2>
341 <p></p>
342 <div class="INFORMALEXAMPLE">
343 <p></p>
344 <a name="AEN689"></a><pre class="PROGRAMLISTING">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
345 &lt;!-- 
346 XML Security Library example: Original XML doc file for sign3 example. 
347 --&gt;
348 &lt;Envelope xmlns="urn:envelope"&gt;
349   &lt;Data&gt;
350         Hello, World!
351   &lt;/Data&gt;
352 &lt;/Envelope&gt;</pre>
353 <p></p>
354 </div>
355 </div>
356 <br clear="all"><div class="SECT2">
357 <h2 class="SECT2"><a name="XMLSEC-EXAMPLE-SIGN3-RES">sign3-res.xml</a></h2>
358 <p></p>
359 <div class="INFORMALEXAMPLE">
360 <p></p>
361 <a name="AEN694"></a><pre class="PROGRAMLISTING">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
362 &lt;!-- 
363 XML Security Library example: Signed XML doc file (sign3 example). 
364 --&gt;
365 &lt;Envelope xmlns="urn:envelope"&gt;
366   &lt;Data&gt;
367         Hello, World!
368   &lt;/Data&gt;
369 &lt;Signature xmlns="http://www.w3.org/2000/09/xmldsig#"&gt;
370 &lt;SignedInfo&gt;
371 &lt;CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/&gt;
372 &lt;SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/&gt;
373 &lt;Reference&gt;
374 &lt;Transforms&gt;
375 &lt;Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/&gt;
376 &lt;/Transforms&gt;
377 &lt;DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/&gt;
378 &lt;DigestValue&gt;HjY8ilZAIEM2tBbPn5mYO1ieIX4=&lt;/DigestValue&gt;
379 &lt;/Reference&gt;
380 &lt;/SignedInfo&gt;
381 &lt;SignatureValue&gt;SIaj/6KY3C1SmDXU2++Gm31U1xTadFp04WhBgfsJFbxrL+q7GKSKN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Certificate&gt;
416 &lt;/X509Data&gt;
417 &lt;/KeyInfo&gt;
418 &lt;/Signature&gt;&lt;/Envelope&gt;</pre>
419 <p></p>
420 </div>
421 </div>
422 </div>
423 <table class="navigation" width="100%" summary="Navigation footer" cellpadding="2" cellspacing="2"><tr valign="middle">
424 <td align="left"><a accesskey="p" href="xmlsec-examples-sign-dynamimc-template.html"><b>&lt;&lt;&lt; Signing a dynamicaly created template.</b></a></td>
425 <td align="right"><a accesskey="n" href="xmlsec-verify-with-key.html"><b>Verifying a signature with a single key. &gt;&gt;&gt;</b></a></td>
426 </tr></table>
427 </td></tr></table></td>
428 </tr></table></body>
429 </html>