comparison crypt.tex @ 143:5d99163f7e32 libtomcrypt-orig

import of libtomcrypt 0.99
author Matt Johnston <matt@ucc.asn.au>
date Sun, 19 Dec 2004 11:34:45 +0000
parents 6362d3854bb4
children 1c15b283127b
comparison
equal deleted inserted replaced
15:6362d3854bb4 143:5d99163f7e32
1 \documentclass[b5paper]{book} 1 \documentclass[a4paper]{book}
2 \usepackage{hyperref} 2 \usepackage{hyperref}
3 \usepackage{makeidx} 3 \usepackage{makeidx}
4 \usepackage{amssymb} 4 \usepackage{amssymb}
5 \usepackage{color} 5 \usepackage{color}
6 \usepackage{alltt} 6 \usepackage{alltt}
45 \def\twiddle{\raisebox{0.3ex}{\mbox{\tiny $\sim$}}} 45 \def\twiddle{\raisebox{0.3ex}{\mbox{\tiny $\sim$}}}
46 46
47 \def\gap{\vspace{0.5ex}} 47 \def\gap{\vspace{0.5ex}}
48 \makeindex 48 \makeindex
49 \begin{document} 49 \begin{document}
50 \title{A Tiny Crypto Library, \\ LibTomCrypt \\ Version 0.96} 50 \title{LibTomCrypt \\ Version 0.99}
51 \author{Tom St Denis \\ 51 \author{Tom St Denis \\
52 \\ 52 \\
53 [email protected] \\ 53 [email protected] \\
54 http://libtomcrypt.org \\ \\ 54 http://libtomcrypt.org
55 Phone: 1-613-836-3160\\
56 111 Banning Rd \\
57 Kanata, Ontario \\
58 K2L 1C3 \\
59 Canada
60 } 55 }
61 \maketitle 56 \maketitle
62 This text and source code library are both hereby placed in the public domain. This book has been 57 This text and source code library are both hereby placed in the public domain. This book has been
63 formatted for B5 [176x250] paper using the \LaTeX{} {\em book} macro package. 58 formatted for A4 paper using the \LaTeX{} {\em book} macro package.
64 59
65 \vspace{10cm} 60 \vspace{10cm}
66 61
67 \begin{flushright}Open Source. Open Academia. Open Minds. 62 \begin{flushright}Open Source. Open Academia. Open Minds.
68 63
69 \mbox{ } 64 \mbox{ }
70 65
71 Tom St Denis, 66 Tom St Denis,
72 67
73 Ontario, Canada 68 Phone: 1-613-836-3160
69
70 111 Banning Rd
71
72 Kanata, Ontario
73
74 K2L 1C3
75
76 Canada
74 \end{flushright} 77 \end{flushright}
75 \newpage 78 \newpage
76 \tableofcontents 79 \tableofcontents
77 \chapter{Introduction} 80 \chapter{Introduction}
78 \section{What is the LibTomCrypt?} 81 \section{What is the LibTomCrypt?}
180 183
181 `mpi.c'' was originally written by Michael Fromberger ([email protected]) but has since been replaced with my LibTomMath 184 `mpi.c'' was originally written by Michael Fromberger ([email protected]) but has since been replaced with my LibTomMath
182 library. 185 library.
183 186
184 ``rc2.c'' is based on publicly available code that is not attributed to a person from the given source. ``safer.c'' 187 ``rc2.c'' is based on publicly available code that is not attributed to a person from the given source. ``safer.c''
185 was written by Richard De Moliner ([email protected]) and is public domain. 188 was written by Richard De Moliner ([email protected]) and seems to be free for use.
186 189
187 The project is hereby released as public domain. 190 The project is hereby released as public domain.
188 191
189 \section{Patent Disclosure} 192 \section{Patent Disclosure}
190 193
191 The author (Tom St Denis) is not a patent lawyer so this section is not to be treated as legal advice. To the best 194 The author (Tom St Denis) is not a patent lawyer so this section is not to be treated as legal advice. To the best
192 of the authors knowledge the only patent related issues within the library are the RC5 and RC6 symmetric block ciphers. 195 of the authors knowledge the only patent related issues within the library are the RC5 and RC6 symmetric block ciphers.
193 They can be removed from a build by simply commenting out the two appropriate lines in the makefile script. The rest 196 They can be removed from a build by simply commenting out the two appropriate lines in ``mycrypt\_custom.h''. The rest
194 of the ciphers and hashes are patent free or under patents that have since expired. 197 of the ciphers and hashes are patent free or under patents that have since expired.
195 198
196 The RC2 and RC4 symmetric ciphers are not under patents but are under trademark regulations. This means you can use 199 The RC2 and RC4 symmetric ciphers are not under patents but are under trademark regulations. This means you can use
197 the ciphers you just can't advertise that you are doing so. 200 the ciphers you just can't advertise that you are doing so.
198 201
199 \section{Building the library}
200
201 To build the library on a GCC equipped platform simply type ``make'' at your command prompt. It will build the library
202 file ``libtomcrypt.a''.
203
204 To install the library copy all of the ``.h'' files into your ``\#include'' path and the single libtomcrypt.a file into
205 your library path.
206
207 With MSVC you can build the library with ``nmake -f makefile.msvc''. This will produce a ``tomcrypt.lib'' file which
208 is the core library. Copy the header files into your MSVC include path and the library in the lib path (typically
209 under where VC98 is installed).
210
211 \section{Building against the library}
212
213 In the recent versions the build steps have changed. The build options are now stored in ``mycrypt\_custom.h'' and
214 no longer in the makefile. If you change a build option in that file you must re-build the library from clean to
215 ensure the build is intact. The perl script ``config.pl'' will help setup the custom header and a custom makefile
216 if you want one (the provided ``makefile'' will work with custom configs).
217
218 \section{Thanks} 202 \section{Thanks}
219 I would like to give thanks to the following people (in no particular order) for helping me develop this project: 203 I would like to give thanks to the following people (in no particular order) for helping me develop this project from
204 early on:
220 \begin{enumerate} 205 \begin{enumerate}
221 \item Richard van de Laarschot 206 \item Richard van de Laarschot
222 \item Richard Heathfield 207 \item Richard Heathfield
223 \item Ajay K. Agrawal 208 \item Ajay K. Agrawal
224 \item Brian Gladman 209 \item Brian Gladman
230 \item Wayne Scott 215 \item Wayne Scott
231 \item Andrew Tyler 216 \item Andrew Tyler
232 \item Sky Schulz 217 \item Sky Schulz
233 \item Christopher Imes 218 \item Christopher Imes
234 \end{enumerate} 219 \end{enumerate}
220
221 There have been quite a few other people as well. Please check the change log to see who else has contributed from
222 time to time.
223
235 224
236 \chapter{The Application Programming Interface (API)} 225 \chapter{The Application Programming Interface (API)}
237 \section{Introduction} 226 \section{Introduction}
238 \index{CRYPT\_ERROR} \index{CRYPT\_OK} 227 \index{CRYPT\_ERROR} \index{CRYPT\_OK}
239 228
579 \begin{small} 568 \begin{small}
580 \begin{center} 569 \begin{center}
581 \begin{tabular}{|l|l|l|} 570 \begin{tabular}{|l|l|l|}
582 \hline TWOFISH\_SMALL & TWOFISH\_TABLES & Speed and Memory (per key) \\ 571 \hline TWOFISH\_SMALL & TWOFISH\_TABLES & Speed and Memory (per key) \\
583 \hline undefined & undefined & Very fast, 4.2KB of ram. \\ 572 \hline undefined & undefined & Very fast, 4.2KB of ram. \\
584 \hline undefined & defined & As above, faster keysetup, larger code (1KB more). \\ 573 \hline undefined & defined & Faster keysetup, larger code. \\
585 \hline defined & undefined & Very slow, 0.2KB of ram. \\ 574 \hline defined & undefined & Very slow, 0.2KB of ram. \\
586 \hline defined & defined & Somewhat faster, 0.2KB of ram, larger code. \\ 575 \hline defined & defined & Faster, 0.2KB of ram, larger code. \\
587 \hline 576 \hline
588 \end{tabular} 577 \end{tabular}
589 \end{center} 578 \end{center}
590 \end{small} 579 \end{small}
591 580
613 printf("Unable to register Blowfish cipher."); 602 printf("Unable to register Blowfish cipher.");
614 return -1; 603 return -1;
615 } 604 }
616 605
617 /* generic call to function (assuming the key in key[] was already setup) */ 606 /* generic call to function (assuming the key in key[] was already setup) */
618 if ((err = cipher_descriptor[find_cipher("blowfish")].setup(key, 8, 0, &skey)) != CRYPT_OK) { 607 if ((err = cipher_descriptor[find_cipher("blowfish")].setup(key, 8, 0, &skey)) !=
608 CRYPT_OK) {
619 printf("Error setting up Blowfish: %s\n", error_to_string(err)); 609 printf("Error setting up Blowfish: %s\n", error_to_string(err));
620 return -1; 610 return -1;
621 } 611 }
622 612
623 /* ... use cipher ... */ 613 /* ... use cipher ... */
818 } 808 }
819 809
820 /* somehow fill out key and IV */ 810 /* somehow fill out key and IV */
821 811
822 /* start up CTR mode */ 812 /* start up CTR mode */
823 if ((err = ctr_start(find_cipher("twofish"), /* index of desired cipher */ 813 if ((err = ctr_start(
824 IV, /* the initial vector */ 814 find_cipher("twofish"), /* index of desired cipher */
825 key, /* the secret key */ 815 IV, /* the initial vector */
826 16, /* length of secret key (16 bytes, 128 bits) */ 816 key, /* the secret key */
827 0, /* 0 == default # of rounds */ 817 16, /* length of secret key (16 bytes, 128 bits) */
828 &ctr) /* where to store initialized CTR state */ 818 0, /* 0 == default # of rounds */
819 &ctr) /* where to store initialized CTR state */
829 ) != CRYPT_OK) { 820 ) != CRYPT_OK) {
830 printf("ctr_start error: %s\n", error_to_string(err)); 821 printf("ctr_start error: %s\n", error_to_string(err));
831 return -1; 822 return -1;
832 } 823 }
833 824
1343 \begin{verbatim} 1334 \begin{verbatim}
1344 int register_hash(const struct _hash_descriptor *hash); 1335 int register_hash(const struct _hash_descriptor *hash);
1345 int unregister_hash(const struct _hash_descriptor *hash); 1336 int unregister_hash(const struct _hash_descriptor *hash);
1346 \end{verbatim} 1337 \end{verbatim}
1347 1338
1348 \subsection{Notice} 1339 \section{Cipher Hash Construction}
1340 \index{Cipher Hash Construction}
1341 An addition to the suite of hash functions is the ``Cipher Hash Construction'' or ``CHC'' mode. In this mode
1342 applicable block ciphers (such as AES) can be turned into hash functions that other LTC functions can use. In
1343 particular this allows a cryptosystem to be designed using very few moving parts.
1344
1345 In order to use the CHC system the developer will have to take a few extra steps. First the ``chc\_desc'' hash
1346 descriptor must be registered with register\_hash(). At this point the CHC hash cannot be used to hash
1347 data. While it is in the hash system you still have to tell the CHC code which cipher to use. This is accomplished
1348 via the chc\_register() function.
1349
1350 \index{chc\_register()}
1351 \begin{verbatim}
1352 int chc_register(int cipher);
1353 \end{verbatim}
1354
1355 A cipher has to be registered with CHC (and also in the cipher descriptor tables with
1356 register\_cipher()). The chc\_register() function will bind a cipher to the CHC system. Only one cipher can
1357 be bound to the CHC hash at a time. There are additional requirements for the system to work.
1358
1359 \begin{enumerate}
1360 \item The cipher must have a block size greater than 64--bits.
1361 \item The cipher must allow an input key the size of the block size.
1362 \end{enumerate}
1363
1364 Example of using CHC with the AES block cipher.
1365
1366 \begin{verbatim}
1367 #include <mycrypt.h>
1368 int main(void)
1369 {
1370 int err;
1371
1372 /* register cipher and hash */
1373 if (register_cipher(&aes_enc_desc) == -1) {
1374 printf("Could not register cipher\n");
1375 return EXIT_FAILURE;
1376 }
1377 if (register_hash(&chc_desc) == -1) {
1378 printf("Could not register hash\n");
1379 return EXIT_FAILURE;
1380 }
1381
1382 /* start chc with AES */
1383 if ((err = chc_register(find_cipher("aes"))) != CRYPT_OK) {
1384 printf("Error binding AES to CHC: %s\n", error_to_string(err));
1385 }
1386
1387 /* now you can use chc_hash in any LTC function [aside from pkcs...] */
1388 /* ... */
1389 \end{verbatim}
1390
1391
1392 \section{Notice}
1349 It is highly recommended that you \textbf{not} use the MD4 or MD5 hashes for the purposes of digital signatures or authentication codes. 1393 It is highly recommended that you \textbf{not} use the MD4 or MD5 hashes for the purposes of digital signatures or authentication codes.
1350 These hashes are provided for completeness and they still can be used for the purposes of password hashing or one-way accumulators 1394 These hashes are provided for completeness and they still can be used for the purposes of password hashing or one-way accumulators
1351 (e.g. Yarrow). 1395 (e.g. Yarrow).
1352 1396
1353 The other hashes such as the SHA-1, SHA-2 (that includes SHA-512, SHA-384 and SHA-256) and TIGER-192 are still considered secure 1397 The other hashes such as the SHA-1, SHA-2 (that includes SHA-512, SHA-384 and SHA-256) and TIGER-192 are still considered secure
1676 int pmac_test(void); 1720 int pmac_test(void);
1677 \end{verbatim} 1721 \end{verbatim}
1678 Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code. 1722 Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code.
1679 1723
1680 1724
1725
1726
1727
1681 \chapter{Pseudo-Random Number Generators} 1728 \chapter{Pseudo-Random Number Generators}
1682 \section{Core Functions} 1729 \section{Core Functions}
1683
1684 The library provides an array of core functions for Pseudo-Random Number Generators (PRNGs) as well. A cryptographic PRNG is 1730 The library provides an array of core functions for Pseudo-Random Number Generators (PRNGs) as well. A cryptographic PRNG is
1685 used to expand a shorter bit string into a longer bit string. PRNGs are used wherever random data is required such as Public Key (PK) 1731 used to expand a shorter bit string into a longer bit string. PRNGs are used wherever random data is required such as Public Key (PK)
1686 key generation. There is a universal structure called ``prng\_state''. To initialize a PRNG call: 1732 key generation. There is a universal structure called ``prng\_state''. To initialize a PRNG call:
1733 \index{PRNG start}
1687 \begin{verbatim} 1734 \begin{verbatim}
1688 int XXX_start(prng_state *prng); 1735 int XXX_start(prng_state *prng);
1689 \end{verbatim} 1736 \end{verbatim}
1690 1737
1691 This will setup the PRNG for future use and not seed it. In order 1738 This will setup the PRNG for future use and not seed it. In order
1692 for the PRNG to be cryptographically useful you must give it entropy. Ideally you'd have some OS level source to tap 1739 for the PRNG to be cryptographically useful you must give it entropy. Ideally you'd have some OS level source to tap
1693 like in UNIX (see section 5.3). To add entropy to the PRNG call: 1740 like in UNIX (see section 5.3). To add entropy to the PRNG call:
1741 \index{PRNG add\_entropy}
1694 \begin{verbatim} 1742 \begin{verbatim}
1695 int XXX_add_entropy(const unsigned char *in, unsigned long len, 1743 int XXX_add_entropy(const unsigned char *in, unsigned long len,
1696 prng_state *prng); 1744 prng_state *prng);
1697 \end{verbatim} 1745 \end{verbatim}
1698 1746
1699 Which returns {\bf CRYPTO\_OK} if the entropy was accepted. Once you think you have enough entropy you call another 1747 Which returns {\bf CRYPTO\_OK} if the entropy was accepted. Once you think you have enough entropy you call another
1700 function to put the entropy into action. 1748 function to put the entropy into action.
1749 \index{PRNG ready}
1701 \begin{verbatim} 1750 \begin{verbatim}
1702 int XXX_ready(prng_state *prng); 1751 int XXX_ready(prng_state *prng);
1703 \end{verbatim} 1752 \end{verbatim}
1704 1753
1705 Which returns {\bf CRYPTO\_OK} if it is ready. Finally to actually read bytes call: 1754 Which returns {\bf CRYPTO\_OK} if it is ready. Finally to actually read bytes call:
1755 \index{PRNG read}
1706 \begin{verbatim} 1756 \begin{verbatim}
1707 unsigned long XXX_read(unsigned char *out, unsigned long len, 1757 unsigned long XXX_read(unsigned char *out, unsigned long len,
1708 prng_state *prng); 1758 prng_state *prng);
1709 \end{verbatim} 1759 \end{verbatim}
1710 1760
1711 Which returns the number of bytes read from the PRNG. 1761 Which returns the number of bytes read from the PRNG. When you are finished with a PRNG state you call
1762 the following.
1763
1764 \index{PRNG done}
1765 \begin{verbatim}
1766 void XXX_done(prng_state *prng);
1767 \end{verbatim}
1768
1769 This will terminate a PRNG state and free any memory (if any) allocated. To export a PRNG state
1770 so that you can later resume the PRNG call the following.
1771
1772 \index{PRNG export}
1773 \begin{verbatim}
1774 int XXX_export(unsigned char *out, unsigned long *outlen,
1775 prng_state *prng);
1776 \end{verbatim}
1777
1778 This will write a ``PRNG state'' to the buffer ``out'' of length ``outlen'' bytes. The idea of
1779 the export is meant to be used as a ``seed file''. That is, when the program starts up there will not likely
1780 be that much entropy available. To import a state to seed a PRNG call the following function.
1781
1782 \index{PRNG import}
1783 \begin{verbatim}
1784 int XXX_import(const unsigned char *in, unsigned long inlen,
1785 prng_state *prng);
1786 \end{verbatim}
1787
1788 This will call the start and add\_entropy functions of the given PRNG. It will use the state in
1789 ``in'' of length ``inlen'' as the initial seed. You must pass the same seed length as was exported
1790 by the corresponding export function.
1791
1792 Note that importing a state will not ``resume'' the PRNG from where it left off. That is, if you export
1793 a state, emit (say) 8 bytes and then import the previously exported state the next 8 bytes will not
1794 specifically equal the 8 bytes you generated previously.
1795
1796 When a program is first executed the normal course of operation is
1797
1798 \begin{enumerate}
1799 \item Gather entropy from your sources for a given period of time or number of events.
1800 \item Start, use your entropy via add\_entropy and ready the PRNG yourself.
1801 \end{enumerate}
1802
1803 When your program is finished you simply call the export function and save the state to a medium (disk,
1804 flash memory, etc). The next time your application starts up you can detect the state, feed it to the
1805 import function and go on your way. It is ideal that (as soon as possible) after startup you export a
1806 fresh state. This helps in the case that the program aborts or the machine is powered down without
1807 being given a chance to exit properly.
1808
1809 Note that even if you have a state to import it is important to add new entropy to the state. However,
1810 there is less pressure to do so.
1811
1812 To test a PRNG for operational conformity call the following functions.
1813
1814 \index{PRNG test}
1815 \begin{verbatim}
1816 int XXX_test(void);
1817 \end{verbatim}
1818
1819 This will return \textbf{CRYPT\_OK} if PRNG is operating properly.
1712 1820
1713 \subsection{Remarks} 1821 \subsection{Remarks}
1714 1822
1715 It is possible to be adding entropy and reading from a PRNG at the same time. For example, if you first seed the PRNG 1823 It is possible to be adding entropy and reading from a PRNG at the same time. For example, if you first seed the PRNG
1716 and call ready() you can now read from it. You can also keep adding new entropy to it. The new entropy will not be used 1824 and call ready() you can now read from it. You can also keep adding new entropy to it. The new entropy will not be used
1717 in the PRNG until ready() is called again. This allows the PRNG to be used and re-seeded at the same time. No real error 1825 in the PRNG until ready() is called again. This allows the PRNG to be used and re-seeded at the same time. No real error
1718 checking is guaranteed to see if the entropy is sufficient or if the PRNG is even in a ready state before reading. 1826 checking is guaranteed to see if the entropy is sufficient or if the PRNG is even in a ready state before reading.
1719 1827
1720 \subsection{Example} 1828 \subsection{Example}
1721 1829
1722 Below is a simple snippet to read 10 bytes from yarrow. Its important to note that this snippet is {\bf NOT} secure since 1830 Below is a simple snippet to read 10 bytes from yarrow. Its important to note that this snippet is
1723 the entropy added is not random. 1831 {\bf NOT} secure since the entropy added is not random.
1724 1832
1725 \begin{verbatim} 1833 \begin{verbatim}
1726 #include <mycrypt.h> 1834 #include <mycrypt.h>
1727 int main(void) 1835 int main(void)
1728 { 1836 {
1751 \index{PRNG Descriptor} 1859 \index{PRNG Descriptor}
1752 PRNGs have descriptors too (surprised?). Stored in the structure ``prng\_descriptor''. The format of an element is: 1860 PRNGs have descriptors too (surprised?). Stored in the structure ``prng\_descriptor''. The format of an element is:
1753 \begin{verbatim} 1861 \begin{verbatim}
1754 struct _prng_descriptor { 1862 struct _prng_descriptor {
1755 char *name; 1863 char *name;
1864 int export_size; /* size in bytes of exported state */
1756 int (*start) (prng_state *); 1865 int (*start) (prng_state *);
1757 int (*add_entropy)(const unsigned char *, unsigned long, prng_state *); 1866 int (*add_entropy)(const unsigned char *, unsigned long, prng_state *);
1758 int (*ready) (prng_state *); 1867 int (*ready) (prng_state *);
1759 unsigned long (*read)(unsigned char *, unsigned long len, prng_state *); 1868 unsigned long (*read)(unsigned char *, unsigned long len, prng_state *);
1869 void (*done)(prng_state *);
1870 int (*export)(unsigned char *, unsigned long *, prng_state *);
1871 int (*import)(const unsigned char *, unsigned long, prng_state *);
1872 int (*test)(void);
1760 }; 1873 };
1761 \end{verbatim} 1874 \end{verbatim}
1762 1875
1763 There is a ``int find\_prng(char *name)'' function as well. Returns -1 if the PRNG is not found, otherwise it returns 1876 There is a ``int find\_prng(char *name)'' function as well. Returns -1 if the PRNG is not found, otherwise it returns
1764 the position in the prng\_descriptor array. 1877 the position in the prng\_descriptor array.
1768 \begin{verbatim} 1881 \begin{verbatim}
1769 int register_prng(const struct _prng_descriptor *prng); 1882 int register_prng(const struct _prng_descriptor *prng);
1770 int unregister_prng(const struct _prng_descriptor *prng); 1883 int unregister_prng(const struct _prng_descriptor *prng);
1771 \end{verbatim} 1884 \end{verbatim}
1772 1885
1773 \subsubsection{PRNGs Provided} 1886 \subsection{PRNGs Provided}
1774 Currently Yarrow (yarrow\_desc), RC4 (rc4\_desc) and the secure RNG (sprng\_desc) are provided as PRNGs within the 1887 \begin{figure}[here]
1775 library. 1888 \begin{center}
1776 1889 \begin{small}
1777 RC4 is provided with a PRNG interface because it is a stream cipher and not well suited for the symmetric block cipher 1890 \begin{tabular}{|c|c|l|}
1778 interface. You provide the key for RC4 via the rc4\_add\_entropy() function. By calling rc4\_ready() the key will be used 1891 \hline \textbf{Name} & \textbf{Descriptor} & \textbf{Usage} \\
1779 to setup the RC4 state for encryption or decryption. The rc4\_read() function has been modified from RC4 since it will 1892 \hline Yarrow & yarrow\_desc & Fast short-term PRNG \\
1780 XOR the output of the RC4 keystream generator against the input buffer you provide. The following snippet will demonstrate 1893 \hline Fortuna & fortuna\_desc & Fast long-term PRNG (recommended) \\
1781 how to encrypt a buffer with RC4: 1894 \hline RC4 & rc4\_desc & Stream Cipher \\
1782 1895 \hline SOBER-128 & sober128\_desc & Stream Cipher (also very fast PRNG) \\
1896 \hline
1897 \end{tabular}
1898 \end{small}
1899 \end{center}
1900 \caption{List of Provided PRNGs}
1901 \end{figure}
1902
1903 \subsubsection{Yarrow}
1904 Yarrow is fast PRNG meant to collect an unspecified amount of entropy from sources
1905 (keyboard, mouse, interrupts, etc) and produce an unbounded string of random bytes.
1906
1907 \textit{Note:} This PRNG is still secure for most taskings but is no longer recommended. Users
1908 should use Fortuna instead.
1909
1910 \subsubsection{Fortuna}
1911
1912 Fortuna is a fast attack tolerant and more thoroughly designed PRNG suitable for long term
1913 usage. It is faster than the default implementation of Yarrow\footnote{Yarrow has been implemented
1914 to work with most cipher and hash combos based on which you have chosen to build into the library.} while
1915 providing more security.
1916
1917 Fortuna is slightly less flexible than Yarrow in the sense that it only works with the AES block cipher
1918 and SHA--256 hash function. Technically Fortuna will work with any block cipher that accepts a 256--bit
1919 key and any hash that produces at least a 256--bit output. However, to make the implementation simpler
1920 it has been fixed to those choices.
1921
1922 Fortuna is more secure than Yarrow in the sense that attackers who learn parts of the entropy being
1923 added to the PRNG learn far less about the state than that of Yarrow. Without getting into to many
1924 details Fortuna has the ability to recover from state determination attacks where the attacker starts
1925 to learn information from the PRNGs output about the internal state. Yarrow on the other hand cannot
1926 recover from that problem until new entropy is added to the pool and put to use through the ready() function.
1927
1928 \subsubsection{RC4}
1929
1930 RC4 is an old stream cipher that can also double duty as a PRNG in a pinch. You ``key'' it by
1931 calling add\_entropy() and setup the key by calling ready(). You can only add upto 256 bytes via
1932 add\_entropy().
1933
1934 When you read from RC4 the output of the RC4 algorithm is XOR'd against your buffer you provide. In this
1935 manner you can use rc4\_read() as an encrypt (and decrypt) function.
1936
1937 You really shouldn't use RC4 anymore. This isn't because RC4 is weak (though biases are known to exist) just
1938 simply that faster alternatives exist.
1939
1940 \subsubsection{SOBER-128}
1941
1942 SOBER-128 is a stream cipher designed by the QUALCOMM Australia team. Like RC4 you ``key'' it by
1943 calling add\_entropy(). There is no need to call ready() for this PRNG as it does not do anything.
1944
1945 Note that this cipher has several oddities about how it operates. The first time you call
1946 add\_entropy() that sets the cipher's key. Every other time you call the same function it sets
1947 the cipher's IV variable. The IV mechanism allows you to encrypt several messages with the same
1948 key and not re--use the same key material.
1949
1950 Unlike Yarrow and Fortuna all of the entropy (and hence security) of this algorithm rests in the data
1951 you pass it on the first call to add\_entropy(). All buffers sent to add\_entropy() must have a length
1952 that is a multiple of four bytes.
1953
1954 Like RC4 the output of SOBER--128 is XOR'ed against the buffer you provide it. In this manner you can use
1955 sober128\_read() as an encrypt (and decrypt) function.
1956
1957 Since SOBER-128 has a fixed keying scheme and is very fast (faster than RC4) the ideal usage of SOBER-128 is to
1958 key it from the output of Fortuna (or Yarrow) and use it to encrypt messages. It is also ideal for
1959 simulations which need a high quality (and fast) stream of bytes.
1960
1961 \subsubsection{Example Usage}
1783 \begin{small} 1962 \begin{small}
1784 \begin{verbatim} 1963 \begin{verbatim}
1785 #include <mycrypt.h> 1964 #include <mycrypt.h>
1786 int main(void) 1965 int main(void)
1787 { 1966 {
2114 2293
2115 Note that the ``rsa\_make\_key()'' function allocates memory at runtime when you make the key. Make sure to call 2294 Note that the ``rsa\_make\_key()'' function allocates memory at runtime when you make the key. Make sure to call
2116 ``rsa\_free()'' (see below) when you are finished with the key. If ``rsa\_make\_key()'' fails it will automatically 2295 ``rsa\_free()'' (see below) when you are finished with the key. If ``rsa\_make\_key()'' fails it will automatically
2117 free the ram allocated itself. 2296 free the ram allocated itself.
2118 2297
2119 There are three types of RSA keys. The types are {\bf PK\_PRIVATE\_OPTIMIZED}, {\bf PK\_PRIVATE} and {\bf PK\_PUBLIC}. The first 2298 \index{PK\_PRIVATE} \index{PK\_PUBLIC}
2120 two are private keys where the ``optimized'' type uses the Chinese Remainder Theorem to speed up decryption/signatures. By 2299 There are two types of RSA keys. The types are {\bf PK\_PRIVATE} and {\bf PK\_PUBLIC}. The first type is a private
2121 default all new keys are of the ``optimized'' type. The non-optimized private type is provided for backwards compatibility 2300 RSA key which includes the CRT parameters\footnote{As of v0.99 the PK\_PRIVATE\_OPTIMIZED type has been deprecated
2122 as well as to save space since the optimized key requires about four times as much memory. 2301 and has been replaced by the PK\_PRIVATE type.} in the form of a RSAPrivateKey. The second type is a public RSA key
2302 which only includes the modulus and public exponent. It takes the form of a RSAPublicKey.
2123 2303
2124 \subsection{RSA Exponentiation} 2304 \subsection{RSA Exponentiation}
2125 2305
2126 To do raw work with the RSA function call: 2306 To do raw work with the RSA function call:
2127 \index{rsa\_exptmod()} 2307 \index{rsa\_exptmod()}
2270 } 2450 }
2271 /* if all went well pt == pt2, l2 == 16, res == 1 */ 2451 /* if all went well pt == pt2, l2 == 16, res == 1 */
2272 } 2452 }
2273 \end{verbatim} 2453 \end{verbatim}
2274 2454
2275 \chapter{Password Based Cryptography} 2455
2276 \section{PKCS \#5} 2456 \chapter{Diffie-Hellman Key Exchange}
2457
2458 \section{Background}
2459
2460 Diffie-Hellman was the original public key system proposed. The system is based upon the group structure
2461 of finite fields. For Diffie-Hellman a prime $p$ is chosen and a ``base'' $b$ such that $b^x\mbox{ }(\mbox{mod }p)$
2462 generates a large sub-group of prime order (for unique values of $x$).
2463
2464 A secret key is an exponent $x$ and a public key is the value of $y \equiv g^x\mbox{ }(\mbox{mod }p)$. The term
2465 ``discrete logarithm'' denotes the action of finding $x$ given only $y$, $g$ and $p$. The key exchange part of
2466 Diffie-Hellman arises from the fact that two users A and B with keys $(A_x, A_y)$ and $(B_x, B_y)$ can exchange
2467 a shared key $K \equiv B_y^{A_x} \equiv A_y^{B_x} \equiv g^{A_xB_x}\mbox{ }(\mbox{mod }p)$.
2468
2469 From this public encryption and signatures can be developed. The trivial way to encrypt (for example) using a public key
2470 $y$ is to perform the key exchange offline. The sender invents a key $k$ and its public copy
2471 $k' \equiv g^k\mbox{ }(\mbox{mod }p)$ and uses $K \equiv k'^{A_x}\mbox{ }(\mbox{mod }p)$ as a key to encrypt
2472 the message with. Typically $K$ would be sent to a one-way hash and the message digested used as a key in a
2473 symmetric cipher.
2474
2475 It is important that the order of the sub-group that $g$ generates not only be large but also prime. There are
2476 discrete logarithm algorithms that take $\sqrt r$ time given the order $r$. The discrete logarithm can be computed
2477 modulo each prime factor of $r$ and the results combined using the Chinese Remainder Theorem. In the cases where
2478 $r$ is ``B-Smooth'' (e.g. all small factors or powers of small prime factors) the solution is trivial to find.
2479
2480 To thwart such attacks the primes and bases in the library have been designed and fixed. Given a prime $p$ the order of
2481 the sub-group generated is a large prime namely ${p - 1} \over 2$. Such primes are known as ``strong primes'' and the
2482 smaller prime (e.g. the order of the base) are known as Sophie-Germaine primes.
2483
2484 \section{Core Functions}
2485
2486 This library also provides core Diffie-Hellman functions so you can negotiate keys over insecure mediums. The routines
2487 provided are relatively easy to use and only take two function calls to negotiate a shared key. There is a structure
2488 called ``dh\_key'' which stores the Diffie-Hellman key in a format these routines can use. The first routine is to
2489 make a Diffie-Hellman private key pair:
2490 \index{dh\_make\_key()}
2491 \begin{verbatim}
2492 int dh_make_key(prng_state *prng, int wprng,
2493 int keysize, dh_key *key);
2494 \end{verbatim}
2495 The ``keysize'' is the size of the modulus you want in bytes. Currently support sizes are 96 to 512 bytes which correspond
2496 to key sizes of 768 to 4096 bits. The smaller the key the faster it is to use however it will be less secure. When
2497 specifying a size not explicitly supported by the library it will round {\em up} to the next key size. If the size is
2498 above 512 it will return an error. So if you pass ``keysize == 32'' it will use a 768 bit key but if you pass
2499 ``keysize == 20000'' it will return an error. The primes and generators used are built-into the library and were designed
2500 to meet very specific goals. The primes are strong primes which means that if $p$ is the prime then
2501 $p-1$ is equal to $2r$ where $r$ is a large prime. The bases are chosen to generate a group of order $r$ to prevent
2502 leaking a bit of the key. This means the bases generate a very large prime order group which is good to make cryptanalysis
2503 hard.
2504
2505 The next two routines are for exporting/importing Diffie-Hellman keys in a binary format. This is useful for transport
2506 over communication mediums.
2507
2508 \index{dh\_export()} \index{dh\_import()}
2509 \begin{verbatim}
2510 int dh_export(unsigned char *out, unsigned long *outlen,
2511 int type, dh_key *key);
2512
2513 int dh_import(const unsigned char *in, unsigned long inlen, dh_key *key);
2514 \end{verbatim}
2515
2516 These two functions work just like the ``rsa\_export()'' and ``rsa\_import()'' functions except these work with
2517 Diffie-Hellman keys. Its important to note you do not have to free the ram for a ``dh\_key'' if an import fails. You can free a
2518 ``dh\_key'' using:
2519 \begin{verbatim}
2520 void dh_free(dh_key *key);
2521 \end{verbatim}
2522 After you have exported a copy of your public key (using {\bf PK\_PUBLIC} as ``type'') you can now create a shared secret
2523 with the other user using:
2524 \index{dh\_shared\_secret()}
2525 \begin{verbatim}
2526 int dh_shared_secret(dh_key *private_key,
2527 dh_key *public_key,
2528 unsigned char *out, unsigned long *outlen);
2529 \end{verbatim}
2530
2531 Where ``private\_key'' is the key you made and ``public\_key'' is the copy of the public key the other user sent you. The result goes
2532 into ``out'' and the length into ``outlen''. If all went correctly the data in ``out'' should be identical for both parties. It is important to
2533 note that the two keys have to be the same size in order for this to work. There is a function to get the size of a
2534 key:
2535 \index{dh\_get\_size()}
2536 \begin{verbatim}
2537 int dh_get_size(dh_key *key);
2538 \end{verbatim}
2539 This returns the size in bytes of the modulus chosen for that key.
2540
2541 \subsection{Remarks on Usage}
2542 Its important that you hash the shared key before trying to use it as a key for a symmetric cipher or something. An
2543 example program that communicates over sockets, using MD5 and 1024-bit DH keys is\footnote{This function is a small example. It is suggested that proper packaging be used. For example, if the public key sent is truncated these routines will not detect that.}:
2544 \newpage
2545 \begin{small}
2546 \begin{verbatim}
2547 int establish_secure_socket(int sock, int mode, unsigned char *key,
2548 prng_state *prng, int wprng)
2549 {
2550 unsigned char buf[4096], buf2[4096];
2551 unsigned long x, len;
2552 int res, err, inlen;
2553 dh_key mykey, theirkey;
2554
2555 /* make up our private key */
2556 if ((err = dh_make_key(prng, wprng, 128, &mykey)) != CRYPT_OK) {
2557 return err;
2558 }
2559
2560 /* export our key as public */
2561 x = sizeof(buf);
2562 if ((err = dh_export(buf, &x, PK_PUBLIC, &mykey)) != CRYPT_OK) {
2563 res = err;
2564 goto done2;
2565 }
2566
2567 if (mode == 0) {
2568 /* mode 0 so we send first */
2569 if (send(sock, buf, x, 0) != x) {
2570 res = CRYPT_ERROR;
2571 goto done2;
2572 }
2573
2574 /* get their key */
2575 if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
2576 res = CRYPT_ERROR;
2577 goto done2;
2578 }
2579 } else {
2580 /* mode >0 so we send second */
2581 if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
2582 res = CRYPT_ERROR;
2583 goto done2;
2584 }
2585
2586 if (send(sock, buf, x, 0) != x) {
2587 res = CRYPT_ERROR;
2588 goto done2;
2589 }
2590 }
2591
2592 if ((err = dh_import(buf2, inlen, &theirkey)) != CRYPT_OK) {
2593 res = err;
2594 goto done2;
2595 }
2596
2597 /* make shared secret */
2598 x = sizeof(buf);
2599 if ((err = dh_shared_secret(&mykey, &theirkey, buf, &x)) != CRYPT_OK) {
2600 res = err;
2601 goto done;
2602 }
2603
2604 /* hash it */
2605 len = 16; /* default is MD5 so "key" must be at least 16 bytes long */
2606 if ((err = hash_memory(find_hash("md5"), buf, x, key, &len)) != CRYPT_OK) {
2607 res = err;
2608 goto done;
2609 }
2610
2611 /* clean up and return */
2612 res = CRYPT_OK;
2613 done:
2614 dh_free(&theirkey);
2615 done2:
2616 dh_free(&mykey);
2617 zeromem(buf, sizeof(buf));
2618 zeromem(buf2, sizeof(buf2));
2619 return res;
2620 }
2621 \end{verbatim}
2622 \end{small}
2623 \newpage
2624 \subsection{Remarks on The Snippet}
2625 When the above code snippet is done (assuming all went well) their will be a shared 128-bit key in the ``key'' array
2626 passed to ``establish\_secure\_socket()''.
2627
2628 \section{Other Diffie-Hellman Functions}
2629 In order to test the Diffie-Hellman function internal workings (e.g. the primes and bases) their is a test function made
2630 available:
2631 \index{dh\_test()}
2632 \begin{verbatim}
2633 int dh_test(void);
2634 \end{verbatim}
2635
2636 This function returns {\bf CRYPT\_OK} if the bases and primes in the library are correct. There is one last helper
2637 function:
2638 \index{dh\_sizes()}
2639 \begin{verbatim}
2640 void dh_sizes(int *low, int *high);
2641 \end{verbatim}
2642 Which stores the smallest and largest key sizes support into the two variables.
2643
2644 \section{DH Packet}
2645 Similar to the RSA related functions there are functions to encrypt or decrypt symmetric keys using the DH public key
2646 algorithms.
2647 \index{dh\_encrypt\_key()} \index{dh\_decrypt\_key()}
2648 \begin{verbatim}
2649 int dh_encrypt_key(const unsigned char *inkey, unsigned long keylen,
2650 unsigned char *out, unsigned long *len,
2651 prng_state *prng, int wprng, int hash,
2652 dh_key *key);
2653
2654 int dh_decrypt_key(const unsigned char *in, unsigned long inlen,
2655 unsigned char *outkey, unsigned long *keylen,
2656 dh_key *key);
2657 \end{verbatim}
2658 Where ``inkey'' is an input symmetric key of no more than 32 bytes. Essentially these routines created a random public key
2659 and find the hash of the shared secret. The message digest is than XOR'ed against the symmetric key. All of the
2660 required data is placed in ``out'' by ``dh\_encrypt\_key()''. The hash must produce a message digest at least as large
2661 as the symmetric key you are trying to share.
2662
2663 Similar to the RSA system you can sign and verify a hash of a message.
2664 \index{dh\_sign\_hash()} \index{dh\_verify\_hash()}
2665 \begin{verbatim}
2666 int dh_sign_hash(const unsigned char *in, unsigned long inlen,
2667 unsigned char *out, unsigned long *outlen,
2668 prng_state *prng, int wprng, dh_key *key);
2669
2670 int dh_verify_hash(const unsigned char *sig, unsigned long siglen,
2671 const unsigned char *hash, unsigned long hashlen,
2672 int *stat, dh_key *key);
2673 \end{verbatim}
2674
2675 The ``dh\_sign\_hash'' function signs the message hash in ``in'' of length ``inlen'' and forms a DH packet in ``out''.
2676 The ``dh\_verify\_hash'' function verifies the DH signature in ``sig'' against the hash in ``hash''. It sets ``stat''
2677 to non-zero if the signature passes or zero if it fails.
2678
2679 \chapter{Elliptic Curve Cryptography}
2680
2681 \section{Background}
2682 The library provides a set of core ECC functions as well that are designed to be the Elliptic Curve analogy of all of the
2683 Diffie-Hellman routines in the previous chapter. Elliptic curves (of certain forms) have the benefit that they are harder
2684 to attack (no sub-exponential attacks exist unlike normal DH crypto) in fact the fastest attack requires the square root
2685 of the order of the base point in time. That means if you use a base point of order $2^{192}$ (which would represent a
2686 192-bit key) then the work factor is $2^{96}$ in order to find the secret key.
2687
2688 The curves in this library are taken from the following website:
2689 \begin{verbatim}
2690 http://csrc.nist.gov/cryptval/dss.htm
2691 \end{verbatim}
2692
2693 They are all curves over the integers modulo a prime. The curves have the basic equation that is:
2694 \begin{equation}
2695 y^2 = x^3 - 3x + b\mbox{ }(\mbox{mod }p)
2696 \end{equation}
2697
2698 The variable $b$ is chosen such that the number of points is nearly maximal. In fact the order of the base points $\beta$
2699 provided are very close to $p$ that is $\vert \vert \phi(\beta) \vert \vert \approx \vert \vert p \vert \vert$. The curves
2700 range in order from $\approx 2^{192}$ points to $\approx 2^{521}$. According to the source document any key size greater
2701 than or equal to 256-bits is sufficient for long term security.
2702
2703 \section{Core Functions}
2704
2705 Like the DH routines there is a key structure ``ecc\_key'' used by the functions. There is a function to make a key:
2706 \index{ecc\_make\_key()}
2707 \begin{verbatim}
2708 int ecc_make_key(prng_state *prng, int wprng,
2709 int keysize, ecc_key *key);
2710 \end{verbatim}
2711
2712 The ``keysize'' is the size of the modulus in bytes desired. Currently directly supported values are 20, 24, 28, 32, 48 and 65 bytes which
2713 correspond to key sizes of 160, 192, 224, 256, 384 and 521 bits respectively. If you pass a key size that is between any key size
2714 it will round the keysize up to the next available one. The rest of the parameters work like they do in the ``dh\_make\_key()'' function.
2715 To free the ram allocated by a key call:
2716 \index{ecc\_free()}
2717 \begin{verbatim}
2718 void ecc_free(ecc_key *key);
2719 \end{verbatim}
2720
2721 To import and export a key there are:
2722 \index{ecc\_export()}
2723 \index{ecc\_import()}
2724 \begin{verbatim}
2725 int ecc_export(unsigned char *out, unsigned long *outlen,
2726 int type, ecc_key *key);
2727
2728 int ecc_import(const unsigned char *in, unsigned long inlen, ecc_key *key);
2729 \end{verbatim}
2730 These two work exactly like there DH counterparts. Finally when you share your public key you can make a shared secret
2731 with:
2732 \index{ecc\_shared\_secret()}
2733 \begin{verbatim}
2734 int ecc_shared_secret(ecc_key *private_key,
2735 ecc_key *public_key,
2736 unsigned char *out, unsigned long *outlen);
2737 \end{verbatim}
2738 Which works exactly like the DH counterpart, the ``private\_key'' is your own key and ``public\_key'' is the key the other
2739 user sent you. Note that this function stores both $x$ and $y$ co-ordinates of the shared
2740 elliptic point. You should hash the output to get a shared key in a more compact and useful form (most of the entropy is
2741 in $x$ anyways). Both keys have to be the same size for this to work, to help there is a function to get the size in bytes
2742 of a key.
2743 \index{ecc\_get\_size()}
2744 \begin{verbatim}
2745 int ecc_get_size(ecc_key *key);
2746 \end{verbatim}
2747
2748 To test the ECC routines and to get the minimum and maximum key sizes there are these two functions:
2749 \index{ecc\_test()}
2750 \begin{verbatim}
2751 int ecc_test(void);
2752 void ecc_sizes(int *low, int *high);
2753 \end{verbatim}
2754 Which both work like their DH counterparts.
2755
2756 \section{ECC Packet}
2757 Similar to the RSA API there are two functions which encrypt and decrypt symmetric keys using the ECC public key
2758 algorithms.
2759
2760 \index{ecc\_encrypt\_key()} \index{ecc\_decrypt\_key()}
2761 \begin{verbatim}
2762 int ecc_encrypt_key(const unsigned char *inkey, unsigned long keylen,
2763 unsigned char *out, unsigned long *len,
2764 prng_state *prng, int wprng, int hash,
2765 ecc_key *key);
2766
2767 int ecc_decrypt_key(const unsigned char *in, unsigned long inlen,
2768 unsigned char *outkey, unsigned long *keylen,
2769 ecc_key *key);
2770 \end{verbatim}
2771
2772 Where ``inkey'' is an input symmetric key of no more than 32 bytes. Essentially these routines created a random public key
2773 and find the hash of the shared secret. The message digest is than XOR'ed against the symmetric key. All of the required
2774 data is placed in ``out'' by ``ecc\_encrypt\_key()''. The hash chosen must produce a message digest at least as large
2775 as the symmetric key you are trying to share.
2776
2777 There are also functions to sign and verify the hash of a message.
2778 \index{ecc\_sign\_hash()} \index{ecc\_verify\_hash()}
2779 \begin{verbatim}
2780 int ecc_sign_hash(const unsigned char *in, unsigned long inlen,
2781 unsigned char *out, unsigned long *outlen,
2782 prng_state *prng, int wprng, ecc_key *key);
2783
2784 int ecc_verify_hash(const unsigned char *sig, unsigned long siglen,
2785 const unsigned char *hash, unsigned long hashlen,
2786 int *stat, ecc_key *key);
2787 \end{verbatim}
2788
2789 The ``ecc\_sign\_hash'' function signs the message hash in ``in'' of length ``inlen'' and forms a ECC packet in ``out''.
2790 The ``ecc\_verify\_hash'' function verifies the ECC signature in ``sig'' against the hash in ``hash''. It sets ``stat''
2791 to non-zero if the signature passes or zero if it fails.
2792
2793
2794 \section{ECC Keysizes}
2795 With ECC if you try and sign a hash that is bigger than your ECC key you can run into problems. The math will still work
2796 and in effect the signature will still work. With ECC keys the strength of the signature is limited by the size of
2797 the hash or the size of they key, whichever is smaller. For example, if you sign with SHA256 and a ECC-160 key in effect
2798 you have 160-bits of security (e.g. as if you signed with SHA-1).
2799
2800 The library will not warn you if you make this mistake so it is important to check yourself before using the
2801 signatures.
2802
2803 \chapter{Digital Signature Algorithm}
2804 \section{Introduction}
2805 The Digital Signature Algorithm (or DSA) is a variant of the ElGamal Signature scheme which has been modified to
2806 reduce the bandwidth of a signature. For example, to have ``80-bits of security'' with ElGamal you need a group of
2807 order at least 1024-bits. With DSA you need a group of order at least 160-bits. By comparison the ElGamal signature
2808 would require at least 256 bytes where as the DSA signature would require only at least 40 bytes.
2809
2810 The API for the DSA is essentially the same as the other PK algorithms. Except in the case of DSA no encryption or
2811 decryption routines are provided.
2812
2813 \section{Key Generation}
2814 To make a DSA key you must call the following function
2815 \begin{verbatim}
2816 int dsa_make_key(prng_state *prng, int wprng,
2817 int group_size, int modulus_size,
2818 dsa_key *key);
2819 \end{verbatim}
2820 The variable ``prng'' is an active PRNG state and ``wprng'' the index to the descriptor. ``group\_size'' and
2821 ``modulus\_size'' control the difficulty of forging a signature. Both parameters are in bytes. The larger the
2822 ``group\_size'' the more difficult a forgery becomes upto a limit. The value of $group\_size$ is limited by
2823 $15 < group\_size < 1024$ and $modulus\_size - group\_size < 512$. Suggested values for the pairs are as follows.
2824
2825 \begin{center}
2826 \begin{tabular}{|c|c|c|}
2827 \hline \textbf{Bits of Security} & \textbf{group\_size} & \textbf{modulus\_size} \\
2828 \hline 80 & 20 & 128 \\
2829 \hline 120 & 30 & 256 \\
2830 \hline 140 & 35 & 384 \\
2831 \hline 160 & 40 & 512 \\
2832 \hline
2833 \end{tabular}
2834 \end{center}
2835
2836 When you are finished with a DSA key you can call the following function to free the memory used.
2837 \index{dsa\_free()}
2838 \begin{verbatim}
2839 void dsa_free(dsa_key *key);
2840 \end{verbatim}
2841
2842 \section{Key Verification}
2843 Each DSA key is composed of the following variables.
2844
2845 \begin{enumerate}
2846 \item $q$ a small prime of magnitude $256^{group\_size}$.
2847 \item $p = qr + 1$ a large prime of magnitude $256^{modulus\_size}$ where $r$ is a random even integer.
2848 \item $g = h^r \mbox{ (mod }p\mbox{)}$ a generator of order $q$ modulo $p$. $h$ can be any non-trivial random
2849 value. For this library they start at $h = 2$ and step until $g$ is not $1$.
2850 \item $x$ a random secret (the secret key) in the range $1 < x < q$
2851 \item $y = g^x \mbox{ (mod }p\mbox{)}$ the public key.
2852 \end{enumerate}
2853
2854 A DSA key is considered valid if it passes all of the following tests.
2855
2856 \begin{enumerate}
2857 \item $q$ must be prime.
2858 \item $p$ must be prime.
2859 \item $g$ cannot be one of $\lbrace -1, 0, 1 \rbrace$ (modulo $p$).
2860 \item $g$ must be less than $p$.
2861 \item $(p-1) \equiv 0 \mbox{ (mod }q\mbox{)}$.
2862 \item $g^q \equiv 1 \mbox{ (mod }p\mbox{)}$.
2863 \item $1 < y < p - 1$
2864 \item $y^q \equiv 1 \mbox{ (mod }p\mbox{)}$.
2865 \end{enumerate}
2866
2867 Tests one and two ensure that the values will at least form a field which is required for the signatures to
2868 function. Tests three and four ensure that the generator $g$ is not set to a trivial value which would make signature
2869 forgery easier. Test five ensures that $q$ divides the order of multiplicative sub-group of $\Z/p\Z$. Test six
2870 ensures that the generator actually generates a prime order group. Tests seven and eight ensure that the public key
2871 is within range and belongs to a group of prime order. Note that test eight does not prove that $g$ generated $y$ only
2872 that $y$ belongs to a multiplicative sub-group of order $q$.
2873
2874 The following function will perform these tests.
2875
2876 \index{dsa\_verify\_key()}
2877 \begin{verbatim}
2878 int dsa_verify_key(dsa_key *key, int *stat);
2879 \end{verbatim}
2880
2881 This will test ``key'' and store the result in ``stat''. If the result is $stat = 0$ the DSA key failed one of the tests
2882 and should not be used at all. If the result is $stat = 1$ the DSA key is valid (as far as valid mathematics are concerned).
2883
2884 \section{Signatures}
2885 To generate a DSA signature call the following function
2886
2887 \index{dsa\_sign\_hash()}
2888 \begin{verbatim}
2889 int dsa_sign_hash(const unsigned char *in, unsigned long inlen,
2890 unsigned char *out, unsigned long *outlen,
2891 prng_state *prng, int wprng, dsa_key *key);
2892 \end{verbatim}
2893
2894 Which will sign the data in ``in'' of length ``inlen'' bytes. The signature is stored in ``out'' and the size
2895 of the signature in ``outlen''. If the signature is longer than the size you initially specify in ``outlen'' nothing
2896 is stored and the function returns an error code. The DSA ``key'' must be of the \textbf{PK\_PRIVATE} persuasion.
2897
2898 To verify a hash created with that function use the following function
2899
2900 \index{dsa\_verify\_hash()}
2901 \begin{verbatim}
2902 int dsa_verify_hash(const unsigned char *sig, unsigned long siglen,
2903 const unsigned char *hash, unsigned long inlen,
2904 int *stat, dsa_key *key);
2905 \end{verbatim}
2906 Which will verify the data in ``hash'' of length ``inlen'' against the signature stored in ``sig'' of length ``siglen''.
2907 It will set ``stat'' to $1$ if the signature is valid, otherwise it sets ``stat'' to $0$.
2908
2909 \section{Import and Export}
2910
2911 To export a DSA key so that it can be transported use the following function
2912 \index{dsa\_export()}
2913 \begin{verbatim}
2914 int dsa_export(unsigned char *out, unsigned long *outlen,
2915 int type,
2916 dsa_key *key);
2917 \end{verbatim}
2918 This will export the DSA ``key'' to the buffer ``out'' and set the length in ``outlen'' (which must have been previously
2919 initialized to the maximum buffer size). The ``type`` variable may be either \textbf{PK\_PRIVATE} or \textbf{PK\_PUBLIC}
2920 depending on whether you want to export a private or public copy of the DSA key.
2921
2922 To import an exported DSA key use the following function
2923
2924 \index{dsa\_import()}
2925 \begin{verbatim}
2926 int dsa_import(const unsigned char *in, unsigned long inlen,
2927 dsa_key *key);
2928 \end{verbatim}
2929
2930 This will import the DSA key from the buffer ``in'' of length ``inlen'' to the ``key''. If the process fails the function
2931 will automatically free all of the heap allocated in the process (you don't have to call dsa\_free()).
2932
2933 \chapter{Standards Support}
2934 \section{DER Support}
2935 DER or ``Distinguished Encoding Rules'' is a subset of the ASN.1 encoding rules that is fully deterministic and
2936 ideal for cryptography. In particular ASN.1 specifies an INTEGER type for storing arbitrary sized integers. DER
2937 further limits the ASN.1 specifications to a deterministic encoding.
2938
2939 \subsection{Storing INTEGER types}
2940 \index{der\_encode\_integer()}
2941 \begin{alltt}
2942 int der_encode_integer(mp_int *num, unsigned char *out, unsigned long *outlen);
2943 \end{alltt}
2944
2945 This will store the integer in ``num'' to the output buffer ``out'' of length ``outlen''. It only stores
2946 non--negative numbers. It stores the number of octets used back in ``outlen''.
2947
2948 \subsection{Reading INTEGER types}
2949 \index{der\_decode\_integer()}
2950 \begin{alltt}
2951 int der_decode_integer(const unsigned char *in, unsigned long *inlen, mp_int *num);
2952 \end{alltt}
2953 This will decode the DER encoded INTEGER in ``in'' of length ``inlen'' and store the resulting integer
2954 in ``num''. It will store the bytes read in ``inlen'' which is handy if you have to parse multiple
2955 data items out of a binary packet.
2956
2957 \subsection{INTEGER length}
2958 \index{der\_length\_integer()}
2959 \begin{alltt}
2960 int der_length_integer(mp_int *num, unsigned long *len);
2961 \end{alltt}
2962 This will determine the length of the DER encoding of the integer ``num'' and store it in ``len''.
2963
2964 \subsection{Multiple INTEGER types}
2965 To simplify the DER encoding/decoding there are two functions two handle multple types at once.
2966
2967 \index{der\_put\_multi\_integer()}
2968 \index{der\_get\_multi\_integer()}
2969 \begin{alltt}
2970 int der_put_multi_integer(unsigned char *dst, unsigned long *outlen, mp_int *num, ...);
2971 int der_get_multi_integer(const unsigned char *src, unsigned long *inlen, mp_int *num, ...);
2972 \end{alltt}
2973
2974 These will handle multiple encodings/decodings at once. They work like their single operand counterparts
2975 except they handle a \textbf{NULL} terminated list of operands.
2976
2977 \begin{verbatim}
2978 #include <mycrypt.h>
2979 int main(void)
2980 {
2981 mp_int a, b, c, d;
2982 unsigned char buffer[1000];
2983 unsigned long len;
2984 int err;
2985
2986 /* init a,b,c,d with some values ... */
2987
2988 /* ok we want to store them now... */
2989 len = sizeof(buffer);
2990 if ((err = der_put_multi_integer(buffer, &len,
2991 &a, &b, &c, &d, NULL)) != CRYPT_OK) {
2992 // error
2993 }
2994 printf("I stored %lu bytes in buf\n", len);
2995
2996 /* ok say we want to get them back for fun */
2997 /* len set previously...otherwise set it to the size of the packet */
2998 if ((err = der_get_multi_integer(buffer, &len,
2999 &a, &b, &c, &d, NULL)) != CRYPT_OK) {
3000 // error
3001 }
3002 printf("I read %lu bytes from buf\n", len);
3003 }
3004 \end{verbatim}
3005 \section{Password Based Cryptography}
3006 \subsection{PKCS \#5}
2277 In order to securely handle user passwords for the purposes of creating session keys and chaining IVs the PKCS \#5 was drafted. PKCS \#5 3007 In order to securely handle user passwords for the purposes of creating session keys and chaining IVs the PKCS \#5 was drafted. PKCS \#5
2278 is made up of two algorithms, Algorithm One and Algorithm Two. Algorithm One is the older fairly limited algorithm which has been implemented 3008 is made up of two algorithms, Algorithm One and Algorithm Two. Algorithm One is the older fairly limited algorithm which has been implemented
2279 for completeness. Algorithm Two is a bit more modern and more flexible to work with. 3009 for completeness. Algorithm Two is a bit more modern and more flexible to work with.
2280 3010
2281 \section{Algorithm One} 3011 \subsection{Algorithm One}
2282 Algorithm One accepts as input a password, an 8--byte salt and an iteration counter. The iteration counter is meant to act as delay for 3012 Algorithm One accepts as input a password, an 8--byte salt and an iteration counter. The iteration counter is meant to act as delay for
2283 people trying to brute force guess the password. The higher the iteration counter the longer the delay. This algorithm also requires a hash 3013 people trying to brute force guess the password. The higher the iteration counter the longer the delay. This algorithm also requires a hash
2284 algorithm and produces an output no longer than the output of the hash. 3014 algorithm and produces an output no longer than the output of the hash.
2285 3015
2286 \index{pkcs\_5\_alg1()} 3016 \index{pkcs\_5\_alg1()}
2295 on the password. The ``hash\_idx'' is the index of the hash you wish to use in the descriptor table. 3025 on the password. The ``hash\_idx'' is the index of the hash you wish to use in the descriptor table.
2296 3026
2297 The output of length upto ``outlen'' is stored in ``out''. If ``outlen'' is initially larger than the size of the hash functions output 3027 The output of length upto ``outlen'' is stored in ``out''. If ``outlen'' is initially larger than the size of the hash functions output
2298 it is set to the number of bytes stored. If it is smaller than not all of the hash output is stored in ``out''. 3028 it is set to the number of bytes stored. If it is smaller than not all of the hash output is stored in ``out''.
2299 3029
2300 \section{Algorithm Two} 3030 \subsection{Algorithm Two}
2301 3031
2302 Algorithm Two is the recommended algorithm for this task. It allows variable length salts and can produce outputs larger than the 3032 Algorithm Two is the recommended algorithm for this task. It allows variable length salts and can produce outputs larger than the
2303 hash functions output. As such it can easily be used to derive session keys for ciphers and MACs as well initial vectors as required 3033 hash functions output. As such it can easily be used to derive session keys for ciphers and MACs as well initial vectors as required
2304 from a single password and invokation of this algorithm. 3034 from a single password and invokation of this algorithm.
2305 3035
2344 3074
2345 /* use material (recall to store the salt in the output) */ 3075 /* use material (recall to store the salt in the output) */
2346 \} 3076 \}
2347 \end{alltt} 3077 \end{alltt}
2348 3078
2349 \chapter{Diffie-Hellman Key Exchange}
2350
2351 \section{Background}
2352
2353 Diffie-Hellman was the original public key system proposed. The system is based upon the group structure
2354 of finite fields. For Diffie-Hellman a prime $p$ is chosen and a ``base'' $b$ such that $b^x\mbox{ }(\mbox{mod }p)$
2355 generates a large sub-group of prime order (for unique values of $x$).
2356
2357 A secret key is an exponent $x$ and a public key is the value of $y \equiv g^x\mbox{ }(\mbox{mod }p)$. The term
2358 ``discrete logarithm'' denotes the action of finding $x$ given only $y$, $g$ and $p$. The key exchange part of
2359 Diffie-Hellman arises from the fact that two users A and B with keys $(A_x, A_y)$ and $(B_x, B_y)$ can exchange
2360 a shared key $K \equiv B_y^{A_x} \equiv A_y^{B_x} \equiv g^{A_xB_x}\mbox{ }(\mbox{mod }p)$.
2361
2362 From this public encryption and signatures can be developed. The trivial way to encrypt (for example) using a public key
2363 $y$ is to perform the key exchange offline. The sender invents a key $k$ and its public copy
2364 $k' \equiv g^k\mbox{ }(\mbox{mod }p)$ and uses $K \equiv k'^{A_x}\mbox{ }(\mbox{mod }p)$ as a key to encrypt
2365 the message with. Typically $K$ would be sent to a one-way hash and the message digested used as a key in a
2366 symmetric cipher.
2367
2368 It is important that the order of the sub-group that $g$ generates not only be large but also prime. There are
2369 discrete logarithm algorithms that take $\sqrt r$ time given the order $r$. The discrete logarithm can be computed
2370 modulo each prime factor of $r$ and the results combined using the Chinese Remainder Theorem. In the cases where
2371 $r$ is ``B-Smooth'' (e.g. all small factors or powers of small prime factors) the solution is trivial to find.
2372
2373 To thwart such attacks the primes and bases in the library have been designed and fixed. Given a prime $p$ the order of
2374 the sub-group generated is a large prime namely ${p - 1} \over 2$. Such primes are known as ``strong primes'' and the
2375 smaller prime (e.g. the order of the base) are known as Sophie-Germaine primes.
2376
2377 \section{Core Functions}
2378
2379 This library also provides core Diffie-Hellman functions so you can negotiate keys over insecure mediums. The routines
2380 provided are relatively easy to use and only take two function calls to negotiate a shared key. There is a structure
2381 called ``dh\_key'' which stores the Diffie-Hellman key in a format these routines can use. The first routine is to
2382 make a Diffie-Hellman private key pair:
2383 \index{dh\_make\_key()}
2384 \begin{verbatim}
2385 int dh_make_key(prng_state *prng, int wprng,
2386 int keysize, dh_key *key);
2387 \end{verbatim}
2388 The ``keysize'' is the size of the modulus you want in bytes. Currently support sizes are 96 to 512 bytes which correspond
2389 to key sizes of 768 to 4096 bits. The smaller the key the faster it is to use however it will be less secure. When
2390 specifying a size not explicitly supported by the library it will round {\em up} to the next key size. If the size is
2391 above 512 it will return an error. So if you pass ``keysize == 32'' it will use a 768 bit key but if you pass
2392 ``keysize == 20000'' it will return an error. The primes and generators used are built-into the library and were designed
2393 to meet very specific goals. The primes are strong primes which means that if $p$ is the prime then
2394 $p-1$ is equal to $2r$ where $r$ is a large prime. The bases are chosen to generate a group of order $r$ to prevent
2395 leaking a bit of the key. This means the bases generate a very large prime order group which is good to make cryptanalysis
2396 hard.
2397
2398 The next two routines are for exporting/importing Diffie-Hellman keys in a binary format. This is useful for transport
2399 over communication mediums.
2400
2401 \index{dh\_export()} \index{dh\_import()}
2402 \begin{verbatim}
2403 int dh_export(unsigned char *out, unsigned long *outlen,
2404 int type, dh_key *key);
2405
2406 int dh_import(const unsigned char *in, unsigned long inlen, dh_key *key);
2407 \end{verbatim}
2408
2409 These two functions work just like the ``rsa\_export()'' and ``rsa\_import()'' functions except these work with
2410 Diffie-Hellman keys. Its important to note you do not have to free the ram for a ``dh\_key'' if an import fails. You can free a
2411 ``dh\_key'' using:
2412 \begin{verbatim}
2413 void dh_free(dh_key *key);
2414 \end{verbatim}
2415 After you have exported a copy of your public key (using {\bf PK\_PUBLIC} as ``type'') you can now create a shared secret
2416 with the other user using:
2417 \index{dh\_shared\_secret()}
2418 \begin{verbatim}
2419 int dh_shared_secret(dh_key *private_key,
2420 dh_key *public_key,
2421 unsigned char *out, unsigned long *outlen);
2422 \end{verbatim}
2423
2424 Where ``private\_key'' is the key you made and ``public\_key'' is the copy of the public key the other user sent you. The result goes
2425 into ``out'' and the length into ``outlen''. If all went correctly the data in ``out'' should be identical for both parties. It is important to
2426 note that the two keys have to be the same size in order for this to work. There is a function to get the size of a
2427 key:
2428 \index{dh\_get\_size()}
2429 \begin{verbatim}
2430 int dh_get_size(dh_key *key);
2431 \end{verbatim}
2432 This returns the size in bytes of the modulus chosen for that key.
2433
2434 \subsection{Remarks on Usage}
2435 Its important that you hash the shared key before trying to use it as a key for a symmetric cipher or something. An
2436 example program that communicates over sockets, using MD5 and 1024-bit DH keys is\footnote{This function is a small example. It is suggested that proper packaging be used. For example, if the public key sent is truncated these routines will not detect that.}:
2437 \newpage
2438 \begin{small}
2439 \begin{verbatim}
2440 int establish_secure_socket(int sock, int mode, unsigned char *key,
2441 prng_state *prng, int wprng)
2442 {
2443 unsigned char buf[4096], buf2[4096];
2444 unsigned long x, len;
2445 int res, err, inlen;
2446 dh_key mykey, theirkey;
2447
2448 /* make up our private key */
2449 if ((err = dh_make_key(prng, wprng, 128, &mykey)) != CRYPT_OK) {
2450 return err;
2451 }
2452
2453 /* export our key as public */
2454 x = sizeof(buf);
2455 if ((err = dh_export(buf, &x, PK_PUBLIC, &mykey)) != CRYPT_OK) {
2456 res = err;
2457 goto done2;
2458 }
2459
2460 if (mode == 0) {
2461 /* mode 0 so we send first */
2462 if (send(sock, buf, x, 0) != x) {
2463 res = CRYPT_ERROR;
2464 goto done2;
2465 }
2466
2467 /* get their key */
2468 if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
2469 res = CRYPT_ERROR;
2470 goto done2;
2471 }
2472 } else {
2473 /* mode >0 so we send second */
2474 if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
2475 res = CRYPT_ERROR;
2476 goto done2;
2477 }
2478
2479 if (send(sock, buf, x, 0) != x) {
2480 res = CRYPT_ERROR;
2481 goto done2;
2482 }
2483 }
2484
2485 if ((err = dh_import(buf2, inlen, &theirkey)) != CRYPT_OK) {
2486 res = err;
2487 goto done2;
2488 }
2489
2490 /* make shared secret */
2491 x = sizeof(buf);
2492 if ((err = dh_shared_secret(&mykey, &theirkey, buf, &x)) != CRYPT_OK) {
2493 res = err;
2494 goto done;
2495 }
2496
2497 /* hash it */
2498 len = 16; /* default is MD5 so "key" must be at least 16 bytes long */
2499 if ((err = hash_memory(find_hash("md5"), buf, x, key, &len)) != CRYPT_OK) {
2500 res = err;
2501 goto done;
2502 }
2503
2504 /* clean up and return */
2505 res = CRYPT_OK;
2506 done:
2507 dh_free(&theirkey);
2508 done2:
2509 dh_free(&mykey);
2510 zeromem(buf, sizeof(buf));
2511 zeromem(buf2, sizeof(buf2));
2512 return res;
2513 }
2514 \end{verbatim}
2515 \end{small}
2516 \newpage
2517 \subsection{Remarks on The Snippet}
2518 When the above code snippet is done (assuming all went well) their will be a shared 128-bit key in the ``key'' array
2519 passed to ``establish\_secure\_socket()''.
2520
2521 \section{Other Diffie-Hellman Functions}
2522 In order to test the Diffie-Hellman function internal workings (e.g. the primes and bases) their is a test function made
2523 available:
2524 \index{dh\_test()}
2525 \begin{verbatim}
2526 int dh_test(void);
2527 \end{verbatim}
2528
2529 This function returns {\bf CRYPT\_OK} if the bases and primes in the library are correct. There is one last helper
2530 function:
2531 \index{dh\_sizes()}
2532 \begin{verbatim}
2533 void dh_sizes(int *low, int *high);
2534 \end{verbatim}
2535 Which stores the smallest and largest key sizes support into the two variables.
2536
2537 \section{DH Packet}
2538 Similar to the RSA related functions there are functions to encrypt or decrypt symmetric keys using the DH public key
2539 algorithms.
2540 \index{dh\_encrypt\_key()} \index{dh\_decrypt\_key()}
2541 \begin{verbatim}
2542 int dh_encrypt_key(const unsigned char *inkey, unsigned long keylen,
2543 unsigned char *out, unsigned long *len,
2544 prng_state *prng, int wprng, int hash,
2545 dh_key *key);
2546
2547 int dh_decrypt_key(const unsigned char *in, unsigned long inlen,
2548 unsigned char *outkey, unsigned long *keylen,
2549 dh_key *key);
2550 \end{verbatim}
2551 Where ``inkey'' is an input symmetric key of no more than 32 bytes. Essentially these routines created a random public key
2552 and find the hash of the shared secret. The message digest is than XOR'ed against the symmetric key. All of the
2553 required data is placed in ``out'' by ``dh\_encrypt\_key()''. The hash must produce a message digest at least as large
2554 as the symmetric key you are trying to share.
2555
2556 Similar to the RSA system you can sign and verify a hash of a message.
2557 \index{dh\_sign\_hash()} \index{dh\_verify\_hash()}
2558 \begin{verbatim}
2559 int dh_sign_hash(const unsigned char *in, unsigned long inlen,
2560 unsigned char *out, unsigned long *outlen,
2561 prng_state *prng, int wprng, dh_key *key);
2562
2563 int dh_verify_hash(const unsigned char *sig, unsigned long siglen,
2564 const unsigned char *hash, unsigned long hashlen,
2565 int *stat, dh_key *key);
2566 \end{verbatim}
2567
2568 The ``dh\_sign\_hash'' function signs the message hash in ``in'' of length ``inlen'' and forms a DH packet in ``out''.
2569 The ``dh\_verify\_hash'' function verifies the DH signature in ``sig'' against the hash in ``hash''. It sets ``stat''
2570 to non-zero if the signature passes or zero if it fails.
2571
2572 \chapter{Elliptic Curve Cryptography}
2573
2574 \section{Background}
2575 The library provides a set of core ECC functions as well that are designed to be the Elliptic Curve analogy of all of the
2576 Diffie-Hellman routines in the previous chapter. Elliptic curves (of certain forms) have the benefit that they are harder
2577 to attack (no sub-exponential attacks exist unlike normal DH crypto) in fact the fastest attack requires the square root
2578 of the order of the base point in time. That means if you use a base point of order $2^{192}$ (which would represent a
2579 192-bit key) then the work factor is $2^{96}$ in order to find the secret key.
2580
2581 The curves in this library are taken from the following website:
2582 \begin{verbatim}
2583 http://csrc.nist.gov/cryptval/dss.htm
2584 \end{verbatim}
2585
2586 They are all curves over the integers modulo a prime. The curves have the basic equation that is:
2587 \begin{equation}
2588 y^2 = x^3 - 3x + b\mbox{ }(\mbox{mod }p)
2589 \end{equation}
2590
2591 The variable $b$ is chosen such that the number of points is nearly maximal. In fact the order of the base points $\beta$
2592 provided are very close to $p$ that is $\vert \vert \phi(\beta) \vert \vert \approx \vert \vert p \vert \vert$. The curves
2593 range in order from $\approx 2^{192}$ points to $\approx 2^{521}$. According to the source document any key size greater
2594 than or equal to 256-bits is sufficient for long term security.
2595
2596 \section{Core Functions}
2597
2598 Like the DH routines there is a key structure ``ecc\_key'' used by the functions. There is a function to make a key:
2599 \index{ecc\_make\_key()}
2600 \begin{verbatim}
2601 int ecc_make_key(prng_state *prng, int wprng,
2602 int keysize, ecc_key *key);
2603 \end{verbatim}
2604
2605 The ``keysize'' is the size of the modulus in bytes desired. Currently directly supported values are 20, 24, 28, 32, 48 and 65 bytes which
2606 correspond to key sizes of 160, 192, 224, 256, 384 and 521 bits respectively. If you pass a key size that is between any key size
2607 it will round the keysize up to the next available one. The rest of the parameters work like they do in the ``dh\_make\_key()'' function.
2608 To free the ram allocated by a key call:
2609 \index{ecc\_free()}
2610 \begin{verbatim}
2611 void ecc_free(ecc_key *key);
2612 \end{verbatim}
2613
2614 To import and export a key there are:
2615 \index{ecc\_export()}
2616 \index{ecc\_import()}
2617 \begin{verbatim}
2618 int ecc_export(unsigned char *out, unsigned long *outlen,
2619 int type, ecc_key *key);
2620
2621 int ecc_import(const unsigned char *in, unsigned long inlen, ecc_key *key);
2622 \end{verbatim}
2623 These two work exactly like there DH counterparts. Finally when you share your public key you can make a shared secret
2624 with:
2625 \index{ecc\_shared\_secret()}
2626 \begin{verbatim}
2627 int ecc_shared_secret(ecc_key *private_key,
2628 ecc_key *public_key,
2629 unsigned char *out, unsigned long *outlen);
2630 \end{verbatim}
2631 Which works exactly like the DH counterpart, the ``private\_key'' is your own key and ``public\_key'' is the key the other
2632 user sent you. Note that this function stores both $x$ and $y$ co-ordinates of the shared
2633 elliptic point. You should hash the output to get a shared key in a more compact and useful form (most of the entropy is
2634 in $x$ anyways). Both keys have to be the same size for this to work, to help there is a function to get the size in bytes
2635 of a key.
2636 \index{ecc\_get\_size()}
2637 \begin{verbatim}
2638 int ecc_get_size(ecc_key *key);
2639 \end{verbatim}
2640
2641 To test the ECC routines and to get the minimum and maximum key sizes there are these two functions:
2642 \index{ecc\_test()}
2643 \begin{verbatim}
2644 int ecc_test(void);
2645 void ecc_sizes(int *low, int *high);
2646 \end{verbatim}
2647 Which both work like their DH counterparts.
2648
2649 \section{ECC Packet}
2650 Similar to the RSA API there are two functions which encrypt and decrypt symmetric keys using the ECC public key
2651 algorithms.
2652
2653 \index{ecc\_encrypt\_key()} \index{ecc\_decrypt\_key()}
2654 \begin{verbatim}
2655 int ecc_encrypt_key(const unsigned char *inkey, unsigned long keylen,
2656 unsigned char *out, unsigned long *len,
2657 prng_state *prng, int wprng, int hash,
2658 ecc_key *key);
2659
2660 int ecc_decrypt_key(const unsigned char *in, unsigned long inlen,
2661 unsigned char *outkey, unsigned long *keylen,
2662 ecc_key *key);
2663 \end{verbatim}
2664
2665 Where ``inkey'' is an input symmetric key of no more than 32 bytes. Essentially these routines created a random public key
2666 and find the hash of the shared secret. The message digest is than XOR'ed against the symmetric key. All of the required
2667 data is placed in ``out'' by ``ecc\_encrypt\_key()''. The hash chosen must produce a message digest at least as large
2668 as the symmetric key you are trying to share.
2669
2670 There are also functions to sign and verify the hash of a message.
2671 \index{ecc\_sign\_hash()} \index{ecc\_verify\_hash()}
2672 \begin{verbatim}
2673 int ecc_sign_hash(const unsigned char *in, unsigned long inlen,
2674 unsigned char *out, unsigned long *outlen,
2675 prng_state *prng, int wprng, ecc_key *key);
2676
2677 int ecc_verify_hash(const unsigned char *sig, unsigned long siglen,
2678 const unsigned char *hash, unsigned long hashlen,
2679 int *stat, ecc_key *key);
2680 \end{verbatim}
2681
2682 The ``ecc\_sign\_hash'' function signs the message hash in ``in'' of length ``inlen'' and forms a ECC packet in ``out''.
2683 The ``ecc\_verify\_hash'' function verifies the ECC signature in ``sig'' against the hash in ``hash''. It sets ``stat''
2684 to non-zero if the signature passes or zero if it fails.
2685
2686
2687 \section{ECC Keysizes}
2688 With ECC if you try and sign a hash that is bigger than your ECC key you can run into problems. The math will still work
2689 and in effect the signature will still work. With ECC keys the strength of the signature is limited by the size of
2690 the hash or the size of they key, whichever is smaller. For example, if you sign with SHA256 and a ECC-160 key in effect
2691 you have 160-bits of security (e.g. as if you signed with SHA-1).
2692
2693 The library will not warn you if you make this mistake so it is important to check yourself before using the
2694 signatures.
2695
2696 \chapter{Digital Signature Algorithm}
2697 \section{Introduction}
2698 The Digital Signature Algorithm (or DSA) is a variant of the ElGamal Signature scheme which has been modified to
2699 reduce the bandwidth of a signature. For example, to have ``80-bits of security'' with ElGamal you need a group of
2700 order at least 1024-bits. With DSA you need a group of order at least 160-bits. By comparison the ElGamal signature
2701 would require at least 256 bytes where as the DSA signature would require only at least 40 bytes.
2702
2703 The API for the DSA is essentially the same as the other PK algorithms. Except in the case of DSA no encryption or
2704 decryption routines are provided.
2705
2706 \section{Key Generation}
2707 To make a DSA key you must call the following function
2708 \begin{verbatim}
2709 int dsa_make_key(prng_state *prng, int wprng,
2710 int group_size, int modulus_size,
2711 dsa_key *key);
2712 \end{verbatim}
2713 The variable ``prng'' is an active PRNG state and ``wprng'' the index to the descriptor. ``group\_size'' and
2714 ``modulus\_size'' control the difficulty of forging a signature. Both parameters are in bytes. The larger the
2715 ``group\_size'' the more difficult a forgery becomes upto a limit. The value of $group\_size$ is limited by
2716 $15 < group\_size < 1024$ and $modulus\_size - group\_size < 512$. Suggested values for the pairs are as follows.
2717
2718 \begin{center}
2719 \begin{tabular}{|c|c|c|}
2720 \hline \textbf{Bits of Security} & \textbf{group\_size} & \textbf{modulus\_size} \\
2721 \hline 80 & 20 & 128 \\
2722 \hline 120 & 30 & 256 \\
2723 \hline 140 & 35 & 384 \\
2724 \hline 160 & 40 & 512 \\
2725 \hline
2726 \end{tabular}
2727 \end{center}
2728
2729 When you are finished with a DSA key you can call the following function to free the memory used.
2730 \index{dsa\_free()}
2731 \begin{verbatim}
2732 void dsa_free(dsa_key *key);
2733 \end{verbatim}
2734
2735 \section{Key Verification}
2736 Each DSA key is composed of the following variables.
2737
2738 \begin{enumerate}
2739 \item $q$ a small prime of magnitude $256^{group\_size}$.
2740 \item $p = qr + 1$ a large prime of magnitude $256^{modulus\_size}$ where $r$ is a random even integer.
2741 \item $g = h^r \mbox{ (mod }p\mbox{)}$ a generator of order $q$ modulo $p$. $h$ can be any non-trivial random
2742 value. For this library they start at $h = 2$ and step until $g$ is not $1$.
2743 \item $x$ a random secret (the secret key) in the range $1 < x < q$
2744 \item $y = g^x \mbox{ (mod }p\mbox{)}$ the public key.
2745 \end{enumerate}
2746
2747 A DSA key is considered valid if it passes all of the following tests.
2748
2749 \begin{enumerate}
2750 \item $q$ must be prime.
2751 \item $p$ must be prime.
2752 \item $g$ cannot be one of $\lbrace -1, 0, 1 \rbrace$ (modulo $p$).
2753 \item $g$ must be less than $p$.
2754 \item $(p-1) \equiv 0 \mbox{ (mod }q\mbox{)}$.
2755 \item $g^q \equiv 1 \mbox{ (mod }p\mbox{)}$.
2756 \item $1 < y < p - 1$
2757 \item $y^q \equiv 1 \mbox{ (mod }p\mbox{)}$.
2758 \end{enumerate}
2759
2760 Tests one and two ensure that the values will at least form a field which is required for the signatures to
2761 function. Tests three and four ensure that the generator $g$ is not set to a trivial value which would make signature
2762 forgery easier. Test five ensures that $q$ divides the order of multiplicative sub-group of $\Z/p\Z$. Test six
2763 ensures that the generator actually generates a prime order group. Tests seven and eight ensure that the public key
2764 is within range and belongs to a group of prime order. Note that test eight does not prove that $g$ generated $y$ only
2765 that $y$ belongs to a multiplicative sub-group of order $q$.
2766
2767 The following function will perform these tests.
2768
2769 \index{dsa\_verify\_key()}
2770 \begin{verbatim}
2771 int dsa_verify_key(dsa_key *key, int *stat);
2772 \end{verbatim}
2773
2774 This will test ``key'' and store the result in ``stat''. If the result is $stat = 0$ the DSA key failed one of the tests
2775 and should not be used at all. If the result is $stat = 1$ the DSA key is valid (as far as valid mathematics are concerned).
2776
2777
2778
2779 \section{Signatures}
2780 To generate a DSA signature call the following function
2781
2782 \index{dsa\_sign\_hash()}
2783 \begin{verbatim}
2784 int dsa_sign_hash(const unsigned char *in, unsigned long inlen,
2785 unsigned char *out, unsigned long *outlen,
2786 prng_state *prng, int wprng, dsa_key *key);
2787 \end{verbatim}
2788
2789 Which will sign the data in ``in'' of length ``inlen'' bytes. The signature is stored in ``out'' and the size
2790 of the signature in ``outlen''. If the signature is longer than the size you initially specify in ``outlen'' nothing
2791 is stored and the function returns an error code. The DSA ``key'' must be of the \textbf{PK\_PRIVATE} persuasion.
2792
2793 To verify a hash created with that function use the following function
2794
2795 \index{dsa\_verify\_hash()}
2796 \begin{verbatim}
2797 int dsa_verify_hash(const unsigned char *sig, unsigned long siglen,
2798 const unsigned char *hash, unsigned long inlen,
2799 int *stat, dsa_key *key);
2800 \end{verbatim}
2801 Which will verify the data in ``hash'' of length ``inlen'' against the signature stored in ``sig'' of length ``siglen''.
2802 It will set ``stat'' to $1$ if the signature is valid, otherwise it sets ``stat'' to $0$.
2803
2804 \section{Import and Export}
2805
2806 To export a DSA key so that it can be transported use the following function
2807 \index{dsa\_export()}
2808 \begin{verbatim}
2809 int dsa_export(unsigned char *out, unsigned long *outlen,
2810 int type,
2811 dsa_key *key);
2812 \end{verbatim}
2813 This will export the DSA ``key'' to the buffer ``out'' and set the length in ``outlen'' (which must have been previously
2814 initialized to the maximum buffer size). The ``type`` variable may be either \textbf{PK\_PRIVATE} or \textbf{PK\_PUBLIC}
2815 depending on whether you want to export a private or public copy of the DSA key.
2816
2817 To import an exported DSA key use the following function
2818
2819 \index{dsa\_import()}
2820 \begin{verbatim}
2821 int dsa_import(const unsigned char *in, unsigned long inlen,
2822 dsa_key *key);
2823 \end{verbatim}
2824
2825 This will import the DSA key from the buffer ``in'' of length ``inlen'' to the ``key''. If the process fails the function
2826 will automatically free all of the heap allocated in the process (you don't have to call dsa\_free()).
2827 3079
2828 \chapter{Miscellaneous} 3080 \chapter{Miscellaneous}
2829 \section{Base64 Encoding and Decoding} 3081 \section{Base64 Encoding and Decoding}
2830 The library provides functions to encode and decode a RFC1521 base64 coding scheme. This means that it can decode what it 3082 The library provides functions to encode and decode a RFC1521 base64 coding scheme. This means that it can decode what it
2831 encodes but the format used does not comply to any known standard. The characters used in the mappings are: 3083 encodes but the format used does not comply to any known standard. The characters used in the mappings are:
3056 Since C does not have standard semaphores this support is not native to Libtomcrypt. Even a C based semaphore is not entire 3308 Since C does not have standard semaphores this support is not native to Libtomcrypt. Even a C based semaphore is not entire
3057 possible as some compilers may ignore the ``volatile'' keyword or have multiple processors. Provide your host application 3309 possible as some compilers may ignore the ``volatile'' keyword or have multiple processors. Provide your host application
3058 is modular enough putting the locks in the right place should not bloat the code significantly and will solve all thread 3310 is modular enough putting the locks in the right place should not bloat the code significantly and will solve all thread
3059 safety issues within the library. 3311 safety issues within the library.
3060 3312
3061 \chapter{Configuring the Library} 3313 \chapter{Configuring and Building the Library}
3062 \section{Introduction} 3314 \section{Introduction}
3063 The library is fairly flexible about how it can be built, used and generally distributed. Additions are being made with 3315 The library is fairly flexible about how it can be built, used and generally distributed. Additions are being made with
3064 each new release that will make the library even more flexible. Most options are placed in the makefile and others 3316 each new release that will make the library even more flexible. Each of the classes of functions can be disabled during
3065 are in ``mycrypt\_cfg.h''. All are used when the library is built from scratch. 3317 the build process to make a smaller library. This is particularly useful for shared libraries.
3066 3318
3067 For GCC platforms the file ``makefile'' is the makefile to be used. On MSVC platforms ``makefile.vc'' and on PS2 platforms 3319 \section{Building a Static Library}
3068 ``makefile.ps2''. 3320 The library can be built as a static library which is generally the simplest and most portable method of
3321 building the library. With a CC or GCC equipped platform you can issue the following
3322
3323 \begin{alltt}
3324 make install_lib
3325 \end{alltt}
3326
3327 Which will build the library and install it in /usr/lib (as well as the headers in /usr/include). The destination
3328 directory of the library and headers can be changed by editing ``makefile''. The variable LIBNAME controls
3329 where the library is to be installed and INCNAME controls where the headers are to be installed. A developer can
3330 then use the library by including ``mycrypt.h'' in their program and linking against ``libtomcrypt.a''.
3331
3332 A static library can also be built with the Intel C Compiler (ICC) by issuing the following
3333
3334 \begin{alltt}
3335 make -f makefile.icc install
3336 \end{alltt}
3337
3338 This will also build ``libtomcrypt.a'' except that it will use ICC. Additionally Microsoft's Visual C 6.00 can be used
3339 by issuing
3340
3341 \begin{alltt}
3342 nmake -f makefile.msvc
3343 \end{alltt}
3344
3345 You will have to manually copy ``tomcrypt.lib'' and the headers to your MSVC lib/inc directories.
3346
3347 \subsection{MPI Control}
3348 If you already have LibTomMath installed you can safely remove it from the build. By commenting the line
3349 in the appropriate makefile which starts with
3350
3351 \begin{alltt}
3352 MPIOBJECT=mpi
3353 \end{alltt}
3354
3355 Simply place a \# at the start and re-build the library. To properly link applications you will have to also
3356 link in LibTomMath. Removing MPI has the benefit of cutting down the library size as well potentially have access
3357 to the latest mpi.
3358
3359 \section{Building a Shared Library}
3360 LibTomCrypt can also be built as a shared library (.so, .dll, etc...). With non-Windows platforms the assumption
3361 of the presence of gcc and ``libtool'' has been made. These are fairly common on Unix/Linux/BSD platforms. To
3362 build a .so shared library issue
3363
3364 \begin{alltt}
3365 make -f makefile.shared
3366 \end{alltt}
3367 This will use libtool and gcc to build a shared library ``libtomcrypt.la'' as well as a static library ``libtomcrypt.a''
3368 and install them into /usr/lib (and the headers into /usr/include). To link your application you should use the
3369 libtool program in ``--mode=link''.
3370
3371 You can also build LibTomCrypt as a shared library (DLL) in Windows with Cygwin. Issue the following
3372
3373 \begin{alltt}
3374 make -f makefile.cygwin_dll
3375 \end{alltt}
3376 This will build ``libtomcrypt.dll.a'' which is an import library for ``libtomcrypt.dll''. You must copy
3377 ``libtomcrypt.dll.a'' to your library directory, ``libtomcrypt.dll' to somewhere in your PATH and the header
3378 files to your include directory. So long as ``libtomcrypt.dll'' is in your system path you can run any LibTomCrypt
3379 program that uses it.
3069 3380
3070 \section{mycrypt\_cfg.h} 3381 \section{mycrypt\_cfg.h}
3071 The file ``mycrypt\_cfg.h'' is what lets you control what functionality you want to remove from the library. By default, 3382 The file ``mycrypt\_cfg.h'' is what lets you control various high level macros which control the behaviour
3072 everything the library has to offer it built. 3383 of the library.
3073 3384
3074 \subsubsection{ARGTYPE} 3385 \subsubsection{ARGTYPE}
3075 This lets you control how the \_ARGCHK macro will behave. The macro is used to check pointers inside the functions against 3386 This lets you control how the \_ARGCHK macro will behave. The macro is used to check pointers inside the functions against
3076 NULL. There are three settings for ARGTYPE. When set to 0 it will have the default behaviour of printing a message to 3387 NULL. There are three settings for ARGTYPE. When set to 0 it will have the default behaviour of printing a message to
3077 stderr and raising a SIGABRT signal. This is provided so all platforms that use libtomcrypt can have an error that functions 3388 stderr and raising a SIGABRT signal. This is provided so all platforms that use libtomcrypt can have an error that functions
3080 3391
3081 \subsubsection{Endianess} 3392 \subsubsection{Endianess}
3082 There are five macros related to endianess issues. For little endian platforms define, ENDIAN\_LITTLE. For big endian 3393 There are five macros related to endianess issues. For little endian platforms define, ENDIAN\_LITTLE. For big endian
3083 platforms define ENDIAN\_BIG. Similarly when the default word size of an ``unsigned long'' is 32-bits define ENDIAN\_32BITWORD 3394 platforms define ENDIAN\_BIG. Similarly when the default word size of an ``unsigned long'' is 32-bits define ENDIAN\_32BITWORD
3084 or define ENDIAN\_64BITWORD when its 64-bits. If you do not define any of them the library will automatically use ENDIAN\_NEUTRAL 3395 or define ENDIAN\_64BITWORD when its 64-bits. If you do not define any of them the library will automatically use ENDIAN\_NEUTRAL
3085 which will work on all platforms. Currently the system will automatically detect GCC or MSVC on a windows platform as well 3396 which will work on all platforms.
3086 as GCC on a PS2 platform. 3397
3398 Currently LibTomCrypt will detect x86-32 and x86-64 running GCC as well as x86-32 running MSVC.
3087 3399
3088 \section{The Configure Script} 3400 \section{The Configure Script}
3089 There are also options you can specify from the configure script or ``mycrypt\_config.h''. 3401 There are also options you can specify from the configure script or ``mycrypt\_custom.h''.
3090 3402
3091 \subsubsection{X memory routines} 3403 \subsubsection{X memory routines}
3092 The makefiles must define three macros denoted as XMALLOC, XCALLOC and XFREE which resolve to the name of the respective 3404 At the top of mycrypt\_custom.h are four macros denoted as XMALLOC, XCALLOC, XREALLOC and XFREE which resolve to
3093 functions. This lets you substitute in your own memory routines. If you substitute in your own functions they must behave 3405 the name of the respective functions. This lets you substitute in your own memory routines. If you substitute in
3094 like the standard C library functions in terms of what they expect as input and output. By default the library uses the 3406 your own functions they must behave like the standard C library functions in terms of what they expect as input and
3095 standard C routines. 3407 output. By default the library uses the standard C routines.
3096 3408
3097 \subsubsection{X clock routines} 3409 \subsubsection{X clock routines}
3098 The rng\_get\_bytes() function can call a function that requires the clock() function. These macros let you override 3410 The rng\_get\_bytes() function can call a function that requires the clock() function. These macros let you override
3099 the default clock() used with a replacement. By default the standard C library clock() function is used. 3411 the default clock() used with a replacement. By default the standard C library clock() function is used.
3100 3412
3101 \subsubsection{NO\_FILE} 3413 \subsubsection{NO\_FILE}
3102 During the build if NO\_FILE is defined then any function in the library that uses file I/O will not call the file I/O 3414 During the build if NO\_FILE is defined then any function in the library that uses file I/O will not call the file I/O
3103 functions and instead simply return CRYPT\_ERROR. This should help resolve any linker errors stemming from a lack of 3415 functions and instead simply return CRYPT\_NOP. This should help resolve any linker errors stemming from a lack of
3104 file I/O on embedded platforms. 3416 file I/O on embedded platforms.
3105 3417
3106 \subsubsection{CLEAN\_STACK} 3418 \subsubsection{CLEAN\_STACK}
3107 When this functions is defined the functions that store key material on the stack will clean up afterwards. Assumes that 3419 When this functions is defined the functions that store key material on the stack will clean up afterwards.
3108 you have no memory paging with the stack. 3420 Assumes that you have no memory paging with the stack.
3421
3422 \subsubsection{LTC\_TEST}
3423 When this has been defined the various self--test functions (for ciphers, hashes, prngs, etc) are included in the build.
3424 When this has been undefined the tests are removed and if called will return CRYPT\_NOP.
3109 3425
3110 \subsubsection{Symmetric Ciphers, One-way Hashes, PRNGS and Public Key Functions} 3426 \subsubsection{Symmetric Ciphers, One-way Hashes, PRNGS and Public Key Functions}
3111 There are a plethora of macros for the ciphers, hashes, PRNGs and public key functions which are fairly self-explanatory. 3427 There are a plethora of macros for the ciphers, hashes, PRNGs and public key functions which are fairly
3112 When they are defined the functionality is included otherwise it is not. There are some dependency issues which are 3428 self-explanatory. When they are defined the functionality is included otherwise it is not. There are some
3113 noted in the file. For instance, Yarrow requires CTR chaining mode, a block cipher and a hash function. 3429 dependency issues which are noted in the file. For instance, Yarrow requires CTR chaining mode, a block
3430 cipher and a hash function.
3114 3431
3115 \subsubsection{TWOFISH\_SMALL and TWOFISH\_TABLES} 3432 \subsubsection{TWOFISH\_SMALL and TWOFISH\_TABLES}
3116 Twofish is a 128-bit symmetric block cipher that is provided within the library. The cipher itself is flexible enough 3433 Twofish is a 128-bit symmetric block cipher that is provided within the library. The cipher itself is flexible enough
3117 to allow some tradeoffs in the implementation. When TWOFISH\_SMALL is defined the scheduled symmetric key for Twofish 3434 to allow some tradeoffs in the implementation. When TWOFISH\_SMALL is defined the scheduled symmetric key for Twofish
3118 requires only 200 bytes of memory. This is achieved by not pre-computing the substitution boxes. Having this 3435 requires only 200 bytes of memory. This is achieved by not pre-computing the substitution boxes. Having this
3126 3443
3127 \subsubsection{SMALL\_CODE} 3444 \subsubsection{SMALL\_CODE}
3128 When this is defined some of the code such as the Rijndael and SAFER+ ciphers are replaced with smaller code variants. 3445 When this is defined some of the code such as the Rijndael and SAFER+ ciphers are replaced with smaller code variants.
3129 These variants are slower but can save quite a bit of code space. 3446 These variants are slower but can save quite a bit of code space.
3130 3447
3448 \section{MPI Tweaks}
3449 \subsection{RSA Only Tweak}
3450 If you plan on only using RSA with moduli in the range of 1024 to 2560 bits you can enable a series of tweaks
3451 to reduce the library size. Follow these steps
3452
3453 \begin{enumerate}
3454 \item Undefine MDSA, MECC and MDH from mycrypt\_custom.h
3455 \item Undefine LTM\_ALL from tommath\_superclass.h
3456 \item Define SC\_RSA\_1 from tommath\_superclass.h
3457 \item Rebuild the library.
3458 \end{enumerate}
3459
3460
3461
3131 \input{crypt.ind} 3462 \input{crypt.ind}
3132 3463
3133 \end{document} 3464 \end{document}