File: prog_enc.html

package info (click to toggle)
xml-security-c 1.2.1-3%2Betch1
  • links: PTS
  • area: main
  • in suites: etch
  • size: 24,472 kB
  • ctags: 6,673
  • sloc: cpp: 36,830; xml: 23,415; sh: 2,365; makefile: 340; perl: 221
file content (556 lines) | stat: -rw-r--r-- 18,856 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta content="Apache Forrest" name="Generator">
<meta name="Forrest-version" content="0.6">
<meta name="Forrest-skin-name" content="pelt">
<title>XML Encryption Programming</title>
<link type="text/css" href="../skin/basic.css" rel="stylesheet">
<link media="screen" type="text/css" href="../skin/screen.css" rel="stylesheet">
<link media="print" type="text/css" href="../skin/print.css" rel="stylesheet">
<link type="text/css" href="../skin/profile.css" rel="stylesheet">
<script src="../skin/getBlank.js" language="javascript" type="text/javascript"></script><script src="../skin/getMenu.js" language="javascript" type="text/javascript"></script><script src="../skin/fontsize.js" language="javascript" type="text/javascript"></script>
</head>
<body onload="init()">
<script type="text/javascript">ndeSetTextSize();</script>
<div id="top">
<!--+
    |breadtrail
    +-->
<div class="breadtrail">
<a href="http://www.apache.org/">apache</a> &gt; <a href="http://xml.apache.org/">xml.apache</a><script src="../skin/breadcrumbs.js" language="JavaScript" type="text/javascript"></script>
</div>
<!--+
    |header
    +-->
<div class="header">
<!--+
    |start group logo
    +-->
<div class="grouplogo">
<a href="http:///xml.apache.org"><img class="logoImage" alt="Apache XML" src="../images/group-logo.gif"></a>
</div>
<!--+
    |end group logo
    +-->
<!--+
    |start Project Logo
    +-->
<div class="projectlogo">
<a href="http://xml.apache.org/security"><img class="logoImage" alt="Apache XML Security" src="../images/project-logo.gif"></a>
</div>
<!--+
    |end Project Logo
    +-->
<!--+
    |start Search
    +-->
<div class="searchbox">
<form action="http://www.google.com/search" method="get" class="roundtopsmall">
<input value="xml.apache.org/security" name="sitesearch" type="hidden"><input onFocus="getBlank (this, 'Search the site with google:');" value="Search the site with google:" size="25" name="q" id="query" type="text">&nbsp; 
                    <input name="Search" value="Search" type="submit">
</form>
</div>
<!--+
    |end search
    +-->
<!--+
    |start Tabs
    +-->
<ul id="tabs">
<li>
<a class="base-not-selected" href="../index.html">Home</a>
</li>
<li>
<a class="base-not-selected" href="../Java/index.html">Java</a>
</li>
<li class="current">
<a class="base-selected" href="../c/index.html">C++</a>
</li>
</ul>
<!--+
    |end Tabs
    +-->
</div>
</div>
<div id="main">
<div id="publishedStrip">
<!--+
    |start Subtabs
    +-->
<div id="level2tabs"></div>
<!--+
    |end Endtabs
    +-->
<script type="text/javascript" language="JavaScript"><!--
              document.write("Published: " + document.lastModified);
              //  --></script>
</div>
<!--+
    |breadtrail
    +-->
<div class="breadtrail">
             
             &nbsp;
           </div>
<!--+
    |start Menu, mainarea
    +-->
<!--+
    |start Menu
    +-->
