home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / crypl200.zip / DOCS.TXT < prev    next >
Text File  |  1996-10-11  |  126KB  |  2,855 lines

  1.                                               #    #     #
  2.                                               #    #  #  #
  3.                                            ####### #     #
  4.                 ####  # ###   #    #  #####   #    #  #  #####
  5.               #       ##   #  #    #  #    #  #    #  #  #    #
  6.               #       #       #    #  #    #  #    #  #  #    #
  7.               #       #       #   ##  #    #  #    #  #  #    #
  8.                 ####  #        ### #  #####   #    #  #  #####
  9.                                    #  #
  10.                               #   ##  #
  11.                                ###    #
  12.  
  13.               P o r t a b l e  E n c r y p t i o n  L i b r a r y
  14.  
  15.                                   Version 2.00
  16.  
  17.        Copyright Peter Gutmann, Eric Young, and Colin Plumb  1992 - 1996
  18.  
  19. The cryptlib encryption library provides an easy-to-use interface which allows
  20. even inexperienced crypto programmers to easily add strong encryption and
  21. authentication services to their software.  The library contains DES, triple
  22. DES, IDEA, MDC/SHS, RC2, RC4, RC5, SAFER, SAFER-SK, Blowfish, and Blowfish-SK
  23. conventional encryption, MD2, MD4, MD5, RIPEMD-160 and SHA hash algorithms, and
  24. Diffie-Hellman, DSA, and RSA public-key encryption, as well as a comprehensive
  25. high-level interface with functions such as cryptCreateSignature() and
  26. cryptExportKey().  The library is supplied as source code for Unix (shared or
  27. static libraries), DOS, Windows (16- and 32-bit DLL's), and the Amiga.
  28.  
  29. cryptlib provides a standardised interface to a number of popular encryption
  30. algorithms, as well as providing a high-level interface which hides most of the
  31. implementation details and provides an operating-system-independant encoding
  32. method which makes it easy to transfer encrypted data from one system to
  33. another.  Although use of the the high-level interface is recommended,
  34. experience programmers can directly access the lower-level encryption routines
  35. for implementing custom encryption protocols or methods not provided by the
  36. library.
  37.  
  38. The cryptlib API serves as an interface to a range of plug-in encryption
  39. modules which allow encryption algorithms to be added in a fairly transparent
  40. manner. The standardised API allows any of the algorithms and modes supported
  41. by the library to be used with a minimum of coding effort.  As such the main
  42. function of the library is to provide a standard, portable, easy-to-use
  43. interface between the underlying encryption routines and the user software.  In
  44. addition the easy-to-use high-level routines allow for the exchange of
  45. encrypted session keys and the creation and checking of digital signatures with
  46. a minimum of programming overhead.
  47.  
  48. cryptlib has been written to be as idiot-proof as possible.  On initialization
  49. it performs extensive self-testing against test data from encryption standards
  50. documents, and the API's check each parameter and function call for errors
  51. before any actions are performed, with error reporting down to the level of
  52. individual parameters.
  53.  
  54. cryptlib implements a security perimeter around the encryption functions, with
  55. encryption contexts consisting of an arbitrary handle referring to (hidden)
  56. data held within the library.  No outside access to state variables or keying
  57. information is possible, provided the underlying OS provides some form of
  58. memory protection.  If the OS supports it, all sensitive information used by
  59. the library will be page-locked to ensure it is never swapped to disk.
  60.  
  61. Author Contact Information:
  62.  
  63.   Peter Gutmann, pgut001@cs.auckland.ac.nz
  64.  
  65.   The cryptlib home page, http://www.cs.auckland.ac.nz/~pgut001/cryptlib.html,
  66.   contains more information on the latest cryptlib developments.
  67.  
  68.  
  69. Usage Conditions
  70. ----------------
  71.  
  72. This software is distributed as copyrighted freeware, with copyrights on
  73. individual encryption modules being held by the contributing authors.  You are
  74. free to use the code in any way you want, with the following restrictions:
  75.  
  76. - If you make any changes to the code, you should send a copy of the changes to
  77.   the author or authors to allow them to integrate the changes into the code.
  78.   This is to allow a central consistent version to be maintained.
  79.  
  80. - If you use the library as part of a product, you should offer a copy to the
  81.   authors of the library.  This is to let the authors know that their work is
  82.   being usefully applied.  You should also give the authors credit in your
  83.   software and/or documentation.  This is to let others know that the authors
  84.   work is being usefully applied :-).
  85.  
  86. - Any commercial software you create with this code may not be merely a set or
  87.   subset of the encryption library, with or without minor added functionality.
  88.   In particular you can't sell the library (or any modified form of it) as
  89.   "your" encryption product.  You can sell your own product which utilizes the
  90.   encryption library, but you can't charge for the library itself or claim it
  91.   as yours.  This is to stop people adding their own wrappers and selling it as
  92.   "their" encryption product.
  93.  
  94. These terms are pretty much identical to the library GPL, which seem to be
  95. about the least restrictive usage terms around apart from outright public
  96. domain software.
  97.  
  98.  
  99. Patent Issues
  100. -------------
  101.  
  102. This library contains a number of algorithms which are covered by patents.
  103. These algorithms are Diffie-Hellman, DSA, IDEA, RC5, and RSA.  A number of
  104. patent holders have very generously granted a license for royalty-free use of
  105. the algorithms in the library under certain circumstances, as explained below.
  106.  
  107. Diffie-Hellman and DSA:
  108.  
  109.   The practice of Diffie-Hellman key exchange is covered by United States
  110.   Patent No 4,200,770 ('Cryptographic Apparatus and Method') which expires in
  111.   September 1997.  The Canadian equivalent expires in September 1998.
  112.  
  113.   The practice of all other public key algorithms is covered by United States
  114.   Patent No 4,218,582 ('Public Key Cryptographic Apparatus and Method') which
  115.   expires in October 1998.  Numerous equivalent patents have been issued in
  116.   Europe and Japan which expire in October 1998.  These patents are licensed
  117.   exclusively by Cylink Corporation of Sunnyvale, California.  Cylink has
  118.   granted a license to all users of this library for non-commercial use,
  119.   including research by non-profit institutions.  This means you may
  120.   incorporate this library in software which is distributed for free, provided
  121.   you include the following notice in the software and all collateral
  122.   documentation which states:
  123.  
  124.   The use of the public key algorithms in this software is covered by US
  125.   Patents No 4,200,770 ('Cryptographic Apparatus and Method') and 4,218,582
  126.   ('Public Key Cryptographic Apparatus and Method') which are licensed
  127.   exclusively by Cylink Corporation.
  128.  
  129.   In order to promote open standards for public key algorithms, Cylink has
  130.   initiated a low cost licensing program for commercial use of public key.  For
  131.   more information, contact Cylink's web page at www.cylink.com or e-mail
  132.   legal@cylink.com.
  133.  
  134. IDEA:
  135.  
  136.   The IDEA algorithm is patented by Ascom Systec Ltd. of CH-5506 Maegenwil,
  137.   Switzerland, who allow it to be used on a royalty-free basis for certain
  138.   non-profit applications.  Commercial users must obtain a license from the
  139.   company in order to use IDEA.  IDEA may be used on a royalty-free basis under
  140.   the following conditions:
  141.  
  142.   Free use for private purposes:
  143.  
  144.   The free use of software containing the algorithm is strictly limited to non
  145.   revenue generating data transfer between private individuals, ie not serving
  146.   commercial purposes.  Requests by freeware developers to obtain a
  147.   royalty-free license to spread an application program containing the
  148.   algorithm for non-commercial purposes must be directed to Ascom.
  149.  
  150.   Special offer for shareware developers:
  151.  
  152.   There is a special waiver for shareware developers.  Such waiver eliminates
  153.   the upfront fees as well as royalties for the first US$10,000 gross sales of
  154.   a product containing the algorithm if and only if:
  155.  
  156.   1. The product is being sold for a minimum of US$10 and a maximum of US$50.
  157.   2. The source code for the shareware is available to the public.
  158.  
  159.   Special conditions for research projects:
  160.  
  161.   The use of the algorithm in research projects is free provided that it serves
  162.   the purpose of such project and within the project duration.  Any use of the
  163.   algorithm after the termination of a project including activities resulting
  164.   from a project and for purposes not directly related to the project requires
  165.   a license.
  166.  
  167.   Ascom Tech requires the following notice to be included for freeware
  168.   products:
  169.  
  170.   This software product contains the IDEA algorithm as described and claimed in
  171.   US patent 5,214,703, EPO patent 0482154 (covering Austria, France, Germany,
  172.   Italy, the Netherlands, Spain, Sweden, Switzerland, and the UK), and Japanese
  173.   patent application 508119/1991, "Device for the conversion of a digital block
  174.   and use of same" (hereinafter referred to as "the algorithm").  Any use of
  175.   the algorithm for commercial purposes is thus subject to a license from Ascom
  176.   Systec Ltd. of CH-5506 Maegenwil (Switzerland), being the patentee and sole
  177.   owner of all rights, including the trademark IDEA.
  178.  
  179.   Commercial purposes shall mean any revenue generating purpose including but
  180.   not limited to:
  181.  
  182.   i) Using the algorithm for company internal purposes (subject to a site
  183.      license).
  184.  
  185.   ii) Incorporating the algorithm into any software and distributing such
  186.       software and/or providing services relating thereto to others (subject to
  187.       a product license).
  188.  
  189.   iii) Using a product containing the algorithm not covered by an IDEA license
  190.        (subject to an end user license).
  191.  
  192.   All such end user license agreements are available exclusively from Ascom
  193.   Systec Ltd and may be requested via the WWW at http://www.ascom.ch/systec or
  194.   by email to idea@ascom.ch.
  195.  
  196.   Use other than for commercial purposes is strictly limited to non-revenue
  197.   generating data transfer between private individuals.  The use by government
  198.   agencies, non-profit organizations, etc is considered as use for commercial
  199.   purposes but may be subject to special conditions.  Any misuse will be
  200.   prosecuted.
  201.  
  202. RC5:
  203.  
  204.   The RC5 algorithm is patented by RSA Data Security Inc. 100 Marine Parkway,
  205.   Redwoord City, California 94065, ph.+1 415 595-8782, fax +1 415 595-1873, and
  206.   cannot be used commercially in the US without a license.
  207.  
  208. RSA:
  209.  
  210.   The RSA algorithm is patented by RSA Data Security Inc. 100 Marine Parkway,
  211.   Redwoord City, California 94065, ph.+1 415 595-8782, fax +1 415 595-1873, and
  212.   cannot be used commercially in the US without a license.  RSA licenses can
  213.   most easily be obtained by waiting until the year 2000 when the patent
  214.   expires.
  215.  
  216.  
  217. Library Basics
  218. --------------
  219.  
  220. Like the standard C file I/O libraries which work with FILE objects, this
  221. library works with an opaque "encryption context" object of type CRYPT_CONTEXT.
  222. To encrypt data, you create an encryption context, load a user key into it,
  223. en/decrypt data, and destroy it when you've finished.  The library also uses an
  224. opaque "key collection" object of type CRYPT_KEYSET, which will be discussed
  225. later on.  The CRYPT_CONTEXT type is the more important of the two, and the one
  226. you'll be using the most.
  227.  
  228. This concept lends itself to implementation either as a C++ class or as C
  229. routines.  Throughout this document all examples are given in C, translation to
  230. C++ is a simple step.
  231.  
  232. The overall library structure is as follows:
  233.  
  234.                            Library core              Plug-in
  235.                                                      modules
  236.                          +---------------+--------------+--------------+
  237.                          |               |   Blowfish   | Blowfish-SK  |
  238.                          |               +--------------+--------------+
  239.                          |               |     DES      |     DESX     |
  240.                          |               +--------------+--------------+
  241.                          |               |2k.Triple DES |3k.Triple DES |
  242.                          |               +--------------+--------------+
  243.                          |               |     IDEA     |   MDC/SHS    |
  244.                          |               +--------------+--------------+
  245.                          |               |     Safer    |   Safer-SK   |
  246.                          |               +--------------+--------------+
  247.                          |               |      RC2     |     RC4      |
  248.                          |               +--------------+--------------+
  249.                          |               |      RC5     |
  250.                          |     Crypt     +--------------+--------------+
  251.               /      \   |               |Diffie-Hellman|      DSA     |
  252.      User   /   ----   \ |    Library    +--------------+--------------+
  253.    Programs \   ----   / |               |      RSA     |
  254.               \      /   |      API      +--------------+--------------+
  255.                          |               |      MD2     |      MD4     |
  256.                          |               +--------------+--------------+
  257.                          |               |      MD5     |      SHA     |
  258.                          |               +--------------+--------------+
  259.                          |               |  RIPEMD-160  |
  260.                          |               +--------------+--------------+
  261.                          |                     export encrypted key    |
  262.                          |                     import encrypted key    |
  263.                          |                -----------------------------+
  264.                          |                   create digital signature  |
  265.                          |                   check digital signature   |
  266.                          |                -----------------------------+
  267.                          |                object-manipulation functions|
  268.                          +---------------------------------------------+
  269.  
  270. Access to the libraries encryption functionality is provided at two levels, via
  271. the low-level API which gives direct access to the encryption functions, and
  272. via the high-level API which provides more abstract functions such as "export
  273. public-key encrypted session key" and "export encrypted data object".  The
  274. recommended interface is the high-level one, since it hides all the details
  275. required to work with the encryption algorithms and takes care of issues like
  276. managing keys and data types.
  277.  
  278. The low-level library API serves as an interface to a range of plug-in
  279. encryption modules which allow encryption algorithms to be added in a fairly
  280. transparent manner.  The standardised API allows any of the algorithms and
  281. modes supported by the library to be used with a minimum of coding effort.  As
  282. such the main function of the library is to provide a standard, portable,
  283. easy-to-use interface between the underlying encryption routines and the user
  284. software.
  285.  
  286. The high-level API provides services such as routines to export and import
  287. encrypted keys, to create and check digital signatures, and to export, query,
  288. and import encrypted and signed data objects.
  289.  
  290. In the following discussion all high-level functions will be marked with a
  291. `(H)' after the title, all low-level functions will be marked with a `(L)'
  292. after the title, and universal functions which are used for both high-level and
  293. low-level work will be marked with a `(U)' after the title.  You can skip the
  294. sections marked `(L)' unless you want to use the low-level routines as building
  295. blocks for your own custom encryption protocol.
  296.  
  297.  
  298. Portability
  299. -----------
  300.  
  301. The library automatically takes care of endianness conversion to the form used
  302. by the local system in a manner invisible to the end user.  In the case of
  303. public-key (PKC) algorithms which work with integers stored as multibyte
  304. strings, the user can specify whether the strings are in big- or little-endian
  305. order.
  306.  
  307.  
  308. Building the Library
  309. --------------------
  310.  
  311. Unix
  312.  
  313. The makefile by default will build the statically-linked library.  To build the
  314. shared library, use 'make shared'.  Once the library has been built, use 'make
  315. testlib' to build the library self-test program and 'make testapp' to build the
  316. test application.  For example to build the shared library and self-test
  317. program, you would use 'make shared;make testlib'.  testlib will run fairly
  318. extensive self-tests of the library, you should run this after you've built the
  319. library to make sure everything is working OK.  testapp will allow PGP-like
  320. encryption and signing of data.  Depending on your system setup and priviledges
  321. you may need to either copy the shared library to /lib or set the
  322. LD_LIBRARY_PATH environment variable to use the shared library.
  323.  
  324. For any common Unix system the library will build without any problems, but in
  325. some cases you may need to edit lib_rand.c and possible cryptapi.c if you're
  326. running an unusual Unix variant which puts include files in strange places or
  327. has broken Posix support.  If you get compiler errors from lib_rand.c, you may
  328. need to change the header files included in the __UNIX__ conditional
  329. compilation section.  If you get error messages from the linker about mlock(),
  330. the problem will be in cryptapi.c.
  331.  
  332. Windows
  333.  
  334. The crypt.mak and crypt32.mak makefiles are for version 1.5x and 4.x of Visual
  335. C and will build the 16- and 32-bit DLL versions of the library.  The IDEA code
  336. will give many warnings, the DES code will give one or two warnings, and the
  337. bnlib code will give one warning (these are all other peoples code), the
  338. remaining code should compile without warnings.  Once the DLL has been built,
  339. test.mak and test32.mak will build the library self-test program, which is a
  340. console application.  You should run this after you've built the library to
  341. make sure everything is working OK.
  342.  
  343. The use of the 16-bit DLL on a Win32 system is not recommended, as the
  344. randomness-polling required by some of the high-level public-key related
  345. routines performs very poorly in the emulated 16-bit environment.
  346.  
  347. DOS
  348.  
  349. No makefile is provided for the DOS version, but the library can be built from
  350. the same files as the 16-bit Windows version.  The library is about 300K in
  351. size (200K of which is code), and any attempt to use the high-level key export
  352. routines will fail with a CRYPT_NORANDOM error code unless a /dev/random-style
  353. driver is available because there isn't any way to reliably obtain random data
  354. under DOS.  Using the library under DOS is possible, but not recommended.
  355.  
  356. Other systems
  357.  
  358. The library should be fairly portable to other systems, the only two parts
  359. which need attention is the memory locking in cryptapi.c (the library will work
  360. without this, but won't be as secure as a version with memory locking because
  361. sensitive data may  be paged out to disk) and the randomness-gathering in
  362. lib_rand.c (the library won't work without this, the code will generate a
  363. compiler error).  The idea behind the randomness-gathering code is to perform a
  364. comprehensive poll of every possible entropy source in the system in a separate
  365. thread or background task ("slowPoll"), as well as providing a less useful but
  366. much faster poll of quick-response sources ("fastPoll").
  367.  
  368. To find out what to compile, look at the Unix makefile which contains all the
  369. necessary source files (the OBJS dependencies) and compiler options (the bnlib
  370. files need to have NDEBUG and HAVE_CONFIG_H=1 defined).  Link all these into a
  371. library (as the makefile does) and then compile and link testlib.c and testhl.c
  372. to create the self-test program.
  373.  
  374. There is additional code included which will lead to noticeable speedups on
  375. some systems.  bnlib includes 68000, 68020, and PPC asm routines (as well as
  376. Unix 80x86, i960 and Alpha code which isn't currently used by the Unix
  377. makefile).  You should modify your build options as appropriate to use these if
  378. possible.
  379.  
  380. Depending on your compiler you may get a few warnings about code in libdes (one
  381. or two), bnlib (one or two), and the IDEA code (many).  This code is by other
  382. people and I haven't bothered changing it to get rid of warnings because
  383. they're mostly related to the use of C as a high-level assembler and changing
  384. things around could be risky.
  385.  
  386.  
  387. Interfacing with the Library (U)
  388. --------------------------------
  389.  
  390. All necessary constants, types, structures, and function prototypes are defined
  391. in the crypt API header file capi.h.  You need to include this file in each
  392. module which uses the encryption library.
  393.  
  394. In addition in some environments you will need to call the cryptInit() and
  395. cryptEnd() functions at the start and finish of your program.  cryptInit()
  396. initializes the library for use, and cryptEnd() performs various cleanup
  397. functions including automatic garbage collection of any encryption information
  398. you may have forgotten to destroy.  Where the encryption library is implemented
  399. as a DLL, there is no need to call cryptInit() or cryptEnd() as these are
  400. called automatically by the operating system when the DLL is loaded and
  401. unloaded.  If you call cryptInit() and the library has already been
  402. initialized, it will return CRYPT_INITED.  If you call cryptEnd() and the
  403. library hasn't been initialized yet, it will return CRYPT_NOTINITED.  These
  404. aren't really serious errors, but can serve as a notification that there's
  405. something wrong in your code.
  406.  
  407. To make the use of cryptEnd() easier, you may want to use the C atexit()
  408. function to have cryptEnd() called automatically when your program exits.
  409.  
  410. Any use of the encryption library when it isn't implemented as a DLL will then
  411. be as follows:
  412.  
  413.   #include "capi.h"
  414.  
  415.   cryptInit();
  416.  
  417.   /* Use encryption library routines */
  418.  
  419.   cryptEnd();
  420.  
  421.  
  422. Creating/Destroying Encryption Contexts (U)
  423. -------------------------------------------
  424.  
  425. Encryption contexts are the basic objects which the library works with.  You
  426. can't do anything without them.  To create an encryption context, you must
  427. specify the encryption algorithm and mode you want to use for that context.
  428. The encryption algorithms and modes are given in the library header file, and
  429. are updated along with the library itself.  For example, to create and destroy
  430. an encryption context for DES in CBC mode, you would use the following code:
  431.  
  432.   CRYPT_CONTEXT cryptContext;
  433.  
  434.   cryptCreateContext( cryptContext, CRYPT_ALGO_DES, CRYPT_MODE_CBC );
  435.  
  436.   /* Perform en/decryption */
  437.  
  438.   cryptDestroyContext( cryptContext );
  439.  
  440. If you don't want to choose an encryption algorithm and mode, you can let the
  441. library do it for you by using CRYPT_USE_DEFAULT in place of the algorithm or
  442. mode.  The default encryption algorithm is two-key triple DES, the default
  443. encryption mode is CFB.
  444.  
  445. In the case of the public-key (PKC) algorithms the encryption mode is either
  446. CRYPT_MODE_PUBKEY or CRYPT_MODE_PRIVKEY, depending on whether you want to
  447. perform private-key or public-key operations within that encryption context.
  448. For example to create and destroy an encryption context for checking an RSA
  449. signature you would use the following code:
  450.  
  451.   CRYPT_CONTEXT cryptContext;
  452.  
  453.   cryptCreateContext( &cryptContext, CRYPT_ALGO_RSA, CRYPT_MODE_PUBKEY );
  454.  
  455.   /* Perform signature check */
  456.  
  457.   cryptDestroyContext( cryptContext );
  458.  
  459. Like standard encryption contexts, PKC contexts will accept CRYPT_USE_DEFAULT
  460. for the algorithm to tell the library to choose the algorithm for you.  The
  461. default PKC algorithm is RSA.
  462.  
  463. In the case of the hash algorithms the encryption mode is usually
  464. CRYPT_MODE_NONE since the algorithms require no key, except for keyed hash
  465. functions (MACs).  For example to create and destroy an encryption context for
  466. creating an MD5 hash of a message you would use the following code:
  467.  
  468.   CRYPT_CONTEXT cryptContext;
  469.  
  470.   cryptCreateContext( &cryptContext, CRYPT_ALGO_MD5, CRYPT_MODE_NONE );
  471.  
  472.   /* Perform hash */
  473.  
  474.   cryptDestroyContext( cryptContext );
  475.  
  476. Like standard encryption contexts, hash contexts will accept CRYPT_USE_DEFAULT
  477. for the algorithm to tell the library to choose the algorithm for you.  The
  478. default hash algorithm is SHA-1.
  479.  
  480. Note that the CRYPT_CONTEXT is passed to cryptCreateContext() by reference, as
  481. cryptCreateContext() modifies it when it creates the encryption context.  In
  482. all other routines in the encryption library, CRYPT_CONTEXT is passed by value.
  483.  
  484. The availability of certain algorithms and encryption modes in the library does
  485. not mean that their use is recommended.  Some are only present because they are
  486. needed for certain protocols or required by some standards.  The
  487. CRYPT_USE_DEFAULT choice for cryptCreateContext() will always choose a secure
  488. algorithm.
  489.  
  490. Some high-level functions will create encryption contexts for you, for example
  491. cryptImportKey() will create an encryption context for the imported key.  These
  492. can be destroyed with cryptDestroyContext() just as if they had been directly
  493. created with cryptCreateContext().
  494.  
  495. The cryptCreateContext() and cryptDestroyContext() functions take care of issues
  496. like initialization, memory management, and erasure of data after use.
  497. Although you should try to call cryptDestroyContext() for every
  498. cryptCreateContext(), this is sometimes not possible, so the library performs
  499. automatic garbage collection of any remaining encryption contexts when
  500. cryptEnd() is called.
  501.  
  502.  
  503. Extended Initialization (U)
  504. ---------------------------
  505.  
  506. The cryptCreateContext() function has a companion function
  507. cryptCreateContextEx() which may be used to perform an extended,
  508. algorithm-specific initialisation. The second parameter passed to the function
  509. is an algorithm-dependant structure used to specify extra information to be
  510. used in the initalisation.  Not all algorithms will support extended
  511. initialisation parameters.
  512.  
  513. The structures have the name CRYPT_INFO_<algorithm_name>, and are laid out as
  514. follows:
  515.  
  516. Structure CRYPT_INFO_DES:
  517.  
  518.   /* Whether to use DES or DESX.  The default is to use DES */
  519.   int isDESX;
  520.  
  521. Structure CRYPT_INFO_3DES:
  522.  
  523.   /* Whether to use two-key or three-key triple DES.  The default is to use
  524.      two-key triple DES as per various ANSI and ISO standards */
  525.   int isThreeKey;
  526.  
  527. Structure CRYPT_INFO_BLOWFISH:
  528.  
  529.   /* Whether to use Blowfish or Blowfish-SK.  The default is to use the
  530.      original algorithm Blowfish.  Blowfish-SK is a version which improves the
  531.      key schedule to simplify the setup process, allow longer keys, and allow
  532.      the number of key setup iterations to be specified */
  533.   int useBlowfishSK;
  534.  
  535.   /* The number of iterations used during the Blowfish-SK key setup process
  536.      triggered by a cryptLoadContext() call.  Using a high value (10 or more)
  537.      will greatly slow down password-guessing attacks by making the key setup
  538.      process painfully slow.  Values in the range of 10-20 are recommended for
  539.      most systems */
  540.   int keySetupIterations;
  541.  
  542. Structure CRYPT_INFO_MDCSHS:
  543.  
  544.   /* The number of iterations used during the key setup process triggered
  545.      by a cryptLoadContext() call.  Using a high value (500 or more) will
  546.      greatly slow down password-guessing attacks by making the key setup
  547.      process painfully slow.  Values in the range of 50-100 are recommended for
  548.      most systems */
  549.   int keySetupIterations;
  550.  
  551. Structure CRYPT_INFO_RC5:
  552.  
  553.   /* The number of rounds of encryption.  The default setting is 12 rounds */
  554.   int rounds;
  555.  
  556. Structure CRYPT_INFO_SAFER:
  557.  
  558.   /* Whether to use SAFER or SAFER-SK.  The default is to use the original
  559.      algorithm SAFER.  SAFER-SK is a version which improves the key schedule to
  560.      eliminate some possible weaknesses when SAFER is used as a keyed hash
  561.      function */
  562.   int useSaferSK;
  563.  
  564.   /* The number of rounds of encryption.  The default settings are 6 rounds for
  565.      SAFER-K64, 8 rounds for SAFER-SK64, and 10 rounds for SAFER-K128 and
  566.      SAFER-SK128 */
  567.   int rounds;
  568.  
  569. Structure CRYPT_INFO_SHA:
  570.  
  571.   /* Whether to use SHA or SHA1.  The default is to use SHA1 */
  572.   int isSHA;
  573.  
  574. You can specify that the default value for the algorithm and mode be loaded
  575. into a field of the CRYPT_INFO_xxx structure by setting it to
  576. CRYPT_USE_DEFAULT.  The library will then set the field to the appropriate
  577. value.  For example to create a SAFER encryption context using the improved
  578. SAFER-SK key schedule and with the standard number of rounds for SAFER-SK, you
  579. would use:
  580.  
  581.   CRYPT_INFO_SAFER cryptInfoEx;
  582.  
  583.   cryptInfoEx.rounds = CRYPT_USE_DEFAULT;
  584.   cryptInfoEx.useSaferSK = 1;
  585.   cryptCreateContextEx( &cryptContext, cryptAlgo, cryptMode, &cryptInfoEx );
  586.  
  587.  
  588. Generating and Deriving Keys into Encryption Contexts (H)
  589. ---------------------------------------------------------
  590.  
  591. Once you've created an encryption context, the next step is to load a key into
  592. it.  These keys will typically be either one-off session keys which are
  593. discarded after use, or long-term storage keys which are used to protect fixed
  594. data such as files or private keys.  You can create a session key with
  595. cryptGenerateContext():
  596.  
  597.   cryptGenerateContext( cryptContext, CRYPT_USE_DEFAULT );
  598.  
  599. which will generate a default-length key for the encryption context.  If you
  600. want to generate a key of a particular length, you can specify it as the second
  601. parameter.  For example to generate a 256-bit (32-byte) key you would use:
  602.  
  603.   cryptGenerateContext( cryptContext, 32 );
  604.  
  605. Keys generated by the library are useful when used with cryptExportKey()/
  606. cryptImportKey() (described later on).  Since cryptExportKey() usually encrypts
  607. the generated key using public-key encryption, you shouldn't make it too long
  608. or it'll be too big to be encrypted.  Unless there's a specific reason for
  609. choosing the key length you should leave the length parameter set to
  610. CRYPT_USE_DEFAULT and let the library choose the correct key length for you.
  611.  
  612. The only time when you may need to explicitly specify a key length is when
  613. you're using very short (in the vicinity of 512 bits) public keys to export
  614. Blowfish, MDC/SHS, or triple DESX keys.  In this case the public key isn't
  615. large enough to export the full-length keys for these algorithms, and
  616. cryptExportKey() will return the error code CRYPT_DATASIZE to indicate that
  617. there's too much data to export.  The solution is to either specify a shorter
  618. key length for cryptGenerateContext(), or, preferably, to use a longer public
  619. key.  This is only a problem with very short public keys, when using the
  620. recommended public key size of 1024 bits this situation will never occur.
  621.  
  622. Before you use cryptGenerateContext() you should read the section "Random
  623. Numbers" below since an understanding of this is essential before you use
  624. cryptGenerateContext().  If you don't manage the use of random data properly,
  625. cryptGenerateContext() will fail with CRYPT_NORANDOM.
  626.  
  627. cryptGenerateContext() only makes sense for conventional-key encryption
  628. contexts and will return the error code CRYPT_NOTAVAIL for a PKC or hash
  629. encryption context to indicate that this operation is not available for PKCs or
  630. hash algorithms.
  631.  
  632. To summarise the steps so far, you can set up an encryption context in its
  633. simplest form so that it's ready to encrypt data with:
  634.  
  635.   CRYPT_CONTEXT cryptContext;
  636.  
  637.   cryptCreateContext( &cryptContext, CRYPT_USE_DEFAULT, CRYPT_USE_DEFAULT );
  638.   cryptGenerateContext( cryptContext, CRYPT_USE_DEFAULT );
  639.  
  640.   /* Encrypt data */
  641.  
  642.   cryptDestroyContext( cryptContext );
  643.  
  644. Note the extensive use of default parameters.  Unless you choose to override
  645. them, you can rely on the library to choose the correct algorithm and options
  646. for you in each case.
  647.  
  648. Sometimes you will need to obtain a fixed-length encryption key from a
  649. variable-length password or passphrase.  You can do this with the
  650. cryptDeriveContext() function:
  651.  
  652.   cryptDeriveContext( cryptContext, passPhrase, passPhraseLength );
  653.  
  654. which takes a passphrase and converts it into an encryption key in a format
  655. suitable for use with the encryption context.  By default this will repeatedly
  656. hash the input passphrase with the SHA1 hash function to generate the key, and
  657. will iterate the hashing process 100 times to make a passphrase-guessing attack
  658. more difficult.  If you want to use a hash function other than SHA1 or use an
  659. iteration count of other than 10 iterations, you can use
  660. cryptDeriveContextEx(), which takes a hash algorithm and iteration count
  661. parameters in addition to the other cryptDeriveContext() parameters:
  662.  
  663.   cryptDeriveContext( cryptContext, passPhrase, passPhraseLength,
  664.                       hashAlgorithm, iterationCount );
  665.  
  666. For example to derive an encryption key from the passphrase "This is a
  667. passphrase", using 100 iterations of RIPEMD-160 instead of the default 10
  668. iterations of SHA1, you would use:
  669.  
  670.   char *passPhrase = "This is a passphrase";
  671.  
  672.   cryptDeriveContextEx( cryptContext, passPhrase, strlen( passPhrase ),
  673.                         CRYPT_ALGO_RIPEMD160, 100 );
  674.  
  675. To summarise the steps so far, you can set up an encryption context in its
  676. simplest form so that it's ready to encrypt data with:
  677.  
  678.   CRYPT_CONTEXT cryptContext;
  679.  
  680.   cryptCreateContext( &cryptContext, CRYPT_USE_DEFAULT, CRYPT_USE_DEFAULT );
  681.   cryptDeriveContext( cryptContext, passPhrase, strlen( passPhrase ) );
  682.  
  683.   /* Encrypt data */
  684.  
  685.   cryptDestroyContext( cryptContext );
  686.  
  687. Note again the use of default parameters.  Unless you choose to override them,
  688. you can rely on the library to choose the correct algorithm and options for you
  689. in each case.
  690.  
  691.  
  692. Loading Keys into Encryption Contexts (L)
  693. -----------------------------------------
  694.  
  695. You can also manually load a key into an encryption context with the
  696. cryptLoadContext() function.  For example to load the key "Secret key" into a
  697. conventional encryption context you would use:
  698.  
  699.   cryptLoadContext( cryptContext, "Secret key", 10 );
  700.  
  701. Unless you need to perform low-level key management yourself, you should use
  702. the high-level routines to load keys into encryption contexts.  The previous
  703. key load should really have been done with cryptDeriveContext() rather than
  704. cryptLoadContext().
  705.  
  706. Some hardware modules which enforce red/black separation will not allow
  707. plaintext keys to pass across the library interface.  In this case the key
  708. parameter passed to cryptLoadContext() will be a key selector or key encryption
  709. key to be passed to the underlying hardware.  For example to pass a key
  710. selector to a key stored inside a DES hardware module you would use:
  711.  
  712.   cryptLoadContext( cryptContext, &keySelector, sizeof( keySelector ) );
  713.  
  714. For PKC encryption a key will typically have a number of components so you
  715. can't load the key directly.  Instead you load the key components into a
  716. CRYPT_PKCINFO structure and then pass this to cryptLoadContext():
  717.  
  718.   cryptLoadContext( cryptContext, &rsaKey, CRYPT_UNUSED );
  719.  
  720. More information on working with CRYPT_PKCINFO data structures is given below.
  721.  
  722. For conventional-key encryption contexts you can also load an IV into the
  723. context, although for encryption you would usually leave this to the library to
  724. perform automatically.  To load an IV you would use:
  725.  
  726.   cryptLoadIV( cryptContext, iv, ivSize );
  727.  
  728. To retrieve an IV which has been generated by the library you would use:
  729.  
  730.   cryptRetrieveIV( cryptContext, iv );
  731.  
  732. cryptLoadIV() and cryptRetrieveIV() will return the error code CRYPT_NOTAVAIL
  733. for a PKC encryption context to indicate that these operations are not
  734. available for PKCs.
  735.  
  736. The hash algorithms usually don't require keys or IV's, and cryptLoadIV() and
  737. cryptRetrieveIV() will return the error code CRYPT_NOTAVAIL for hash encryption
  738. contexts.
  739.  
  740. The cryptLoadContext(), cryptLoadIV(), and cryptRetrieveIV() functions take
  741. care of issues like initialization, memory management, endianness conversion,
  742. and key setup.
  743.  
  744. If you need to reserve space for conventional and PKC keys, IV's, and hash
  745. values, you can use the CRYPT_MAX_KEYSIZE, CRYPT_MAX_PKCSIZE, CRYPT_MAX_IVSIZE,
  746. and CRYPT_MAX_HASHSIZE defines to determine the mount of memory you need.  No
  747. key, IV, or hash value used by the library will ever need more storage than the
  748. settings given in these defines.
  749.  
  750.  
  751. Working with PKC Keys (L)
  752. -------------------------
  753.  
  754. Since PKC keys have multiple components, you can't pass them directly to
  755. cryptLoadContext().  Instead, you load them into a CRYPT_PKCINFO structure and
  756. then pass that to cryptLoadContext().  There are several CRYPT_PKCINFO
  757. structures, one for each type of PKC supported by the library.  These have the
  758. following members:
  759.  
  760. Structure CRYPT_PKCINFO_DH (Diffie-Hellman key exchange):
  761.  
  762.   p         Prime
  763.   g         Base
  764.  
  765. Structure CRYPT_PKCINFO_RSA (Rivest-Shamir-Adelman public-key encryption):
  766.  
  767.   n         Modulus
  768.   e         Public exponent
  769.   d         Private exponent
  770.   p         Prime factor 1
  771.   q         Prime factor 2
  772.   u         Mult.inverse of q, mod p
  773.   e1        Private exponent 1 (PKCS)
  774.   e2        Private exponent 2 (PKCS)
  775.  
  776. Structure CRYPT_PKCINFO_DSA (Digital Signature Algorithm digital signatures):
  777.  
  778.   p         Prime modulus
  779.   q         Prime divisor
  780.   g         Element of order q mod p
  781.   x         Public random integer
  782.   y         Private random integer
  783.  
  784. The components of CRYPT_PKCINFO_DH need not be present for the library routines
  785. to work.  The library has built-in values for 512-bit, 768-bit, 1024-bit,
  786. 1280-bit, 1536-bit, 2048-bit, 3072-bit, and 4096-bit Diffie-Hellman key
  787. exchange, and will use those if the components are not set.  The values used by
  788. the library are taken from the SKIP standard.
  789.  
  790. The e1 and e2 components of CRYPT_PKCINFO_RSA may not be present in some keys.
  791. The library will make use of them if they are present, but can also work
  792. without them.  Private-key operations are marginally faster if these two values
  793. are present.
  794.  
  795. The multibyte integer strings which make up PKC keys can be stored in either
  796. big-endian or little-endian format.  If the integer string is little-endian, it
  797. will be stored in the format:
  798.  
  799.     "xxxxxxxxxxxxxxx00000000000000000000000000000000000000"
  800.  
  801. (where "xxx" are the digits of the number).  If the integer string is
  802. big-endian, it will be stored in the format:
  803.  
  804.     "000000000000000000000000000000000000000000000xxxxxxxxxxxxxxx"
  805.  
  806. For example the number "123456789" would be stored in little-endian format as:
  807.  
  808.     "987654321000000000000000000000000000000000000000000000000000"
  809.  
  810. (with the least-significant digit stored first, going through to the
  811. most-significant digit, and padded with zeroes to fill the number).  In
  812. big-endian format this is:
  813.  
  814.     "000000000000000000000000000000000000000000000000000123456789"
  815.  
  816. In practice the numbers won't be stored with excessively long precision as they
  817. are in the above examples, so instead of being stored with 60 digits of
  818. precision of which 51 bytes contain zero padding, they would be stored with 9
  819. digits of precision:
  820.  
  821.     "987654321"
  822.  
  823. and:
  824.  
  825.     "123456789"
  826.  
  827. A multibyte integer therefore consists of two parameters, the data itself and
  828. the precision to which it is stored.  When you load multibyte integer
  829. components into a CRYPT_PKCINFO structure you need to specify both of these
  830. parameters.
  831.  
  832. Before you can use the CRYPT_PKCINFO structure, you need to initialise it with
  833. cryptInitComponents(), which takes as parameter the endianness of the multibyte
  834. integer strings which make up PKC keys, either CRYPT_COMPONENTS_LITTLENDIAN or
  835. CRYPT_COMPONENTS_BIGENDIAN, and the type of the key, either
  836. CRYPT_KEYTYPE_PRIVATE or CRYPT_KEYTYPE_PUBLIC:
  837.  
  838.   CRYPT_PKCINFO_RSA rsaKey;
  839.  
  840.   cryptInitComponents( rsaKey, CRYPT_COMPONENTS_LITTLENDIAN,
  841.                        CRYPT_KEYTYPE_PRIVATE );
  842.  
  843. Now you can initialise whatever parameters you need with the multibyte integer
  844. strings used in PKC's by using cryptSetComponent(), specifying the integer
  845. length in bits:
  846.  
  847.   cryptSetComponent( rsaKey.n, modulus, 1024 );
  848.   cryptSetComponent( rsaKey.e, pubExponent, 17 );
  849.   cryptSetComponent( rsaKey.d, privExponent, 1024 );
  850.  
  851. You can now pass the result to cryptLoadContext() as explained above.  Once
  852. you've finished working with the CRYPT_PKCINFO information, use
  853. cryptDestroyComponents() to destroy the information:
  854.  
  855.   cryptDestroyComponents( rsaKey );
  856.  
  857. Since the library has built-in default values for 512-bit, 768-bit, 1024-bit,
  858. 1280-bit, 1536-bit, 2048-bit, 3072-bit, and 4096-bit Diffie-Hellman key
  859. exchange, you don't need to specify these unless you've generated your own
  860. values and would prefer to use these instead of the default ones.  To use the
  861. default values, call cryptInitComponents() with the size in bits of the key and
  862. the key type set to CRYPT_UNUSED:
  863.  
  864.   CRYPT_PKCINFO_DH dhKey;
  865.  
  866.   cryptInitComponents( dhKey, 1024, CRYPT_UNUSED );
  867.  
  868. The library will then use its default keys when you call cryptLoadContext().
  869.  
  870.  
  871. Encrypting/Decrypting Data (U)
  872. ------------------------------
  873.  
  874. Now that the encryption context is set up, you're ready to encrypt or decrypt
  875. data.  To encrypt or decrypt a block of data you use:
  876.  
  877.   cryptEncrypt( cryptContext, buffer, length );
  878.  
  879. and:
  880.  
  881.   cryptDecrypt( cryptContext, buffer, length );
  882.  
  883. If a block encryption mode is being used, these functions will recognise a call
  884. with length = 0 as a courtesy call to indicate that this is the last data block
  885. and will take whatever special action is necessary for this case.
  886.  
  887. Hash algorithms don't actually encrypt the data being hashed and can be called
  888. via cryptEncrypt() or cryptDecrypt().  They require a final call with length =
  889. 0 as a courtesy call to indicate to the hash function that this is the last
  890. data block and will take whatever special action is necessary for this case.
  891. The hash value can be retrieved by calling cryptQueryContext() to query the
  892. encryption context information, as explained below.  If you call cryptEncrypt()
  893. or cryptDecrypt() after the final call with length = 0, the function will
  894. return CRYPT_COMPLETE to indicate that the hashing has completed and cannot be
  895. continued.
  896.  
  897. The public-key algorithms encrypt a single block of data equal in length to the
  898. size of the public key being used.  For example if you are using a 1024-bit
  899. public key then the length of the data to be encrypted should be 128 bytes.
  900. Since the length is fixed, the length parameter should be set to
  901. CRYPT_USE_DEFAULT to tell the function to use whatever length is appropriate
  902. for the key.  Preparation of the block of data to be encrypted requires special
  903. care; in general you should use high-level functions such as cryptExportKey()/
  904. cryptImportKey() and cryptCreateSignature()/cryptCheckSignature() rather than
  905. cryptEncrypt() and cryptDecrypt() when working with public-key algorithms.  If
  906. the en/decryption operation fails due to incorrect public or private key
  907. parameters or incorrectly formatted input data, the function will return
  908. CRYPT_PKCCRYPT to indicate that the operation failed.
  909.  
  910. If the encryption context doesn't support the operation you are trying to
  911. perform (for example calling cryptEncrypt() with a DSA public key), the
  912. function will return CRYPT_NOTAVAIL to indicate that this functionality is not
  913. available.
  914.  
  915. If the key loaded into an encryption context doesn't allow the operation you
  916. are trying to perform (for example calling cryptDecrypt() with an encrypt-only
  917. key), the function will return CRYPT_KEYPERM to indicate that the context
  918. doesn't have the required key permissions to perform the requested operation.
  919.  
  920.  
  921. Exchanging Keys (H)
  922. -------------------
  923.  
  924. Although you can now encrypt and decrypt data with your encryption context, the
  925. key you're using is locked inside the context and (if you used
  926. cryptGenerateContext() to create it) won't be known to you or the person you're
  927. trying to communicate with.  To share the key with another party, you need to
  928. export it from the context and the other party needs to import it into an
  929. encryption context of their own.
  930.  
  931. To do this, you use the cryptExportKey() and cryptImportKey() functions in
  932. combination with a public-key encryption context.  Let's say you've created a
  933. key in an encryption context cryptContext and want to send it to someone whose
  934. public key is in the encryption context publicKeyContext (you can also pass in
  935. a private key if you want, cryptExportKey() will only use the public key
  936. components, although unless you're the government it's not clear why you'd want
  937. to be in posession of someone elses private key).  To do this you'd use:
  938.  
  939.   CRYPT_CONTEXT publicKeyContext, cryptContext;
  940.   BYTE *encryptedKey;
  941.   int encryptedKeyLength;
  942.  
  943.   /* Generate a key */
  944.   cryptCreateContext( &cryptContext, CRYPT_USE_DEFAULT, CRYPT_USE_DEFAULT );
  945.   cryptGenerateContext( cryptContext, CRYPT_USE_DEFAULT );
  946.  
  947.   /* Export the key using a public-key encrypted blob */
  948.   cryptExportKey( encryptedKey, &encryptedKeyLength, publicKeyContext,
  949.                   cryptContext );
  950.  
  951. The resulting public-key encrypted blob is placed in the memory buffer pointed
  952. to by encryptedKey, and the length is stored in encryptedKeyLength.  This leads
  953. to a small problem: How do you know how big to make the buffer?  The answer is
  954. to use cryptExportKey() to tell you.  If you pass in a null pointer for
  955. encryptedKey, the function will set encryptedKeyLength to the size of the
  956. resulting blob, but not do anything else.  You can then use code like:
  957.  
  958.   cryptExportKey( NULL, &encryptedKeyLength, publicKeyContext, cryptContext );
  959.   encryptedKey = malloc( encryptedKeyLength );
  960.   cryptExportKey( encryptedKey, &encryptedKeyLength, publicKeyContext,
  961.                   cryptContext );
  962.  
  963. to create the exported key blob.
  964.  
  965. Alternatively, you can just allocate a reasonably sized block of memory and use
  966. that to hold the encrypted key.  "Reasonably sized" means a few Kb, a 4K block
  967. is plenty (an encrypted key blob for a 1024-bit public key is only about 200
  968. bytes long).
  969.  
  970. If the encryption context contains too much data to encode using the given
  971. public key (for example trying to export an encryption context with a 600-bit
  972. key using a 512-bit public key) the function will return CRYPT_DATASIZE.  As a
  973. rule of thumb a 1024-bit public key should be large enough to export the
  974. default key sizes for any encryption context.
  975.  
  976. You don't need to use public-key encryption to export a key blob, it's also
  977. possible to use a conventional key to export another conventional key.  For
  978. example if you were using the key "This is a secret key" in an encryption
  979. context sharedContext which was also known to the other party, you would use:
  980.  
  981.   CRYPT_CONTEXT sharedContext, cryptContext;
  982.   BYTE *encryptedKey;
  983.   int encryptedKeyLength;
  984.  
  985.   /* Load the key into an encryption context */
  986.   cryptCreateContext( &sharedContext, CRYPT_USE_DEFAULT, CRYPT_USE_DEFAULT );
  987.   cryptDeriveContext( sharedContext, "This is a secret key", 20 );
  988.  
  989.   /* Generate a key */
  990.   cryptCreateContext( &cryptContext, CRYPT_USE_DEFAULT, CRYPT_USE_DEFAULT );
  991.   cryptGenerateContext( cryptContext, CRYPT_USE_DEFAULT );
  992.  
  993.   /* Export the key using a conventionally encrypted blob */
  994.   cryptExportKey( encryptedKey, &encryptedKeyLength, sharedContext,
  995.                   cryptContext );
  996.  
  997. This kind of key export isn't as convenient as using public keys since it
  998. requires that both sides know the encryption key in sharedContext.
  999.  
  1000. Now that you've exported the key, the other party needs to import it.  This is
  1001. done using the cryptImportKey() function and the private key corresponding to
  1002. the public key used by the sender:
  1003.  
  1004.   CRYPT_CONTEXT privateKeyContext, cryptContext;
  1005.  
  1006.   /* Import the key from the public-key encrypted blob */
  1007.   cryptImportKey( encryptedKey, privateKeyContext, &cryptContext );
  1008.  
  1009. All the parameters necessary to recreate the encryption context cryptContext
  1010. are transmitted in encrypted form in the exported key blob, and
  1011. cryptImportKey() takes care of initialising the encryption context and setting
  1012. up the key inside it.  A single function call is all it takes to import a key.
  1013.  
  1014. To summarise, sharing an encryption context between two parties using
  1015. public-key encryption involves the following steps:
  1016.  
  1017.   /* Party A creates the required encryption context and generates a key into
  1018.      it */
  1019.   cryptCreateContext( &cryptContext, CRYPT_USE_DEFAULT, CRYPT_USE_DEFAULT );
  1020.   cryptGenerateContext( cryptContext, CRYPT_USE_DEFAULT );
  1021.  
  1022.   /* Party A exports the key using party B's public key */
  1023.   cryptExportKey( encryptedKey, &encryptedKeyLength, publicKeyContext,
  1024.                   cryptContext );
  1025.  
  1026.   /* Party B imports the key using their private key */
  1027.   cryptImportKey( encryptedKey, privateKeyContext, &cryptContext );
  1028.  
  1029. Doing the same with conventional encryption involves changing the last two
  1030. steps to:
  1031.  
  1032.   /* Party A exports the key using the shared conventional key */
  1033.   cryptExportKey( encryptedKey, &encryptedKeyLength, sharedContext,
  1034.                   cryptContext );
  1035.  
  1036.   /* Party B imports the key using the shared conventional key */
  1037.   cryptImportKey( encryptedKey, sharedContext, &cryptContext );
  1038.  
  1039. The library supports a third kind of key export/import which doesn't actually
  1040. export or import a key but merely provides a means of agreeing on a shared
  1041. secret key with another party.  You don't need to use cryptGenerateContext() or
  1042. cryptDeriveKey()/cryptLoadContext() for this one, the act of performing the key
  1043. exchange will create a random, secret shared key.  To use this form of key
  1044. exchange, both parties call cryptExportKey() to generate the blob to send to
  1045. the other party, and then both in turn call cryptImportKey() to import the blob
  1046. sent by the other party.
  1047.  
  1048. Since there's a two-way exchange of messages, either both parties must create
  1049. an identical "template" encryption context so cryptExportKey() knows what kind
  1050. of key to export, or one party has to wait for the initial exported key blob
  1051. from the other party and create an identical template to export.  For now lets
  1052. assume that both sides know they'll be using Blowfish in CFB mode.  The first
  1053. step of the key exchange is thus:
  1054.  
  1055.   /* Create the key template */
  1056.   cryptCreateContext( &cryptContext, CRYPT_ALGO_BLOWFISH, CRYPT_MODE_CFB );
  1057.  
  1058.   /* Export the key using the template */
  1059.   cryptExportKey( encryptedKey, &encryptedKeyLength, dhContext, cryptContext );
  1060.   cryptDestroyContext( cryptContext );
  1061.  
  1062. Note that there's no need to load a key into the template, since this is
  1063. generated automatically as part of the export/import process.  In addition the
  1064. template is destroyed once the key has been exported, since there's no further
  1065. use for it - it acts merely as a template to tell cryptExportKey() what to do.
  1066.  
  1067. Both parties now exchange encryptedKey blobs, and then use:
  1068.  
  1069.   cryptImportKey( encryptedKey, dhContext, &cryptContext );
  1070.  
  1071. to create the cryptContext containing the shared key.
  1072.  
  1073. If one side wants to control the encryption type, this exchange becomes
  1074. somewhat more complicated since a simultaneous exchange of encryptedKey blobs
  1075. is no longer possible.  Lets assume that party A gets to set the encryption
  1076. type being used:
  1077.  
  1078.   /* Party A creates the key template and exports it to party B */
  1079.   cryptCreateContext( &cryptContext, CRYPT_ALGO_BLOWFISH, CRYPT_MODE_CFB );
  1080.   cryptExportKey( encryptedKey, &encryptedKeyLength, dhContext, cryptContext );
  1081.   cryptDestroyContext( cryptContext );
  1082.  
  1083.   /* Party B imports the encrypted key blob and uses the resulting cryptContext
  1084.      as a template to create their own encrypted key blob for party A */
  1085.   cryptImportKey( encryptedKey, dhContext, &cryptContext );
  1086.   cryptExportKey( encryptedKey, &encryptedKeyLength, dhContext, cryptContext );
  1087.  
  1088.   /* Party A imports the encrypted key blob created by party B */
  1089.   cryptImportKey( encryptedKey, dhContext, &cryptContext );
  1090.  
  1091. If the en/decryption part of the export/import operation fails due to incorrect
  1092. public or private key parameters, the function will return CRYPT_PKCCRYPT to
  1093. indicate that the operation failed.  If the input data or decrypted data is
  1094. corrupt and the key couldn't be recovered, the function will return
  1095. CRYPT_BADDATA.  In general CRYPT_PKCCRYPT will be returned for incorrect public
  1096. or private key parameters and CRYPT_BADDATA will be returned if the input data
  1097. has been corrupted.  You can treat both of these as "key export/import failed"
  1098. unless you want to include special-case error handling for them.
  1099.  
  1100. Before you use cryptExportKey() you should read the section "Random Numbers"
  1101. below since an understanding of this is essential before you use
  1102. cryptExportKey().  If you don't manage the use of random data properly,
  1103. cryptExportKey() will fail with CRYPT_NORANDOM.
  1104.  
  1105.  
  1106. Signing Data (H)
  1107. ----------------
  1108.  
  1109. PKC's can also be used to generate digital signatures.  A digital signature is
  1110. created by signing the contents of a hash context with a private key to create
  1111. a signature blob and verified by checking the signature blob with the
  1112. corresponding public key.
  1113.  
  1114. To do this, you use the cryptCreateSignature() and cryptCheckSignature()
  1115. functions in combination with a public-key encryption context.  Let's say
  1116. you've hashed some data with a hash context hashContext and want to sign it
  1117. with your private key in the encryption context privateKeyContext.  To do this
  1118. you'd use:
  1119.  
  1120.   CRYPT_CONTEXT privateKeyContext, hashContext;
  1121.   BYTE *signature;
  1122.   int signatureLength;
  1123.  
  1124.   /* Generate a hash context */
  1125.   cryptCreateContext( &hashContext, CRYPT_USE_DEFAULT, CRYPT_USE_DEFAULT );
  1126.  
  1127.   /* Hash the data */
  1128.   cryptEncrypt( hashContext, data, dataLength );
  1129.   cryptEncrypt( hashContext, data, 0 );
  1130.  
  1131.   /* Sign the hash to create a signature blob */
  1132.   cryptCreateSignature( signature, signatureLength, privateKeyContext,
  1133.                         hashContext );
  1134.  
  1135. The resulting signature blob is placed in the memory buffer pointed to by
  1136. signature, and the length is stored in signatureLength.  This leads to the same
  1137. problem with allocating the buffer which was described above with
  1138. cryptExportKey(), and the solution is again the same: You use
  1139. cryptCreateSignature() to tell you how big to make the buffer.  If you pass in
  1140. a null pointer for signature, the function will set signatureLength to the size
  1141. of the resulting blob, but not do anything else.  You can then use code like:
  1142.  
  1143.   cryptCreateSignature( NULL, &signatureLength, privateKeyContext,
  1144.                         hashContext );
  1145.   signature = malloc( signatureLength );
  1146.   cryptCreateSignature( signature, &signatureLength, privateKeyContext,
  1147.                         hashContext );
  1148.  
  1149. to create the signature blob.
  1150.  
  1151. Alternatively, you can just allocate a reasonably sized block of memory and use
  1152. that to hold the signature.  "Reasonably sized" means a few Kb, a 4K block is
  1153. plenty (a signature blob for a 1024-bit public key is only about 200 bytes
  1154. long).
  1155.  
  1156. If the hash context contains too much data to encode using the given private
  1157. key (for example trying to sign a hash context with a 768-bit hash using a
  1158. 512-bit private key) the function will return CRYPT_DATASIZE.  As a rule of
  1159. thumb a 1024-bit private key should be enough to sign any hash context.
  1160.  
  1161. Now that you've created the signature, the other side needs to check it.  This
  1162. is done using the cryptCheckSignature() function and the public key
  1163. corresponding to the private key used to create the signature (you can also
  1164. pass in a private key if you want, cryptCheckSignature() will only use the
  1165. public key components, although it's not clear why you'd be in posession of
  1166. someone elses private key).  To do this you'd use:
  1167.  
  1168.   CRYPT_CONTEXT privateKeyContext, hashContext;
  1169.   BYTE *signature;
  1170.   int signatureLength;
  1171.  
  1172.   /* Generate a hash context */
  1173.   cryptCreateContext( &hashContext, CRYPT_USE_DEFAULT, CRYPT_USE_DEFAULT );
  1174.  
  1175.   /* Hash the data */
  1176.   cryptEncrypt( hashContext, data, dataLength );
  1177.   cryptEncrypt( hashContext, data, 0 );
  1178.  
  1179.   /* Check the signature using the signature blob */
  1180.   cryptCheckSignature( signature, publicKeyContext, hashContext );
  1181.  
  1182. If the en/decryption part of the signature create/check operation fails due to
  1183. incorrect public or private key parameters, the function will return
  1184. CRYPT_PKCCRYPT to indicate that the operation failed.  If the signature is
  1185. corrupt and couldn't be recovered, the function will return CRYPT_BADDATA.  In
  1186. general CRYPT_PKCCRYPT will be returned for incorrect public or private key
  1187. parameters and CRYPT_BADDATA will be returned if the signature has been
  1188. corrupted.  Finally, if the signature doesn't match the hash context, the
  1189. function will return CRYPT_BADSIG.  You can treat all three of these as
  1190. "signature generation/check failed" unless you want to include special-case
  1191. error handling for them.
  1192.  
  1193.  
  1194. Encrypted Object Management (H)
  1195. -------------------------------
  1196.  
  1197. If you look at the previous sections on key exchange and signature generation
  1198. you'll notice that there are a lot of assumptions made about various
  1199. parameters.  How do you know which private/public keys to use to decrypt an
  1200. encrypted key blob or check a signature?  How do you know which hash algorithm
  1201. to use to hash the data for a signature check?
  1202.  
  1203. This is where the libraries object management routines come in.  These are used
  1204. to hide the messy details of working with encrypted and signed data.  Each
  1205. object type wraps up a particular type of data such as signed or encrypted data
  1206. into a format which the library can work with.
  1207.  
  1208. The simplest form of object is the RawData object of type
  1209. CRYPT_OBJECT_RAW_DATA, which encapsulates a block of raw data such as an email
  1210. message or a file:
  1211.  
  1212.   +--------+
  1213.   |  Data  |
  1214.   +--------+
  1215.  
  1216. Once you've created the data object, you can perform other operations on it
  1217. such as encrypting or signing it.  To encrypt the data, you encapsulate it
  1218. within an EncryptedData object of type CRYPT_OBJECT_ENCRYPTED_DATA:
  1219.  
  1220.                   +--------------+
  1221.   +---------------+  +--------+  |
  1222.   | EncryptedData |  |  Data  |  |
  1223.   +---------------+  +--------+  |
  1224.                   +--------------+
  1225.  
  1226. To sign the data, you encapsulate it within a SignedData object of type
  1227. CRYPT_OBJECT_SIGNED_DATA:
  1228.  
  1229.                +--------------+
  1230.   +------------+  +--------+  |  +-----------+
  1231.   | SignedData |  |  Data  |  |  | Signature |
  1232.   +------------+  +--------+  |  +-----------+
  1233.                +--------------+
  1234.  
  1235. In this case the SignedData object is followed by a Signature object of type
  1236. CRYPT_OBJECT_SIGNATURE which contains the signature, although this could be
  1237. stored seperately.
  1238.  
  1239. These objects can be nested as required.  For example to sign and encrypt a
  1240. block of data, you would combine the previous two types of encapsulation to
  1241. obtain:
  1242.                                                                            //
  1243.                                        +----------------------------------//
  1244.                                        |               +--------------+  //
  1245.   +-----------------+  +---------------+  +------------+  +--------+  | //
  1246.   | PKCEncryptedKey |  | EncryptedData |  | SignedData |  |  Data  |  |//
  1247.   +-----------------+  +---------------+  +------------+  +--------+  //
  1248.                                        |               +-------------//
  1249.                                        +----------------------------//
  1250.                                                                    //
  1251.                                         //
  1252.                                       //-----------+
  1253.                                      //            |
  1254.                                     //-----------+ |
  1255.                                    //| Signature | |
  1256.                                   // +-----------+ |
  1257.                                  //                |
  1258.                                 //-----------------+
  1259.                                //
  1260.  
  1261. Here another type of object, a PKCEncryptedKey object of type
  1262. CRYPT_OBJECT_PKCENCRYPTED_KEY, is prepended to the outermost EncryptedData
  1263. object to allow the recipient to decrypt it.  This object could also be an
  1264. EncryptedKey object of type CRYPT_OBJECT_ENCRYPTED_KEY.  This data block is
  1265. typical of the kind of structure which a program like PGP would create and
  1266. contains an encrypted session key followed by an encrypted data block
  1267. containing a digitally signed message.
  1268.  
  1269. There are three functions which are used to work with these objects,
  1270. cryptExportObject() to create and export them, cryptImportObject() to import
  1271. them, and cryptQueryObject() to return information on them.  The simplest is
  1272. cryptQueryObject(), with returns information on an object in a
  1273. CRYPT_OBJECT_INFO structure:
  1274.  
  1275.   CRYPT_OBJECT_INFO cryptObjectInfo;
  1276.  
  1277.   cryptQueryObject( object, &cryptObjectInfo );
  1278.  
  1279. The CRYPT_OBJECT_INFO structure contains the following fields:
  1280.  
  1281.   /* The object type, object size, header size, and payload size */
  1282.   CRYPT_OBJECT_TYPE type;
  1283.   long size;
  1284.   int headerSize;
  1285.   long payloadSize;
  1286.  
  1287.   /* The encryption algorithm and mode for EncryptedKey, PKCEncryptedKey,
  1288.      Signature, and SignedData objects */
  1289.   CRYPT_ALGO cryptAlgo;
  1290.   CRYPT_MODE cryptMode;
  1291.  
  1292.   /* The key ID for PKCEncryptedKey and Signature objects, consisting of the
  1293.      key ID hash algorithm and the key ID and key ID length */
  1294.   CRYPT_ALGO keyIDalgo;
  1295.   unsigned char keyID[ CRYPT_MAX_HASHSIZE ];
  1296.   int keyIDsize;
  1297.  
  1298.   /* The key derivation algorithm and iteration count for EncryptedKey
  1299.      objects */
  1300.   CRYPT_ALGO keySetupAlgo;
  1301.   int keySetupIterations;
  1302.  
  1303.   /* The control vector and algorithm-specific information for
  1304.      EncryptedKey objects.  The algorithm-specific information can be
  1305.      passed directly to cryptCreateContextEx() for any algorithm (even
  1306.      those which would normally use cryptCreateContext()) */
  1307.   long controlVector;
  1308.   void *cryptContextExInfo;
  1309.  
  1310.   /* The cookie and cookie size for EncryptedKey, PKCEncryptedKey,
  1311.      EncryptedData, and SignedData objects */
  1312.   unsigned char cookie[ CRYPT_MAX_HASHSIZE ];
  1313.   int cookieSize;
  1314.  
  1315.   /* The IV and IV size for EncryptedData objects */
  1316.   unsigned char iv[ CRYPT_MAX_IVSIZE ];
  1317.   int ivSize;
  1318.  
  1319. You'll never need to use most of these fields (or even know they exist) unless
  1320. you're writing your own object managment routines.  The only really useful
  1321. fields you need to know about for now are the four at the start, which contain
  1322. the object type (such as CRYPT_OBJECT_SIGNED_DATA for a SignedData object), the
  1323. total object size, the size of the objects header, and the payload size.  The
  1324. object header contains information on the object such as type, length, and
  1325. various attributes.  The payload size is the size of the actual data in the
  1326. object:
  1327.  
  1328.    <------------- size ------------->
  1329.   +- Object -------+-----------------+
  1330.   |                |                 |
  1331.   |     Header     |     Payload     |
  1332.   |                |                 |
  1333.   +----------------+-----------------+
  1334.    <- headerSize -> <- payloadSize ->
  1335.  
  1336. The payload is either another object or raw data.
  1337.  
  1338. Now that we have a way of obtaining information on objects, we can construct a
  1339. general-purpose handler for processing them:
  1340.  
  1341.   CRYPT_OBJECT_INFO cryptObjectInfo;
  1342.  
  1343.   cryptQueryObject( object, &cryptObjectInfo );
  1344.   switch( cryptObjectInfo.type )
  1345.     {
  1346.     case CRYPT_OBJECT_PKCENCRYPTED_KEY:
  1347.       cryptImportKey( object, ... );
  1348.       break;
  1349.  
  1350.     case CRYPT_OBJECT_ENCRYPTED_KEY:
  1351.       cryptImportKey( object, ... );
  1352.       break;
  1353.  
  1354.     case CRYPT_OBJECT_SIGNATURE:
  1355.       cryptCheckSignature( object, ... );
  1356.       break;
  1357.  
  1358.    ...
  1359.    }
  1360.  
  1361. In order to process the various types of data objects, we use the
  1362. cryptImportObject() function.  The simplest type of object is the RawData
  1363. object:
  1364.  
  1365.   int payloadStart;
  1366.   long payloadLength;
  1367.  
  1368.   cryptImportObject( object, &payloadStart, &payloadLength );
  1369.  
  1370. The data contained in the object begins at [ object + payloadStart ] and
  1371. continues for payloadLength bytes.
  1372.  
  1373. Other object types are more complex and involve the use of encryption contexts.
  1374. These require the use of the extended cryptImportObjectEx() function to import
  1375. them.  For example if cryptQueryObject() reports a SignedData object then we
  1376. need to pass it a pointer to an encryption context:
  1377.  
  1378.   CRYPT_CONTEXT hashContext;
  1379.   int payloadStart;
  1380.   long payloadLength;
  1381.  
  1382.   cryptImportObjectEx( object, &payloadStart, &payloadLength, &hashContext );
  1383.  
  1384. This is how we can tell in advance which hash algorithm we need to use when
  1385. checking a digital signature - the object tells us what to use, and
  1386. cryptImportObjectEx() creates and initialises the hash context for us.
  1387. Checking a SignedData object therefore involves passing the signed data object
  1388. and an empty hash context to cryptImportObjectEx(), which sets up the hash
  1389. context ready for use with the signed data.
  1390.  
  1391. The same thing goes for encrypted data objects:
  1392.  
  1393.   CRYPT_CONTEXT cryptContext;
  1394.   int payloadStart;
  1395.   long payloadLength;
  1396.  
  1397.   cryptImportKey( encryptedKey, privateKeyContext, &cryptContext );
  1398.     [...]
  1399.   cryptImportObjectEx( object, &payloadStart, &payloadLength, &cryptContext );
  1400.  
  1401. The object tells us what encryption parameters to use, and cryptImportObject()
  1402. sets the encryption context up appropriately.  Note that we have to import a
  1403. key into the encryption context before we can pass it to cryptImportObject().
  1404. Typically an EncryptedData object is preceded by an EncryptedKey or
  1405. PKCEncryptedKey object to allow it to be decrypted.
  1406.  
  1407. We can now extend the encrypted object handler to the following:
  1408.  
  1409.   CRYPT_OBJECT_INFO cryptObjectInfo;
  1410.  
  1411.   cryptQueryObject( object, &cryptObjectInfo );
  1412.   switch( cryptObjectInfo.type )
  1413.     {
  1414.     case CRYPT_OBJECT_PKCENCRYPTED_KEY:
  1415.       cryptImportKey( object, ... );
  1416.       break;
  1417.  
  1418.     case CRYPT_OBJECT_ENCRYPTED_KEY:
  1419.       cryptImportKey( object, ... );
  1420.       break;
  1421.  
  1422.     case CRYPT_OBJECT_SIGNATURE:
  1423.       cryptCheckSignature( object, ... );
  1424.       break;
  1425.  
  1426.    case CRYPT_OBJECT_ENCRYPTED_DATA:
  1427.      cryptImportObjectEx( object, ... );
  1428.      break;
  1429.  
  1430.    case CRYPT_OBJECT_SIGNED_DATA:
  1431.      cryptImportObjectEx( object, ... );
  1432.      break;
  1433.  
  1434.    case CRYPT_OBJECT_RAW_DATA:
  1435.      break;
  1436.    }
  1437.  
  1438. This code provides a skeleton outline for a function which will unwrap
  1439. arbitrarily nested objects, decrypting and checking signatures as it goes until
  1440. it finds the raw data which makes up the message, at which point it will stop.
  1441. This shows how complex encryption systems can be built up using the object
  1442. management functions.  Of course if you're using a relatively fixed message
  1443. format with (say) an encrypted key followed by encrypted, signed data, you
  1444. don't need to write such general-purpose code.  A simple fixed handler for the
  1445. nested objects example in the previous diagram can be written as:
  1446.  
  1447.   CRYPT_CONTEXT decryptContext, sessionKeyContext, hashContext;
  1448.   unsigned char *encryptedData, signedData, payload, signature;
  1449.   int payloadStart;
  1450.   long payloadSize;
  1451.  
  1452.   /* Recreate the session key by importing the encrypted key */
  1453.   cryptImportKey( exportedKey, decryptContext, &sessionKeyContext );
  1454.  
  1455.   /* Set up the session key to decrypt the encrypted data */
  1456.   encryptedData = exportedKey + payloadStart + payloadSize;
  1457.   cryptImportObjectEx( encryptedData, &payloadStart, &payloadSize,
  1458.  
  1459.   /* Decrypt the encrypted data */
  1460.   signedData = encryptedData + payloadStart;
  1461.   cryptDecrypt( sessionKeyContext, signedData, payloadSize );
  1462.   cryptDestroyContext( sessionKeyContext );
  1463.  
  1464.   /* Import the signed data object */
  1465.   cryptImportObjectEx( signedData, &payloadStart, &payloadSize,
  1466.                        &hashContext );
  1467.  
  1468.   /* Hash the signed data */
  1469.   payload = signedData + payloadStart;
  1470.   cryptEncrypt( hashContext, payload, payloadSize );
  1471.   cryptEncrypt( hashContext, payload, 0 );
  1472.  
  1473.   /* Check the signature */
  1474.   signature = signedData + payloadStart + payloadSize;
  1475.   cryptCheckSignature( signature, signContext, hashContext );
  1476.   cryptDestroyContext( hashContext );
  1477.  
  1478.   /* Import the raw data object */
  1479.   cryptImportObject( payload, &payloadStart, &payloadSize );
  1480.  
  1481. Note the use of the payloadStart and payloadSize values to unwrap each layer of
  1482. nested objects until the raw data is revealed.
  1483.  
  1484. The routines used to create objects are slightly more complex than the ones
  1485. used to import them.  They work more or less like cryptExportKey() and
  1486. cryptCreateSignature(), but they export various types of data objects rather
  1487. than keys or signatures.  Unlike the other two functions, they don't export the
  1488. data itself, only the header or wrapper for the blob.  Since the data can be of
  1489. arbitrary length and may not all be available when you export the blob, this
  1490. allows you to create the header seperately and then attach the data to it as
  1491. required.
  1492.  
  1493. Let's say you want to create the simplest type of object, a RawData object
  1494. containing 4 bytes of information.  To do this you'd use:
  1495.  
  1496.   BYTE *rawDataObject;
  1497.  
  1498.   cryptCreateObject( rawDataObject, &rawDataObjectLength,
  1499.                      CRYPT_OBJECT_RAW_DATA, 4 );
  1500.  
  1501. The resulting data blob (or at least the header for the blob) is placed in the
  1502. memory buffer pointed to by rawDataObject, and the length of the blob header is
  1503. stored in rawDataObjectLength.  This leads to the same problem with allocating
  1504. the buffer which was described above with cryptExportKey() and
  1505. cryptCreateSignature(), and the solution is again the same: You use
  1506. cryptExportObject() to tell you how big to make the buffer. If you pass in a
  1507. null pointer for rawDataObject, the function will set rawDataObjectLength to
  1508. the size of the resulting blob, but not do anything else.  You can then use
  1509. code like:
  1510.  
  1511.   cryptExportObject( NULL, &rawDataObjectLength, CRYPT_OBJECT_RAW_DATA,
  1512.                      4 );
  1513.   rawDataObject = malloc( rawDataObjectLength );
  1514.   cryptExportObject( rawDataObject, &rawDataObjectLength,
  1515.                      CRYPT_OBJECT_RAW_DATA, 4 );
  1516.  
  1517. to create the data object blob.
  1518.  
  1519. Alternatively, you can just allocate a reasonably sized block of memory and use
  1520. that to hold the object blob.  "Reasonably sized" means a few hundred bytes, a
  1521. 1K block is plenty.
  1522.  
  1523. Some types of data objects are more complex, and require an extended form of
  1524. the cryptExportObject() function.  This is cryptExportObjectEx(), which takes
  1525. an extra parameter in the form of an encryption context.  For an EncryptedData
  1526. object the context contains the encryption context being used to encrypt the
  1527. data.  For a SignedData object the context contains the hash context being used
  1528. to hash the data.  For example to create a SignedData object you would use:
  1529.  
  1530.   CRYPT_CONTEXT hashContext;
  1531.   BYTE *signedDataObject;
  1532.   int signedDataObjectLength;
  1533.  
  1534.   /* Generate a hash context */
  1535.   cryptCreateContext( &hashContext, CRYPT_USE_DEFAULT, CRYPT_USE_DEFAULT );
  1536.  
  1537.   /* Create the SignedData object */
  1538.   cryptExportContextEx( signedDataObject, &signedDataObjectLength,
  1539.                         CRYPT_OBJECT_SIGNED_DATA, hashContext );
  1540.  
  1541. You can now hash the data using the hash context and then sign it with
  1542. cryptCreateSignature().  You don't have to create the SignedData object before
  1543. you hash the data or create the signature, you can create it at any point
  1544. during the hashing or signing operation.  The same goes for the creation of
  1545. EncryptedData objects.  In both cases the encryption contexts are used merely
  1546. as templates to tell the library how to process the object.
  1547.  
  1548. With this information you can now create the code to produce the fixed-format
  1549. messages shown the previous diagram:
  1550.  
  1551.   CRYPT_CONTEXT sessionKeyContext, hashContext;
  1552.   BYTE *exportedKeyObject, *encryptedDataObject, *signedDataObject;
  1553.   BYTE *rawDataObject, *signature;
  1554.   int encryptedDataObjectSize, signedDataObjectSize, rawDataObjectSize;
  1555.   int signatureSize;
  1556.  
  1557.   /* Create an encryption context for the session key and a hash context
  1558.      for the signature */
  1559.   cryptCreateContext( &sessionKeyContext, cryptAlgo, CRYPT_MODE_CFB );
  1560.   cryptGenerateContext( sessionKeyContext );
  1561.   cryptCreateContext( &hashContext, CRYPT_ALGO_SHA, CRYPT_MODE_NONE );
  1562.  
  1563.   /* Export the session key */
  1564.   cryptExportKey( exportedKeyObject, &exportedKeySize, cryptContext,
  1565.                   sessionKeyContext );
  1566.  
  1567.   /* Assemble the EncryptedData, SignedData, and RawData objects */
  1568.   cryptExportObjectEx( encryptedDataObject, &encryptedDataObjectSize,
  1569.                        CRYPT_OBJECT_ENCRYPTED_DATA, signedDataObjectSize +
  1570.                        rawDataObjectSize + dataLength + signatureSize,
  1571.                        sessionKeyContext );
  1572.   cryptExportObjectEx( signedDataObject, &signedDataObjectSize,
  1573.                        CRYPT_OBJECT_SIGNED_DATA, rawDataObjectSize +
  1574.                        dataLength, hashContext );
  1575.   cryptExportObject( rawDataObject, &rawDataObjectSize, CRYPT_OBJECT_RAW_DATA,
  1576.                      dataLength );
  1577.   memcpy( rawDataObject + rawDataObjectSize, data, dataLength );
  1578.  
  1579.   /* Hash the RawData object, sign the hash, and store the result in the
  1580.      SignedData object */
  1581.   cryptEncrypt( hashContext, rawDataObject, dataLength + rawDataObjectSize );
  1582.   cryptEncrypt( hashContext, rawDataObject, 0 );
  1583.   cryptCreateSignature( signature, &signatureSize, signContext, hashContext );
  1584.   cryptDestroyContext( hashContext );
  1585.  
  1586.   /* Encrypt the SignedData and Signature objects */
  1587.   cryptEncrypt( sessionKeyContext, signedDataObject, signedDataObjectSize +
  1588.                 rawDataObjectSize + dataLength + signatureSize );
  1589.   cryptDestroyContext( sessionKeyContext );
  1590.  
  1591. The buffer management hasn't been shown in the code to simplify it, but
  1592. consists of using cryptExportObject() and cryptExportObjectEx() with a NULL
  1593. buffer to query the size of each object, followed by a call to allocate a
  1594. buffer big enough to hold the objects.  The order of the objects in the buffer
  1595. is:
  1596.  
  1597.   [ ExportedKey ][ EncryptedData[ SignedData[ RawData[ data ] ][ Signature ] ] ]
  1598.  
  1599. with exportedKeyObject pointing to the start of the buffer, encryptedDataObject
  1600. pointing to the start of the EncryptedData object in the buffer, and so on.
  1601. Once everything is complete, the entire buffer can be written to disk or sent
  1602. to a remote machine as required.
  1603.  
  1604. A complete example of the above two code fragments is given in the file test.c.
  1605. A longer example which will process arbitrary-length pieces of data and allows
  1606. data to be signed, public-key encrypted, conventional-key encrypted, or signed
  1607. and public/conventional-key encrypted, is given in the file testapp.c.  Most of
  1608. the code in both examples actually consists of buffer management rather than
  1609. encryption.
  1610.  
  1611.  
  1612. Random Numbers (U)
  1613. ------------------
  1614.  
  1615. The cryptlib cryptGenerateContext() and cryptExportKey() functions require
  1616. access to a source of cryptographically strong random numbers.  These numbers
  1617. are obtained by taking system information and stirring it into an internal data
  1618. pool using the Secure Hash Algorithm.  The random-data-gathering operation is
  1619. controlled with the cryptAddRandom() function, which can be used to either
  1620. inject your own random information into the internal pool or to tell the
  1621. library to poll the system for random information.  To add your own random data
  1622. (such as keystroke timings when the user enters a password) to the pool, use:
  1623.  
  1624.   cryptAddRandom( buffer, bufferLength );
  1625.  
  1626. The library can also perform its own polling for random information.  There are
  1627. two polling methods, a fast poll which returns immediately and retrieves a
  1628. moderate amount of random information, and a slow poll which may take some time
  1629. but which retrieves much larger amounts of random information.  A fast poll is
  1630. performed with:
  1631.  
  1632.   cryptAddRandom( NULL, CRYPT_RANDOM_FASTPOLL );
  1633.  
  1634. In general you should sprinkle these throughout your code to build up the
  1635. amount of randomness in the pool.
  1636.  
  1637. A slow poll is performed with:
  1638.  
  1639.   cryptAddRandom( NULL, CRYPT_RANDOM_SLOWPOLL );
  1640.  
  1641. The effect of this call varies depending on the operating system.  Under DOS
  1642. the call returns immediately (see below).  Under Windows 3.x the call will get
  1643. all the information it can in about 1 second, then return (there is usually
  1644. more information present in the system than can be obtained in 1 second). Under
  1645. Unix, Windows 95, and Windows NT the call will spawn one or more separate
  1646. processes or threads to perform the polling and will return immediately.
  1647.  
  1648. Before the first call to cryptGenerateContext() or cryptExportKey() you must
  1649. perform at least one slow poll (or, in some cases, several fast polls - see
  1650. below) in order to accumulate enough random information in the pool to safely
  1651. generate a key into an encryption context or export a key.  Since many systems
  1652. will perform a nonblocking poll, you can usually do this by calling the slow
  1653. poll routine on program startup so that the random information will have
  1654. accumulated by the time you call cryptGenerateContext() or cryptExportKey():
  1655.  
  1656.     [ program startup ]
  1657.  
  1658.     cryptAddRandom( NULL, CRYPT_RANDOM_SLOWPOLL );
  1659.  
  1660.     [ other code, slow poll runs in the background ]
  1661.  
  1662.     cryptGenerateContext( cryptContext, ... );
  1663.  
  1664. If you forget to perform a slow poll beforehand, the cryptGenerateContext() or
  1665. cryptExportKey() call will block until the slow poll completes.  The fact that
  1666. the call is blocking is usually fairly obvious.  If no reliable random data is
  1667. available then functions such as cryptGenerateContext() and cryptExportKey()
  1668. which require it will return the error CRYPT_NORANDOM.
  1669.  
  1670. cryptGenerateContext() spawns another slow poll once it completes to refresh
  1671. the random pool, so after the first call there's no need to perform another
  1672. slow poll, although it can never hurt to do so, especially if your program is
  1673. waiting around for other things such as a network or disk I/O request to
  1674. complete.
  1675.  
  1676. The information obtained by the slow and fast polls under various operating
  1677. systems and DOS is as follows:
  1678.  
  1679.   DOS
  1680.  
  1681.   Since DOS is so simple, it provides very little random information.  A fast
  1682.   poll simply adds the value of the system clock to a 1-second resolution
  1683.   (which is next to useless).  A slow poll relies on the presence of a
  1684.   /dev/random-style driver such as Robert Rothenburg Walking-Owl's noise.sys,
  1685.   which records the timing between keystrokes, variations in disk access times,
  1686.   clock drift while the system is idling at the command line, the variation in
  1687.   EGA/VGA retrace events, and mouse movements.
  1688.  
  1689.   The addition of external random data via cryptaddrandom() is strongly
  1690.   recommended under DOS.  Without either this or the presence of a
  1691.   /dev/random-style driver, the random numbers (and therefor the encryption
  1692.   keys) generated by the library will be extremely easy to guess and will
  1693.   provide virtually no security.  For this reason any functions which require
  1694.   random numbers will always return CRYPT_NORANDOM unless a /dev/random driver
  1695.   is present or external randomness is added via cryptAddRandom().
  1696.  
  1697.   At least one /dev/random slow poll is required to accumulate enough
  1698.   randomness for use by the library.
  1699.  
  1700.   Windows 3.x
  1701.  
  1702.   A fast poll adds the number of bytes free in the global heap, the cursor
  1703.   position when the last message was received, a 55ms time for the last
  1704.   message, whether the system queue has any events in it, the number of active
  1705.   tasks, the 55ms time since Windows started, the handle of the window with the
  1706.   mouse capture and input focus, the current mouse cursor and caret position,
  1707.   the largest free memory block, number of lockable pages, number of unlocked
  1708.   pages, number of free and used pages, number of swapped pages, 1ms execution
  1709.   time of the current task and virtual machine, and percentage free and memory
  1710.   segment of the user and GDI heaps.
  1711.  
  1712.   A slow poll adds the linear address, size in bytes, handle, lock count,
  1713.   owner, object type, and segment type of every object in the global heap, the
  1714.   module name, handle, reference count, executable path, and next module link
  1715.   of every loaded module, the task handle, parent task handle, instance handle,
  1716.   stack segment and offset, stack size, number of pending events, task queue,
  1717.   code segment and instruction pointer, and the name of the module executing
  1718.   the task for every running task.
  1719.  
  1720.   At least one slow poll or five fast polls are required to accumulate enough
  1721.   randomness for use by the library.
  1722.  
  1723.   Windows 95
  1724.  
  1725.   A fast poll adds the handle of the active window, the handle of the window
  1726.   with mouse capture, the handle of the clipboard owner, the handle of the
  1727.   start of the clipboard viwer list, the pseudohandle of the current process,
  1728.   the current process ID, the pseudohandle of the current thread, the current
  1729.   thread ID, the number of milliseconds since Windows started, the handle of
  1730.   the desktop window, the handle of the window with the keyboard focus, whether
  1731.   the system queue has any events in it, the cursor position for the last
  1732.   message in the queue, the millisecond time for the last message in the queue,
  1733.   the handle of the window with the clipboard open, the handle of the process
  1734.   heap, the handle of the processes window station, a bitmap of the types of
  1735.   events in the input queue, the current caret and mouse cursor position, the
  1736.   percentage of memory in use, bytes of physical memory available, bytes of
  1737.   free physical memory, bytes in the paging file, free bytes in the paging
  1738.   file, user bytes of address space, and free user bytes of memory, the thread
  1739.   and process creation time, exit time, time in kernel mode, and time in user
  1740.   mode in 100ns intervals, the minimum and maximum working set size for the
  1741.   current process, the name of the desktop, console window title, position and
  1742.   size for new windows, window flags, and handles for stdin, stdout, and
  1743.   stderr.
  1744.  
  1745.   A slow poll adds the process ID, heap ID, size in bytes, handle, linear
  1746.   address, type, and lock count of every object on the local heap, the module
  1747.   ID, process ID, global usage count, module usage count, base address, size in
  1748.   bytes, handle, and executable path of every module in the system, the usage
  1749.   count, process ID, heap ID, module ID, number of threads, parent process ID,
  1750.   base priority class, and executable path of every running process, and the
  1751.   thread ID, process ID, base priority, and priority level change of every
  1752.   executing thread in the system.
  1753.  
  1754.   At least one slow poll or three fast polls are required to accumulate enough
  1755.   randomness for use by the library.
  1756.  
  1757.   Windows NT
  1758.  
  1759.   A fast poll adds the handle of the active window, the handle of the window
  1760.   with mouse capture, the handle of the clipboard owner, the handle of the
  1761.   start of the clipboard viwer list, the pseudohandle of the current process,
  1762.   the current process ID, the pseudohandle of the current thread, the current
  1763.   thread ID, the number of milliseconds since Windows started, the handle of
  1764.   the desktop window, the handle of the window with the keyboard focus, whether
  1765.   the system queue has any events in it, the cursor position for the last
  1766.   message in the queue, the millisecond time for the last message in the queue,
  1767.   the handle of the window with the clipboard open, the handle of the process
  1768.   heap, the handle of the processes window station, a bitmap of the types of
  1769.   events in the input queue, the current caret and mouse cursor position, the
  1770.   percentage of memory in use, bytes of physical memory available, bytes of
  1771.   free physical memory, bytes in the paging file, free bytes in the paging
  1772.   file, user bytes of address space, and free user bytes of memory, the thread
  1773.   and process creation time, exit time, time in kernel mode, and time in user
  1774.   mode in 100ns intervals, the minimum and maximum working set size for the
  1775.   current process, the name of the desktop, console window title, position and
  1776.   size for new windows, window flags, and handles for stdin, stdout, and
  1777.   stderr.
  1778.  
  1779.   A slow poll adds the number of bytes read from and written to disk, the disk
  1780.   read and write time, the number of read and write operations, the depth of
  1781.   the I/O queue, a large number of network statistics such as the number of
  1782.   bytes sent and received, the number of SMB's sent and received, the number of
  1783.   paging, nonpaging, and cached bytes sent and received, the number of failed
  1784.   initial and failed completion operations, the number of reads, random reads,
  1785.   large/small SMB reads, writes, random writes, large and small SMB writes, the
  1786.   number of reads and writes denied, the number of sessions, failed sessions,
  1787.   reconnects, and hung sessions, and various lan manager statistics, and an
  1788.   equally large number of system performance-related statistics such covering
  1789.   virtually every aspect of the operation of the system (the exact details vary
  1790.   from machine to machine, but the library will query every available
  1791.   performance counter and system monitor).
  1792.  
  1793.   At least one slow poll or three fast polls are required to accumulate enough
  1794.   randomness for use by the library.
  1795.  
  1796.   UNIX
  1797.  
  1798.   A fast poll adds the current time to a reasonably high resolution (usually
  1799.   milliseconds or microseconds), the total user and system time, resident set
  1800.   size, page fault statistics, number of I/O operations, messages sent and
  1801.   received, signals received, number of context switches, and various other
  1802.   system statistics.
  1803.  
  1804.   A slow poll varies with the Unix flavour being used.  Under Linux the library
  1805.   will try to use the /dev/random driver, which continually accumulates random
  1806.   data from the system.  If this is not present it will use a variety of
  1807.   information on disk I/O, network traffic, NFS traffic, packet filter
  1808.   statistics, multiprocessor statistics, process information, users, VM
  1809.   statistics, process statistics, open files, inodes, terminals, vector
  1810.   processors, streams, and loaded code.  The exact data collected depends on
  1811.   the system, but generally includes quite detailed operating statistics and
  1812.   information.
  1813.  
  1814.   At least one slow poll is required to accumulate enough randomness for use by
  1815.   the library.
  1816.  
  1817.  
  1818. Controlling the Operation of the Library (L)
  1819. --------------------------------------------
  1820.  
  1821. In order to allow you to control various parts of its operation, the library
  1822. provides a cryptIoctl() function so you can tune its performance.  This is
  1823. called as:
  1824.  
  1825.     cryptIoctl( ioctlCode, ioctlInformation, cryptContext );
  1826.  
  1827. The ioctlCode specifies the type of IOCTL function to perform.  The
  1828. ioctlInformation contains the information passed to the library to control its
  1829. operation.  The cryptContext is the context which the option applies to, or
  1830. NULL if the option is to be applied globally.  The IOCTL functions are as
  1831. follows:
  1832.  
  1833. CRYPT_IOCTL_NONE    Do nothing.
  1834.  
  1835. CRYPT_IOCTL_MEMORY  Change the way in which memory blocks which must store
  1836.                     sensitive information are allocated.  By default the
  1837.                     library will try to lock all pages containing keys and
  1838.                     sensitive information to prevent them from being paged to
  1839.                     disk, but will continue if the memory locking fails.
  1840.                     Specifying CRYPT_MEMORY_NOLOCK as the memory lock type will
  1841.                     disable the locking of memory.  Specifying
  1842.                     CRYPT_MEMORY_LOCK will give the default behaviour.
  1843.                     Specifying CRYPT_MEMORY_FORCELOCK will cause memory
  1844.                     allocations to fail if the pages cannot be locked, and the
  1845.                     library will return the error code CRYPT_NOLOCK.  This is a
  1846.                     more stringent check than CRYPT_MEMORY_LOCK, which will try
  1847.                     to lock the pages but continue anyway if they can't be
  1848.                     locked.
  1849.  
  1850.                     A CRYPT_IOCTL_MEMORY call will only affect memory allocated
  1851.                     after the call is made, so you can't pass a cryptContext to
  1852.                     the function.  The settings will continue in effect until
  1853.                     the next call to CRYPT_IOCTL_MEMORY is made.
  1854.  
  1855.                     Locking pages is unnecessary under DOS, impossible under
  1856.                     Windows 3.x and Windows 95, possible under Windows NT, and
  1857.                     requires root priviledges under Unix.  Each encryption
  1858.                     context will lock approximately two 4K pages (or equivalent
  1859.                     regions) of memory, each call to cryptExportKey() or
  1860.                     cryptImportKey() will temporarily lock one page, and the
  1861.                     library itself keeps one page locked.  This creates no
  1862.                     noticeable effect on system performance when used in
  1863.                     moderation.
  1864.  
  1865. CRYPT_IOCTL_KEYCOOKIE
  1866. CRYPT_IOCTL_SIGCOOKIE
  1867.                     Control the export of key and signature cookies.  By
  1868.                     default the library will export key and signature cookies.
  1869.                     You can disable the export of cookies by setting the IOCTL
  1870.                     parameter to 0, enable it by setting it to 1, and restore
  1871.                     the default behaviour by setting it to CRYPT_USE_DEFAULT.
  1872.  
  1873.                     Passing in a cryptContext will set the option for the
  1874.                     encryption context, passing in a NULL pointer will set the
  1875.                     option for the entire library.  An export cookie option set
  1876.                     for an encryption context will override an export cookie
  1877.                     option set for the entire library.  For example if the
  1878.                     library as a whole is set to export key cookies but a
  1879.                     particular cryptContext is set to not export a cookie, the
  1880.                     cookie for that context won't be exported.
  1881.  
  1882. The structures used by the cryptIoctl() function are as follows:
  1883.  
  1884. Structure CRYPT_IOCTLINFO_MEMORY:
  1885.  
  1886.   /* What to do with memory blocks */
  1887.   int memoryLockType;
  1888.  
  1889. Structure CRYPT_IOCTLINFO_COOKIE:
  1890.  
  1891.   /* What to do with key or signature cookies */
  1892.   int exportCookie;
  1893.  
  1894. For example to disable the export of signature cookies for the entire library
  1895. you would use:
  1896.  
  1897.   CRYPT_IOCTLINFO_COOKIE cryptIoctlInfoCookie;
  1898.  
  1899.   cryptIoctlInfoCookie.exportCookie = FALSE;
  1900.   cryptIoctl( CRYPT_IOCTL_SIGCOOKIE, &cryptIoctlInfoCookie, NULL );
  1901.  
  1902.  
  1903. Working with Newer Versions of the Library
  1904. ------------------------------------------
  1905.  
  1906. Your software can automatically support new encryption algorithms and modes as
  1907. they are added to the library if you check for the range of supported
  1908. algorithms and modes instead of hard-coding in the values which existed when
  1909. you wrote the program.  In order to support this, the library predefines the
  1910. values CRYPT_ALGO_FIRST_CONVENTIONAL and CRYPT_ALGO_LAST_CONVENTIONAL for the
  1911. first and last possible conventional encryption algorithms,
  1912. CRYPT_ALGO_FIRST_PKC and CRYPT_ALGO_LAST_PKC for the first and last possible
  1913. public-key encryption algorithms, and CRYPT_ALGO_FIRST_HASH and
  1914. CRYPT_ALGO_LAST_HASH for the first and last possible hash algorithms.  By
  1915. checking each algorithm within this range using cryptAlgoAvailable(), your
  1916. software can automatically incorporate any new algorithms as they are added.
  1917. For example to scan for all available conventional encryption algorithms you
  1918. would use:
  1919.  
  1920.   CRYPT_ALGO cryptAlgo;
  1921.  
  1922.   for( cryptAlgo = CRYPT_ALGO_FIRST_CONVENTIONAL;
  1923.        cryptAlgo <= CRYPT_ALGO_LAST_CONVENTIONAL; cryptAlgo++ )
  1924.     if( cryptStatusOK( cryptAlgoAvailable( cryptAlgo ) )
  1925.         /* Perform action with algorithm */;
  1926.  
  1927. The action to perform would typically be building a list of available
  1928. algorithms and allowing the user to choose the one they preferred.  The same
  1929. can be done for the public-key and hash algorithms.
  1930.  
  1931. The library also predefines CRYPT_MODE_FIRST_CONVENTIONAL and
  1932. CRYPT_MODE_LAST_CONVENTIONAL which cover the range of available conventional
  1933. encryption modes.  Once you've determined which conventional algorithm to use
  1934. you can use:
  1935.  
  1936.   CRYPT_MODE cryptMode;
  1937.  
  1938.   for( cryptMode = CRYPT_MODE_FIRST_CONVENTIONAL;
  1939.        cryptMode <= CRYPT_MODE_LAST_CONVENTIONAL; cryptMode++ )
  1940.     if( cryptStatusOK( cryptModeAvailable( cryptAlgo, cryptMode ) )
  1941.         /* Perform action with algorithm */;
  1942.  
  1943. If your code follows these guidelines, it will automatically handle any new
  1944. encryption algorithms and modes which are added in newer versions of the
  1945. library.  If you are using the shared library or DLL form of the encryption
  1946. library, your softwares' encryption capabilities will be upgraded every time
  1947. the library is upgraded.
  1948.  
  1949.  
  1950. Error Checking
  1951. --------------
  1952.  
  1953. When the library is initialised, each of the built-in encryption algorithms
  1954. goes through a self-test procedure which checks the implementation using
  1955. standard test vectors and methods given with the algorithm specification
  1956. (typically FIPS publications, ANSI standards, or standard reference
  1957. implementations).  This self-test is used to verify that each encryption
  1958. algorithm is performing as required.
  1959.  
  1960. Each function in the library performs extensive error checking (although
  1961. monitoring of error codes has been left out in the code samples below for
  1962. readability).  The file TEST.C, included with the crypt library, includes
  1963. better error handling than the short examples below.
  1964.  
  1965. For functions which complete with no error, the library will return CRYPT_OK.
  1966. For functions which complete with some form of error internal to the library
  1967. itself, the library will return CRYPT_ERROR (this situation should never occur
  1968. and should be reported to the library author).
  1969.  
  1970. Other errors are:
  1971.  
  1972. CRYPT_SELFTEST      The encryption code or hardware has failed an internal
  1973.                     self-test.  This code is returned if an attempt is made to
  1974.                     use the encryption module which failed the self-test.
  1975.  
  1976. CRYPT_BADPARM1...   There is a problem with a parameter passed to a library
  1977.   CRYPT_BADPARM15   function.  The exact code depends on the parameter in
  1978.                     error.  If the function cannot resolve the exact parameter
  1979.                     error type it will return CRYPT_BADPARM.
  1980.  
  1981. CRYPT_NOMEM         There is not enough memory available to perform this
  1982.                     operation (generally the operation would be the creation of
  1983.                     an encryption context or a signature or key export or
  1984.                     import operation).
  1985.  
  1986. CRYPT_NOTINITED     The encryption context you have tried to use hasn't been
  1987.                     initialised yet.
  1988.  
  1989. CRYPT_INITED        The encryption context you have tried to initialise has
  1990.                     already been initialised previously.
  1991.  
  1992. CRYPT_NOALGO        The requested encryption algorithm or mode is unavailable.
  1993. CRYPT_NOMODE
  1994.  
  1995. CRYPT_NOKEY         The encryption key or IV hasn't been loaded into an
  1996. CRYPT_NOIV          encryption context yet.
  1997.  
  1998. CRYPT_NOLOCK        The operating system cannot lock pages containing sensitive
  1999.                     information in memory to prevent them from being swapped to
  2000.                     disk.
  2001.  
  2002. CRYPT_NORANDOM      Not enough randomness information is available to the
  2003.                     library to perform the requested operation.
  2004.  
  2005. CRYPT_NOTAVAIL      The requested operation is not available for this algorithm
  2006.                     (for example an attempt to load an encryption key into a
  2007.                     hash algorithm context, or to decrypt a Diffie-Hellman
  2008.                     shared integer with an RSA key).
  2009. CRYPT_KEYPERM       The key used does not have the permission to perform this
  2010.                     type of operation (for example an encrypt-only key being
  2011.                     used for a decrypt operation).
  2012. CRYPT_WRONGKEY      The key being used to decrypt a piece of data is incorrect.
  2013.  
  2014. CRYPT_INCOMPLETE    An operation which consists of multiple steps (such as a
  2015.                     message hash) is still in progress and requires further
  2016.                     steps before it can be regarded as having completed.
  2017. CRYPT_COMPLETE      An operation which consists of multiple steps (such as a
  2018.                     message hash) is complete and cannot be continued.
  2019.  
  2020. CRYPT_ORPHAN        There were were still encryption contexts allocated when
  2021.                     cryptEnd() was called.  This error type is not serious
  2022.                     since the library performs automatic garbage collection of
  2023.                     any orphaned encryption contexts, but may serve as a
  2024.                     warning that something is wrong in a user program.
  2025.  
  2026. CRYPT_DATASIZE      There is too much data for this function to work with.  For
  2027.                     a public-key encryption or signature function this means
  2028.                     there is too much data for this public/private key to
  2029.                     encrypt/sign.  You should either use a larger
  2030.                     public/private key (in general a 1024-bit or larger key
  2031.                     should be sufficient for most purposes) or less data (for
  2032.                     example by reducing the key size in the encryption context
  2033.                     passed to cryptExportKey()).  For a key certificate
  2034.                     function this means the amount of data you have supplied is
  2035.                     more than what is allowed for the field you are trying to
  2036.                     store it in.
  2037.  
  2038. CRYPT_PKCCRYPT      The public/private key encryption/decryption failed,
  2039.                     probably due to incorrect public or private key parameters.
  2040. CRYPT_BADDATA       The object (typically encrypted or signed data, or a key
  2041.                     certificate) was corrupt and can't be processed.
  2042. CRYPT_BADSIG        The signature did not match the data.
  2043.  
  2044. The macros cryptStatusError() and cryptStatusOK() can be used to determine
  2045. whether a return value denotes an error condition, for example:
  2046.  
  2047.   CRYPT_CONTEXT cryptContext;
  2048.   int status;
  2049.  
  2050.   status = cryptCreateContext( &cryptContext, CRYPT_ALGO_IDEA, CRYPT_MODE_CFB );
  2051.   if( cryptStatusError( status ) )
  2052.       /* Perform error processing */
  2053.  
  2054. The macros cryptIsParamError(), cryptIsResourceError(), cryptIsSecurityError(),
  2055. cryptIsHighlevelError(), cryptIsKeysetError(), and cryptIsCertError() can be
  2056. used to determine whether a return value denotes a function parameter error, an
  2057. error due to insufficient resources, a cryptlib API security violation, a
  2058. high-level function related error, a key collection related error, or a
  2059. certificate management error.  Note that high-level errors also cover key
  2060. collection and certificate operations (for example checking a certificate might
  2061. return CRYPT_BADSIG), so you should check for these as well when you check for
  2062. classes of key collection or certificate errors.
  2063.  
  2064.  
  2065. Examples
  2066. --------
  2067.  
  2068. The following examples have had error checking removed for readability.  See
  2069. the test code in TEST.C for an example with full error checking.
  2070.  
  2071. To encrypt a buffer using DES in CFB mode with the password 0x0123456789ABCDEF
  2072. and an IV generated automatically by the library:
  2073.  
  2074.   CRYPT_CONTEXT cryptContext;
  2075.   unsigned char key[] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };
  2076.  
  2077.   /* Load the key, encrypt the buffer (the IV is automatically generated if we
  2078.      don't specify one, it can be obtained with cryptRetrieveIV()), and destroy
  2079.      the encryption context */
  2080.   cryptCreateContext( &cryptContext, CRYPT_ALGO_DES, CRYPT_MODE_CFB );
  2081.   cryptLoadContext( cryptContext, key, sizeof( key ) );
  2082.   cryptEncrypt( cryptContext, buffer, length );
  2083.   cryptDestroyContext( cryptContext );
  2084.  
  2085. To hash an arbitrary-size passphrase down to the one used by a particular
  2086. cryptosystem (in this case triple DES) using MD5:
  2087.  
  2088.   CRYPT_QUERY_INFO cryptQueryInfo;
  2089.   CRYPT_CONTEXT cryptContext;
  2090.   unsigned char key[ CRYPT_MAX_KEYSIZE ];
  2091.   int keySize;
  2092.  
  2093.   /* Find out how long we can make the key */
  2094.   cryptQueryAlgoMode( CRYPT_ALGO_3DES, CRYPT_MODE_CBC, &cryptQueryInfo );
  2095.   keySize = cryptQueryInfo->maxKeySize;   /* Use all we can */
  2096.  
  2097.   /* Hash the user key with MD5 and query the encryption context to get the
  2098.      final hash value */
  2099.   cryptCreateContext( &cryptContext, CRYPT_ALGO_MD5, CRYPT_MODE_NONE );
  2100.   cryptEncrypt( cryptContext, passphrase, strlen( passphrase ) );
  2101.   cryptEncrypt( cryptContext, passphrase, 0 );
  2102.   cryptQueryContext( cryptContext, &cryptQueryInfo );
  2103.   cryptDestroyContext( cryptContext );
  2104.  
  2105.   /* Use the hashed value of the passphrase as the key */
  2106.   memcpy( key, cryptQueryInfo.hashValue, keySize );
  2107.  
  2108. Note that this code uses the encryption library querying functions, which will
  2109. be explained in the next section of the documentation.
  2110.  
  2111. To encrypt a file using triple DES in CBC mode with the key generated in the
  2112. previous example:
  2113.  
  2114.   int firstTime = 1;
  2115.  
  2116.   /* Load the previously-generated key */
  2117.   cryptCreateContext( &cryptContext, CRYPT_ALGO_3DES, CRYPT_MODE_CBC );
  2118.   cryptLoadContext( cryptContext, key, keySize );
  2119.  
  2120.   /* Copy the data across, encrypting as we go */
  2121.   while( ( length = fread( buffer, 1, BUFSIZE, inFile ) ) != 0 )
  2122.       {
  2123.       /* Encrypt the data in the buffer */
  2124.       cryptEncrypt( cryptContext, buffer, length );
  2125.  
  2126.       /* If it's the first block, retrieve the IV and prepend it to the output
  2127.          data.  Note the since we've let the library generate the IV for us
  2128.          automatically, we can't retrieve it until after the first
  2129.          cryptEncrypt() call */
  2130.       if( firstTime )
  2131.           {
  2132.           CRYPT_QUERY_INFO cryptQueryInfo;
  2133.           unsigned char iv[ CRYPT_MAX_IVSIZE ];
  2134.           int ivSize;
  2135.  
  2136.           /* Find out how long the IV we're using is */
  2137.           cryptQueryContext( cryptContext, &cryptQueryInfo );
  2138.           ivSize = cryptQueryInfo->ivSize;
  2139.  
  2140.           /* Retrieve the IV and write it to the output file */
  2141.           cryptRetrieveIV( cryptContext, iv );
  2142.           fwrite( iv, 1, ivSize, outFile );
  2143.  
  2144.           firstTime = 0;
  2145.           }
  2146.  
  2147.       /* Write the encrypted data to the output file */
  2148.       fwrite( buffer, 1, length, outFile );
  2149.       }
  2150.  
  2151.   /* Since CBC is a block cipher, we perform a courtesy close call to let the
  2152.      encryption routines handle the last block */
  2153.   cryptEncrypt( cryptContext, buffer, 0 );
  2154.  
  2155.   cryptDestroyContext( cryptContext );
  2156.  
  2157. To decrypt the previously encrypted file with the key generated in the previous
  2158. example:
  2159.  
  2160.   CRYPT_QUERY_INFO cryptQueryInfo;
  2161.   unsigned char iv[ CRYPT_MAX_IVSIZE ];
  2162.   int ivSize;
  2163.  
  2164.   /* Load the previously-generated key */
  2165.   cryptCreateContext( &cryptContext, CRYPT_ALGO_3DES, CRYPT_MODE_CBC );
  2166.   cryptLoadContext( cryptContext, key, keySize );
  2167.  
  2168.   /* Find out how long the IV we're using is */
  2169.   cryptQueryContext( cryptContext, &cryptQueryInfo );
  2170.   ivSize = cryptQueryInfo.ivSize;
  2171.  
  2172.   /* Read the IV from the input file and load it into the encryption context */
  2173.   fread( iv, 1, ivSize, inFile );
  2174.   cryptLoadIV( cryptContext, iv, ivSize );
  2175.  
  2176.   /* Copy the data across, decrypting as we go */
  2177.   while( ( length = fread( buffer, 1, BUFSIZE, inFile ) ) != 0 )
  2178.       {
  2179.       /* Encrypt the data in the buffer */
  2180.       cryptDecrypt( cryptContext, buffer, length );
  2181.  
  2182.       /* Write the decrypted data to the output file */
  2183.       fwrite( buffer, 1, length, outFile );
  2184.       }
  2185.  
  2186.   /* Since CBC mode implements a block cipher, we perform a courtesy close call
  2187.      to let the encryption routines handle the last block */
  2188.   cryptDecrypt( cryptContext, buffer, 0 );
  2189.  
  2190.   cryptDestroyContext( cryptContext );
  2191.  
  2192. To export an RSA-encrypted triple DES session key contained in the
  2193. sessionKeyContext encryption context for an encrypted message exchange:
  2194.  
  2195.   CRYPT_CONTEXT cryptContext, sessionKeyContext;
  2196.   CRYPT_PKCINFO_RSA rsaKey;
  2197.   BYTE *encryptedKey;
  2198.   int encryptedKeyLength;
  2199.  
  2200.   /* Create an RSA encryption context */
  2201.   cryptCreateContext( cryptContext, CRYPT_ALGO_RSA, CRYPT_MODE_PKC );
  2202.   cryptInitComponents( rsaKey, CRYPT_COMPONENTS_BIGENDIAN,
  2203.                        CRYPT_KEYTYPE_PUBLIC );
  2204.   cryptSetComponent( rsaKey.n, ... );
  2205.   cryptSetComponent( rsaKey.e, ... );
  2206.   cryptLoadContext( cryptContext, &rsaKey, CRYPT_UNUSED );
  2207.   cryptDestroyComponents( rsaKey );
  2208.  
  2209.   /* Create and export the session key */
  2210.   cryptCreateContext( sessionKeyContext, CRYPT_ALGO_3DES, CRYPT_MODE_CFB );
  2211.   cryptGenerateContext( sessionKeyContext, CRYPT_USE_DEFAULT );
  2212.   cryptExportKey( cryptContext, sessionKeyContext, NULL,
  2213.                   &encryptedKeyLength );
  2214.   encryptedKey = malloc( encryptedKeyLength );
  2215.   cryptExportKey( cryptContext, sessionKeyContext, encryptedKey,
  2216.                   &encryptedKeyLength );
  2217.  
  2218.   cryptDestroyContext( cryptContext );
  2219.  
  2220. You can now encrypt the data using the session key context, and send both the
  2221. encrypted key and encrypted data to the recipient (remember to destroy the
  2222. session key context when you've finished).
  2223.  
  2224. To import the RSA-encrypted triple DES session key at the other end of the
  2225. communications channel:
  2226.  
  2227.   CRYPT_CONTEXT cryptContext, sessionKeyContext;
  2228.  
  2229.   /* Create an RSA decryption context */
  2230.   cryptCreateContext( decryptContext, CRYPT_ALGO_RSA, CRYPT_MODE_PKC );
  2231.   cryptInitComponents( rsaKey, CRYPT_COMPONENTS_BIGENDIAN,
  2232.                        CRYPT_KEYTYPE_PRIVATE );
  2233.   cryptSetComponent( rsaKey.n, ... );
  2234.   cryptSetComponent( rsaKey.e, ... );
  2235.   cryptSetComponent( rsaKey.d, ... );
  2236.   cryptSetComponent( rsaKey.p, ... );
  2237.   cryptSetComponent( rsaKey.q, ... );
  2238.   cryptSetComponent( rsaKey.u, ... );
  2239.   cryptSetComponent( rsaKey.e1, ... );
  2240.   cryptSetComponent( rsaKey.e2, ... );
  2241.   cryptLoadContext( decryptContext, &rsaKey, CRYPT_UNUSED );
  2242.   cryptDestroyComponents( rsaKey );
  2243.  
  2244.   /* Import the session key */
  2245.   cryptImportKey( decryptContext, &sessionKeyContext, encryptedKey );
  2246.   cryptDestroyContext( decryptContext );
  2247.  
  2248. You can now decrypt the encrypted data using the session key context (remember
  2249. to destroy the session key context when you've finished).
  2250.  
  2251. To sign a message using the message hash contained in the hashContext
  2252. encryption context:
  2253.  
  2254.   CRYPT_CONTEXT signContext;
  2255.   BYTE signature;
  2256.   int signatureSize;
  2257.  
  2258.   /* Create an RSA signature context */
  2259.   cryptCreateContext( signContext, CRYPT_ALGO_RSA, CRYPT_MODE_PKC );
  2260.   cryptInitComponents( rsaKey, CRYPT_COMPONENTS_BIGENDIAN,
  2261.                        CRYPT_KEYTYPE_PRIVATE );
  2262.   cryptSetComponent( rsaKey.n, ... );
  2263.   cryptSetComponent( rsaKey.e, ... );
  2264.   cryptSetComponent( rsaKey.d, ... );
  2265.   cryptSetComponent( rsaKey.p, ... );
  2266.   cryptSetComponent( rsaKey.q, ... );
  2267.   cryptSetComponent( rsaKey.u, ... );
  2268.   cryptSetComponent( rsaKey.e1, ... );
  2269.   cryptSetComponent( rsaKey.e2, ... );
  2270.   cryptLoadContext( signContext, &rsaKey, CRYPT_UNUSED );
  2271.   cryptDestroyComponents( rsaKey );
  2272.  
  2273.   /* Sign the hashed data */
  2274.   cryptCreateSignature( signContext, hashContext, NULL, &signatureSize );
  2275.   signature = malloc( &signatureSize );
  2276.   cryptCreateSignature( signContext, hashContext, buffer, &signatureSize );
  2277.   cryptDestroyContext( signContext );
  2278.  
  2279. You can now send the signature and the data it pertains to to the recipient.
  2280.  
  2281. To check the signature at the other end of the communications channel against a
  2282. hash of the data contained in the hashContext encryption context:
  2283.  
  2284.   CRYPT_CONTEXT checkContext;
  2285.  
  2286.   /* Create an RSA signature check context */
  2287.   cryptCreateContext( checkContext, CRYPT_ALGO_RSA, CRYPT_MODE_PKC );
  2288.   cryptInitComponents( rsaKey, CRYPT_COMPONENTS_BIGENDIAN,
  2289.                        CRYPT_KEYTYPE_PUBLIC );
  2290.   cryptSetComponent( rsaKey.n, ... );
  2291.   cryptSetComponent( rsaKey.e, ... );
  2292.   cryptLoadContext( checkContext, &rsaKey, CRYPT_UNUSED );
  2293.   cryptDestroyComponents( rsaKey );
  2294.  
  2295.   /* Check the signature on the hash */
  2296.   if( cryptCheckSignature( checkContext, hashContext, signature ) == CRYPT_BADSIG )
  2297.         /* Signature check failed */
  2298.  
  2299. A longer usage example including proper error checking and with various other
  2300. test routines can be found in the file test.c included with the code.
  2301.  
  2302.  
  2303. Querying the Encryption Library Capabilities (L)
  2304. ------------------------------------------------
  2305.  
  2306. The previous examples showed the use of the cryptQueryAlgoMode() and
  2307. cryptQueryContext() calls to retrieve information about the characteristics of
  2308. a particular algorithm as implemented by the encryption library.  There are
  2309. four such calls in total, of which two query the existence of an implementation
  2310. of an algorithm or an algorithm/mode combination, and two return information
  2311. about the implementation itself.
  2312.  
  2313. The library can be interrogated about the existence of a particular encryption
  2314. algorithm or algorithm and encryption mode combination with:
  2315.  
  2316.   status = cryptAlgoAvailabile( algorithm );
  2317.  
  2318. or:
  2319.  
  2320.   status = cryptModeAvailabile( algorithm, mode );
  2321.  
  2322. In addition to requesting information on the availability of an encryption
  2323. algorithm and mode, you can request extra information to be returned in a
  2324. CRYPT_QUERY_INFO structure with:
  2325.  
  2326.   status = cryptQueryAlgoMode( algorithm, mode, &cryptQueryInfo );
  2327.  
  2328. or
  2329.  
  2330.   status = cryptQueryContext( cryptContext, &cryptQueryInfo );
  2331.  
  2332. with the former being used to request information on a given algorithm/mode
  2333. combination and the latter being used to request information about the
  2334. current encryption context being used.
  2335.  
  2336. The CRYPT_QUERY_INFO structure contains the following fields:
  2337.  
  2338.   /* The encryption algorithm, encryption mode, and algorithm and mode names
  2339.      ASCII strings */
  2340.   CRYPT_ALGO cryptAlgo;
  2341.   CRYPT_MODE cryptMode;
  2342.   char *algoName;
  2343.   char *modeName;
  2344.  
  2345.   /* The algorithm block size in bytes, the minimum, recommended, and
  2346.      maximum key size in bytes (if the algorithm uses a key), and the minimum,
  2347.      recommended, and maximum IV size in bytes (if the algorithm uses an IV) */
  2348.   int blockSize;
  2349.   int minKeySize;
  2350.   int keySize;
  2351.   int maxKeySize;
  2352.   int minIVsize;
  2353.   int ivSize;
  2354.   int maxIVsize;
  2355.  
  2356.   /* The algorithm speed relative to a block copy operation.  This value
  2357.      ranges from 1 ... CRYPT_MAX_SPEED, or CRYPT_ERROR if no speed rating is
  2358.      available */
  2359.   int speed;
  2360.  
  2361.   /* The hash value (set to 0 if the encryption context isn't for a hash
  2362.      algorithm) */
  2363.   unsigned char hashValue[ CRYPT_MAX_HASHSIZE ];
  2364.  
  2365.   /* The key ID information (set to 0 if the encryption context isn't for a
  2366.      public-key algorithm */
  2367.   CRYPT_ALGO keyIDalgo;
  2368.   unsigned char *keyID;
  2369.   unsigned char keyIDlength;
  2370.  
  2371.   /* The control vector (set to 0 if the encryption context isn't for a
  2372.      conventional encryption algorithm */
  2373.   long controlVector;
  2374.  
  2375.  
  2376. Algorithm-Specific Notes
  2377. ------------------------
  2378.  
  2379. DES:
  2380. Triple DES:
  2381.  
  2382.   Although the library routines use 64, 128, or 192-bit DES keys (depending on
  2383.   whether one, two, or three-key DES is being used), only 56, 112, or 168 bits
  2384.   of the key are actually used.  The high bit in each byte is used as a parity
  2385.   bit (the library will set the correct parity values for you, so you don't
  2386.   have to worry about this).  You can treat the algorithms as having 64, 128,
  2387.   or 192-bit keys, but bear in mind that only 7 of the 8 bits in each byte
  2388.   are actually used as keying material.
  2389.  
  2390.   cryptLoadContext() will return a bad parameter code if the key is a weak key
  2391.   (CRYPT_BADPARM2 in this case).
  2392.  
  2393.   cryptEncrypt() and cryptDecrypt() will return a bad parameter code if the
  2394.   encryption mode is ECB, CBC, or PCBC and the encrypted data length is not a
  2395.   multiple of the block size (CRYPT_BADPARM3 in this case).
  2396.  
  2397.   cryptExportKey() will export the correct parity-adjusted version of the key,
  2398.   not the raw version as passed to cryptLoadContext().
  2399.  
  2400. Diffie-Hellman
  2401. DSA
  2402.  
  2403.   These algorithms are covered by patents, see the section "Patents" above.
  2404.  
  2405. IDEA:
  2406.  
  2407.   cryptEncrypt() and cryptDecrypt() will return a bad parameter code if the
  2408.   encryption mode is ECB, CBC, or PCBC and the encrypted data length is not a
  2409.   multiple of the block size (CRYPT_BADPARM3 in this case).
  2410.  
  2411.   This algorithm is covered by patents, see the section "Patents" above.
  2412.  
  2413. MDCSHS:
  2414.  
  2415.   None
  2416.  
  2417. Blowfish:
  2418. Blowfish-SK:
  2419. RC2:
  2420. SAFER:
  2421. SAFER-SK:
  2422.  
  2423.   cryptEncrypt() and cryptDecrypt() will return a bad parameter code if the
  2424.   encryption mode is ECB, CBC, or PCBC and the encrypted data length is not a
  2425.   multiple of the block size (CRYPT_BADPARM3 in this case).
  2426.  
  2427. RC4:
  2428.  
  2429.   None
  2430.  
  2431. RC5:
  2432.  
  2433.   cryptEncrypt() and cryptDecrypt() will return a bad parameter code if the
  2434.   encryption mode is ECB, CBC, or PCBC and the encrypted data length is not a
  2435.   multiple of the block size (CRYPT_BADPARM3 in this case).
  2436.  
  2437.   This algorithm is covered by patents, see the section "Patents" above.
  2438.  
  2439. RSA:
  2440.  
  2441.   cryptEncrypt() and cryptDecrypt() will return a bad parameter code if the
  2442.   length parameter is not CRYPT_USE_DEFAULT (CRYPT_BADPARM3 in this case).
  2443.  
  2444.   This algorithm is covered by patents, see the section "Patents" above.
  2445.  
  2446.  
  2447. Plug-In Module Implementation
  2448. -----------------------------
  2449.  
  2450. These notes are rather brief since there is a lot of ground to cover, and the
  2451. easiest way to see what is required is to look at the crypt.c code and the way
  2452. it interfaces to the lib_XXX.c code, which may be regarded as standard
  2453. implementations of a plug-in module (the triple DES module is a good example).
  2454. Note that internally the library uses pointers to CRYPT_INFO structures rather
  2455. than the opaque CRYPT_CONTEXT cookies which exist outside the libraries'
  2456. security perimeter.
  2457.  
  2458. Implementors must provide the following services in their plug-in modules (if
  2459. the algorithm doesn't require this service, the pointer to it should be set to
  2460. NULL in the capabilityInfo table):
  2461.  
  2462. int selfTestFunction( void );
  2463.  
  2464.   Perform a self-test on the encryption hardware/software module.  This
  2465.   function is called once before any other function is called.
  2466.  
  2467. int initFunction( CRYPT_INFO *cryptInfo );
  2468.  
  2469.   Initialise the appropriate private CRYPT_INFO fields.
  2470.  
  2471. int initExFunction( CRYPT_INFO *cryptInfo, void *cryptInfoEx );
  2472.  
  2473.   Initialiase the appropriate private CRYPT_INFO fields based on the extended
  2474.   information given in the second parameter.
  2475.  
  2476. int endFunction( CRYPT_INFO *cryptInfo );
  2477.  
  2478.   Clear the appropriate private CRYPT_INFO fields.
  2479.  
  2480. int initKeyFunction( CRYPT_INFO *cryptInfo );
  2481.  
  2482.   Initialise the internal key based on the user key.  Typically this might
  2483.   perform one or more of the following:
  2484.  
  2485.     Hash the user key down to the size of the key used by the algorithm
  2486.  
  2487.     Perform some type of key schedule operation
  2488.  
  2489.     Perform endianness conversion for the current operating environment
  2490.  
  2491.     Load the key into external crypto hardware.
  2492.  
  2493.     Perform a key selection in external hardware based on the specified key
  2494.     selector.
  2495.  
  2496.   For algorithms with asymmetric internal keys, both an encryption and a
  2497.   decryption key will have to be generated, as a crypt context may be used for
  2498.   encryption or decryption.
  2499.  
  2500. int initIVFunction( CRYPT_INFO *cryptInfo );
  2501.  
  2502.   Initialise the IV.  Typically this might perform one or more of the
  2503.   following:
  2504.  
  2505.     Perform endianness conversion for the current operating environment
  2506.  
  2507.     Load the IV into external crypto hardware.
  2508.  
  2509. int getKeysizeFunction( CRYPT_INFO *cryptInfo );
  2510.  
  2511.    Return the maximum key size for this encryption context in bits if the
  2512.    algorithm can have multiple maximum key sizes (for example triple DES can
  2513.    have 112 or 168 bit maximum key sizes).
  2514.  
  2515. int getDataFunction( CRYPT_INFO *cryptInfo );
  2516.  
  2517.    Returns any user-visible data created by the algorithm for this encryption
  2518.    context.  Currently only used to get the result of a hash operation for hash
  2519.    encryption contexts.
  2520.  
  2521. int encryptFunction( CRYPT_INFO *cryptInfo, void *buffer, int length );
  2522. int decryptFunction( CRYPT_INFO *cryptInfo, void *buffer, int length );
  2523.  
  2524.   Encrypt/decrypt a block of data based on the algorithm and keying information
  2525.   in CRYPT_INFO.  Some algorithms may require special handling for the last
  2526.   block (eg block truncation in CBC) so both routines should recognise a call
  2527.   with length = 0 to indicate the end of the encrypted data block.
  2528.  
  2529.  
  2530. Standards Conformance
  2531. ---------------------
  2532.  
  2533. Blowfish/Blowfish-SK:
  2534.  
  2535. Blowfish has been implemented as per:
  2536.  
  2537.   "Description of a New Varible-Length Key, 64-bit Block Cipher (Blowfish)",
  2538.   Bruce Schneier, "Fast Software Encryption", Lecture Notes in Computer Science
  2539.   No. 809, Springer-Verlag 1994.
  2540.  
  2541. The Blowfish modes of operation are given in:
  2542.  
  2543.   ISO/IEC 8372, "Information Technology - Modes of Operation for a 64-bit Block
  2544.   Cipher Algorithm".
  2545.  
  2546. The Blowfish code has been validated against the Blowfish reference
  2547. implementation test vectors.
  2548.  
  2549. DES:
  2550.  
  2551. DES has been implemented as per:
  2552.  
  2553.   ANSI X3.92, "American National Standard, Data Encryption Algorithm", 1981.
  2554.  
  2555.   FIPS PUB 46-2, "Data Encryption Standard", 1994.
  2556.  
  2557.   FIPS PUB 74, "Guidelines for Implementing and Using the NBS Data Encryption
  2558.   Standard", 1981.
  2559.  
  2560.   ISO/IEC 8731:1987, "Banking - Approved Algorithms for Message Authentication
  2561.   - Part 1: Data Encryption Algorithm (DEA)".
  2562.  
  2563. The DES modes of operation are given in:
  2564.  
  2565.   ANSI X3.106, "American National Standard, Information Systems - Data
  2566.   Encryption Algorithm - Modes of Operation", 1983.
  2567.  
  2568.   FIPS PUB 81, "DES Modes of Operation", 1980.
  2569.  
  2570.   ISO/IEC 8372, "Information Technology - Modes of Operation for a 64-bit Block
  2571.   Cipher Algorithm".
  2572.  
  2573. The DES code has been validated against the test vectors given in:
  2574.  
  2575.   NIST Special Publication 500-20, "Validating the Correctness of Hardware
  2576.   Implementations of the NBS Data Encryption Standard".
  2577.  
  2578. Triple DES:
  2579.  
  2580. Triple DES has been implemented as per:
  2581.  
  2582.   ANSI X9.17, "American National Standard, Financial Institution Key Management
  2583.   (Wholesale)", 1985.
  2584.  
  2585.   ISO/IEC 8732:1987, "Banking - Key Management (Wholesale)".
  2586.  
  2587. The triple DES modes of operation are given in:
  2588.  
  2589.   ISO/IEC 8372, "Information Technology - Modes of Operation for a 64-bit Block
  2590.   Cipher Algorithm".
  2591.  
  2592. Diffie-Hellman:
  2593.  
  2594. DH has been implemented as per:
  2595.  
  2596.   PKCS #3, "Diffie-Hellman Key Agreement Standard", 1991.
  2597.  
  2598. DSA:
  2599.  
  2600. DSA has been implemented as per:
  2601.  
  2602.   ANSI X9.30-1, "American National Standard, Public-Key Cryptography Using
  2603.   Irreversible Algorithms for the Financial Services Industry", 1993.
  2604.  
  2605.   FIPS PUB 186, "Digital Signature Standard", 1994.
  2606.  
  2607. IDEA:
  2608.  
  2609. IDEA has been implemented as per:
  2610.  
  2611.   "Device for the Conversion of a Digital Block and the Use Thereof", James
  2612.   Massey and Xuejia Lai, International Patent PCT/CH91/00117, 1991.
  2613.  
  2614.   "Device for the Conversion of a Digital Block and Use of Same", James Massey
  2615.   and Xuejia Lai, US Patent #5,214,703, 1993.
  2616.  
  2617.   "On the Design and Security of Block Ciphers", Xuejia Lai, ETH Series in
  2618.   Information Processing, Vol.1, Hartung-Gorre Verlag, 1992.
  2619.  
  2620.   ISO/IEC 9979, "Data Cryptographic Tecniques - Procedures for the Registration
  2621.   of Cryptographic Algorithms".
  2622.  
  2623. The IDEA modes of operation are given in:
  2624.  
  2625.   ISO/IEC 8372, "Information Technology - Modes of Operation for a 64-bit Block
  2626.   Cipher Algorithm".
  2627.  
  2628. The IDEA code has been validated against the ETH reference implementation test
  2629. vectors.
  2630.  
  2631. MD2:
  2632.  
  2633. MD2 has been implemented as per:
  2634.  
  2635.   RFC 1319, "The MD2 Message Digest Algorithm", Burt Kaliski, 1992.
  2636.  
  2637. The MD2 code has been validated against the RFC 1319 reference implementation
  2638. test vectors.
  2639.  
  2640.  
  2641. MD4:
  2642.  
  2643. MD4 has been implemented as per:
  2644.  
  2645.   RFC 1320, "The MD4 Message Digest Algorithm", Ronald Rivest, 1992.
  2646.  
  2647. The MD4 code has been validated against the RFC 1320 reference implementation
  2648. test vectors.
  2649.  
  2650. MD5:
  2651.  
  2652. MD5 has been implemented as per:
  2653.  
  2654.   RFC 1321, "The MD5 Message Digest Algorithm", Ronald Rivest, 1992.
  2655.  
  2656. The MD5 code has been validated against the RFC 1321 reference implementation
  2657. test vectors.
  2658.  
  2659. MDC/SHS:
  2660.  
  2661. The SHS code in MDC/SHS has been implemented as per:
  2662.  
  2663.   ANSI X9.30-2, ""American National Standard, Public-Key Cryptography Using
  2664.   Irreversible Algorithms for the Financial Services Industry", 1993.
  2665.  
  2666.   FIPS PUB 180, "Secure Hash Standard", 1993
  2667.  
  2668. The MDC/SHS mode of operation is given in:
  2669.  
  2670.   ISO/IEC 10116, "Information Technology - Security Techniques - Modes of
  2671.   Operation for an n-bit Block Cipher Algorithm".
  2672.  
  2673. The SHS code has been validated against the test vectors given in:
  2674.  
  2675.   FIPS PUB 180, "Secure Hash Standard", 1993
  2676.  
  2677. RSA:
  2678.  
  2679. The RSA code is implemented as per:
  2680.  
  2681.   ANSI X9.31-1, "American National Standard, Public-Key Cryptography Using
  2682.   Reversible Algorithms for the Financial Services Industry", 1993.
  2683.  
  2684.   PKCS #1, "RSA Encryption Standard", 1991.
  2685.  
  2686.   ISO IEC 9594-8/ITU-T X.509, "Information Technology - Open Systems
  2687.   Interconnection - The Directory: Authentication Framework".
  2688.  
  2689. RC2:
  2690.  
  2691. The RC2 code is implemented as per:
  2692.  
  2693.   "The RC2 Encryption Algorithm", Ronald Rivest, RSA Data Security Inc, 1992.
  2694.  
  2695. The RC2 modes of operation are given in:
  2696.  
  2697.   ISO/IEC 8372, "Information Technology - Modes of Operation for a 64-bit Block
  2698.   Cipher Algorithm".
  2699.  
  2700. The RC2 code has been validated against RSADSI BSAFE test vectors.
  2701.  
  2702. RC4:
  2703.  
  2704. The RC4 code is implemented as per:
  2705.  
  2706.   "The RC4 Encryption Algorithm", Ronald Rivest, RSA Data Security Inc, 1992.
  2707.  
  2708. The RC4 code has been validated against RSADSI BSAFE test vectors.
  2709.  
  2710. RC5:
  2711.  
  2712. The RC5 code is implemented as per:
  2713.  
  2714.   "The RC5 Encrypion Algorithm", Ronald Rivest, "Fast Software Encryption II",
  2715.   Lecture Notes in Computer Science No.1008, Springer-Verlag 1995.
  2716.  
  2717. The RC5 modes of operation are given in:
  2718.  
  2719.   ISO/IEC 8372, "Information Technology - Modes of Operation for a 64-bit Block
  2720.   Cipher Algorithm".
  2721.  
  2722. The RC5 code has been validated against the RC5 reference implementation test
  2723. vectors.
  2724.  
  2725. SHA/SHA1:
  2726.  
  2727. The SHA code has been implemented as per:
  2728.  
  2729.   ANSI X9.30-2, "American National Standard, Public-Key Cryptography Using
  2730.   Irreversible Algorithms for the Financial Services Industry", 1993.
  2731.  
  2732.   FIPS PUB 180, "Secure Hash Standard", 1993
  2733.  
  2734.   FIPS PUB 180-1, "Secure Hash Standard", 1994
  2735.  
  2736. The SHA code has been validated against the test vectors given in:
  2737.  
  2738.   FIPS PUB 180, "Secure Hash Standard", 1993
  2739.  
  2740. The SHA1 code has been validated against the test vectors given in:
  2741.  
  2742.   FIPS PUB 180-1, "Secure Hash Standard", 1994
  2743.  
  2744. Safer/Safer-SK:
  2745.  
  2746. The Safer code has been implemented as per:
  2747.  
  2748.   "SAFER K-64: A Byte-Oriented Block-Ciphering Algorithm", James L.Massey,
  2749.   "Fast Software Encryption", Lecture Notes in Computer Science No. 809,
  2750.   Springer-Verlag 1994.
  2751.  
  2752. The Safer-SK code has been implemented as per:
  2753.  
  2754.   "SAFER K-64: One Year Later", James L.Massey, "Fast Software Encryption II",
  2755.   Lecture Notes in Computer Science No.1008, Springer-Verlag 1995.
  2756.  
  2757. The Safer/Safer-SK modes of operation are given in:
  2758.  
  2759.   ISO/IEC 8372, "Information Technology - Modes of Operation for a 64-bit Block
  2760.   Cipher Algorithm".
  2761.  
  2762. The Safer/Safer-SK code has been validated against the ETH reference
  2763. implementation test vectors.
  2764.  
  2765. Data Structures:
  2766.  
  2767. All message exchange data structures are specified as per:
  2768.  
  2769.   ISO/IEC 8824-1:1993/ITU-T X.680, "Information Technology - Open Systems
  2770.   Interconnection - Abstract Syntax Notation One (ASN.1) - Part 1:
  2771.   Specification of Basic Notation".
  2772.  
  2773. The encoding is as per:
  2774.  
  2775.   ISO/IEC 8825-3:1993/ITU-T X.692, "Information Technology - Open Systems
  2776.   Interconnection - Specification of ASN.1 Encoding Rules - Part 3:
  2777.   Distinguished Canonical Encoding Rules".
  2778.  
  2779. The ASN.1 specifications for the message structures are given in the file
  2780. cryptlib.asn.
  2781.  
  2782. General:
  2783.  
  2784. The encryption subsystem has been implemented at a level equivalent to level 1
  2785. of the standard given in:
  2786.  
  2787.   FIPS PUB 140-1, "Security Requirements for Cryptographic Modules", 1993.
  2788.  
  2789. The random-data acquisition routines follow the guidelines laid out in:
  2790.  
  2791.   "Randomness Recommendations for Security", RFC 1750, Donald Eastlake, Stephen
  2792.   Crocker, and Jeffrey Schiller, December 1994.
  2793.  
  2794.   "Cryptographic Random Numbers", IEEE P1363 Appendix E, Draft version 1.0, 11
  2795.   November 1995.
  2796.  
  2797.  
  2798. Revisions
  2799. ---------
  2800.  
  2801. Version 0.99
  2802.  
  2803.   First public release.
  2804.  
  2805. Version 1.10
  2806.  
  2807.   Added RC2, RC5, and Blowfish/Blowfish-SK encryption algorithms.
  2808.  
  2809.   Added MD4, MD5, and SHA hash algorithms.
  2810.  
  2811.   Moved encryption context information into the library, making the information
  2812.   contained within it opaque to end users.
  2813.  
  2814. Version 1.20
  2815.  
  2816.   Added MD2 hash algorithm.
  2817.  
  2818.   Added Diffie-Hellman and RSA public-key encryption algorithm.
  2819.  
  2820.   Cleaned up the name space.
  2821.  
  2822.   Added locking of memory objects to stop them being paged to disk.
  2823.  
  2824.   Added random number management routines
  2825.  
  2826.   Added high-level encrypted object management routines
  2827.  
  2828.  
  2829. Acknowledgements
  2830. ----------------
  2831.  
  2832. The DES and 3DES encryption code was contributed by Eric Young
  2833. <eay@psych.psy.uq.oz.au> and is part of his libdes package.  The primary ftp
  2834. site for the full libdes is
  2835. ftp://ftp.psy.uq.oz.au/pub/Crypto/DES/libdes-x.xx.tar.gz.  libdes is now also
  2836. shipped with SSLeay.  The primary site for this is
  2837. ftp://ftp.psy.uq.oz.au/pub/Crypto/SSL/SSLeay-x.xx.tar.gz.
  2838.  
  2839. The IDEA code was written by Colin Plumb, and scanned from the book "PGP Source
  2840. Code and Internals", MIT Press, 1995 (see the comments in the code for more
  2841. information).
  2842.  
  2843. The bignum maths library used for the public-key encryption was contributed by
  2844. Colin Plumb.
  2845.  
  2846. Matt Thomlinson and Blake Coverett helped fix up and debug the Win32 random
  2847. data gathering routines.
  2848.  
  2849. Chris Wedgwood and Paul Kendall wrote the Unix random data gathering routines.
  2850.  
  2851. Scott Morris did the VMS port.
  2852.  
  2853. Cylink Corporation very generously granted permission for the use of their
  2854. patents for non-commercial purposes.
  2855.