Git init
[external/xmlsec1.git] / docs / api / xmlsec-encrypt-with-session-key.html
1 <html>
2 <head>
3 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
4 <title>Encrypting data with a session key.</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="Encrypting data with a dynamicaly created template." href="xmlsec-encrypt-dynamic-template.html">
9 <link rel="NEXT" title="Decrypting data with a single key." href="xmlsec-decrypt-with-signle-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-encrypt-dynamic-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-decrypt-with-signle-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-ENCRYPT-WITH-SESSION-KEY">Encrypting data with a session key.</a></h1>
89 <br clear="all"><div class="SECT2">
90 <h2 class="SECT2"><a name="XMLSEC-EXAMPLE-ENCRYPT3">encrypt3.c</a></h2>
91 <p></p>
92 <div class="INFORMALEXAMPLE">
93 <p></p>
94 <a name="AEN783"></a><pre class="PROGRAMLISTING">/** 
95  * XML Security Library example: Encrypting XML file with a session key and dynamicaly created template.
96  * 
97  * Encrypts XML file using a dynamicaly created template file and a session 
98  * DES key (encrypted with an RSA key).
99  * 
100  * Usage: 
101  *      ./encrypt3 &lt;xml-doc&gt; &lt;rsa-pem-key-file&gt; 
102  *
103  * Example:
104  *      ./encrypt3 encrypt3-doc.xml rsakey.pem &gt; encrypt3-res.xml
105  *
106  * The result could be decrypted with decrypt3 example:
107  *      ./decrypt3 encrypt3-res.xml
108  *
109  * This is free software; see Copyright file in the source
110  * distribution for preciese wording.
111  * 
112  * Copyright (C) 2002-2003 Aleksey Sanin &lt;aleksey@aleksey.com&gt;
113  */
114 #include &lt;stdlib.h&gt;
115 #include &lt;string.h&gt;
116 #include &lt;assert.h&gt;
117
118 #include &lt;libxml/tree.h&gt;
119 #include &lt;libxml/xmlmemory.h&gt;
120 #include &lt;libxml/parser.h&gt;
121
122 #ifndef XMLSEC_NO_XSLT
123 #include &lt;libxslt/xslt.h&gt;
124 #endif /* XMLSEC_NO_XSLT */
125
126 #include &lt;xmlsec/xmlsec.h&gt;
127 #include &lt;xmlsec/xmltree.h&gt;
128 #include &lt;xmlsec/xmlenc.h&gt;
129 #include &lt;xmlsec/templates.h&gt;
130 #include &lt;xmlsec/crypto.h&gt;
131
132 xmlSecKeysMngrPtr load_rsa_keys(char* key_file);
133 int encrypt_file(xmlSecKeysMngrPtr mngr, const char* xml_file, const char* key_name);
134
135 int 
136 main(int argc, char **argv) {
137     xmlSecKeysMngrPtr mngr;
138     
139     assert(argv);
140
141     if(argc != 3) {
142         fprintf(stderr, "Error: wrong number of arguments.\n");
143         fprintf(stderr, "Usage: %s &lt;xml-file&gt; &lt;key-file&gt;\n", argv[0]);
144         return(1);
145     }
146
147     /* Init libxml and libxslt libraries */
148     xmlInitParser();
149     LIBXML_TEST_VERSION
150     xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
151     xmlSubstituteEntitiesDefault(1);
152 #ifndef XMLSEC_NO_XSLT
153     xmlIndentTreeOutput = 1; 
154 #endif /* XMLSEC_NO_XSLT */
155                 
156     /* Init xmlsec library */
157     if(xmlSecInit() &lt; 0) {
158         fprintf(stderr, "Error: xmlsec initialization failed.\n");
159         return(-1);
160     }
161
162     /* Check loaded library version */
163     if(xmlSecCheckVersion() != 1) {
164         fprintf(stderr, "Error: loaded xmlsec library version is not compatible.\n");
165         return(-1);
166     }
167
168     /* Load default crypto engine if we are supporting dynamic
169      * loading for xmlsec-crypto libraries. Use the crypto library
170      * name ("openssl", "nss", etc.) to load corresponding 
171      * xmlsec-crypto library.
172      */
173 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
174     if(xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) &lt; 0) {
175         fprintf(stderr, "Error: unable to load default xmlsec-crypto library. Make sure\n"
176                         "that you have it installed and check shared libraries path\n"
177                         "(LD_LIBRARY_PATH) envornment variable.\n");
178         return(-1);     
179     }
180 #endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */
181
182     /* Init crypto library */
183     if(xmlSecCryptoAppInit(NULL) &lt; 0) {
184         fprintf(stderr, "Error: crypto initialization failed.\n");
185         return(-1);
186     }
187
188     /* Init xmlsec-crypto library */
189     if(xmlSecCryptoInit() &lt; 0) {
190         fprintf(stderr, "Error: xmlsec-crypto initialization failed.\n");
191         return(-1);
192     }
193
194     /* create keys manager and load keys */
195     mngr = load_rsa_keys(argv[2]);
196     if(mngr == NULL) {
197         return(-1);
198     }
199
200     /* we use key filename as key name here */
201     if(encrypt_file(mngr, argv[1], argv[2]) &lt; 0) {
202         xmlSecKeysMngrDestroy(mngr);
203         return(-1);
204     }    
205
206     /* destroy keys manager */
207     xmlSecKeysMngrDestroy(mngr);
208     
209     /* Shutdown xmlsec-crypto library */
210     xmlSecCryptoShutdown();
211     
212     /* Shutdown crypto library */
213     xmlSecCryptoAppShutdown();
214     
215     /* Shutdown xmlsec library */
216     xmlSecShutdown();
217
218     /* Shutdown libxslt/libxml */
219 #ifndef XMLSEC_NO_XSLT
220     xsltCleanupGlobals();            
221 #endif /* XMLSEC_NO_XSLT */
222     xmlCleanupParser();
223     
224     return(0);
225 }
226
227 /**
228  * load_rsa_keys:
229  * @key_file:           the key filename.
230  *
231  * Creates simple keys manager and load RSA key from #key_file in it.
232  * The caller is responsible for destroing returned keys manager using
233  * @xmlSecKeysMngrDestroy.
234  *
235  * Returns the pointer to newly created keys manager or NULL if an error
236  * occurs.
237  */
238 xmlSecKeysMngrPtr 
239 load_rsa_keys(char* key_file) {
240     xmlSecKeysMngrPtr mngr;
241     xmlSecKeyPtr key;
242     
243     assert(key_file);
244     
245     /* create and initialize keys manager, we use a simple list based
246      * keys manager, implement your own xmlSecKeysStore klass if you need
247      * something more sophisticated 
248      */
249     mngr = xmlSecKeysMngrCreate();
250     if(mngr == NULL) {
251         fprintf(stderr, "Error: failed to create keys manager.\n");
252         return(NULL);
253     }
254     if(xmlSecCryptoAppDefaultKeysMngrInit(mngr) &lt; 0) {
255         fprintf(stderr, "Error: failed to initialize keys manager.\n");
256         xmlSecKeysMngrDestroy(mngr);
257         return(NULL);
258     }    
259     
260     /* load private RSA key */
261     key = xmlSecCryptoAppKeyLoad(key_file, xmlSecKeyDataFormatPem, NULL, NULL, NULL);
262     if(key == NULL) {
263         fprintf(stderr,"Error: failed to load rsa key from file \"%s\"\n", key_file);
264         xmlSecKeysMngrDestroy(mngr);
265         return(NULL);
266     }
267
268     /* set key name to the file name, this is just an example! */
269     if(xmlSecKeySetName(key, BAD_CAST key_file) &lt; 0) {
270         fprintf(stderr,"Error: failed to set key name for key from \"%s\"\n", key_file);
271         xmlSecKeyDestroy(key);  
272         xmlSecKeysMngrDestroy(mngr);
273         return(NULL);
274     }
275         
276     /* add key to keys manager, from now on keys manager is responsible 
277      * for destroying key 
278      */
279     if(xmlSecCryptoAppDefaultKeysMngrAdoptKey(mngr, key) &lt; 0) {
280         fprintf(stderr,"Error: failed to add key from \"%s\" to keys manager\n", key_file);
281         xmlSecKeyDestroy(key);
282         xmlSecKeysMngrDestroy(mngr);
283         return(NULL);
284     }
285
286     return(mngr);
287 }
288
289 /**
290  * encrypt_file:
291  * @mngr:               the pointer to keys manager.
292  * @xml_file:           the encryption template file name.
293  * @key_name:           the RSA key name.
294  *
295  * Encrypts #xml_file using a dynamicaly created template, a session DES key 
296  * and an RSA key from keys manager.
297  *
298  * Returns 0 on success or a negative value if an error occurs.
299  */
300 int 
301 encrypt_file(xmlSecKeysMngrPtr mngr, const char* xml_file, const char* key_name) {
302     xmlDocPtr doc = NULL;
303     xmlNodePtr encDataNode = NULL;
304     xmlNodePtr keyInfoNode = NULL;
305     xmlNodePtr encKeyNode = NULL;
306     xmlNodePtr keyInfoNode2 = NULL;
307     xmlSecEncCtxPtr encCtx = NULL;
308     int res = -1;
309     
310     assert(mngr);
311     assert(xml_file);
312     assert(key_name);
313
314     /* load template */
315     doc = xmlParseFile(xml_file);
316     if ((doc == NULL) || (xmlDocGetRootElement(doc) == NULL)){
317         fprintf(stderr, "Error: unable to parse file \"%s\"\n", xml_file);
318         goto done;      
319     }
320     
321     /* create encryption template to encrypt XML file and replace 
322      * its content with encryption result */
323     encDataNode = xmlSecTmplEncDataCreate(doc, xmlSecTransformDes3CbcId,
324                                 NULL, xmlSecTypeEncElement, NULL, NULL);
325     if(encDataNode == NULL) {
326         fprintf(stderr, "Error: failed to create encryption template\n");
327         goto done;   
328     }
329
330     /* we want to put encrypted data in the &lt;enc:CipherValue/&gt; node */
331     if(xmlSecTmplEncDataEnsureCipherValue(encDataNode) == NULL) {
332         fprintf(stderr, "Error: failed to add CipherValue node\n");
333         goto done;   
334     }
335
336     /* add &lt;dsig:KeyInfo/&gt; */
337     keyInfoNode = xmlSecTmplEncDataEnsureKeyInfo(encDataNode, NULL);
338     if(keyInfoNode == NULL) {
339         fprintf(stderr, "Error: failed to add key info\n");
340         goto done;              
341     }
342
343     /* add &lt;enc:EncryptedKey/&gt; to store the encrypted session key */
344     encKeyNode = xmlSecTmplKeyInfoAddEncryptedKey(keyInfoNode, 
345                                     xmlSecTransformRsaPkcs1Id, 
346                                     NULL, NULL, NULL);
347     if(encKeyNode == NULL) {
348         fprintf(stderr, "Error: failed to add key info\n");
349         goto done;              
350     }
351
352     /* we want to put encrypted key in the &lt;enc:CipherValue/&gt; node */
353     if(xmlSecTmplEncDataEnsureCipherValue(encKeyNode) == NULL) {
354         fprintf(stderr, "Error: failed to add CipherValue node\n");
355         goto done;   
356     }
357
358     /* add &lt;dsig:KeyInfo/&gt; and &lt;dsig:KeyName/&gt; nodes to &lt;enc:EncryptedKey/&gt; */
359     keyInfoNode2 = xmlSecTmplEncDataEnsureKeyInfo(encKeyNode, NULL);
360     if(keyInfoNode2 == NULL) {
361         fprintf(stderr, "Error: failed to add key info\n");
362         goto done;              
363     }
364     
365     /* set key name so we can lookup key when needed */
366     if(xmlSecTmplKeyInfoAddKeyName(keyInfoNode2, key_name) == NULL) {
367         fprintf(stderr, "Error: failed to add key name\n");
368         goto done;              
369     }
370
371     /* create encryption context */
372     encCtx = xmlSecEncCtxCreate(mngr);
373     if(encCtx == NULL) {
374         fprintf(stderr,"Error: failed to create encryption context\n");
375         goto done;
376     }
377
378     /* generate a Triple DES key */
379     encCtx-&gt;encKey = xmlSecKeyGenerate(xmlSecKeyDataDesId, 192, xmlSecKeyDataTypeSession);
380     if(encCtx-&gt;encKey == NULL) {
381         fprintf(stderr,"Error: failed to generate session des key\n");
382         goto done;
383     }
384
385     /* encrypt the data */
386     if(xmlSecEncCtxXmlEncrypt(encCtx, encDataNode, xmlDocGetRootElement(doc)) &lt; 0) {
387         fprintf(stderr,"Error: encryption failed\n");
388         goto done;
389     }
390     
391     /* we template is inserted in the doc */
392     encDataNode = NULL;
393         
394     /* print encrypted data with document to stdout */
395     xmlDocDump(stdout, doc);
396     
397     /* success */
398     res = 0;
399
400 done:    
401
402     /* cleanup */
403     if(encCtx != NULL) {
404         xmlSecEncCtxDestroy(encCtx);
405     }
406
407     if(encDataNode != NULL) {
408         xmlFreeNode(encDataNode);
409     }
410         
411     if(doc != NULL) {
412         xmlFreeDoc(doc); 
413     }
414     return(res);
415 }\r</pre>
416 <p></p>
417 </div>
418 </div>
419 <br clear="all"><div class="SECT2">
420 <h2 class="SECT2"><a name="XMLSEC-EXAMPLE-ENCRYPT3-DOC">encrypt3-doc.xml</a></h2>
421 <p></p>
422 <div class="INFORMALEXAMPLE">
423 <p></p>
424 <a name="AEN788"></a><pre class="PROGRAMLISTING">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
425 &lt;!-- 
426 XML Security Library example: Original XML doc file before encryption (encrypt3 example). 
427 --&gt;
428 &lt;Envelope xmlns="urn:envelope"&gt;
429   &lt;Data&gt;
430         Hello, World!
431   &lt;/Data&gt;
432 &lt;/Envelope&gt;</pre>
433 <p></p>
434 </div>
435 </div>
436 <br clear="all"><div class="SECT2">
437 <h2 class="SECT2"><a name="XMLSEC-EXAMPLE-ENCRYPT3-RES">encrypt3-res.xml</a></h2>
438 <p></p>
439 <div class="INFORMALEXAMPLE">
440 <p></p>
441 <a name="AEN793"></a><pre class="PROGRAMLISTING">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
442 &lt;!-- 
443 XML Security Library example: XML doc file encrypted with a session DES key (encrypt3 example). 
444 --&gt;
445 &lt;EncryptedData xmlns="http://www.w3.org/2001/04/xmlenc#" Type="http://www.w3.org/2001/04/xmlenc#Element"&gt;
446 &lt;EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"/&gt;
447 &lt;KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"&gt;
448 &lt;EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#"&gt;
449 &lt;EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"/&gt;
450 &lt;KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"&gt;
451 &lt;KeyName&gt;rsakey.pem&lt;/KeyName&gt;
452 &lt;/KeyInfo&gt;
453 &lt;CipherData&gt;
454 &lt;CipherValue&gt;IPiEu9Nv+EsGyvVeXO9nl5iZhhi+uzQH1I3/DTs3+eamBvioyaawRIlvTql7LYL5
455 Mi91Qs8ozfW/fWZ8zB8AE2PosaX37SqiuEta68+65/Ed4v1rkGN0Awux8+gJqJmp
456 c2kJhzAoQIAIGAW4nTGP9tl9QUHfwKh2KPA104vezk70ijvF7TrbTmhdfmULAuWK
457 Tbsg8sXAPhGmPh5KckM2Xe387iPh4ue2+2TGdWqwXygVdvIUIbcIMq6F+/mWlcmf
458 Gs5FVI7CTjaLmeyO4ho+FGmicmqH2hEkZW0a2ktDh4BU/MxYF6L7oayrVWDGp2IH
459 dzQAwUT2qJcFjElO8xUz3g==&lt;/CipherValue&gt;
460 &lt;/CipherData&gt;
461 &lt;/EncryptedKey&gt;
462 &lt;/KeyInfo&gt;
463 &lt;CipherData&gt;
464 &lt;CipherValue&gt;xrfPSA+BEI+8ca23RN34gtee5lOMx8Cn+ZGWyxitiktdZ1+XREH+57li63VutCwp
465 s6ifbZgXIBsFdxPpMBUFlyTWAAO+NLooIwGoczXi14z62lHr7Ck6FA==&lt;/CipherValue&gt;
466 &lt;/CipherData&gt;
467 &lt;/EncryptedData&gt;</pre>
468 <p></p>
469 </div>
470 </div>
471 </div>
472 <table class="navigation" width="100%" summary="Navigation footer" cellpadding="2" cellspacing="2"><tr valign="middle">
473 <td align="left"><a accesskey="p" href="xmlsec-encrypt-dynamic-template.html"><b>&lt;&lt;&lt; Encrypting data with a dynamicaly created template.</b></a></td>
474 <td align="right"><a accesskey="n" href="xmlsec-decrypt-with-signle-key.html"><b>Decrypting data with a single key. &gt;&gt;&gt;</b></a></td>
475 </tr></table>
476 </td></tr></table></td>
477 </tr></table></body>
478 </html>