# Adding support for new cryptographic library.

## Overview.

XML Security Library can support practicaly any cryptographic library. Currently, it has "out-of-the-box" support for OpenSSL, MSCrypto, NSS, GnuTLS and GCrypt. If your favorite library is not supported yet then you can write necessary code yourself. If you and your company (university, ...) are willing to share the results of your work I would be happy to add support for new libraries to the main XML Security Library distribution.

The XML Security Library separates the cryptographic library (engine) specific code in an "xmlsec-<crypto>" library (where "<crypto>" is "openssl", "mscrypt", "gnutls", "gcrypt", "nss", etc.) which includes following items:

- xmlSecCryptoApp* functions.

- Cryptographic transforms and keys data implementation.

- Keys store support (X509, PGP, etc.).

In this chapter, we will discuss a task of creating "xmlsec-mycrypto" library that provides support for your favorite "MyCrypto" cryptographic library.

## xmlSecCryptoApp* functions.

The XML Security Library allows application to load multiple "xmlsec-<crypto> libraries. To prevent symbol conflicts, all "xmlsec-mycrypto" library names MUST start with "xmlSecMyCrypto". However, in some applications (for example, the xmlsec command line utility) that can use any crypto library, would prefer to use a generic function names where possible. The "include/xmlsec/crypto.h" and "include/xmlsec/mycrypto/symbols.h" include files do the magic by mapping "xmlSecMyCrypto*" to "xmlSecCrypto*" names using "XMLSEC_CRYPTO_*" defines.

In order to build xmlsec command line utility, the "xmlsec-<crypto>" library must implement several functions. While these functions are not required to be implemented by "xmlsec-<crypto>" library, you should consider doing so (if possible) to simplify testing (thru xmlsec command line utility) and application development.

In adition to xmlSecCryptoApp* functions, the xmlsec-<crypto> library MUST implement following xmlSecCrypto* functions:

## xmlSecCrypto* functions.

xmlSecCryptoInit() | Initializes xmlsec-<crypto> library: registers cryptographic transforms implemented by the library, keys, etc. Please note, that the application might want to intialize the cryprographic library by itself. The default cryprographic library initialization (for example, used by xmlsec utility) is implemented in xmlSecCryptoAppInit() function.
xmlSecCryptoShutdown() | Shuts down xmlsec-<crypto> library. Please note, that the application might want to shutdown the cryprographic library by itself. The default cryprographic library shutdown (for example, used by xmlsec utility) is implemented in xmlSecCryptoAppShutdown() function.
xmlSecCryptoKeysMngrInit() | Adds keys stores implemented by the xmlsec-<crypto> library to the keys manager object.

## Klasses and objects.

The XML Security Library is written in C but it uses some OOP techniques: the objects in the library have "klasses" and there is "klasses" inheritance. (see signature and encryption klasses diagrams). The "klass" is different from C++ "class" (btw, this is one of the reasons why it is spelled differently). The idea of "klasses" used in XML Security Library are close to one in the GLIB/GTK/GNOME and many other C projects. If you ever seen an OOP code written in C you should find everything familiar.

XML Security Library "klass" includes three main parts:

- "Klass" declaration structure that defines "klass" interfaces and global constant data (for example, the human-readable name of the "klass").

  ### Base transform "klass" and its child XPath transform "klass" structure.

      struct _xmlSecTransformKlass {
          /* data */
          size_t				klassSize;
          size_t				objSize;
          const xmlChar*			name;
          const xmlChar*			href;
          xmlSecTransformUsage		usage;

          /* methods */
          xmlSecTransformInitializeMethod	initialize;
          xmlSecTransformFinalizeMethod	finalize;

          xmlSecTransformNodeReadMethod	readNode;
          xmlSecTransformNodeWriteMethod	writeNode;

          ...
      };

      ...

      static xmlSecTransformKlass xmlSecTransformXPathKlass = {
          /* klass/object sizes */
          sizeof(xmlSecTransformKlass),	/* size_t klassSize */
          xmlSecXPathTransformSize,		/* size_t objSize */

          xmlSecNameXPath,			/* const xmlChar* name; */
          xmlSecXPathNs, 			/* const xmlChar* href; */
          xmlSecTransformUsageDSigTransform,	/* xmlSecTransformUsage	usage; */

          xmlSecTransformXPathInitialize,	/* xmlSecTransformInitializeMethod initialize; */
          xmlSecTransformXPathFinalize,	/* xmlSecTransformFinalizeMethod finalize; */
          xmlSecTransformXPathNodeRead,	/* xmlSecTransformNodeReadMethod readNode; */
          NULL,				/* xmlSecTransformNodeWriteMethod writeNode; */

          ...
      };

