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 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
|
<!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 Signature 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> > <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">
<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">
</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="menupage">
<div class="menupagetitle">Signatures</div>
</div>
<div class="menuitem">
<a title="" href="../c/prog_enc.html">Encryption</a>
</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 Signature Programming</h1>
<a name="N1000D"></a><a name="Overview"></a>
<h2 class="h3">Overview</h2>
<div class="section">
<p>
There are two main signature modes of operation for the libraries.
Signing and verifying. Verifying is the simplest operation, as
it (generally) operates on a DOM <Signature> structure that
has already been created.
</p>
<p>
Signing on the other hand can be more difficult, as there may be a
requirement to create the DOM structure necessary for the signature
prior to the actual signing operation.
</p>
<p>
The rest of this section provides a very high level overview on how
to use the library for signing and verificataion of signatures.
</p>
<div class="frame note">
<div class="label">Note</div>
<div class="content">
Full API documentation for the current official release can be found
<a href="apiDocs/index.html">here</a>. The API documentation is
also generated <a class="external" href="http://nagoya.apache.org/~blautenb/xml-security-c/apiDocs/">nightly</a> from the CVS repository.
</div>
</div>
<p>
Two samples are provided :
</p>
<ul>
<li>
<a href="programming.html#simplehmac">Simple HMAC Signing
</a>
</li>
<li>
<a href="programming.html#simpledsa">Simple DSA Validation
</a>
</li>
</ul>
<p>
The code snippets are taken directly from some of the sample code
provided in the src/samples directory in the distribution. More
information on the API can be found in the API Documentation.
</p>
</div>
<a name="N1003B"></a><a name="simplehmac"></a>
<h2 class="h3">A simple HMAC Signing example</h2>
<div class="section">
<p>
The first example is based on the simpleHMAC.cpp code in samples. It
creates an XML letter, the appends a dummy signature to the end, using
an enveloped-signature transform.
</p>
<a name="N10044"></a><a name="Setup"></a>
<h3 class="h4">Setup</h3>
<p>
The following code snippet initialises Xerces, Xalan and XSEC.
Note that the enveloped transform is implemented using an XPath
expression, so it is imperitive the Xalan libraries are initialised.
</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 &e) {
cerr << "Error during initialisation of Xerces" << endl;
cerr << "Error Message = : "
<< e.getMessage() << endl;
}
// Create a blank Document
DOMImplementation *impl =
DOMImplementationRegistry::getDOMImplementation(MAKE_UNICODE_STRING("Core"));
// Create a letter
DOMDocument *doc = createLetter(impl);
DOMElement *rootElem = doc->getDocumentElement();
</pre>
<p>
In the sample application, the call to <em>createLetter(impl)</em>
simply creates a
letter DOM structure with a to and from address and some text.
This is done using standard DOM calls via Xerces.
</p>
<p>
Once the system is initialised and the DOM document is created,
a DSIGSignature object is created via the <em>XSECProvider</em>
interface class. The signature object is then used to create
a blank signature DOM node structure which is then inserted at
the end of the document.
</p>
<pre class="code">
XSECProvider prov;
DSIGSignature *sig;
DOMElement *sigNode;
try {
// Create a signature object
sig = prov.newSignature();
sig->setDSIGNSPrefix("ds");
// Use it to create a blank signature DOM structure from the doc
sigNode = sig->createBlankSignature(doc,
CANON_C14N_COM,
SIGNATURE_HMAC,
HASH_SHA1);
</pre>
<p>
The call to <em>newSignature</em> creates a signature
object only. No DOM nodes are created at this point.
The call to <em>setDSIGNSPrefix</em> tells the XSEC
library what namespace prefix to use for the signature object when
it starts to create DOM nodes (in this case "ds" will be used).
By default, the library will use "dsig" as the prefix for the name
space for Digital Signatures.
</p>
<p>
Finally, the call to sig->createBlankSignature sets up both the
DOM structure and the XSEC objects for a new signature with no
<Reference> elements. In this case, the signature will be
made using Commented C14n canonicalisation, and a HMAC-SHA1
signature.
</p>
<div class="frame warning">
<div class="label">Warning</div>
<div class="content">
The XSECProvider class still "owns" the DSIGSignature object.
To delete the object, the original provider.release(sig) call
should be used. Never delete a DSIGSignature object directly.
</div>
</div>
<a name="N10071"></a><a name="Create+a+Reference+and+Sign"></a>
<h3 class="h4">Create a Reference and Sign</h3>
<p>
Now that the signature object is created, the signature is inserted
into the document, and a reference is created and set for an
enveloping transform.
</p>
<pre class="code">
// Insert the signature DOM nodes into the doc
rootElem->appendChild(doc->createTextNode(MAKE_UNICODE_STRING("\n")));
rootElem->appendChild(sigNode);
rootElem->appendChild(doc->createTextNode(MAKE_UNICODE_STRING("\n")));
// Create an envelope reference for the text to be signed
DSIGReference * ref = sig->createReference("");
ref->appendEnvelopedSignatureTransform();
</pre>
<p>
The <em>""</em> parameter to <em>createReference</em> sets the
URI attribute for the reference to be "" - indicating the root
element of the document in which the signature resides.
The call to <em>appendEnvelopedSignatureTransform</em> adds
a standard eneveloped-signature transform to the Reference node.
</p>
<p>
The macro MAKE_UNICODE_STRING is defined within the library
header files and is used to transcode local code page strings.
</p>
<div class="frame note">
<div class="label">Note</div>
<div class="content">
There is no need to insert the reference object into the DOM structure.
This is done automatically by the <em>createReference</em> call.
</div>
</div>
<p>
Finally we create a signing key and sign the document.
</p>
<pre class="code">
// Set the HMAC Key to be the string "secret"
OpenSSLCryptoKeyHMAC * hmacKey = new OpenSSLCryptoKeyHMAC();
hmacKey->setKey((unsigned char *) "secret", strlen("secret"));
sig->setSigningKey(hmacKey);
// Add a KeyInfo element
sig->appendKeyName("The secret key is \"secret\"");
// Sign
sig->sign();
}
catch (XSECException &e)
{
cerr << "An error occured during a signature load\n Message: "
<< e.getMsg() << endl;
exit(1);
}
</pre>
<p>
The first two code lines create an OpenSSLCryptoKeyHMAC object,
and set the key value to the string "secret". The OpenSSL...
classes are the interface layer between XSEC and OpenSSL. More
information can be found in the API documentation, but the main
point of note is that the XSEC library never deals directly with
OpenSSL - it works via the XSECCrypto abstract classes which are
implemented in the OpenSSLCrypto code. This would allow another
person to re-implement the XSECCrypto code to use any cryptographic
provider required.
</p>
<div class="frame note">
<div class="label">Note</div>
<div class="content">
Once the key is passed to the signature it is owned by the signature.
The signature object will delete the key when it is itself deleted,
or a new key is passed in.
</div>
</div>
<p>
The call to <em>sig->appendKeyName()</em> is used to append a
<KeyName> element into the <KeyInfo> block. The
KeyInfo block was created as part of this call.
</p>
<p>
After the call to <em>sig->sign()</em> the DOM structure has the
correct hash and signature values. The owner program can write,
store or further manipulate the document as required. If a document
manipulation might affect the signature (in this case almost anything
would, as we are using an enveloping transform which effectively
signs everything that is not part of the signature), then a further
call to <em>sig->sign()</em> will re-sign the changes.
</p>
<p>
The last part of the code does some work to output the new DOM
structure. The output should look something like the following:
</p>
<pre class="code">
<Letter>
<ToAddress>The address of the Recipient</ToAddress>
<FromAddress>The address of the Sender</FromAddress>
<Text>
To whom it may concern
...
</Text>
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm=
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"/>
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#hmac-sha1"/>
<ds:Reference URI="">
<ds:Transforms>
<ds:Transform Algorithm=
"http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<ds:DigestValue>askxS/A3BaLCjFjZ/ttU9c12kA4=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>oYEdQYG1IHzbkR1UcJ9Q5VriRPs=
</ds:SignatureValue>
<ds:KeyInfo>
<ds:KeyName>The secret key is "secret"</ds:KeyName>
</ds:KeyInfo>
</ds:Signature>
</Letter>
</pre>
<p>Note that the DigestValue and SignatureValue elements have been
filled in.
</p>
</div>
<a name="N100BB"></a><a name="simpledsa"></a>
<h2 class="h3">A simple validation example</h2>
<div class="section">
<p>
The second example takes a pre-signed document and an associated
certificate and verifies the embedded signature. The document in
question is a simple purchase order, and changes are made to the
value of the order to demonstrate a signature failing verification.
</p>
<a name="N100C4"></a><a name="Setup-N100C4"></a>
<h3 class="h4">Setup</h3>
<p>
As in the first example, Initialisation of the libraries is
performed, and Xerces is used to read in the document (which in
this case is stored in a string in the source code).
</p>
<p>
In order to be able to modify the contents of the document later
on, we also quickly find the string containing the value of the
purchase order.
</p>
<p>
For the sake of brevity, the code relating to parsing the in-memory
document has been removed from the snippet below.
</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 &e) {
cerr << "Error during initialisation of Xerces" << endl;
cerr << "Error Message = : "
<< DOMString(e.getMessage()) << endl;
}
...
Xerces is used to parse the document here
DOM_Document doc = parser->getDocument();
// Find the Amount node
DOMNode *amt = doc->getDocumentElement();
if (amt != NULL)
amt = amt->getFirstChild();
while (amt != NULL &&
(amt->getNodeType() != DOMNode::ELEMENT_NODE ||
!strEquals(amt->getNodeName(), "Amount")))
amt = amt->getNextSibling();
if (amt != NULL)
amt = amt->getFirstChild();
if (amt == NULL || amt->getNodeType() != DOMNode::TEXT_NODE) {
cerr << "Error finding amount in purchase order" << endl;
exit (1);
}
</pre>
<a name="N100D8"></a><a name="Create+the+Signature+and+Key+objects"></a>
<h3 class="h4">Create the Signature and Key objects</h3>
<p>
Now that the document is in memory, an XSECProvider is
created and used to create a new DSIGSignature object. In
addition, the OpenSSL interface routines are used to
read in a certificate and obtain the associated public
key.
</p>
<pre class="code">
XSECProvider prov;
DSIGSignature * sig = prov.newSignatureFromDOM(doc);
try {
// Use the OpenSSL interface objects to get a signing key
OpenSSLCryptoX509 * x509 = new OpenSSLCryptoX509();
x509->loadX509Base64Bin(cert, strlen(cert));
sig->load();
</pre>
<p>
In this case, the signature is create with the
<em>newSignatureFromDOM</em> method. This tells the library that
the signature structure (although not necessarily a signed
structure) already exists in the DOM nodes. The library attempts
to find the <Signature> node so that the load will work.
(The library will throw an XSECException if it cannot find the
Element.)
</p>
<p>
The later call to <em>sig->load()</em> tells the library to
read the DOM structure and create the appropriate DSIG elements.
</p>
<p>
In this case an OpenSSLCryptoX509 object is also created. It is
used to read in the <em>cert</em> string and convert to an X509
structure. This could also be done using standard calls directly
to OpenSSL, but this is a quick shortcut.
</p>
<a name="N100F8"></a><a name="Find+a+key"></a>
<h3 class="h4">Find a key</h3>
<p>
As we already know the key, the following code snippet loads the
key directly from the related X509. However prior to doing this,
the code demonstrates
using the DSIGKeyInfo structures to find the key name that was
embedded in the certificate. In an application, this could be
used to reference the correct key to be passed in. (Maybe via
an XKMS call.)
</p>
<p>
the <em>safeBuffer</em> type is used extensively within the XSEC
library to safely handle variable length strings and raw buffers.
The call to <em>rawCharBuffer()</em> simply returns a (char *)
type pointer to the buffer within the <em>safeBuffer</em>
</p>
<p>
The call to <em>clonePublicKey()</em> returns a copy of the
public key embedded in the certificate. It is owned by the caller,
so in this case it can safely be passed to the DSIGSignature object
where it will be destroyed when another key is loaded or the
object is released by the XSECProvider.
</p>
<pre class="code">
DSIGKeyInfoList * kinfList = sig->getKeyInfoList();
// See if we can find a Key Name
safeBuffer kname;
DSIGKeyInfo * kinf = kinfList->getFirstKeyInfo();
while (kinf != NULL) {
kname = kinf->getKeyName();
if (kname.sbStrcmp("")) {
cout << "Key Name = "
<< kname.rawCharBuffer() << endl;
}
kinf = kinfList->getNextKeyInfo();
}
sig->setSigningKey(x509->clonePublicKey());
</pre>
<a name="N10118"></a><a name="Validate+the+signature"></a>
<h3 class="h4">Validate the signature</h3>
<p>
Finally the signature is validated. In this case, we validate it
three times. First with the original DOM structure, then with the
price changed and finally with the price set back to the original
value.
</p>
<pre class="code">
cout << "Amount = " << amt << " -> ";
if (sig->verify()) {
cout << "Signature Valid\n";
}
else {
cout << "Incorrect Signature\n";
}
amt.setNodeValue("$0.50");
cout << "Amount = " << amt << " -> ";
if (sig->verify()) {
cout << "Signature Valid\n";
}
else {
cout << "Incorrect Signature\n";
}
amt.setNodeValue("$16.50");
cout << "Amount = " << amt << " -> ";
if (sig->verify()) {
cout << "Signature Valid\n";
}
else {
cout << "Incorrect Signature\n";
}
</pre>
<p>
When run, the program outputs the following:
</p>
<pre class="code">
Key Name = C=AU, ST=Vic, O=XML-Security-C Project,
CN=Samples Demo Certificate
Amount = $16.50 -> Signature Valid
Amount = $0.50 -> Incorrect Signature
Amount = $16.50 -> Signature Valid
</pre>
</div>
</div>
<!--+
|end content
+-->
<div class="clearboth"> </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 © 2002-2005 The Apache Software Foundation.</div>
<!--+
|end bottomstrip
+-->
</div>
</body>
</html>
|