<div id="menu">
<div onclick="SwitchMenu('menu_1.1', '../skin/')" id="menu_1.1Title" class="menutitle">C++</div>
<div id="menu_1.1" class="menuitemgroup">
<div class="menuitem">
<a title="" href="../c/index.html">Index</a>
</div>
<div class="menuitem">
<a title="" href="../c/installation.html">Installation</a>
</div>
<div class="menuitem">
<a title="" href="../c/faq.html">FAQs</a>
</div>
<div class="menuitem">
<a title="" href="../c/apiDocs/index.html">API Docs</a>
</div>
<div class="menuitem">
<a title="" href="http://nagoya.apache.org/~blautenb/xml-security-c/apiDocs/">Nightly API build</a>
</div>
<div class="menuitem">
<a title="" href="../c/tools.html">Tools</a>
</div>
<div class="menuitem">
<a title="" href="../c/releases.html">Release Information</a>
</div>
<div class="menuitem">
<a title="" href="../c/credits.html">Credits</a>
</div>
<div class="menuitem">
<a title="" href="../c/interop.html">Interoperability</a>
</div>
</div>
<div onclick="SwitchMenu('menu_selected_1.2', '../skin/')" id="menu_selected_1.2Title" class="menutitle" style="background-image: url('../skin/images/chapter_open.gif');">Programming</div>
<div id="menu_selected_1.2" class="selectedmenuitemgroup" style="display: block;">
<div class="menuitem">
<a title="" href="../c/programming.html">Signatures</a>
</div>
<div class="menupage">
<div class="menupagetitle">Encryption</div>
</div>
</div>
<div id="credit"></div>
<div id="roundbottom">
<img style="display: none" class="corner" height="15" width="15" alt="" src="../skin/images/rc-b-l-15-1body-2menu-3menu.png"></div>
<!--+
  |alternative credits
  +-->
</div>
<!--+
    |end Menu
    +-->
<!--+
    |start content
    +-->
<div id="content">
<div id="skinconf-txtlink"></div>
<h1>XML Encryption Programming</h1>
	
<a name="N1000D"></a><a name="overview"></a>
<h2 class="h3">Overview</h2>
<div class="section">
<p>
		As with signatures, there are two main modes of operation for the
		library when performing encryption functions - Encryption and
		Decryption.  Decryption is generally fairly simple, as the library
		will handle most of the work around de-referencing key material and
		re-creating a DOM document (or returning a byte stream).
	  </p>
<p>
		Encryption is fairly simple if you are trying to encrypt a DOM
		structure.  The library will encrypt the nodes and then replace them
		with the encrypted version.  However if you want to embed an
		arbitrary encrypted object in the document, you will need to
		encrypt it first and then pass the encrypted text into the library.
	  </p>
<p>
		The rest of this page looks at some simple examples around
		encrypting and decrypting nodes within an XML document
	  </p>
</div>
	
<a name="N1001D"></a><a name="simpleencrypt"></a>
<h2 class="h3">A simple encryption example</h2>
<div class="section">
<p>
		The next example encrypts an element (and all its children) from
		a pre-generated document.  It uses a randomly generated key to
		handle the bulk encryption, and then encrypts this using an RSA
		public key.  The resultant encrypted key is embedded in an
		&lt;EncryptedKey&gt; element.
	  </p>
<p>
		This example can be found in the src/samples directory as
		<em>simpleEncrypt.cpp</em>.
	  </p>
<a name="N1002C"></a><a name="Setup"></a>
<h3 class="h4">Setup</h3>
<p>
		  The first step is initialisation of Xerces, Xalan (if used) and
		  XML-Security.  Once this is done, we create a document.  For 
		  brevity, the details of the call to <em>createLetter</em> are
		  not included on this page.  The function is very simple - it creates
		  an XML DOM document that represents a letter, and sets a global
		  variable (<em>g_toEncrypt</em>) that will be used later on to
		  determine what node to encrypt.
		</p>
