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 {
12 border: solid 1px #aaaaaa;
17 border: solid 1px #aaaaff;
26 border: solid 1px #ffaaaa;
33 .navigation a:visited {
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>
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>
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>
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>
66 <td><a href="http://xmlsoft.org/"><img src="../images/libxml2-logo.png" alt="LibXML2" border="0"></a></td>
70 <td><a href="http://xmlsoft.org/XSLT"><img src="../images/libxslt-logo.png" alt="LibXSLT" border="0"></a></td>
74 <td><a href="http://www.openssl.org/"><img src="../images/openssl-logo.png" alt="OpenSSL" border="0"></a></td>
76 <!--Links - start--><!--Links - end-->
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>
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>
92 <div class="INFORMALEXAMPLE">
94 <a name="AEN783"></a><pre class="PROGRAMLISTING">/**
95 * XML Security Library example: Encrypting XML file with a session key and dynamicaly created template.
97 * Encrypts XML file using a dynamicaly created template file and a session
98 * DES key (encrypted with an RSA key).
101 * ./encrypt3 <xml-doc> <rsa-pem-key-file>
104 * ./encrypt3 encrypt3-doc.xml rsakey.pem > encrypt3-res.xml
106 * The result could be decrypted with decrypt3 example:
107 * ./decrypt3 encrypt3-res.xml
109 * This is free software; see Copyright file in the source
110 * distribution for preciese wording.
112 * Copyright (C) 2002-2003 Aleksey Sanin <aleksey@aleksey.com>
114 #include <stdlib.h>
115 #include <string.h>
116 #include <assert.h>
118 #include <libxml/tree.h>
119 #include <libxml/xmlmemory.h>
120 #include <libxml/parser.h>
122 #ifndef XMLSEC_NO_XSLT
123 #include <libxslt/xslt.h>
124 #endif /* XMLSEC_NO_XSLT */
126 #include <xmlsec/xmlsec.h>
127 #include <xmlsec/xmltree.h>
128 #include <xmlsec/xmlenc.h>
129 #include <xmlsec/templates.h>
130 #include <xmlsec/crypto.h>
132 xmlSecKeysMngrPtr load_rsa_keys(char* key_file);
133 int encrypt_file(xmlSecKeysMngrPtr mngr, const char* xml_file, const char* key_name);
136 main(int argc, char **argv) {
137 xmlSecKeysMngrPtr mngr;
142 fprintf(stderr, "Error: wrong number of arguments.\n");
143 fprintf(stderr, "Usage: %s <xml-file> <key-file>\n", argv[0]);
147 /* Init libxml and libxslt libraries */
150 xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
151 xmlSubstituteEntitiesDefault(1);
152 #ifndef XMLSEC_NO_XSLT
153 xmlIndentTreeOutput = 1;
154 #endif /* XMLSEC_NO_XSLT */
156 /* Init xmlsec library */
157 if(xmlSecInit() < 0) {
158 fprintf(stderr, "Error: xmlsec initialization failed.\n");
162 /* Check loaded library version */
163 if(xmlSecCheckVersion() != 1) {
164 fprintf(stderr, "Error: loaded xmlsec library version is not compatible.\n");
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.
173 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
174 if(xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 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");
180 #endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */
182 /* Init crypto library */
183 if(xmlSecCryptoAppInit(NULL) < 0) {
184 fprintf(stderr, "Error: crypto initialization failed.\n");
188 /* Init xmlsec-crypto library */
189 if(xmlSecCryptoInit() < 0) {
190 fprintf(stderr, "Error: xmlsec-crypto initialization failed.\n");
194 /* create keys manager and load keys */
195 mngr = load_rsa_keys(argv[2]);
200 /* we use key filename as key name here */
201 if(encrypt_file(mngr, argv[1], argv[2]) < 0) {
202 xmlSecKeysMngrDestroy(mngr);
206 /* destroy keys manager */
207 xmlSecKeysMngrDestroy(mngr);
209 /* Shutdown xmlsec-crypto library */
210 xmlSecCryptoShutdown();
212 /* Shutdown crypto library */
213 xmlSecCryptoAppShutdown();
215 /* Shutdown xmlsec library */
218 /* Shutdown libxslt/libxml */
219 #ifndef XMLSEC_NO_XSLT
220 xsltCleanupGlobals();
221 #endif /* XMLSEC_NO_XSLT */
229 * @key_file: the key filename.
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.
235 * Returns the pointer to newly created keys manager or NULL if an error
239 load_rsa_keys(char* key_file) {
240 xmlSecKeysMngrPtr mngr;
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
249 mngr = xmlSecKeysMngrCreate();
251 fprintf(stderr, "Error: failed to create keys manager.\n");
254 if(xmlSecCryptoAppDefaultKeysMngrInit(mngr) < 0) {
255 fprintf(stderr, "Error: failed to initialize keys manager.\n");
256 xmlSecKeysMngrDestroy(mngr);
260 /* load private RSA key */
261 key = xmlSecCryptoAppKeyLoad(key_file, xmlSecKeyDataFormatPem, NULL, NULL, NULL);
263 fprintf(stderr,"Error: failed to load rsa key from file \"%s\"\n", key_file);
264 xmlSecKeysMngrDestroy(mngr);
268 /* set key name to the file name, this is just an example! */
269 if(xmlSecKeySetName(key, BAD_CAST key_file) < 0) {
270 fprintf(stderr,"Error: failed to set key name for key from \"%s\"\n", key_file);
271 xmlSecKeyDestroy(key);
272 xmlSecKeysMngrDestroy(mngr);
276 /* add key to keys manager, from now on keys manager is responsible
279 if(xmlSecCryptoAppDefaultKeysMngrAdoptKey(mngr, key) < 0) {
280 fprintf(stderr,"Error: failed to add key from \"%s\" to keys manager\n", key_file);
281 xmlSecKeyDestroy(key);
282 xmlSecKeysMngrDestroy(mngr);
291 * @mngr: the pointer to keys manager.
292 * @xml_file: the encryption template file name.
293 * @key_name: the RSA key name.
295 * Encrypts #xml_file using a dynamicaly created template, a session DES key
296 * and an RSA key from keys manager.
298 * Returns 0 on success or a negative value if an error occurs.
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;
315 doc = xmlParseFile(xml_file);
316 if ((doc == NULL) || (xmlDocGetRootElement(doc) == NULL)){
317 fprintf(stderr, "Error: unable to parse file \"%s\"\n", xml_file);
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");
330 /* we want to put encrypted data in the <enc:CipherValue/> node */
331 if(xmlSecTmplEncDataEnsureCipherValue(encDataNode) == NULL) {
332 fprintf(stderr, "Error: failed to add CipherValue node\n");
336 /* add <dsig:KeyInfo/> */
337 keyInfoNode = xmlSecTmplEncDataEnsureKeyInfo(encDataNode, NULL);
338 if(keyInfoNode == NULL) {
339 fprintf(stderr, "Error: failed to add key info\n");
343 /* add <enc:EncryptedKey/> to store the encrypted session key */
344 encKeyNode = xmlSecTmplKeyInfoAddEncryptedKey(keyInfoNode,
345 xmlSecTransformRsaPkcs1Id,
347 if(encKeyNode == NULL) {
348 fprintf(stderr, "Error: failed to add key info\n");
352 /* we want to put encrypted key in the <enc:CipherValue/> node */
353 if(xmlSecTmplEncDataEnsureCipherValue(encKeyNode) == NULL) {
354 fprintf(stderr, "Error: failed to add CipherValue node\n");
358 /* add <dsig:KeyInfo/> and <dsig:KeyName/> nodes to <enc:EncryptedKey/> */
359 keyInfoNode2 = xmlSecTmplEncDataEnsureKeyInfo(encKeyNode, NULL);
360 if(keyInfoNode2 == NULL) {
361 fprintf(stderr, "Error: failed to add key info\n");
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");
371 /* create encryption context */
372 encCtx = xmlSecEncCtxCreate(mngr);
374 fprintf(stderr,"Error: failed to create encryption context\n");
378 /* generate a Triple DES key */
379 encCtx->encKey = xmlSecKeyGenerate(xmlSecKeyDataDesId, 192, xmlSecKeyDataTypeSession);
380 if(encCtx->encKey == NULL) {
381 fprintf(stderr,"Error: failed to generate session des key\n");
385 /* encrypt the data */
386 if(xmlSecEncCtxXmlEncrypt(encCtx, encDataNode, xmlDocGetRootElement(doc)) < 0) {
387 fprintf(stderr,"Error: encryption failed\n");
391 /* we template is inserted in the doc */
394 /* print encrypted data with document to stdout */
395 xmlDocDump(stdout, doc);
404 xmlSecEncCtxDestroy(encCtx);
407 if(encDataNode != NULL) {
408 xmlFreeNode(encDataNode);
419 <br clear="all"><div class="SECT2">
420 <h2 class="SECT2"><a name="XMLSEC-EXAMPLE-ENCRYPT3-DOC">encrypt3-doc.xml</a></h2>
422 <div class="INFORMALEXAMPLE">
424 <a name="AEN788"></a><pre class="PROGRAMLISTING"><?xml version="1.0" encoding="UTF-8"?>
426 XML Security Library example: Original XML doc file before encryption (encrypt3 example).
428 <Envelope xmlns="urn:envelope">
432 </Envelope></pre>
436 <br clear="all"><div class="SECT2">
437 <h2 class="SECT2"><a name="XMLSEC-EXAMPLE-ENCRYPT3-RES">encrypt3-res.xml</a></h2>
439 <div class="INFORMALEXAMPLE">
441 <a name="AEN793"></a><pre class="PROGRAMLISTING"><?xml version="1.0" encoding="UTF-8"?>
443 XML Security Library example: XML doc file encrypted with a session DES key (encrypt3 example).
445 <EncryptedData xmlns="http://www.w3.org/2001/04/xmlenc#" Type="http://www.w3.org/2001/04/xmlenc#Element">
446 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"/>
447 <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
448 <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
449 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"/>
450 <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
451 <KeyName>rsakey.pem</KeyName>
454 <CipherValue>IPiEu9Nv+EsGyvVeXO9nl5iZhhi+uzQH1I3/DTs3+eamBvioyaawRIlvTql7LYL5
455 Mi91Qs8ozfW/fWZ8zB8AE2PosaX37SqiuEta68+65/Ed4v1rkGN0Awux8+gJqJmp
456 c2kJhzAoQIAIGAW4nTGP9tl9QUHfwKh2KPA104vezk70ijvF7TrbTmhdfmULAuWK
457 Tbsg8sXAPhGmPh5KckM2Xe387iPh4ue2+2TGdWqwXygVdvIUIbcIMq6F+/mWlcmf
458 Gs5FVI7CTjaLmeyO4ho+FGmicmqH2hEkZW0a2ktDh4BU/MxYF6L7oayrVWDGp2IH
459 dzQAwUT2qJcFjElO8xUz3g==</CipherValue>
461 </EncryptedKey>
464 <CipherValue>xrfPSA+BEI+8ca23RN34gtee5lOMx8Cn+ZGWyxitiktdZ1+XREH+57li63VutCwp
465 s6ifbZgXIBsFdxPpMBUFlyTWAAO+NLooIwGoczXi14z62lHr7Ck6FA==</CipherValue>
467 </EncryptedData></pre>
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><<< 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. >>></b></a></td>
476 </td></tr></table></td>