- "Klass" id which is simply a pointer to the "klass" declaration strucutre. "Klass" id is used to bind "klass" objects to the "klass" declaration and to pass "klass" strucutre to functions.

  ### Base transform "klass" id declaration and its child XPath transform "klass" id implementation.

      typedef const struct _xmlSecTransformKlass		xmlSecTransformKlass, *xmlSecTransformId;

      ...

      #define xmlSecTransformXPathId 		xmlSecTransformXPathGetKlass()

      ...

      xmlSecTransformId
      xmlSecTransformXPathGetKlass(void) {
          return(&xmlSecTransformXPathKlass);
      }

- "Klass" object structure that contains object specific data. The child object specific data are placed after the parent "klass" object data.

  ### Base transform object strucutre and its child XPath transform object.

      struct _xmlSecTransform {
          xmlSecTransformId 			id;
          xmlSecTransformOperation		operation;
          xmlSecTransformStatus		status;
          xmlNodePtr				hereNode;

          /* transforms chain */
          xmlSecTransformPtr			next;
          xmlSecTransformPtr			prev;

          ...
      };

      ...

      /******************************************************************************
       *
       * XPath/XPointer transforms
       *
       * xmlSecPtrList with XPath expressions is located after xmlSecTransform structure
       *
       *****************************************************************************/
      #define xmlSecXPathTransformSize	\
          (sizeof(xmlSecTransform) + sizeof(xmlSecPtrList))
      #define xmlSecXPathTransformGetDataList(transform) \
          ((xmlSecTransformCheckSize((transform), xmlSecXPathTransformSize)) ? \
      	(xmlSecPtrListPtr)(((unsigned char*)(transform)) + sizeof(xmlSecTransform)) : \
      	(xmlSecPtrListPtr)NULL)

## Cryptographic transforms.

The cryptographic transforms (digests, signatures and encryption) implementation is the main goal of "xmlsec-<crypto>" library. Most of the cryptographic transforms use default pushBin and popBin methods and provide custom execute method. The binary transform execute method processes data from the input buffer inBuf and pushes results to outBuf. The transform should try to consume and remove data from inBuf buffer as soon as the data became available. However, it might happen that current data size in the input buffer is not enough (for example, RSA-PKCS1 algorithm requires that all the data are available in one buffer). In this case, transform might keep the data in the input buffer till the next call to execute method. The "last" parameter of the execute indicates that transform MUST process all the data in the input buffer and return as much as possible in the output buffer. The execute method might be called multiple times with non-zero "last" parameter until the transforms returns nothing in the output buffer. In addition, the transform implementation is responsible for managing the transform status variable.

## Typical transform status managing.

xmlSecTransformStatusNone | Transform initializes itself (for example, cipher transform generates or reads IV) and sets status variable to xmlSecTransformStatusWorking.
xmlSecTransformStatusWorking | Transform process the next (if "last" parameter is zero) or last block of data (if "last" parameter is non-zero). When transform returns all the data, it sets the status variable to xmlSecTransformStatusFinished.
xmlSecTransformStatusFinished | Transform returns no data to indicate that it finished processing.

In adition to execute methods, signature, hmac or digest transforms MUST implement verify method. The verify method is called after transform execution is finished. The verify method implementation must set the "status" member to xmlSecTransformStatusOk if signature, hmac or digest is successfully verified or to xmlSecTransformStatusFail otherwise.

The transforms that require a key (signature or encryption transforms, for example) MUST imlpement setKeyReq (prepares the key requirements for key search) and setKey (sets the key in the transform) methods.

## Keys data and keys data stores.

There are two key data types: key value data (for example, AES, DES, DSA, HMAC or RSA key data) and others (for example, key name, X509 or PGP data). The key data implementation should implement at least one of xmlRead or binRead methods.

TODO

## Default keys manager.

Any "xmlsec-<crypto>" library implementation must provide a default keys store. The XML Security Library has a built-in flat list based simple keys store which could be used if cryptographic library does not have one itself.

## Sharing the results.

If you implemented support for new cryptographic library (or extended an existing one) and both you and your company/university/... are willing to share the code I would be glad to add your work to XML Security Library. Many people will thank you for this and will use your library. Of course, you'll get all the credits for your work.

The best way to submit your enchancements is to send a pull request through GitHub. I will try to review and merge your pool request as soon as possible.