<pre class="code">
int main (int argc, char **argv) {

    try {
        XMLPlatformUtils::Initialize();
#ifndef XSEC_NO_XALAN
        XalanTransformer::initialize();
#endif
        XSECPlatformUtils::Initialise();
    }
    catch (const XMLException &amp;e) {

        cerr &lt;&lt; "Error during initialisation of Xerces" &lt;&lt; endl;
        cerr &lt;&lt; "Error Message = : "
             &lt;&lt; e.getMessage() &lt;&lt; endl;

    }

    // Create a blank Document

    DOMImplementation *impl = 
        DOMImplementationRegistry::getDOMImplementation(MAKE_UNICODE_STRING("Core"));
	
    // Create a letter
    DOMDocument *doc = createLetter(impl);
		  </pre>
<a name="N10040"></a><a name="Setup+for+Encryption"></a>
<h3 class="h4">Setup for Encryption</h3>
<p>
		  Once the library is initialised, we create a <em>XENCCipher</em>
		  object in a manner similar to the creation of a 
		  <em>DSIGSignature</em> object.  The <em>XENCCipher</em> object
		  is used to actually perform encryption/decryption functions and
		  to manipulate the various encryption objects provided by the
		  library.
		</p>
<p>
		  As well as creating the <em>XENCCipher</em> object, the sample
		  uses the <em>RAND_bytes</em> function within the 
		  <strong>OpenSSL</strong>
		  library to create a random key that will be used during the
		  encryption process.
		</p>
<pre class="code">
    try {
		
        /* Create the cipher object that we need */

        XSECProvider prov;
        XENCCipher *cipher;

        cipher = prov.newCipher(doc);

        /* Now generate a random key that we can use to encrypt the element
         *
         * First check the status of the random generation in OpenSSL
         */

        if (RAND_status() != 1) {

            cerr &lt;&lt; "OpenSSL random generation not properly initialised" &lt;&lt; endl;
            exit(1);

        }

        unsigned char keyBuf[24];
        if (RAND_bytes(keyBuf, 24) == 0) {

            cerr &lt;&lt; "Error obtaining 24 bytes of random from OpenSSL" &lt;&lt; endl;
            exit(1);

        }
</pre>
<a name="N10063"></a><a name="Encryption+of+Element"></a>
<h3 class="h4">Encryption of Element</h3>
<p>
		  The actual code to perform encryption is very small.  Most of the
		  complexity for standard encryption is hidden within the library.
		</p>
<p>
		  The first two lines of code wrap the generated key bytes in an
		  OpenSSL 3DES key.  This is then passed into the <em>cipher</em>
		  object with a call to <em>setKey(key)</em>.
		</p>
<p>
		  The last line in the following block performs the actual encryption.
		  the first parameter to <em>cipher-&gt;encryptElement</em> is the 
		  node that will be encrypted.  The second is the algorithm to be 
		  used.  This is used to calcualte the Algorithm URI to be set in
		  the &lt;EncryptedData&gt; element.
		</p>
<p>
		  This call to <em>EncryptElement</em> will encrypt the provided
		  element using the key set previously.  The passed in element will
		  be replaced with an &lt;EncryptedData&gt; element containing the
		  encrypted version of the element and all its children.
		</p>
<p>
		  If no further information is required to be embedded in the
		  &lt;EncryptedData&gt; structure (such as &lt;KeyInfo&gt; nodes),
		  the usage of the library could be terminated here.
		</p>
<pre class="code">
        /* Wrap this in a Symmetric 3DES key */

        OpenSSLCryptoSymmetricKey * key = 
            new OpenSSLCryptoSymmetricKey(XSECCryptoSymmetricKey::KEY_3DES_192);
        key-&gt;setKey(keyBuf, 24);
        cipher-&gt;setKey(key);

        /* Encrypt the element that needs to be hidden */
        cipher-&gt;encryptElement(g_toEncrypt, ENCRYPT_3DES_CBC);
</pre>
<a name="N10089"></a><a name="Create+an+%3CEncryptedKey%3E"></a>
<h3 class="h4">Create an &lt;EncryptedKey&gt;</h3>
<p>
		  The following snippet of code uses the previously created
		  <em>XENCCipher</em> object to encrypt the pseudo random key using
		  an RSA key loaded from a X.509 certificate.
		</p>
<p>
		  The first two lines load the certificate into an OpenSSLCryptoX509
		  structure, which is then used to extract the public key from the
		  certificate and pass into the cipher.
		</p>
<p>
		  A call to <em>setKEK</em> is used rather than <em>setKey</em>.
		  This call is used to tell the cipher object that the key being used
		  is a Key Encryption Key, and should be used for encrypting/decrypting
		  &lt;EncryptedKey&gt; elements.
		</p>
<p>
		  The final line actually performs the encryption and created
		  the &lt;EncryptedKey&gt; structure.  The first two parameters define
		  the buffer and its length to be encrypted.  The last defines the
		  encryption algorithm to be used.
		</p>
<p>
		  The <em>encryptedKey</em> method returns an <em>XENCEncryptedKey</em>
		  object.  This contains the DOM structure for the object, but it is
		  not yet rooted in a particular document.  (Although it is created
		  using the <em>DOMDocument</em> that was passed in during the call
		  to <em>newCipher</em>.)
		</p>
<pre class="code">
        /* Now lets create an EncryptedKey element to hold the generated key */

        /* First lets load the public key in the certificate */
        OpenSSLCryptoX509 * x509 = new OpenSSLCryptoX509();
        x509-&gt;loadX509Base64Bin(cert, strlen(cert));
	
        /* Now set the Key Encrypting Key (NOTE: Not the normal key) */
        cipher-&gt;setKEK(x509-&gt;clonePublicKey());
		

        /* Now do the encrypt, using RSA with PKCS 1.5 padding */

        XENCEncryptedKey * encryptedKey = 
            cipher-&gt;encryptKey(keyBuf, 24, ENCRYPT_RSA_15);
</pre>
<a name="N100B8"></a><a name="Append+%3CEncryptedKey%3E+to+%3CEncryptedData%3E"></a>
<h3 class="h4">Append &lt;EncryptedKey&gt; to &lt;EncryptedData&gt;</h3>
<p>
		  The final part (other than outputting the result) is to 
		  retrieve the &lt;EncryptedData&gt; element that was previously 
		  created and append the newly created &lt;EncryptedKey&gt; as a 
		  &lt;KeyInfo&gt; element.
		</p>
<pre class="code">
        /*
         * Add the encrypted Key to the previously created EncryptedData, which
         * we first retrieve from the cipher object.  This will automatically create
         * the appropriate &lt;KeyInfo&gt; element within the EncryptedData
         */

        XENCEncryptedData * encryptedData = cipher-&gt;getEncryptedData();
        encryptedData-&gt;appendEncryptedKey(encryptedKey);
</pre>
<p>
		The above code results in a document that contains the newly created
		&lt;EncryptedData&gt; as follows:
	  </p>
<pre class="code">
&lt;Letter&gt;
&lt;ToAddress&gt;The address of the Recipient&lt;/ToAddress&gt;
&lt;FromAddress&gt;The address of the Sender&lt;/FromAddress&gt;
&lt;xenc:EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" 
xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"&gt;
&lt;xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"/&gt;
&lt;ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"&gt;
&lt;xenc:EncryptedKey xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"&gt;
&lt;xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/&gt;
&lt;xenc:CipherData&gt;
&lt;xenc:CipherValue&gt;Wh8pAkDsQceHiktGxnlhXGfEMPDOLB6FwWp8PLedFEB3L3F6xHUoCOerIvA7Pgvv
VYzVqLv4a5x5YdnCqikkFBLE/fruAUe2Z8ZTEn/CaPYmpzU6qYHALCl7Q61LcbqH
R87TzroBYsYwfHmXmrKHL9K9sB6zmuec1TjVzm2c/Xs=
&lt;/xenc:CipherValue&gt;
&lt;/xenc:CipherData&gt;
&lt;/xenc:EncryptedKey&gt;
&lt;/ds:KeyInfo&gt;
&lt;xenc:CipherData&gt;
&lt;xenc:CipherValue&gt;YhqQciiFkLG1z0I1TJC6Pewnzw/gmVuGqcTvHtWpgak/b3NQDRAlv07lJOmBLoHX
23LQ1CdPSxvnyerlJGwkY6xJ0M5tjpDregTVcECXo/bd+x8eIsF2kaawoZGCqD1K
96T36Fx9rHek9bY/Hp1OiQ==
&lt;/xenc:CipherValue&gt;
&lt;/xenc:CipherData&gt;
&lt;/xenc:EncryptedData&gt;&lt;/Letter&gt;
</pre>
</div>
	
<a name="N100CE"></a><a name="simpledecrypt"></a>
<h2 class="h3">A simple decryption example</h2>
<div class="section">
<p>
		The final example shows how to use the library to decrypt an
		EncryptedData structure.  A private key is loaded as a Key
		Encryption Key (KEK), and a call is made to the library which
		decrypts the encrypted data and inserts the resulting DOM nodes
		back into the original document.
	  </p>
<p>
		This example can be found in the src/samples directory as
		<em>simpleDecrypt.cpp</em>.
	  </p>
<a name="N100DD"></a><a name="Setup-N100DD"></a>
<h3 class="h4">Setup</h3>
<p>
		  The setup process is much the same as for 
		  <a target="_top" href="#simpledsa">simpleVerify</a>.  The document
		  (which is the document created in simpleEncrypt) is parsed using 
		  Xerces and a <em>DOMDocument</em> is returned.
		</p>
<a name="N100EE"></a><a name="Load+Private+Key"></a>
<h3 class="h4">Load Private Key</h3>
<p>
		  The <em>simpleDecrypt</em> uses a preloaded RSA private key for
		  the decryption.  A key resolver (<em>XSECKeyInfoResolver</em>) can 
		  also be used to provide a callback mechanism such that applications 
		  can determine the correct key at run time.
		</p>
<p>
		  The following code uses a <em>XSECProvider</em> to obtain a
		  <em>XENCCipher</em>uses OpenSSL to load the private key from the
		  <em>s_privateKey</em> char array.
		</p>
<p>
		  The key is loaded using a call to <em>setKEK</em>.  This method
		  loads the key as a Key Encryption Key - which means it will be used
		  to decrypt an &lt;EncryptedKey&gt; structure.
		</p>
<pre class="code">

        XSECProvider prov;
        XENCCipher *cipher;

        cipher = prov.newCipher(doc);

        /* Load the private key via OpenSSL and then wrap in an OpenSSLCrypto construct */
        BIO * bioMem = BIO_new(BIO_s_mem());
        BIO_puts(bioMem, s_privateKey);
        EVP_PKEY * pk = PEM_read_bio_PrivateKey(bioMem, NULL, NULL, NULL);

        /* NOTE : For simplicity - no error checking here */

        OpenSSLCryptoKeyRSA * k = new OpenSSLCryptoKeyRSA(pk);
        cipher-&gt;setKEK(k);

</pre>
<a name="N10114"></a><a name="Perform+Decryption"></a>
<h3 class="h4">Perform Decryption</h3>
<p>
		  Now that the key is loaded, the actual decryption is performed
		  using two lines of code.  The first finds the node to be
		  decrypted.  In this case, the <em>findXENCNode</em> library
		  function is used.
		</p>
<p>
		  The second line, <em>decryptElement</em> actually performs the
		  decryption.  It performs the following steps :
		</p>
<ul>
		  
<li>Load the &lt;EncryptedData&gt; structure into an 
			<em>XENCEncryptedData</em> structure.</li>
		  
<li>if no decryption key is loaded (in this case, none is),
			search the &lt;KeyInfo&gt; list for an &lt;EncryptedKey&gt;
			element (one will be found in this case).</li>
		  
<li>Use the previously loaded KEK to decrypt the key found in
			the previous step.</li>
		  
<li>Use the decrypted key to decrypt the &lt;EncryptedData&gt;
			data</li>
		  
<li>Parse the decrypted data into DOM nodes</li>
		  
<li>Replace the &lt;EncryptedData&gt; with the DOM fragment
			returned in the previous step</li>
		
</ul>
<pre class="code">
		
        /* Find the EncryptedData node */
        DOMNode * encryptedNode = findXENCNode(doc, "EncryptedData");

        /* Do the decrypt */
        cipher-&gt;decryptElement((DOMElement *) encryptedNode);

</pre>
<p>
		The result of these steps is the decrypted letter.
	  </p>
<pre class="code">
&lt;Letter&gt;
&lt;ToAddress&gt;The address of the Recipient&lt;/ToAddress&gt;
&lt;FromAddress&gt;The address of the Sender&lt;/FromAddress&gt;
&lt;Text&gt;
To whom it may concern, my secret credit card number is : 
  0123 4567 89ab cdef

...
&lt;/Text&gt;&lt;/Letter&gt;
</pre>
</div>
  
</div>
<!--+
    |end content
    +-->
<div class="clearboth">&nbsp;</div>
</div>
<div id="footer">
<!--+
    |start bottomstrip
    +-->
<div class="lastmodified">
<script type="text/javascript"><!--
document.write("Last Published: " + document.lastModified);
//  --></script>
</div>
<div class="copyright">
 Copyright &copy; 2002-2005 The Apache Software Foundation.</div>
<!--+
    |end bottomstrip
    +-->
</div>
</body>
</html>