Home | History | Annotate | Download | only in libtomcrypt

Lines Matching defs:the

51 \newcommand{\mysection}[1]    % Re-define the chaptering command to use
57 \newcommand{\mystarsection}[1] % Re-define the chaptering command to use
92 This document is part of the LibTomCrypt package and is hereby released into the public domain.
118 \mysection{What is the LibTomCrypt?}
123 The library was designed such that new ciphers/hashes/PRNGs can be added at run-time and the existing API
124 (and helper API functions) are able to use the new designs automatically. There exists self-check functions for each
125 block cipher and hash function to ensure that they compile and execute to the published design specifications. The library
128 \subsection{What the library IS for?}
130 The library serves as a toolkit for developers who have to solve cryptographic problems. Out of the box LibTomCrypt
132 provide all of the tools required to build such functionality. LibTomCrypt was designed to be a flexible library that
136 You may be wondering, \textit{Tom, why did you write a crypto library. I already have one.} Well the reason falls into
143 The idea is that I am not striving to replace OpenSSL or Crypto++ or Cryptlib or etc. I'm trying to write my
144 {\bf own} crypto library and hopefully along the way others will appreciate the work.
146 With this library all core functions (ciphers, hashes, prngs, and bignum) have the same prototype definition. They all load
147 and store data in a format independent of the platform. This means if you encrypt with Blowfish on a PPC it should decrypt
148 on an x86 with zero problems. The consistent API also means that if you learn how to use Blowfish with the library you
149 know how to use Safer+, RC6, or Serpent as well. With all of the core functions there are central descriptor tables
151 application can support all ciphers/hashes/prngs/bignum without changing the source code.
153 Not only did I strive to make a consistent and simple API to work with but I also attempted to make the library
154 configurable in terms of its build options. Out of the box the library will build with any modern version of GCC
155 without having to use configure scripts. This means that the library will work with platforms where development
158 On top of making the build simple and the API approachable I've also attempted for a reasonably high level of
165 The LibTomCrypt package has also been written to be very modular. The block ciphers, one--way hashes,
166 pseudo--random number generators (PRNG), and bignum math routines are all used within the API through \textit{descriptor} tables which
168 directly (\textit{e.g. sha256\_process()}) this descriptor interface allows the developer to customize their
169 usage of the library.
172 that for the PRNG needs within the library (\textit{e.g. making a RSA key}). All the developer has to do
173 is write a descriptor and the few support routines required for the device. After that the rest of the
174 API can make use of it without change. Similarly imagine a few years down the road when AES2
175 (\textit{or whatever they call it}) has been invented. It can be added to the library and used within applications
176 with zero modifications to the end applications provided they are written properly.
178 This flexibility within the library means it can be used with any combination of primitive algorithms and
180 mode routines for every single cipher. That means every time you add or remove a cipher from the library
181 you have to update the associated support code as well. In LibTomCrypt the associated code (\textit{chaining modes in this case})
182 are not directly tied to the ciphers. That is a new cipher can be added to the library by simply providing
183 the key setup, ECB decrypt and encrypt and test vector routines. After that all five chaining mode routines
184 can make use of the cipher right away.
188 The project is hereby released as public domain.
192 The author (Tom St Denis) is not a patent lawyer so this section is not to be treated as legal advice. To the best
193 of the authors knowledge the only patent related issues within the library are the RC5 and RC6 symmetric block ciphers.
194 They can be removed from a build by simply commenting out the two appropriate lines in \textit{tomcrypt\_custom.h}. The rest
195 of the ciphers and hashes are patent free or under patents that have since expired.
197 The RC2 and RC4 symmetric ciphers are not under patents but are under trademark regulations. This means you can use
198 the ciphers you just can't advertise that you are doing so.
201 I would like to give thanks to the following people (in no particular order) for helping me develop this project from
219 There have been quite a few other people as well. Please check the change log to see who else has contributed from
222 \chapter{The Application Programming Interface (API)}
226 In general the API is very simple to memorize and use. Most of the functions return either {\bf void} or {\bf int}. Functions
227 that return {\bf int} will return {\bf CRYPT\_OK} if the function was successful, or one of the many error codes
253 There is no initialization routine for the library and for the most part the code is thread safe. The only thread
254 related issue is if you use the same symmetric cipher, hash or public key state data in multiple threads. Normally
257 To include the prototypes for \textit{LibTomCrypt.a} into your own program simply include \textit{tomcrypt.h} like so:
267 The header file \textit{tomcrypt.h} also includes \textit{stdio.h}, \textit{string.h}, \textit{stdlib.h}, \textit{time.h} and \textit{ctype.h}.
271 There are a few helper macros to make the coding process a bit easier. The first set are related to loading and storing
272 32/64-bit words in little/big endian format. The macros are:
320 must pass it the length of the buffer where the output will be stored. For example:
331 /* ... Make up the RSA key somehow ... */
333 /* lets export the key, set x to the size of the
342 * the size of the output */
345 /* ... do something with the buffer */
351 In the above example if the size of the RSA public key was more than 1024 bytes this function would return an error code
352 indicating a buffer overflow would have occurred. If the function succeeds, it stores the length of the output back into
353 \textit{x} so that the calling application will know how many bytes were used.
355 As of v1.13, most functions will update your length on failure to indicate the size required by the function. Not all functions
356 support this so please check the source before you rely on it doing that.
361 the PRNG themselves so it is the responsibility of the calling function to initialize the PRNG before calling them.
363 Certain PRNG algorithms do not require a \textit{prng\_state} argument (sprng for example). The \textit{prng\_state} argument
374 /* register the system RNG */
377 /* make a 1024-bit RSA key with the system RNG */
384 /* use the key ... */
392 Most functions require inputs that are arrays of the data type \textit{unsigned char}. Whether it is a symmetric key, IV
393 for a chaining mode or public key packet it is assumed that regardless of the actual size of \textit{unsigned char} only the
398 For the purposes of this library, the term \textit{byte} will refer to an octet or eight bit word. Typically an array of
404 should never use the ECB modes directly to encrypt data. Instead you should use the ECB functions to make a chaining mode,
405 or use one of the provided chaining modes. All of the ciphers are written as ECB interfaces since it allows the rest of
406 the API to grow in a modular fashion.
410 have the same prototype and store their keys as naturally as possible. This also removes the need for dynamic memory
412 functions which are (given that XXX is the name of the cipher) the following:
421 The XXX\_setup() routine will setup the cipher to be used with a given number of rounds and a given key length (in bytes).
422 The number of rounds can be set to zero to use the default, which is generally a good idea.
424 If the function returns successfully the variable \textit{skey} will have a scheduled key stored in it. It's important to note
425 that you should only used this scheduled key with the intended cipher. For example, if you call \textit{blowfish\_setup()} do not
426 pass the scheduled key onto \textit{rc5\_ecb\_encrypt()}. All built--in setup functions do not allocate memory off the heap so
427 when you are done with a key you can simply discard it (e.g. they can be on the stack). However, to maintain proper coding
428 practices you should always call the respective XXX\_done() function. This allows for quicker porting to applications with
443 These two functions will encrypt or decrypt (respectively) a single block of text\footnote{The size of which depends on
444 which cipher you are using.}, storing the result in the \textit{ct} buffer (\textit{pt} resp.). It is possible that the input and output buffer are
445 the same buffer. For the encrypt function \textit{pt}\footnote{pt stands for plaintext.} is the input and
446 \textit{ct}\footnote{ct stands for ciphertext.} is the output. For the decryption function it's the opposite. They both
448 call the following self-test function.
455 This function will return {\bf CRYPT\_OK} if the cipher matches the test vectors from the design publication it is
464 Essentially, it will round the input keysize in \textit{keysize} down to the next appropriate key size. This function
465 will return {\bf CRYPT\_OK} if the key size specified is acceptable. For example:
487 When you are finished with a cipher you can de--initialize it with the done function.
491 For the software based ciphers within LibTomCrypt, these functions will not do anything. However, user supplied
493 setup function must also call the respective cipher done function when finished.
511 /* schedule the key */
512 if ((err = blowfish_setup(key, /* the key we will use */
515 &skey) /* where to put the scheduled key */
521 /* encrypt the block */
526 /* now ct holds the encrypted version of pt */
528 /* decrypt the block */
533 /* now we have decrypted ct to the original plaintext in pt */
535 /* Terminate the cipher context */
545 As a general rule of thumb, do not use symmetric keys under 80 bits if you can help it. Only a few of the ciphers support smaller
547 because you are to be paranoid. It is because if your PRNG has a bias of any sort the more bits the better. For
548 example, if you have $\mbox{Pr}\left[X = 1\right] = {1 \over 2} \pm \gamma$ where $\vert \gamma \vert > 0$ then the
553 The number of rounds of most ciphers is not an option you can change. Only RC5 allows you to change the number of
554 rounds. By passing zero as the number of rounds all ciphers will use their default number of rounds. Generally the
555 ciphers are configured such that the default number of rounds provide adequate security for the given block and key
558 \mysection{The Cipher Descriptors}
560 To facilitate automatic routines an array of cipher descriptors is provided in the array \textit{cipher\_descriptor}. An element
561 of this array has the following (partial) format (See Section \ref{sec:cipherdesc}):
588 Where \textit{name} is the lower case ASCII version of the name. The fields \textit{min\_key\_length} and \textit{max\_key\_length}
589 are the minimum and maximum key sizes in bytes. The \textit{block\_length} member is the block size of the cipher
590 in bytes. As a good rule of thumb it is assumed that the cipher supports
591 the min and max key lengths but not always everything in between. The \textit{default\_rounds} field is the default number
594 For a plugin to be compliant it must provide at least each function listed before the accelerators begin. Accelerators are optional,
597 The remaining fields are all pointers to the core functions for each cipher. The end of the cipher\_descriptor array is
600 As of this release the current cipher\_descriptors elements are the following:
639 For AES, (also known as Rijndael) there are four descriptors which complicate issues a little. The descriptors
640 rijndael\_desc and rijndael\_enc\_desc provide the cipher named \textit{rijndael}. The descriptors aes\_desc and
641 aes\_enc\_desc provide the cipher name \textit{aes}. Functionally both \textit{rijndael} and \textit{aes} are the same cipher. The
642 only difference is when you call find\_cipher() you have to pass the correct name. The cipher descriptors with \textit{enc}
643 in the middle (e.g. rijndael\_enc\_desc) are related to an implementation of Rijndael with only the encryption routine
644 and tables. The decryption and self--test function pointers of both \textit{encrypt only} descriptors are set to \textbf{NULL} and
647 The \textit{encrypt only} descriptors are useful for applications that only use the encryption function of the cipher. Algorithms such
648 as EAX, PMAC and OMAC only require the encryption function. So far this \textit{encrypt only} functionality has only been implemented for
649 Rijndael as it makes the most sense for this cipher.
652 Note that for \textit{DES} and \textit{3DES} they use 8 and 24 byte keys but only 7 and 21 [respectively] bytes of the keys are in
653 fact used for the purposes of encryption. My suggestion is just to use random 8/24 byte keys instead of trying to make a 8/24
654 byte string from the real 7/21 byte key.
658 the file \textit{tomcrypt\_cfg.h}. The first option is \textit{TWOFISH\_SMALL} which when defined will force the Twofish code
659 to not pre-compute the Twofish \textit{$g(X)$} function as a set of four $8 \times 32$ s-boxes. This means that a scheduled
660 key will require less ram but the resulting cipher will be slower. The second option is \textit{TWOFISH\_TABLES} which when
661 defined will force the Twofish code to use pre-computed tables for the two s-boxes $q_0, q_1$ as well as the multiplication
662 by the polynomials 5B and EF used in the MDS multiplication. As a result the code is faster and slightly larger. The
663 speed increase is useful when \textit{TWOFISH\_SMALL} is defined since the s-boxes and MDS multiply form the heart of the
686 To work with the cipher\_descriptor array there is a function:
691 Which will search for a given name in the array. It returns $-1$ if the cipher is not found, otherwise it returns
692 the location in the array where the cipher was found. For example, to indirectly setup Blowfish you can also use:
709 /* generic call to function (assuming the key
723 A good safety would be to check the return value of \textit{find\_cipher()} before accessing the desired function. In order
724 to use a cipher with the descriptor table you must register it first using:
729 Which accepts a pointer to a descriptor and returns the index into the global descriptor table. If an error occurs such
730 as there is no more room (it can have 32 ciphers at most) it will return {\bf{-1}}. If you try to add the same cipher more
731 than once it will just return the index of the first copy. To remove a cipher call:
736 Which returns {\bf CRYPT\_OK} if it removes the cipher, otherwise it returns {\bf CRYPT\_ERROR}.
744 /* register the cipher */
766 A typical symmetric block cipher can be used in chaining modes to effectively encrypt messages larger than the block
767 size of the cipher. Given a key $k$, a plaintext $P$ and a cipher $E$ we shall denote the encryption of the block
768 $P$ under the key $k$ as $E_k(P)$. In some modes there exists an initial vector denoted as $C_{-1}$.
772 ECB or Electronic Codebook Mode is the simplest method to use. It is given as:
776 This mode is very weak since it allows people to swap blocks and perform replay attacks if the same key is used more
786 It is important that the initial vector be unique and preferably random for each message encrypted under the same key.
790 CTR or Counter Mode is a mode which only uses the encryption function of the cipher. Given a initial vector which is
791 treated as a large binary counter the CTR mode is given as:
796 Where $W$ is the size of a block in bits (e.g. 64 for Blowfish). As long as the initial vector is random for each message
797 encrypted under the same key replay and swap attacks are infeasible. CTR mode may look simple but it is as secure
798 as the block cipher is under a chosen plaintext attack (provided the initial vector is unique).
807 Note that in this library the output feedback width is equal to the size of the block cipher. That is this mode is used
808 to encrypt whole blocks at a time. However, the library will buffer data allowing the user to encrypt or decrypt partial
809 blocks without a delay. When this mode is first setup it will initially encrypt the initial vector as required.
818 Like the CFB mode the output width in CFB mode is the same as the width of the block cipher. OFB mode will also
819 buffer the output which will allow you to encrypt or decrypt partial blocks without delay.
822 My personal preference is for the CTR mode since it has several key benefits:
824 \item No short cycles which is possible in the OFB and CFB modes.
825 \item Provably as secure as the block cipher being used under a chosen plaintext attack.
826 \item Technically does not require the decryption routine of the cipher.
827 \item Allows random access to the plaintext.
828 \item Allows the encryption of block sizes that are not equal to the size of the block cipher.
830 The CTR, CFB and OFB routines provided allow you to encrypt block sizes that differ from the ciphers block size. They
831 accomplish this by buffering the data required to complete a block. This allows you to encrypt or decrypt any size
832 block of memory with either of the three modes.
834 The ECB and CBC modes process blocks of the same size as the cipher at a time. Therefore, they are less flexible than the
839 Ciphertext stealing is a method of dealing with messages in CBC mode which are not a multiple of the block length. This is accomplished
840 by encrypting the last ciphertext block in ECB mode, and XOR'ing the output against the last partial block of plaintext. LibTomCrypt does not
841 support this mode directly but it is fairly easy to emulate with a call to the cipher's ecb\_encrypt() callback function.
843 The more sane way to deal with partial blocks is to pad them with zeroes, and then use CBC normally.
848 The library provides simple support routines for handling CBC, CTR, CFB, OFB and ECB encoded messages. Assuming the mode
849 you want is XXX there is a structure called \textit{symmetric\_XXX} that will contain the information required to
875 In each case, \textit{cipher} is the index into the cipher\_descriptor array of the cipher you want to use. The \textit{IV} value is
876 the initialization vector to be used with the cipher. You must fill the IV yourself and it is assumed they are the same
877 length as the block size\footnote{In other words the size of a block of plaintext for the cipher, e.g. 8 for DES, 16 for AES, etc.}
878 of the cipher you choose. It is important that the IV be random for each unique message you want to encrypt. The
879 parameters \textit{key}, \textit{keylen} and \textit{num\_rounds} are the same as in the XXX\_setup() function call. The final parameter
880 is a pointer to the structure you want to hold the information for the mode of operation.
883 In the case of CTR mode there is an additional parameter \textit{ctr\_mode} which specifies the mode that the counter is to be used in.
884 If \textbf{CTR\_COUNTER\_ LITTLE\_ENDIAN} was specified then the counter will be treated as a little endian value. Otherwise, if
885 \textbf{CTR\_COUNTER\_BIG\_ENDIAN} was specified the counter will be treated as a big endian value. As of v1.15 the RFC 3686 style of
886 increment then encrypt is also supported. By OR'ing \textbf{LTC\_CTR\_RFC3686} with the CTR \textit{mode} value, ctr\_start() will increment
887 the counter before encrypting it for the first time.
889 The routines return {\bf CRYPT\_OK} if the cipher initialized correctly, otherwise, they return an error code.
892 To actually encrypt or decrypt the following routines are provided:
908 In all cases, \textit{len} is the size of the buffer (as number of octets) to encrypt or decrypt. The CTR, OFB and CFB modes are order sensitive but not
910 and end up with the same ciphertext. However, encrypting \textit{ABC} and \textit{DABC} will result in different ciphertexts. All
911 five of the modes will return {\bf CRYPT\_OK} on success from the encrypt or decrypt functions.
913 In the ECB and CBC cases, \textit{len} must be a multiple of the ciphers block size. In the CBC case, you must manually pad the end of your message (either with
916 To decrypt in either mode, perform the setup like before (recall you have to fetch the IV value you used), and use the decrypt routine on all of the blocks.
919 To change or read the IV of a previously initialized chaining mode use the following two functions.
932 The XXX\_getiv() functions will read the IV out of the chaining mode and store it into \textit{IV} along with the length of the IV
933 stored in \textit{len}. The XXX\_setiv will initialize the chaining mode state as if the original IV were the new IV specified. The length
934 of the IV passed in must be the size of the ciphers block size.
936 The XXX\_setiv() functions are handy if you wish to change the IV without re--keying the cipher.
938 What the \textit{setiv} function will do depends on the mode being changed. In CBC mode, the new IV replaces the existing IV as if it
939 were the last ciphertext block. In CFB mode, the IV is encrypted as if it were the prior encrypted pad. In CTR mode, the IV is encrypted without
940 first incrementing it (regardless of the LTC\_RFC\_3686 flag presence). In F8 mode, the IV is encrypted and becomes the new pad. It does not change
941 the salted IV, and is only meant to allow seeking within a session. In LRW, it changes the tweak, forcing a computation of the tweak pad, allowing for
942 seeking within the session. In OFB mode, the IV is encrypted and becomes the new pad.
945 To terminate an open stream call the done function.
952 This will terminate the stream (by terminating the cipher) and return \textbf{CRYPT\_OK} if successful.
976 IV, /* the initial vector */
977 key, /* the secret key */
981 &ctr) /* where to store the CTR state */
1000 if ((err = ctr_setiv( IV, /* the initial IV we gave to ctr_start */
1001 16, /* the IV is 16 bytes long */
1002 &ctr) /* the ctr state we wish to modify */
1017 /* terminate the stream */
1033 LRW mode is a cipher mode which is meant for indexed encryption like used to handle storage media. It is meant to have efficient seeking and overcome the
1034 security problems of ECB mode while not increasing the storage requirements. It is used much like any other chaining mode except with two key differences.
1036 The key is specified as two strings the first key $K_1$ is the (normally AES) key and can be any length (typically 16, 24 or 32 octets long). The second key
1037 $K_2$ is the \textit{tweak} key and is always 16 octets long. The tweak value is \textbf{NOT} a nonce or IV value it must be random and secret.
1052 This will initialize the LRW context with the given (16 octet) \textit{IV}, cipher $K_1$ \textit{key} of length \textit{keylen} octets and the (16 octet) $K_2$ \textit{tweak}.
1053 While LRW was specified to be used only with AES, LibTomCrypt will allow any 128--bit block cipher to be specified as indexed by \textit{cipher}. The
1054 number of rounds for the block cipher \textit{num\_rounds} can be 0 to use the default number of rounds for the given cipher.
1056 To process data use the following functions:
1071 These will encrypt (or decrypt) the plaintext to the ciphertext buffer (or vice versa). The length is specified by \textit{len} in octets but must be a multiple
1072 of 16. The LRW code uses a fast tweak update such that consecutive blocks are encrypted faster than if random seeking where used.
1074 To manipulate the IV use the following functions:
1086 These will get or set the 16--octet IV. Note that setting the IV is the same as \textit{seeking} and unlike other modes is not a free operation. It requires
1087 the entire tweak which is slower than sequential use. Avoid seeking excessively in performance constrained code.
1089 To terminate the LRW state use the following:
1098 The F8 Chaining mode (see RFC 3711 for instance) is yet another chaining mode for block ciphers. It behaves much like CTR mode in that it XORs a keystream
1099 against the plaintext to encrypt. F8 mode comes with the additional twist that the counter value is secret, encrypted by a \textit{salt key}. We
1100 initialize F8 mode with the following function call:
1113 This will start the F8 mode state using \textit{key} as the secret key, \textit{IV} as the counter. It uses the \textit{salt\_key} as IV encryption key
1114 (\textit{m} in the RFC 3711). The salt\_key can be shorter than the secret key but it should not be longer.
1116 To encrypt or decrypt data we use the following two functions:
1130 These will encrypt or decrypt a variable length array of bytes using the F8 mode state specified. The length is specified in bytes and does not have to be a multiple
1131 of the ciphers block size.
1133 To change or retrieve the current counter IV value use the following functions:
1144 These work with the current IV value only and not the encrypted IV value specified during the call to f8\_start(). The purpose of these two functions is to be
1145 able to seek within a current session only. If you want to change the session IV you will have to call f8\_done() and then start a new state with
1148 To terminate an F8 state call the following function:
1160 M. Bellare, P. Rogaway, D. Wagner, A Conventional Authenticated-Encryption Mode.} in a manner similar to the way it was intended to be used
1161 by the designers. First, a short description of what EAX mode is before we explain how to use it. EAX is a mode that requires a cipher,
1166 The \textit{header} data is meant to be meta--data associated with a stream that isn't private (e.g., protocol messages). It can
1167 be added at anytime during an EAX stream, and is part of the authentication tag. That is, changes in the meta-data can be detected by changes in the output tag.
1169 The mode can then process plaintext producing ciphertext as well as compute a partial checksum. The actual checksum
1170 called a \textit{tag} is only emitted when the message is finished. In the interim, the user can process any arbitrary
1171 sized message block to send to the recipient as ciphertext. This makes the EAX mode especially suited for streaming modes
1174 The mode is initialized with the following function.
1187 Where \textit{eax} is the EAX state. The \textit{cipher} parameter is the index of the desired cipher in the descriptor table.
1188 The \textit{key} parameter is the shared secret symmetric key of length \textit{keylen} octets. The \textit{nonce} parameter is the
1189 random public string of length \textit{noncelen} octets. The \textit{header} parameter is the random (or fixed or \textbf{NULL}) header for the
1192 When this function completes, the \textit{eax} state will be initialized such that you can now either have data decrypted or
1195 To encrypt or decrypt data in a streaming mode use the following.
1208 The function \textit{eax\_encrypt} will encrypt the bytes in \textit{pt} of \textit{length} octets, and store the ciphertext in
1209 \textit{ct}. Note: \textit{ct} and \textit{pt} may be the same region in memory. This function will also send the ciphertext
1210 through the OMAC function. The function \textit{eax\_decrypt} decrypts \textit{ct}, and stores it in \textit{pt}. This also allows
1211 \textit{pt} and \textit{ct} to be the same region in memory.
1213 You cannot both encrypt or decrypt with the same \textit{eax} context. For bi--directional communication you will need to initialize
1216 Note: both of these functions allow you to send the data in any granularity but the order is important. While
1217 the eax\_init() function allows you to add initial header data to the stream you can also add header data during the
1218 EAX stream with the following.
1226 This will add the \textit{length} octet from \textit{header} to the given \textit{eax} header. Once the message is finished, the
1227 \textit{tag} (checksum) may be computed with the following function:
1235 This will terminate the EAX state \textit{eax}, and store up to \textit{taglen} bytes of the message tag in \textit{tag}. The function
1236 then stores how many bytes of the tag were written out back in to \textit{taglen}.
1238 The EAX mode code can be tested to ensure it matches the test vectors by calling the following function:
1243 This requires that the AES (or Rijndael) block cipher be registered with the cipher\_descriptor table first.
1264 nonce, /* the nonce */
1293 /* now we have the authentication tag in "tag" and
1298 You can also perform an entire EAX state on a block of memory in a single function call with the
1324 Both essentially just call eax\_init() followed by eax\_encrypt() (or eax\_decrypt() respectively) and eax\_done(). The parameters
1325 have the same meaning as with those respective functions.
1327 The only difference is eax\_decrypt\_verify\_memory() does not emit a tag. Instead you pass it a tag as input and it compares it against
1328 the tag it computed while decrypting the message. If the tags match then it stores a $1$ in \textit{res}, otherwise it stores a $0$.
1345 This will initialize the \textit{ocb} context using cipher descriptor \textit{cipher}. It will use a \textit{key} of length \textit{keylen}
1346 and the random \textit{nonce}. Note that \textit{nonce} must be a random (public) string the same length as the block ciphers
1349 This mode has no \textit{Associated Data} like EAX mode does which means you cannot authenticate metadata along with the stream.
1350 To encrypt or decrypt data use the following.
1363 This will encrypt (or decrypt for the latter) a fixed length of data from \textit{pt} to \textit{ct} (vice versa for the latter).
1364 They assume that \textit{pt} and \textit{ct} are the same size as the block cipher's block size. Note that you cannot call
1366 states (with different nonces). Also \textit{pt} and \textit{ct} may point to the same location in memory.
1370 When you are finished encrypting the message you call the following function to compute the tag.
1383 you can pass them here. This will also encrypt the \textit{ptlen} bytes in \textit{pt} and store them in \textit{ct}. It will also
1384 store up to \textit{taglen} bytes of the tag into \textit{tag}.
1386 Note that \textit{ptlen} must be less than or equal to the block size of block cipher chosen. Also note that if you have
1387 an input message equal to the length of the block size then you pass the data here (not to ocb\_encrypt()) only.
1389 To terminate a decrypt stream and compared the tag you call the following.
1401 Similarly to the previous function you can pass trailing message bytes into this function. This will compute the
1402 tag of the message (internally) and then compare it against the \textit{taglen} bytes of \textit{tag} provided. By default
1407 To make life simpler the following two functions are provided for memory bound OCB.
1420 This will OCB encrypt the message \textit{pt} of length \textit{ptlen}, and store the ciphertext in \textit{ct}. The length \textit{ptlen}
1435 Similarly, this will OCB decrypt, and compare the internally computed tag against the tag provided. \textit{res} is set
1440 it is only meant for \textit{packet} mode where the length of the input is known in advance. Since it is a packet mode function, CCM only has one
1441 function that performs the protocol.
1457 This performs the \textit{CCM} operation on the data. The \textit{cipher} variable indicates which cipher in the descriptor table to use. It must have a
1460 The key can be specified in one of two fashions. First, it can be passed as an array of octets in \textit{key} of length \textit{keylen}. Alternatively,
1461 it can be passed in as a previously scheduled key in \textit{uskey}. The latter fashion saves time when the same key is used for multiple packets. If
1464 The nonce or salt is \textit{nonce} of length \textit{noncelen} octets. The header is meta--data you want to send with the message but not have
1465 encrypted, it is stored in \textit{header} of length \textit{headerlen} octets. The header can be zero octets long (if $headerlen = 0$ then
1468 The plaintext is stored in \textit{pt}, and the ciphertext in \textit{ct}. The length of both are expected to be equal and is passed in as \textit{ptlen}. It is
1469 allowable that $pt = ct$. The \textit{direction} variable indicates whether encryption (direction $=$ \textbf{CCM\_ENCRYPT}) or
1474 You can test the implementation of CCM with the following function.
1481 This will return \textbf{CRYPT\_OK} if the CCM routine passes known test vectors. It requires AES or Rijndael to be registered previously, otherwise it will
1485 The following is a sample of how to call CCM.
1517 /* ct[0..31] and tag[0..15] now hold the output */
1535 /* now pt[0..31] should hold the original plaintext,
1536 tagcp[0..15] and tag[0..15] should have the same contents */
1546 A GCM stream is meant to be processed in three modes, one after another. First, the initial vector (per session) data is processed. This should be
1547 unique to every session. Next, the the optional additional authentication data is processed, and finally the plaintext (or ciphertext depending on the direction).
1550 To initialize the GCM context with a secret key call the following function.
1559 This initializes the GCM state \textit{gcm} for the given cipher indexed by \textit{cipher}, with a secret key \textit{key} of length \textit{keylen} octets. The cipher
1563 After the state has been initialized (or reset) the next step is to add the session (or packet) initial vector. It should be unique per packet encrypted.
1571 This adds the initial vector octets from \textit{IV} of length \textit{IVlen} to the GCM state \textit{gcm}. You can call this function as many times as required
1572 to process the entire IV.
1574 Note: the GCM protocols provides a \textit{shortcut} for 12--byte IVs where no pre-processing is to be done. If you want to minimize per packet latency it is ideal
1578 After the entire IV has been processed, the additional authentication data can be processed. Unlike the IV, a packet/session does not require additional
1579 authentication data (AAD) for security. The AAD is meant to be used as side--channel data you want to be authenticated with the packet. Note: once
1580 you begin adding AAD to the GCM state you cannot return to adding IV data until the state has been reset.
1588 This adds the additional authentication data \textit{adata} of length \textit{adatalen} to the GCM state \textit{gcm}.
1591 After the AAD has been processed, the plaintext (or ciphertext depending on the direction) can be processed.
1601 This processes message data where \textit{pt} is the plaintext and \textit{ct} is the ciphertext. The length of both are equal and stored in \textit{ptlen}. Depending on
1602 the mode \textit{pt} is the input and \textit{ct} is the output (or vice versa). When \textit{direction} equals \textbf{GCM\_ENCRYPT} the plaintext is read,
1603 encrypted and stored in the ciphertext buffer. When \textit{direction} equals \textbf{GCM\_DECRYPT} the opposite occurs.
1606 To terminate a GCM state and retrieve the message authentication tag call the following function.
1614 This terminates the GCM state \textit{gcm} and stores the tag in \textit{tag} of length \textit{taglen} octets.
1617 The call to gcm\_init() will perform considerable pre--computation (when \textbf{GCM\_TABLES} is defined) and if you're going to be dealing with a lot of packets
1618 it is very costly to have to call it repeatedly. To aid in this endeavour, the reset function has been provided.
1625 This will reset the GCM state \textit{gcm} to the state that gcm\_init() left it. The user would then call gcm\_add\_iv(), gcm\_add\_aad(), etc.
1628 To process a single packet under any given key the following helper function can be used.
1644 This will initialize the GCM state with the given key, IV and AAD value then proceed to encrypt or decrypt the message text and store the final
1645 message tag. The definition of the variables is the same as it is for all the manual functions.
1647 If you are processing many packets under the same key you shouldn't use this function as it invokes the pre--computation with each call.
1650 The following is an example usage of how to use GCM over multiple packets with a shared secret key.
1665 /* reset the state */
1670 /* Add the IV */
1675 /* Add the AAD (note: aad can be NULL if aadlen == 0) */
1680 /* process the plaintext */
1686 /* Finish up and get the MAC tag */
1692 /* ... send a header describing the lengths ... */
1694 /* depending on the protocol and how IV is
1698 /* send the aad */
1701 /* send the ciphertext */
1704 /* send the tag */
1722 /* init the GCM state */
1751 Like the ciphers, there are hash core functions and a universal data type to hold the hash state called \textit{hash\_state}. To initialize hash
1752 XXX (where XXX is the name) call:
1758 This simply sets up the hash to the default state governed by the specifications of the hash. To add data to the message being hashed call:
1765 are buffered. The data can be passed in any sized chunks as long as the order of the bytes are the same the message digest (hash output) will be the same. For example,
1771 Will produce the same message digest as the single call:
1777 To finally get the message digest (the hash) call:
1783 This function will finish up the hash and store the result in the \textit{out} array. You must ensure that \textit{out} is long
1784 enough for the hash in question. Often hashes are used to get keys for symmetric ciphers so the \textit{XXX\_done()} functions
1785 will wipe the \textit{md} variable before returning automatically.
1792 This will return {\bf CRYPT\_OK} if the hash matches the test vectors, otherwise it returns an error code. An
1802 /* setup the hash */
1805 /* add the message */
1808 /* get the hash in out[0..15] */
1817 Like the set of ciphers, the set of hashes have descriptors as well. They are stored in an array called \textit{hash\_descriptor} and
1824 unsigned long blocksize; /* the block size the hash uses */
1839 The \textit{name} member is the name of the hash function (all lowercase). The \textit{hashsize} member is the size of the digest output
1840 in bytes, while \textit{blocksize} is the size of blocks the hash expects to the compression function. Technically, this detail is not important
1843 The \textit{init} member initializes the hash, \textit{process} passes data through the hash, \textit{done} terminates the hash and retrieves the
1844 digest. The \textit{test} member tests the hash against the specified test vectors.
1846 There is a function to search the array as well called \textit{int find\_hash(char *name)}. It returns -1 if the hash is not found, otherwise, the
1847 position in the descriptor table of the hash.
1849 In addition, there is also find\_hash\_oid() which finds a hash by the ASN.1 OBJECT IDENTIFIER string.
1855 You can use the table to indirectly call a hash function that is chosen at run-time. For example:
1900 Note the usage of \textbf{MAXBLOCKSIZE}. In LibTomCrypt, no symmetric block, key or hash digest is larger than \textbf{MAXBLOCKSIZE} in
1903 There are three helper functions to make working with hashes easier. The first is a function to hash a buffer, and produce the digest in a single
1915 This will hash the data pointed to by \textit{in} of length \textit{inlen}. The hash used is indexed by the \textit{hash} parameter. The message
1916 digest is stored in \textit{out}, and the \textit{outlen} parameter is updated to hold the message digest size.
1918 The next helper function allows for the hashing of a file based on a file name.
1927 This will hash the file named by \textit{fname} using the hash indexed by \textit{hash}. The file named in this function call must be readable by the
1928 user owning the process performing the request. This function can be omitted by the \textbf{LTC\_NO\_FILE} define, which forces it to return \textbf{CRYPT\_NOP}
1929 when it is called. The message digest is stored in \textit{out}, and the \textit{outlen} parameter is updated to hold the message digest size.
1939 This will hash the file identified by the handle \textit{in} using the hash indexed by \textit{hash}. This will begin hashing from the current file pointer position, and
1940 will not rewind the file pointer when finished. This function can be omitted by the \textbf{LTC\_NO\_FILE} define, which forces it to return \textbf{CRYPT\_NOP}
1941 when it is called. The message digest is stored in \textit{out}, and the \textit{outlen} parameter is updated to hold the message digest size.
1943 To perform the above hash with md5 the following code could be used:
1953 /* register the hash */
1959 /* get the index of the hash */
1962 /* call the hash */
1975 Similar to the cipher descriptor table you must register your hash algorithms before you can use them. These functions
1976 work exactly like those of the cipher registration code. The functions are:
1984 The following hashes are provided as of this release within the LibTomCrypt library:
2014 An addition to the suite of hash functions is the \textit{Cipher Hash Construction} or \textit{CHC} mode. In this mode
2018 In order to use the CHC system the developer will have to take a few extra steps. First the \textit{chc\_desc} hash
2019 descriptor must be registered with register\_hash(). At this point the CHC hash cannot be used to hash
2020 data. While it is in the hash system you still have to tell the CHC code which cipher to use. This is accomplished
2021 via the chc\_register() function.
2028 A cipher has to be registered with CHC (and also in the cipher descriptor tables with
2029 register\_cipher()). The chc\_register() function will bind a cipher to the CHC system. Only one cipher can
2030 be bound to the CHC hash at a time. There are additional requirements for the system to work.
2033 \item The cipher must have a block size greater than 64--bits.
2034 \item The cipher must allow an input key the size of the block size.
2037 Example of using CHC with the AES block cipher.
2068 It is highly recommended that you \textbf{not} use the MD4 or MD5 hashes for the purposes of digital signatures or authentication codes.
2069 These hashes are provided for completeness and they still can be used for the purposes of password hashing or one-way accumulators
2072 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
2077 Thanks to Dobes Vandermeer, the library now includes support for hash based message authentication codes, or HMAC for short. An HMAC
2078 of a message is a keyed authentication code that only the owner of a private symmetric key will be able to verify. The purpose is
2080 eavesdropper will not be able to verify the authenticity of a message.
2082 The HMAC support works much like the normal hash functions except that the initialization routine requires you to pass a key
2083 and its length. The key is much like a key you would pass to a cipher. That is, it is simply an array of octets stored in
2084 unsigned characters. The initialization routine is:
2092 The \textit{hmac} parameter is the state for the HMAC code. The \textit{hash} parameter is the index into the descriptor table of the hash you want
2093 to use to authenticate the message. The \textit{key} parameter is the pointer to the array of chars that make up the key. The \textit{keylen} parameter is the
2094 length (in octets) of the key you want to use to authenticate the message. To send octets of a message through the HMAC system you must use the following function:
2101 \textit{hmac} is the HMAC state you are working with. \textit{buf} is the array of octets to send into the HMAC process. \textit{len} is the
2102 number of octets to process. Like the hash process routines you can send the data in arbitrarily sized chunks. When you
2103 are finished with the HMAC process you must call the following function to get the HMAC code:
2110 The \textit{hmac} parameter is the HMAC state you are working with. The \textit{out} parameter is the array of octets where the HMAC code should be stored.
2111 You must set \textit{outlen} to the size of the destination buffer before calling this function. It is updated with the length of the HMAC code
2112 produced (depending on which hash was picked). If \textit{outlen} is less than the size of the message digest (and ultimately
2113 the HMAC code) then the HMAC code is truncated as per FIPS-198 specifications (e.g. take the first \textit{outlen} bytes).
2115 There are two utility functions provided to make using HMACs easier to do. They accept the key and information about the
2116 message (file pointer, address in memory), and produce the HMAC result in one shot. These are useful if you want to avoid
2117 calling the three step process yourself.
2127 This will produce an HMAC code for the array of octets in \textit{in} of length \textit{inlen}. The index into the hash descriptor
2128 table must be provided in \textit{hash}. It uses the key from \textit{key} with a key length of \textit{keylen}.
2129 The result is stored in the array of octets \textit{out} and the length in \textit{outlen}. The value of \textit{outlen} must be set
2130 to the size of the destination buffer before calling this function. Similarly for files there is the following function:
2139 \textit{hash} is the index into the hash descriptor table of the hash you want to use. \textit{fname} is the filename to process.
2140 \textit{key} is the array of octets to use as the key of length \textit{keylen}. \textit{out} is the array of octets where the
2143 To test if the HMAC code is working there is the following function:
2148 Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code. Some example code for using the
2172 /* start the HMAC */
2190 printf("The hmac is %lu bytes long\n", dstlen);
2202 CMAC within NIST, for the purposes of this library OMAC and CMAC are synonymous. From an API standpoint, the OMAC routines work much like the
2213 The \textit{omac} parameter is the state for the OMAC algorithm. The \textit{cipher} parameter is the index into the cipher\_descriptor table
2214 of the cipher\footnote{The cipher must have a 64 or 128 bit block size. Such as CAST5, Blowfish, DES, AES, Twofish, etc.} you
2215 wish to use. The \textit{key} and \textit{keylen} parameters are the keys used to authenticate the data.
2217 To send data through the algorithm call
2224 This will send \textit{inlen} bytes from \textit{in} through the active OMAC state \textit{state}. Returns \textbf{CRYPT\_OK} if the
2225 function succeeds. The function is not sensitive to the granularity of the data. For example,
2232 Would produce the same result as,
2238 When you are done processing the message you can call the following to compute the message tag.
2246 Which will terminate the OMAC and output the \textit{tag} (MAC) to \textit{out}. Note that unlike the HMAC and other code
2247 \textit{outlen} can be smaller than the default MAC size (for instance AES would make a 16-byte tag). Part of the OMAC
2248 specification states that the output may be truncated. So if you pass in $outlen = 5$ and use AES as your cipher than
2249 the output MAC code will only be five bytes long. If \textit{outlen} is larger than the default size it is set to the default
2252 Similar to the HMAC code thethe
2263 This will compute the OMAC of \textit{inlen} bytes of \textit{in} using the key \textit{key} of length \textit{keylen} bytes and the cipher
2264 specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same
2277 Which will OMAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes
2278 and the cipher specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with
2279 the same rules as omac\_done.
2281 To test if the OMAC code is working there is the following function:
2286 Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code. Some example code for using the
2310 /* start the OMAC */
2328 printf("The omac is %lu bytes long\n", dstlen);
2337 The PMAC\footnote{J.Black, P.Rogaway, \textit{A Block--Cipher Mode of Operation for Parallelizable Message Authentication}}
2338 protocol is another MAC algorithm that relies solely on a symmetric-key block cipher. It uses essentially the same
2339 API as the provided OMAC code.
2341 A PMAC state is initialized with the following.
2350 Which initializes the \textit{pmac} state with the given \textit{cipher} and \textit{key} of length \textit{keylen} bytes. The chosen cipher
2353 To MAC data simply send it through the process function.
2361 This will process \textit{inlen} bytes of \textit{in} in the given \textit{state}. The function is not sensitive to the granularity of the
2369 Would produce the same result as,
2375 When a complete message has been processed the following function can be called to compute the message tag.
2383 This will store up to \textit{outlen} bytes of the tag for the given \textit{state} into \textit{out}. Note that if \textit{outlen} is larger
2384 than the size of the tag it is set to the amount of bytes stored in \textit{out}.
2386 Similar to the OMAC code the file and memory functions are also provided. To PMAC a buffer of memory in one shot use the
2397 This will compute the PMAC of \textit{msglen} bytes of \textit{msg} using the key \textit{key} of length \textit{keylen} bytes, and the cipher
2398 specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same
2411 Which will PMAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes,
2412 and the cipher specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with
2413 the same rules as pmac\_done().
2415 To test if the PMAC code is working there is the following function:
2420 Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code.
2423 Pelican MAC is a new (experimental) MAC by the AES team that uses four rounds of AES as a \textit{mixing function}. It achieves a very high
2433 This will initialize the Pelican state with the given AES key. Once this has been done you can begin processing data.
2441 This will process \textit{inlen} bytes of \textit{in} through the Pelican MAC. It's best that you pass in multiples of 16 bytes as it makes the
2449 This terminates a Pelican MAC and writes the 16--octet tag to \textit{out}.
2464 if ((err = pelican_init(&pelstate, /* the state */
2474 if ((err = pelican_process(&pelstate, /* the state */
2483 /* Terminate the MAC */
2484 if ((err = pelican_done(&pelstate,/* the state */
2485 tag /* where to store the tag */
2492 /* tag[0..15] has the MAC output now */
2500 by using a cipher in CBC mode. It also uses a single key which it expands into the requisite three keys for the MAC function. A XCBC--MAC state is
2501 initialized with the following function:
2511 This will initialize the XCBC--MAC state \textit{xcbc}, with the key specified in \textit{key} of length \textit{keylen} octets. The cipher indicated
2512 by the \textit{cipher} index can be either a 64 or 128--bit block cipher. This will return \textbf{CRYPT\_OK} on success.
2514 To process data through XCBC--MAC use the following function:
2523 This will add the message octets pointed to by \textit{in} of length \textit{inlen} to the XCBC--MAC state pointed to by \textit{state}. Like the other MAC functions,
2524 the granularity of the input is not important but the order is. This will return \textbf{CRYPT\_OK} on success.
2526 To compute the MAC tag value use the following function:
2535 This will retrieve the XCBC--MAC tag from the state pointed to by \textit{state}, and store it in the array pointed to by \textit{out}. The \textit{outlen} parameter
2536 specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when the function returns. This will return \textbf{CRYPT\_OK} on success.
2538 Helper functions are provided to make parsing memory buffers and files easier. The following functions are provided:
2548 This will compute the XCBC--MAC of \textit{msglen} bytes of \textit{msg}, using the key \textit{key} of length \textit{keylen} bytes, and the cipher
2549 specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same rules as xcbc\_done().
2561 Which will XCBC--MAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes, and the cipher
2562 specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same rules as xcbc\_done().
2565 To test XCBC--MAC for RFC 3566 compliance use the following function:
2572 This will return \textbf{CRYPT\_OK} on success. This requires the AES or Rijndael descriptor be previously registered, otherwise, it will return
2576 The F9--MAC is yet another CBC--MAC variant proposed for the 3GPP standard. Originally specified to be used with the KASUMI block cipher, it can also be used
2577 with other ciphers. For LibTomCrypt, the F9--MAC code can use any cipher.
2580 F9--MAC differs slightly from the other MAC functions in that it requires the caller to perform the final message padding. The padding quite simply is a direction
2581 bit followed by a 1 bit and enough zeros to make the message a multiple of the cipher block size. If the message is byte aligned, the padding takes on the form of
2582 a single 0x40 or 0xC0 byte followed by enough 0x00 bytes to make the message proper multiple.
2584 If the user simply wants a MAC function (hint: use OMAC) padding with a single 0x40 byte should be sufficient for security purposes and still be reasonably compatible
2588 A F9--MAC state is initialized with the following function:
2597 This will initialize the F9--MAC state \textit{f9}, with the key specified in \textit{key} of length \textit{keylen} octets. The cipher indicated
2598 by the \textit{cipher} index can be either a 64 or 128--bit block cipher. This will return \textbf{CRYPT\_OK} on success.
2600 To process data through F9--MAC use the following function:
2608 This will add the message octets pointed to by \textit{in} of length \textit{inlen} to the F9--MAC state pointed to by \textit{state}. Like the other MAC functions,
2609 the granularity of the input is not important but the order is. This will return \textbf{CRYPT\_OK} on success.
2611 To compute the MAC tag value use the following function:
2620 This will retrieve the F9--MAC tag from the state pointed to by \textit{state}, and store it in the array pointed to by \textit{out}. The \textit{outlen} parameter
2621 specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when the function returns. This will return
2624 Helper functions are provided to make parsing memory buffers and files easier. The following functions are provided:
2634 This will compute the F9--MAC of \textit{msglen} bytes of \textit{msg}, using the key \textit{key} of length \textit{keylen} bytes, and the cipher
2635 specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same rules as f9\_done().
2647 Which will F9--MAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes, and the cipher
2648 specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same rules as f9\_done().
2651 To test f9--MAC for RFC 3566 compliance use the following function:
2658 This will return \textbf{CRYPT\_OK} on success. This requires the
2663 The library provides an array of core functions for Pseudo-Random Number Generators (PRNGs) as well. A cryptographic PRNG is
2671 This will setup the PRNG for future use and not seed it. In order for the PRNG to be cryptographically useful you must give it
2672 entropy. Ideally you'd have some OS level source to tap like in UNIX. To add entropy to the PRNG call:
2679 Which returns {\bf CRYPT\_OK} if the entropy was accepted. Once you think you have enough entropy you call another
2680 function to put the entropy into action.
2694 Which returns the number of bytes read from the PRNG. When you are finished with a PRNG state you call
2695 the following.
2703 so that you can later resume the PRNG call the following.
2712 This will write a \textit{PRNG state} to the buffer \textit{out} of length \textit{outlen} bytes. The idea of
2713 the export is meant to be used as a \textit{seed file}. That is, when the program starts up there will not likely
2714 be that much entropy available. To import a state to seed a PRNG call the following function.
2723 This will call the start and add\_entropy functions of the given PRNG. It will use the state in
2724 \textit{in} of length \textit{inlen} as the initial seed. You must pass the same seed length as was exported
2725 by the corresponding export function.
2727 Note that importing a state will not \textit{resume} the PRNG from where it left off. That is, if you export
2728 a state, emit (say) 8 bytes and then import the previously exported state the next 8 bytes will not
2729 specifically equal the 8 bytes you generated previously.
2731 When a program is first executed the normal course of operation is:
2735 \item Start, use your entropy via add\_entropy and ready the PRNG yourself.
2738 When your program is finished you simply call the export function and save the state to a medium (disk,
2739 flash memory, etc). The next time your application starts up you can detect the state, feed it to the
2741 fresh state. This helps in the case that the program aborts or the machine is powered down without
2744 Note that even if you have a state to import it is important to add new entropy to the state. However,
2747 To test a PRNG for operational conformity call the following functions.
2758 It is possible to be adding entropy and reading from a PRNG at the same time. For example, if you first seed the PRNG
2759 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
2760 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
2761 checking is guaranteed to see if the entropy is sufficient, or if the PRNG is even in a ready state before reading.
2765 the entropy added is not random.
2796 PRNGs have descriptors that allow plugin driven functions to be created using PRNGs. The plugin descriptors are stored in the structure \textit{prng\_descriptor}. The
2823 To find a PRNG in the descriptor table the following function can be used:
2828 This will search the PRNG descriptor table for the PRNG named \textit{name}. It will return -1 if the PRNG is not found, otherwise, it returns
2829 the index into the descriptor table.
2831 Just like the ciphers and hashes, you must register your prng before you can use it. The two functions provided work exactly as those for the cipher registry functions.
2832 They are the following:
2839 The register function will register the PRNG, and return the index into the table where it was placed (or -1 for error). It will avoid registering the same
2840 descriptor twice, and will return the index of the current placement in the table if the caller attempts to register it more than once. The unregister function
2841 will return \textbf{CRYPT\_OK} if the PRNG was found and removed. Otherwise, it returns \textbf{CRYPT\_ERROR}.
2870 usage. It is faster than the default implementation of Yarrow\footnote{Yarrow has been implemented
2871 to work with most cipher and hash combos based on which you have chosen to build into the library.} while
2874 Fortuna is slightly less flexible than Yarrow in the sense that it only works with the AES block cipher
2876 key, and any hash that produces at least a 256--bit output. However, to make the implementation simpler
2879 Fortuna is more secure than Yarrow in the sense that attackers who learn parts of the entropy being
2880 added to the PRNG learn far less about the state than that of Yarrow. Without getting into to many
2881 details Fortuna has the ability to recover from state determination attacks where the attacker starts
2882 to learn information from the PRNGs output about the internal state. Yarrow on the other hand, cannot
2883 recover from that problem until new entropy is added to the pool and put to use through the ready() function.
2888 calling add\_entropy(), and setup the key by calling ready(). You can only add up to 256 bytes via
2891 When you read from RC4, the output is XOR'ed against your buffer you provide. In this manner, you can use rc4\_read()
2895 the fact that faster alternatives exist.
2899 SOBER--128 is a stream cipher designed by the QUALCOMM Australia team. Like RC4, you key it by
2902 Note: this cipher has several oddities about how it operates. The first call to add\_entropy() sets the cipher's key.
2903 Every other time call to the add\_entropy() function sets the cipher's IV variable. The IV mechanism allows you to
2904 encrypt several messages with the same key, and not re--use the same key material.
2906 Unlike Yarrow and Fortuna, all of the entropy (and hence security) of this algorithm rests in the data
2907 you pass it on the \textbf{first} call to add\_entropy(). All buffers sent to add\_entropy() must have a length
2910 Like RC4, the output of SOBER--128 is XOR'ed against the buffer you provide it. In this manner, you can use
2913 Since SOBER-128 has a fixed keying scheme, and is very fast (faster than RC4) the ideal usage of SOBER-128 is to
2914 key it from the output of Fortuna (or Yarrow), and use it to encrypt messages. It is also ideal for
2932 /* use "key" as the key */
2954 To decrypt you have to do the exact same steps.
2956 \mysection{The Secure RNG}
2958 An RNG is related to a PRNG in many ways, except that it does not expand a smaller seed to get the data. They generate their random bits
2959 by performing some computation on fresh input bits. Possibly the hardest thing to get correctly in a cryptosystem is the
2972 Which will try one of three methods of getting random data. The first is to open the popular \textit{/dev/random} device which
2973 on most *NIX platforms provides cryptographic random bits\footnote{This device is available in Windows through the Cygwin compiler suite. It emulates \textit{/dev/random} via the Microsoft CSP.}.
2974 The second method is to try the Microsoft Cryptographic Service Provider, and read the RNG. The third method is an ANSI C
2975 clock drift method that is also somewhat popular but gives bits of lower entropy. The \textit{callback} parameter is a pointer to a function that returns void. It is
2976 used when the slower ANSI C RNG must be used so the calling application can still work. This is useful since the ANSI C RNG has a throughput of roughly three
2977 bytes a second. The callback pointer may be set to {\bf NULL} to avoid using it if you do not want to. The function returns the number of bytes actually read from
2986 This will try to initialize the prng with a state of at least \textit{bits} of entropy. The \textit{callback} parameter works much like
2987 the callback in \textit{rng\_get\_bytes()}. It is highly recommended that you use this function to setup your PRNGs unless you have a
2988 platform where the RNG does not work well. Example usage of this function is given below:
3005 /* setup the PRNG */
3023 \subsection{The Secure PRNG Interface}
3024 It is possible to access the secure RNG through the PRNG interface, and in turn use it within dependent functions such
3025 as the PK API. This simplifies the cryptosystem on platforms where the secure RNG is fast. The secure PRNG never
3026 requires to be started, that is you need not call the start, add\_entropy, or ready functions. For example, consider
3027 the previous example using this PRNG.
3057 RSA wrote the PKCS \#1 specifications which detail RSA Public Key Cryptography. In the specifications are
3058 The standard includes the \textit{v1.5} and \textit{v2.1} algorithms.
3059 To simplify matters a little the v2.1 encryption and signature padding algorithms are called OAEP and PSS respectively.
3062 PKCS \#1 v1.5 padding is so simple that both signature and encryption padding are performed by the same function. Note: the
3063 signature padding does \textbf{not} include the ASN.1 padding required. That is performed by the rsa\_sign\_hash\_ex() function
3067 The following function performs PKCS \#1 v1.5 padding:
3081 This will encode the message pointed to by \textit{msg} of length \textit{msglen} octets. The \textit{block\_type} parameter must be set to
3082 \textbf{LTC\_PKCS\_1\_EME} to perform encryption padding. It must be set to \textbf{LTC\_PKCS\_1\_EMSA} to perform signature padding. The \textit{modulus\_bitlen}
3083 parameter indicates the length of the modulus in bits. The padded data is stored in \textit{out} with a length of \textit{outlen} octets. The output will not be
3084 longer than the modulus which helps allocate the correct output buffer size.
3086 Only encryption padding requires a PRNG. When performing signature padding the \textit{prng\_idx} parameter may be left to zero as it is not checked for validity.
3089 The following function performs PKCS \#1 v1.5 de--padding:
3102 This will remove the PKCS padding data pointed to by \textit{msg} of length \textit{msglen}. The decoded data is stored in \textit{out} of length
3103 \textit{outlen}. If the padding is valid, a 1 is stored in \textit{is\_valid}, otherwise, a 0 is stored. The \textit{block\_type} parameter must be set to either
3107 PKCS \#1 RSA Encryption amounts to OAEP padding of the input message followed by the modular exponentiation. As far as this portion of
3108 the library is concerned we are only dealing with th OAEP padding of the message.
3112 The following function performs PKCS \#1 v2.1 encryption padding:
3129 This accepts \textit{msg} as input of length \textit{msglen} which will be OAEP padded. The \textit{lparam} variable is an additional system specific
3130 tag that can be applied to the encoding. This is useful to identify which system encoded the message. If no variance is desired then
3133 OAEP encoding requires the length of the modulus in bits in order to calculate the size of the output. This is passed as the parameter
3134 \textit{modulus\_bitlen}. \textit{hash\_idx} is the index into the hash descriptor table of the hash desired. PKCS \#1 allows any hash to be
3135 used but both the encoder and decoder must use the same hash in order for this to succeed. The size of hash output affects the maximum
3136 sized input message. \textit{prng\_idx} and \textit{prng} are the random number generator arguments required to randomize the padding process.
3137 The padded message is stored in \textit{out} along with the length in \textit{outlen}.
3139 If $h$ is the length of the hash and $m$ the length of the modulus (both in octets) then the maximum payload for \textit{msg} is
3140 $m - 2h - 2$. For example, with a $1024$--bit RSA key and SHA--1 as the hash the maximum payload is $86$ bytes.
3142 Note that when the message is padded it still has not been RSA encrypted. You must pass the output of this function to
3161 This function decodes an OAEP encoded message and outputs the original message that was passed to the OAEP encoder. \textit{msg} is the
3162 output of pkcs\_1\_oaep\_encode() of length \textit{msglen}. \textit{lparam} is the same system variable passed to the OAEP encoder. If it does not
3163 match what was used during encoding this function will not decode the packet. \textit{modulus\_bitlen} is the size of the RSA modulus in bits
3164 and must match what was used during encoding. Similarly the \textit{hash\_idx} index into the hash descriptor table must match what was used
3167 If the function succeeds it decodes the OAEP encoded message into \textit{out} of length \textit{outlen} and stores a
3168 $1$ in \textit{res}. If the packet is invalid it stores $0$ in \textit{res} and if the function fails for another reason
3174 PSS encoding is the second half of the PKCS \#1 standard which is padding to be applied to messages that are signed.
3190 This function assumes the message to be PSS encoded has previously been hashed. The input hash \textit{msghash} is of length
3191 \textit{msghashlen}. PSS allows a variable length random salt (it can be zero length) to be introduced in the signature process.
3192 \textit{hash\_idx} is the index into the hash descriptor table of the hash to use. \textit{prng\_idx} and \textit{prng} are the random
3193 number generator information required for the salt.
3195 Similar to OAEP encoding \textit{modulus\_bitlen} is the size of the RSA modulus (in bits). It limits the size of the salt. If $m$ is the length
3196 of the modulus $h$ the length of the hash output (in octets) then there can be $m - h - 2$ bytes of salt.
3198 This function does not actually sign the data it merely pads the hash of a message so that it can be processed by rsa\_exptmod().
3202 To decode a PSS encoded signature block you have to use the following.
3216 This will decode the PSS encoded message in \textit{sig} of length \textit{siglen} and compare it to values in \textit{msghash} of length
3217 \textit{msghashlen}. If the block is a valid PSS block and the decoded hash equals the hash supplied \textit{res} is set to non--zero. Otherwise,
3218 it is set to zero. The rest of the parameters are as in the PSS encode call.
3220 It's important to use the same \textit{saltlen} and hash for both encoding and decoding as otherwise the procedure will not work.
3225 RSA is a public key algorithm that is based on the inability to find the \textit{e-th} root modulo a composite of unknown
3226 factorization. Normally the difficulty of breaking RSA is associated with the integer factoring problem but they are
3229 The system begins with with two primes $p$ and $q$ and their product $N = pq$. The order or \textit{Euler totient} of the
3231 $\mbox{lcm}(p - 1, q - 1)$. The public key consists of the composite $N$ and some integer $e$ such that
3232 $\mbox{gcd}(e, \phi(N)) = 1$. The private key consists of the composite $N$ and the inverse of $e$ modulo $\phi(N)$
3235 A person who wants to encrypt with your public key simply forms an integer (the plaintext) $M$ such that
3236 $1 < M < N-2$ and computes the ciphertext $C = M^e\mbox{ }(\mbox{mod }N)$. Since finding the inverse exponent $d$
3237 given only $N$ and $e$ appears to be intractable only the owner of the private key can decrypt the ciphertext and compute
3238 $C^d \equiv \left (M^e \right)^d \equiv M^1 \equiv M\mbox{ }(\mbox{mod }N)$. Similarly the owner of the private key
3243 the plaintext to be encrypted than it is possible that $M^3 < N$ in which case finding the cube-root would be trivial.
3244 The most often suggested value for $e$ is $65537$ since it is large enough to make such attacks impossible and also well
3247 It is important to pad the input to RSA since it has particular mathematical structure. For instance
3249 to have a forged signature for. Simply get the signatures for $M_1$ and $M_2$ on their own and multiply the result
3251 the hash of documents only but also to pad the inputs with data to remove such structure.
3265 Where \textit{wprng} is the index into the PRNG descriptor array. The \textit{size} parameter is the size in bytes of the RSA modulus desired.
3266 The \textit{e} parameter is the encryption exponent desired, typical values are 3, 17, 257 and 65537. Stick with 65537 since it is big enough to prevent
3267 trivial math attacks, and not super slow. The \textit{key} parameter is where the constructed key is placed. All keys must be at
3271 Note: the \textit{rsa\_make\_key()} function allocates memory at run--time when you make the key. Make sure to call
3272 \textit{rsa\_free()} (see below) when you are finished with the key. If \textit{rsa\_make\_key()} fails it will automatically
3273 free the memory allocated.
3276 There are two types of RSA keys. The types are {\bf PK\_PRIVATE} and {\bf PK\_PUBLIC}. The first type is a private
3277 RSA key which includes the CRT parameters\footnote{As of v0.99 the PK\_PRIVATE\_OPTIMIZED type has been deprecated, and has been replaced by the
3278 PK\_PRIVATE type.} in the form of a RSAPrivateKey (PKCS \#1 compliant). The second type, is a public RSA key which only includes the modulus and public exponent.
3279 It takes the form of a RSAPublicKey (PKCS \#1 compliant).
3282 To do raw work with the RSA function, that is without padding, use the following function:
3292 This will load the bignum from \textit{in} as a big endian integer in the format PKCS \#1 specifies, raises it to either \textit{e} or \textit{d} and stores the result
3293 in \textit{out} and the size of the result in \textit{outlen}. \textit{which} is set to {\bf PK\_PUBLIC} to use \textit{e}
3294 (i.e. for encryption/verifying) and set to {\bf PK\_PRIVATE} to use \textit{d} as the exponent (i.e. for decrypting/signing).
3296 Note: the output of this function is zero--padded as per PKCS \#1 specification. This allows this routine to work with PKCS \#1 padding functions properly.
3300 To facilitate encrypting short keys the following functions have been provided.
3316 This function will OAEP pad \textit{in} of length \textit{inlen} bytes, RSA encrypt it, and store the ciphertext
3317 in \textit{out} of length \textit{outlen} octets. The \textit{lparam} and \textit{lparamlen} are the same parameters you would pass
3321 As of v1.15, the library supports both v1.5 and v2.1 PKCS \#1 style paddings in these higher level functions. The following is the extended
3341 The parameters are all the same as for rsa\_encrypt\_key() except for the addition of the \textit{padding} parameter. It must be set to
3344 When performing v1.5 encryption, the hash and lparam parameters are totally ignored and can be set to \textbf{NULL} or zero (respectively).
3360 This function will RSA decrypt \textit{in} of length \textit{inlen} then OAEP de-pad the resulting data and store it in
3361 \textit{out} of length \textit{outlen}. The \textit{lparam} and \textit{lparamlen} are the
3364 If the RSA decrypted data is not a valid OAEP packet then \textit{stat} is set to $0$. Otherwise, it is set to $1$.
3367 As of v1.15, the library supports both v1.5 and v2.1 PKCS \#1 style paddings in these higher level functions. The following is the extended
3385 Similar to the extended encryption, the new parameter \textit{padding} indicates which version of the PKCS \#1 standard to use.
3388 When performing v1.5 decryption, the hash and lparam parameters are totally ignored and can be set to \textbf{NULL} or zero (respectively).
3393 process the following functions have been provided.
3408 This will PSS encode the message digest pointed to by \textit{in} of length \textit{inlen} octets. Next, the PSS encoded hash will be RSA
3409 \textit{signed} and the output stored in the buffer pointed to by \textit{out} of length \textit{outlen} octets.
3411 The \textit{hash\_idx} parameter indicates which hash will be used to create the PSS encoding. It should be the same as the hash used to
3412 hash the message being signed. The \textit{saltlen} parameter indicates the length of the desired salt, and should typically be small. A good
3413 default value is between 8 and 16 octets. Strictly, it must be small than $modulus\_len - hLen - 2$ where \textit{modulus\_len} is the size of
3414 the RSA modulus (in octets), and \textit{hLen} is the length of the message digest produced by the chosen hash.
3418 As of v1.15, the library supports both v1.5 and v2.1 signatures. The extended signature generation function has the following prototype:
3435 This will PKCS encode the message digest pointed to by \textit{in} of length \textit{inlen} octets. Next, the PKCS encoded hash will be RSA
3436 \textit{signed} and the output stored in the buffer pointed to by \textit{out} of length \textit{outlen} octets. The \textit{padding} parameter
3440 When performing a v1.5 signature the \textit{prng}, \textit{prng\_idx}, and \textit{hash\_idx} parameters are not checked and can be left to any
3456 This will RSA \textit{verify} the signature pointed to by \textit{sig} of length \textit{siglen} octets. Next, the RSA decoded data is PSS decoded
3457 and the extracted hash is compared against the message digest pointed to by \textit{msghash} of length \textit{msghashlen} octets.
3459 If the RSA decoded data is not a valid PSS message, or if the PSS decoded hash does not match the \textit{msghash}
3460 value, \textit{res} is set to $0$. Otherwise, if the function succeeds, and signature is valid \textit{res} is set to $1$.
3464 As of v1.15, the library supports both v1.5 and v2.1 signature verification. The extended signature verification function has the following prototype:
3480 This will RSA \textit{verify} the signature pointed to by \textit{sig} of length \textit{siglen} octets. Next, the RSA decoded data is PKCS decoded
3481 and the extracted hash is compared against the message digest pointed to by \textit{msghash} of length \textit{msghashlen} octets.
3483 If the RSA decoded data is not a valid PSS message, or if the PKCS decoded hash does not match the \textit{msghash}
3484 value, \textit{res} is set to $0$. Otherwise, if the function succeeds, and signature is valid \textit{res} is set to $1$.
3486 The \textit{padding} parameter must be set to \textbf{LTC\_PKCS\_1\_V1\_5} to perform a v1.5 verification. Otherwise, it must be set to
3487 \textbf{LTC\_PKCS\_1\_PSS} to perform a v2.1 verification. When performing a v1.5 verification the \textit{hash\_idx} parameter is ignored.
3521 &key) /* where to store the key */
3544 /* now let's decrypt the encrypted key */
3566 The RSA key format adopted for exporting and importing keys is the PKCS \#1 format defined by the ASN.1 constructs known as
3567 RSAPublicKey and RSAPrivateKey. Additionally, the OpenSSL key format is supported by the import function only.
3570 To export a RSA key use the following function.
3579 This will export the RSA key in either a RSAPublicKey or RSAPrivateKey (PKCS \#1 types) depending on the value of \textit{type}. When it is
3580 set to \textbf{PK\_PRIVATE} the export format will be RSAPrivateKey and otherwise it will be RSAPublicKey.
3583 To import a RSA key use the following function.
3592 This will import the key stored in \textit{inlen} and import it to \textit{key}. If the function fails it will automatically free any allocated memory. This
3596 import the key, strip off the additional data (it's the preferred hash) and fill in the rsa\_key structure as if it were a native RSAPublicKey. Note that
3602 The library provides a set of core ECC functions as well that are designed to be the Elliptic Curve analogy of all of the
3603 Diffie-Hellman routines in the previous chapter. Elliptic curves (of certain forms) have the benefit that they are harder
3604 to attack (no sub-exponential attacks exist unlike normal DH crypto) in fact the fastest attack requires the square root
3605 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
3606 192-bit key) then the work factor is $2^{96}$ in order to find the secret key.
3608 The curves in this library are taken from the following website:
3613 As of v1.15 three new curves from the SECG standards are also included they are the secp112r1, secp128r1, and secp160r1 curves. These curves were added to
3616 They are all curves over the integers modulo a prime. The curves have the basic equation that is:
3621 The variable $b$ is chosen such that the number of points is nearly maximal. In fact the order of the base points $\beta$
3622 provided are very close to $p$ that is $\vert \vert \phi(\beta) \vert \vert \approx \vert \vert p \vert \vert$. The curves
3623 range in order from $\approx 2^{112}$ points to $\approx 2^{521}$. According to the source document any key size greater
3630 supported by any conforming math plugin. It is enabled by defining \textbf{MECC\_FP} during the build, such as
3636 which will build LTC using the TFM math library and enabling this new feature. The feature is not enabled by default as it is \textbf{NOT} thread
3637 safe (by default). It supports the LTC locking macros (such as by enabling LTC\_PTHREAD), but by default is not locked.
3640 The optimization works by using a Fixed Point multiplier on any base point you use twice or more in a short period of time. It has a limited size
3641 cache (of FP\_ENTRIES entries) which it uses to hold recent bases passed to ltc\_ecc\_mulmod(). Any base detected to be used twice is sent through the
3642 pre--computation phase, and then the fixed point algorithm can be used. For example, if you use a NIST base point twice in a row, the 2$^{nd}$ and
3643 all subsequent point multiplications with that point will use the faster algorithm.
3646 The optimization uses a window on the multiplicand of FP\_LUT bits (default: 8, min: 2, max: 12), and this controls the memory/time trade-off. The larger the
3647 value the faster the algorithm will be but the more memory it will take. The memory usage is $3 \cdot 2^{FP\_LUT}$ integers which by default
3648 with TFM amounts to about 400kB of memory. Tuning TFM (by changing FP\_SIZE) can decrease the usage by a fair amount. Memory is only used by a cache entry
3649 if it is active. Both FP\_ENTRIES and FP\_LUT are definable on the command line if you wish to override them. For instance,
3657 would define a window of 6 bits and limit the cache to 8 entries. Generally, it is better to first tune TFM by adjusting FP\_SIZE (from tfm.h). It defaults
3659 ECC--256 you will only need 576 bits, which would reduce the memory usage by 700\%.
3664 In the case of LibTomCrypt, it is meant \textbf{solely} for NIST and SECG $GF(p)$ curves. The format of the keys is as follows:
3673 pubkey.x INTEGER, -- The X co-ordinate of the public key point
3674 pubkey.y INTEGER, -- The Y co-ordinate of the public key point
3681 pubkey.x INTEGER, -- The X co-ordinate of the public key point
3682 pubkey.y INTEGER, -- The Y co-ordinate of the public key point
3683 secret.k INTEGER, -- The secret key scalar
3688 The first flags bit denotes whether the key is public (zero) or private (one).
3693 The library uses the following structure to describe an elliptic curve. This is used internally, as well as by the new
3694 extended ECC functions which allow the user to specify their own curves.
3700 /** The size of the curve in octets */
3706 /** The prime that defines the field (encoded in hex) */
3709 /** The fields B param (hex) */
3712 /** The order of the curve (hex) */
3715 /** The x co-ordinate of the base point on the curve (hex) */
3718 /** The y co-ordinate of the base point on the curve (hex) */
3723 The curve must be of the form $y^2 = x^3 - 3x + b$, and all of the integer parameters are encoded in hexadecimal format.
3727 There is a key structure called \textit{ecc\_key} used by the ECC functions. There is a function to make a key:
3736 The \textit{keysize} is the size of the modulus in bytes desired. Currently directly supported values are 12, 16, 20, 24, 28, 32, 48, and 65 bytes which
3738 the keysize up to the next available one.
3740 The function will free any internally allocated resources if there is an error.
3743 As of v1.16, the library supports an extended key generation routine which allows the user to specify their own curve. It is specified as follows:
3754 This function generates a random ECC key over the curve specified by the parameters by \textit{dp}. The rest of the parameters are equivalent to
3755 those from the original key generation function.
3758 To free the memory allocated by a ecc\_make\_key(), ecc\_make\_key\_ex(), ecc\_import(), or ecc\_import\_ex() call use the following function:
3765 To export an ECC key using the LibTomCrypt format call the following function:
3773 This will export the key with the given \textit{type} (\textbf{PK\_PUBLIC} or \textbf{PK\_PRIVATE}), and store it to \textit{out}.
3776 The following function imports a LibTomCrypt format ECC key:
3783 This will import the ECC key from \textit{in}, and store it in the ecc\_key structure pointed to by \textit{key}. If the operation fails it will free
3788 The following function imports a LibTomCrypt format ECC key using a specified set of curve parameters:
3796 This will import the key from the array pointed to by \textit{in} of length \textit{inlen} octets. The key is stored in
3797 the ECC structure pointed to by \textit{key}. The curve is specified by the parameters pointed to by \textit{dp}. The function will free
3801 The following function exports an ECC public key in the ANSI X9.63 format:
3809 The ECC key pointed to by \textit{key} is exported in public fashion to the array pointed to by \textit{out}. The ANSI X9.63 format used is from
3810 section 4.3.6 of the standard. It does not allow for the export of private keys.
3813 The following function imports an ANSI X9.63 section 4.3.6 format public ECC key:
3821 This will import the key stored in the array pointed to by \textit{in} of length \textit{inlen} octets. The imported key is stored in the ECC key pointed to by
3822 \textit{key}. The function will free any allocated memory upon error.
3825 The following function allows the importing of an ANSI x9.63 section 4.3.6 format public ECC key using user specified domain parameters:
3834 This will import the key stored in the array pointed to by \textit{in} of length \textit{inlen} octets using the domain parameters pointed to by \textit{dp}.
3835 The imported key is stored in the ECC key pointed to by \textit{key}. The function will free any allocated memory upon error.
3838 To construct a Diffie-Hellman shared secret with a private and public ECC key, use the following function:
3846 The \textit{private\_key} is typically the local private key, and \textit{public\_key} is the key the remote party has shared.
3847 Note: this function stores only the $x$ co-ordinate of the shared elliptic point as described in ANSI X9.63 ECC--DH.
3850 ECC--DH Encryption is performed by producing a random key, hashing it, and XOR'ing the digest against the plaintext. It is not strictly ANSI X9.63 compliant
3851 but it is very similar. It has been extended by using an ASN.1 sequence and hash object identifiers to allow portable usage. The following function
3852 encrypts a short string (no longer than the message digest) using this technique:
3867 As the name implies this function encrypts a (symmetric) key, and is not intended for encrypting long messages directly. It will encrypt the
3868 plaintext in the array pointed to by \textit{in} of length \textit{inlen} octets. It uses the public ECC key pointed to by \textit{key}, and
3869 hash algorithm indexed by \textit{hash} to construct a shared secret which may be XOR'ed against the plaintext. The ciphertext is stored in
3870 the output buffer pointed to by \textit{out} of length \textit{outlen} octets.
3872 The data is encrypted to the public ECC \textit{key} such that only the holder of the private key can decrypt the payload. To have multiple
3885 This function will decrypt an encrypted payload. The \textit{key} provided must be the private key corresponding to the public key
3886 used during encryption. If the wrong key is provided the function will not specifically return an error code. It is important
3890 The packet format for the encrypted keys is the following ASN.1 SEQUENCE:
3903 There are also functions to sign and verify messages. They use the ANSI X9.62 EC-DSA algorithm to generate and verify signatures in the
3907 To sign a message digest (hash) use the following function:
3920 This function will EC--DSA sign the message digest stored in the array pointed to by \textit{in} of length \textit{inlen} octets. The signature
3921 will be stored in the array pointed to by \textit{out} of length \textit{outlen} octets. The function requires a properly seeded PRNG, and
3922 the ECC \textit{key} provided must be a private key.
3935 This function will verify the EC-DSA signature in the array pointed to by \textit{sig} of length \textit{siglen} octets, against the message digest
3936 pointed to by the array \textit{hash} of length \textit{hashlen}. It will store a non--zero value in \textit{stat} if the signature is valid. Note:
3937 the function will not return an error if the signature is invalid. It will return an error, if the actual signature payload is an invalid format.
3938 The ECC \textit{key} must be the public (or private) ECC key corresponding to the key that performed the signature.
3941 The signature code is an implementation of X9.62 EC--DSA, and the output is compliant for GF(p) curves.
3944 With ECC if you try to sign a hash that is bigger than your ECC key you can run into problems. The math will still work, and in effect the signature will still
3945 work. With ECC keys the strength of the signature is limited by the size of the hash, or the size of they key, whichever is smaller. For example, if you sign with
3948 The library will not warn you if you make this mistake, so it is important to check yourself before using the signatures.
3952 The Digital Signature Algorithm (or DSA) is a variant of the ElGamal Signature scheme which has been modified to
3953 reduce the bandwidth of the signatures. For example, to have \textit{80-bits of security} with ElGamal, you need a group with an order of at least 1024--bits.
3954 With DSA, you need a group of order at least 160--bits. By comparison, the ElGamal signature would require at least 256 bytes of storage, whereas the DSA signature
3958 Since no useful public standard for DSA key storage was presented to me during the course of this development I made my own ASN.1 SEQUENCE which I document
3992 The leading BIT STRING has a single bit in it which is zero for public keys and one for private keys. This makes the structure uniquely decodable,
3996 To make a DSA key you must call the following function
4004 The variable \textit{prng} is an active PRNG state and \textit{wprng} the index to the descriptor. \textit{group\_size} and
4005 \textit{modulus\_size} control the difficulty of forging a signature. Both parameters are in bytes. The larger the
4006 \textit{group\_size} the more difficult a forgery becomes upto a limit. The value of $group\_size$ is limited by
4007 $15 < group\_size < 1024$ and $modulus\_size - group\_size < 512$. Suggested values for the pairs are as follows.
4023 When you are finished with a DSA key you can call the following function to free the memory used.
4030 Each DSA key is composed of the following variables.
4037 \item $x$ a random secret (the secret key) in the range $1 < x < q$
4038 \item $y = g^x \mbox{ (mod }p\mbox{)}$ the public key.
4041 A DSA key is considered valid if it passes all of the following tests.
4054 Tests one and two ensure that thethe signatures to
4055 function. Tests three and four ensure that the generator $g$ is not set to a trivial value which would make signature
4056 forgery easier. Test five ensures that $q$ divides the order of multiplicative sub-group of $\Z/p\Z$. Test six
4057 ensures that the generator actually generates a prime order group. Tests seven and eight ensure that the public key
4061 The following function will perform these tests.
4068 This will test \textit{key} and store the result in \textit{stat}. If the result is $stat = 0$ the DSA key failed one of the tests
4069 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).
4073 To generate a DSA signature call the following function:
4086 Which will sign the data in \textit{in} of length \textit{inlen} bytes. The signature is stored in \textit{out} and the size
4087 of the signature in \textit{outlen}. If the signature is longer than the size you initially specify in \textit{outlen} nothing
4088 is stored and the function returns an error code. The DSA \textit{key} must be of the \textbf{PK\_PRIVATE} persuasion.
4091 To verify a hash created with that function use the following function:
4102 Which will verify the data in \textit{hash} of length \textit{inlen} against the signature stored in \textit{sig} of length \textit{siglen}.
4103 It will set \textit{stat} to $1$ if the signature is valid, otherwise it sets \textit{stat} to $0$.
4106 As of version 1.07, the DSA keys can be used to encrypt and decrypt small payloads. It works similar to the ECC encryption where
4107 a shared key is computed, and the hash of the shared key XOR'ed against the plaintext forms the ciphertext. The format used is functional port of
4108 the ECC encryption format to the DSA algorithm.
4125 This will encrypt the payload in \textit{in} of length \textit{inlen} and store the ciphertext in the output buffer \textit{out}. The
4126 length of the ciphertext \textit{outlen} must be originally set to the length of the output buffer. The DSA \textit{key} can be
4139 This will decrypt the ciphertext \textit{in} of length \textit{inlen}, and store the original payload in \textit{out} of length \textit{outlen}.
4140 The DSA \textit{key} must be a private key.
4145 To export a DSA key so that it can be transported use the following function:
4153 This will export the DSA \textit{key} to the buffer \textit{out} and set the length in \textit{outlen} (which must have been previously
4154 initialized to the maximum buffer size). The \textit{type} variable may be either \textbf{PK\_PRIVATE} or \textbf{PK\_PUBLIC}
4155 depending on whether you want to export a private or public copy of the DSA key.
4158 To import an exported DSA key use the following function
4167 This will import the DSA key from the buffer \textit{in} of length \textit{inlen} to the \textit{key}. If the process fails the function
4168 will automatically free all of the heap allocated in the process (you don't have to call dsa\_free()).
4172 LibTomCrypt supports a variety of ASN.1 data types encoded with the Distinguished Encoding Rules (DER) suitable for various cryptographic protocols. The data types
4173 are all provided with three basic functions with \textit{similar} prototypes. One function has been dedicated to calculate the length in octets of a given
4174 format, and two functions have been dedicated to encoding and decoding the format.
4176 On top of the basic data types are the SEQUENCE and SET data types which are collections of other ASN.1 types. They are provided
4177 in the same manner as the other data types except they use list of objects known as the \textbf{ltc\_asn1\_list} structure. It is defined as the following:
4192 The \textit{type} field is one of the following ASN.1 field definitions. The \textit{data} pointer is a void pointer to the data to be encoded (or the destination) and the
4193 \textit{size} field is specific to what you are encoding (e.g. number of bits in the BIT STRING data type). The \textit{used} field is primarily for the CHOICE decoder
4194 and reflects if the particular member of a list was the decoded data type. To help build the lists in an orderly fashion the macro
4197 It will assign to the \textit{index}th position in the \textit{list} the triplet (Type, Data, Size). An example usage would be:
4211 The macro is relatively safe with respect to modifying variables, for instance the following code is equivalent.
4254 The SEQUENCE data type is a collection of other ASN.1 data types encapsulated with a small header which is a useful way of sending multiple data types in one packet.
4257 To encode a sequence a \textbf{ltc\_asn1\_list} array must be initialized with the members of the sequence and their respective pointers. The encoding is performed
4258 with the following function.
4267 This encodes a sequence of items pointed to by \textit{list} where the list has \textit{inlen} items in it. The SEQUENCE will be encoded to \textit{out} and of length \textit{outlen}. The
4268 function will terminate when it reads all the items out of the list (upto \textit{inlen}) or it encounters an item in the list with a type of \textbf{LTC\_ASN1\_EOL}.
4270 The \textit{data} pointer in the list would be the same pointer you would pass to the respective ASN.1 encoder (e.g. der\_encode\_bit\_string()) and it is simply passed on
4271 verbatim to the dependent encoder. The list can contain other SEQUENCE or SET types which enables you to have nested SEQUENCE and SET definitions. In these cases
4272 the \textit{data} pointer is simply a pointer to another \textbf{ltc\_asn1\_list}.
4278 Decoding a SEQUENCE is similar to encoding. You set up an array of \textbf{ltc\_asn1\_list} where in this case the \textit{size} member is the maximum size
4279 (in certain cases). For types such as IA5 STRING, BIT STRING, OCTET STRING (etc) the \textit{size} field is updated after successful decoding to reflect how many
4280 units of the respective type has been loaded.
4289 This will decode upto \textit{outlen} items from the input buffer \textit{in} of length \textit{inlen} octets. The function will stop (gracefully) when it runs out of items to decode.
4292 For the following types the \textit{size} field will be updated to reflect the number of units read of the given type.
4303 The length of a SEQUENCE can be determined with the following function.
4312 This will get the encoding size for the given \textit{list} of length \textit{inlen} and store it in \textit{outlen}.
4316 For small or simple sequences an encoding or decoding can be performed with one of the following two functions.
4329 These either encode or decode (respectively) a SEQUENCE data type where the items in the sequence are specified after the length parameter.
4331 The list of items are specified as a triple of the form \textit{(type, size, data)} where \textit{type} is an \textbf{int}, \textit{size} is a \textbf{unsigned long}
4332 and \textit{data} is \textbf{void} pointer. The list of items must be terminated with an item with the type \textbf{LTC\_ASN1\_EOL}.
4334 It is ideal that you cast the \textit{size} values to unsigned long to ensure that the proper data type is passed to the function. Constants such as \textit{1} without
4335 a cast or prototype are of type \textbf{int} by default. Appending \textit{UL} or pre-pending \textit{(unsigned long)} is enough to cast it to the correct type.
4354 This example encodes a SEQUENCE with two IA5 STRING types containing ``Hello'' and `` World!'' respectively. Note the usage of the \textbf{UL} modifier
4355 on the size parameters. This forces the compiler to pass the numbers as the required \textbf{unsigned long} type that the function expects.
4360 SET and SET OF are related to the SEQUENCE type in that they can be pretty much be decoded with the same code. However, they are different, and they should
4361 be carefully noted. The SET type is an unordered array of ASN.1 types sorted by the TAG (type identifier), whereas the SET OF type is an ordered array of
4362 a \textbf{single} ASN.1 object sorted in ascending order by the DER their respective encodings.
4366 SETs use the same array structure of ltc\_asn1\_list that the SEQUENCE functions use. They are encoded with the following function:
4376 This will encode the list of ASN.1 objects in \textit{list} of length \textit{inlen} objects, and store the output in \textit{out} of length \textit{outlen} bytes.
4377 The function will make a copy of the list provided, and sort it by the TAG. Objects with identical TAGs are additionally sorted on their original placement in the
4378 array (to make the process deterministic).
4380 This function will \textbf{NOT} recognize \textit{DEFAULT} objects, and it is the responsibility of the caller to remove them as required.
4384 The SET type can be decoded with the following function.
4394 This will decode the SET specified by \textit{list} of length \textit{outlen} objects from the input buffer \textit{in} of length \textit{inlen} octets.
4396 It handles thethe list to decode all the objects.
4399 The length of a SET can be determined by calling der\_length\_sequence() since they have the same encoding length.
4402 A \textit{SET OF} object is an array of identical objects (e.g. OCTET STRING) sorted in ascending order by the DER encoding of the object. They are
4403 used to store objects deterministically based solely on their encoding. It uses the same array structure of ltc\_asn1\_list that the SEQUENCE functions
4404 use. They are encoded with the following function.
4414 This will encode a \textit{SET OF} containing the \textit{list} of \textit{inlen} ASN.1 objects and store the encoding in the output buffer \textit{out} of length \textit{outlen}.
4416 The routine will first encode the SET OF in an unordered fashion (in a temporary buffer) then sort using the XQSORT macro and copy back to the output buffer. This
4417 means you need at least enough memory to keep an additional copy of the output on the heap.
4420 Since the decoding of a \textit{SET OF} object is unambiguous it can be decoded with der\_decode\_sequence().
4423 Like the SET type the der\_length\_sequence() function can be used to determine the length of a \textit{SET OF} object.
4427 To encode or decode INTEGER data types use the following functions.
4443 These will encode or decode a signed INTEGER data type using the bignum data type to store the large INTEGER. To encode smaller values without allocating
4444 a bignum to store the value, the \textit{short} INTEGER functions were made available.
4460 These will encode or decode an unsigned \textbf{unsigned long} type (only reads upto 32--bits). For values in the range $0 \dots 2^{32} - 1$ the integer
4481 These will encode or decode a BIT STRING data type. The bits are passed in (or read out) using one \textbf{char} per bit. A non--zero value will be interpreted
4502 These will encode or decode an OCTET STRING data type. The octets are stored using one \textbf{unsigned char} each.
4523 These will encode or decode an OBJECT IDENTIFIER object. The words of the OID are stored in individual \textbf{unsigned long} elements, and must be in the range
4545 These will encode or decode an IA5 STRING. The characters are read or stored in individual \textbf{char} elements. These functions performs internal character
4546 to numerical conversions based on the conventions of the compiler being used. For instance, on an x86\_32 machine 'A' == 65 but the same may not be true on
4548 that the build platform honours the run--time platforms character conventions.
4569 These will encode or decode an PRINTABLE STRING. The characters are read or stored in individual \textbf{char} elements. These functions performs internal character
4570 to numerical conversions based on the conventions of the compiler being used. For instance, on an x86\_32 machine 'A' == 65 but the same may not be true on
4572 that the build platform honours the run-time platforms character conventions.
4593 These will encode or decode an UTF8 STRING. The characters are read or stored in individual \textbf{wchar\_t} elements. These function performs no internal
4594 mapping and treat the characters as literals.
4596 These functions use the \textbf{wchar\_t} type which is not universally available. In those cases, the library will typedef it to \textbf{unsigned long}. If you
4597 intend to use the ISO C functions for working with wide--char arrays, you should make sure that wchar\_t has been defined previously.
4601 The UTCTIME type is to store a date and time in ASN.1 format. It uses the following structure to organize the time.
4618 The time can be offset plus or minus a set amount of hours (off\_hh) and minutes (off\_mm). When \textit{off\_dir} is zero, the time will be added otherwise it
4619 will be subtracted. For instance, the array $\lbrace 5, 6, 20, 22, 4, 00, 0, 5, 0 \rbrace$ represents the current time of
4636 The encoder will store time in one of the two ASN.1 formats, either \textit{YYMMDDhhmmssZ} or \textit{YYMMDDhhmmss$\pm$hhmm}, and perform minimal error checking on the
4637 input. The decoder will read all valid ASN.1 formats and perform range checking on the values (not complete but rational) useful for catching packet errors.
4643 The CHOICE ASN.1 type represents a union of ASN.1 types all of which are stored in a \textit{ltc\_asn1\_list}. There is no encoder for the CHOICE type, only a
4644 decoder. The decoder will scan through the provided list attempting to use the appropriate decoder on the input packet. The list can contain any ASN.1 data
4647 There is no encoder for the CHOICE type as the actual DER encoding is the encoding of the chosen type.
4657 This will decode the input in the \textit{in} field of length \textit{inlen}. It uses the provided ASN.1 list specified in the \textit{list} field which has
4658 \textit{outlen} elements. The \textit{inlen} field will be updated with the length of the decoded data type, as well as the respective entry in the \textit{list} field
4659 will have the \textit{used} flag set to non--zero to reflect it was the data type decoded.
4662 The ASN.1 \textit{flexi} decoder allows the developer to decode arbitrary ASN.1 DER packets (provided they use data types LibTomCrypt supports) without first knowing
4663 the structure of the data. Where der\_decode \_sequence() requires the developer to specify the data types to decode in advance the flexi decoder is entirely
4666 The flexi decoder uses the same \textit{ltc\_asn1\_list} but instead of being stored in an array it uses the linked list pointers \textit{prev}, \textit{next}, \textit{parent}
4667 and \textit{child}. The list works as a \textit{doubly-linked list} structure where decoded items at the same level are siblings (using next and prev) and items
4670 When a SEQUENCE or SET has been encountered a SEQUENCE (or SET resp.) item will be added as a sibling (e.g. list.type == LTC\_ASN1\_SEQUENCE) and the child
4671 pointer points to a new list of items contained within the object.
4680 This will decode items in the \textit{in} buffer of max input length \textit{inlen} and store the newly created pointer to the list in \textit{out}. This function allocates
4681 all required memory for the decoding. It stores the number of octets read back into \textit{inlen}.
4683 The function will terminate when either it hits an invalid ASN.1 tag, or it reads \textit{inlen} octets. An early termination is a soft error, and returns
4684 normally. The decoded list \textit{out} will point to the very first element of the list (e.g. both parent and prev pointers will be \textbf{NULL}).
4686 An invalid decoding will terminate the process, and free the allocated memory automatically.
4688 \textbf{Note:} the list decoded by this function is \textbf{NOT} in the correct form for der\_encode\_sequence() to use directly. You will have to first
4689 have to convert the list by first storing all of the siblings in an array then storing all the children as sub-lists of a sequence using the \textit{.data}
4693 Suppose we decode the following structure:
4706 \begin{flushleft}and we decoded it with the following code:\end{flushleft}
4723 At this point \textit{list} would point to thethe child
4724 node with the following code will bring us to the \textit{Name} portion of the SEQUENCE:
4730 Now \textit{list} points to the \textit{Name} member (with the tag IA5 STRING). The \textit{data}, \textit{size}, and \textit{type} members of \textit{list} should reflect
4731 that of an IA5 STRING. The sibbling will now be the \textit{LoginToken} SEQUENCE. The sibbling has a child node which points to the \textit{passwdHash} OCTET STRING.
4732 We can walk to this node with the following code:
4739 At this point, \textit{list} will point to the \textit{passwdHash} member of the innermost SEQUENCE. This node has a sibbling, the \textit{pubkey} member of the SEQUENCE.
4740 The \textit{LastOn} member of the SEQUENCE is a sibbling of the LoginToken node, if we wanted to walk there we would have to go up and over via:
4746 At this point, we are pointing to the last node of the list. Lists are terminated in all directions by a \textbf{NULL} pointer. All nodes are doubly linked so that you
4747 can walk up and down the nodes without keeping pointers lying around.
4754 To free the list use the following function.
4761 This will free all of the memory allocated by der\_decode\_sequence\_flexi().
4766 In order to securely handle user passwords for the purposes of creating session keys and chaining IVs the PKCS \#5 was drafted. PKCS \#5
4767 is made up of two algorithms, Algorithm One and Algorithm Two. Algorithm One is the older fairly limited algorithm which has been implemented
4771 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
4772 people trying to brute force guess the password. The higher the iteration counter the longer the delay. This algorithm also requires a hash
4773 algorithm and produces an output no longer than the output of the hash.
4785 Where \textit{password} is the user's password. Since the algorithm allows binary passwords you must also specify the length in \textit{password\_len}.
4786 The \textit{salt} is a fixed size 8--byte array which should be random for each user and session. The \textit{iteration\_count} is the delay desired
4787 on the password. The \textit{hash\_idx} is the index of the hash you wish to use in the descriptor table.
4789 The output of length up to \textit{outlen} is stored in \textit{out}. If \textit{outlen} is initially larger than the size of the hash functions output
4790 it is set to the number of bytes stored. If it is smaller than not all of the hash output is stored in \textit{out}.
4794 Algorithm Two is the recommended algorithm for this task. It allows variable length salts, and can produce outputs larger than the
4809 Where \textit{password} is the users password. Since the algorithm allows binary passwords you must also specify the length in \textit{password\_len}.
4810 The \textit{salt} is an array of size \textit{salt\_len}. It should be random for each user and session. The \textit{iteration\_count} is the delay desired
4811 on the password. The \textit{hash\_idx} is the index of the hash you wish to use in the descriptor table. The output of length up to
4830 /* create the material (100 iterations in algorithm) */
4844 /* use material (recall to store the salt in the output) */
4850 The library provides functions to encode and decode a RFC 1521 base--64 coding scheme. The characters used in the mappings are:
4854 Those characters are supported in the 7-bit ASCII map, which means they can be used for transport over
4855 common e-mail, usenet and HTTP mediums. The format of an encoded stream is just a literal sequence of ASCII characters
4856 where a group of four represent 24-bits of input. The first four chars of the encoders output is the length of the
4857 original input. After the first four characters is the rest of the message.
4859 Often, it is desirable to line wrap the output to fit nicely in an e-mail or usenet posting. The decoder allows you to
4860 put any character (that is not in the above sequence) in between any character of the encoders output. You may not however,
4861 break up the first four characters.
4871 Where \textit{in} is the binary string and \textit{out} is where the ASCII output is placed. You must set the value of \textit{outlen} prior
4872 to calling this function and it sets the length of the base64 output in \textit{outlen} when it is done. To decode a base64
4883 The library includes primality testing and random prime functions as well. The primality tester will perform the test in
4884 two phases. First it will perform trial division by the first few primes. Second it will perform eight rounds of the
4885 Rabin-Miller primality testing algorithm. If the candidate passes both phases it is declared prime otherwise it is declared
4886 composite. No prime number will fail the two phases but composites can. Each round of the Rabin-Miller algorithm reduces
4887 the probability of a pseudo-prime by $1 \over 4$ therefore after sixteen rounds the probability is no more than
4888 $\left ( { 1 \over 4 } \right )^{8} = 2^{-16}$. In practice the probability of error is in fact much lower than that.
4890 When making random primes the trial division step is in fact an optimized implementation of \textit{Implementation of Fast RSA Key Generation on Smart Cards}\footnote{Chenghuai Lu, Andre L. M. dos Santos and Francisco R. Pimentel}.
4891 In essence a table of machine-word sized residues are kept of a candidate modulo a set of primes. When the candidate
4892 is rejected and ultimately incremented to test the next number the residues are updated without using multi-word precision
4893 math operations. As a result the routine can scan ahead to the next number required for testing with very little work
4896 In the event that a composite did make it through it would most likely cause the the algorithm trying to use it to fail. For
4897 instance, in RSA two primes $p$ and $q$ are required. The order of the multiplicative sub-group (modulo $pq$) is given
4898 as $\phi(pq)$ or $(p - 1)(q - 1)$. The decryption exponent $d$ is found as $de \equiv 1\mbox{ }(\mbox{mod } \phi(pq))$. If either $p$ or $q$ is composite the value of $d$ will be incorrect and the user
4900 the multi-prime RSA. Suppose $q = rs$ for two primes $r$ and $s$ then $\phi(pq) = (p - 1)(r - 1)(s - 1)$ which clearly is
4903 These are not technically part of the LibTomMath library but this is the best place to document them.
4908 This puts a one in \textit{result} if the number is probably prime, otherwise it places a zero in it. It is assumed that if
4909 it returns an error that the value in \textit{result} is undefined. To make
4917 Where \textit{len} is the size of the prime in bytes ($2 \le len \le 256$). You can set \textit{len} to the negative size you want
4918 to get a prime of the form $p \equiv 3\mbox{ }(\mbox{mod } 4)$. So if you want a 1024-bit prime of this sort pass
4919 \textit{len = -128} to the function. Upon success it will return {\bf CRYPT\_OK} and \textit{N} will contain an integer which
4925 Probably the single most vulnerable point of any cryptosystem is the PRNG. Without one, generating and protecting secrets
4926 would be impossible. The requirement that one be setup correctly is vitally important, and to address this point the library
4927 does provide two RNG sources that will address the largest amount of end users as possible. The \textit{sprng} PRNG provides an easy to
4928 access source of entropy for any application on a UNIX (and the like) or Windows computer.
4930 However, when the end user is not on one of these platforms, the application developer must address the issue of finding
4932 a cryptosystem make sure the first problem you solve is getting a fresh source of entropy.
4935 Two simple ways to prevent trivial errors is to prevent overflows, and to check the return values. All of the functions
4936 which output variable length strings will require you to pass the length of the destination. If the size of your output
4937 buffer is smaller than the output it will report an error. Therefore, make sure the size you pass is correct!
4939 Also, virtually all of the functions return an error code or {\bf CRYPT\_OK}. You should detect all errors, as simple
4943 To avoid linking and other run--time errors it is important to register the ciphers, hashes and PRNGs you intend to use
4946 A neat bonus to the registry system is that you can add external algorithms that are not part of the library without
4947 having to hack the library. For example, suppose you have a hardware specific PRNG on your system. You could easily
4948 write the few functions required plus a descriptor. After registering your PRNG, all of the library functions that
4949 need a PRNG can instantly take advantage of it. The same applies for ciphers, hashes, and bignum math routines.
4954 For symmetric ciphers, use as large as of a key as possible. For the most part \textit{bits are cheap} so using a 256--bit key
4958 The following chart gives the work factor for solving a DH/RSA public key using the NFS. The work factor for a key of order
4964 Note that $n$ is not the bit-length but the magnitude. For example, for a 1024-bit key $n = 2^{1024}$. The work required
4984 The work factor for ECC keys is much higher since the best attack is still fully exponential. Given a key of magnitude
4985 $n$ it requires $\sqrt n$ work. The following table summarizes the work required:
5004 Using the above tables the following suggestions for key sizes seems appropriate:
5016 The library is not fully thread safe but several simple precautions can be taken to avoid any problems. The registry functions
5020 The rest of the code uses state variables you must pass it such as hash\_state, hmac\_state, etc. This means that if each
5025 The only sticky issue is a shared PRNG which can be alleviated with the careful use of mutex devices. Defining LTC\_PTHREAD for instance, enables
5026 pthreads based mutex locking in various routines such as the Yarrow and Fortuna PRNGs, the fixed point ECC multiplier, and other routines.
5028 \chapter{Configuring and Building the Library}
5030 The library is fairly flexible about how it can be built, used, and generally distributed. Additions are being made with
5031 each new release that will make the library even more flexible. Each of the classes of functions can be disabled during
5032 the build process to make a smaller library. This is particularly useful for shared libraries.
5034 As of v1.06 of the library, the build process has been moved to two steps for the
5037 The build process now consists of installing a math library first, and then building and installing LibTomCrypt with a math library
5039 build, or run time for the application. LibTomCrypt comes with three math descriptors that provide a standard interface to math
5044 All GNU driven makefiles (including the makefile for ICC) use a set of common variables to control the build and install process. Most of the
5045 settings can be overwritten from the command line which makes custom installation a breeze.
5049 The MAKE, CC and AR flags can all be overwritten. They default to \textit{make}, \textit{\$CC} and \textit{\$AR} respectively.
5056 \begin{flushleft} will build and install the libraries with the \textit{gmake} tool. Similarly, \end{flushleft}
5062 \begin{flushleft} will build the library using \textit{arm--gcc} as the compiler and \textit{arm--ar} as the archiver. \end{flushleft}
5066 When \textbf{IGNORE\_SPEED} has been defined the default optimization flags for CFLAGS will be disabled which allows the developer to specify new
5067 CFLAGS on the command line. E.g. to add debugging
5073 This will turn off optimizations and add \textit{-g3} to the CFLAGS which enables debugging.
5077 \textbf{LIBNAME} is the name of the output library (archive) to create. It defaults to \textit{libtomcrypt.a} for static builds and \textit{libtomcrypt.la} for
5078 shared. The \textbf{LIBNAME\_S} variable is the static name while doing shared builds. Ideally they should have the same prefix but don't have to.
5081 Similarly \textbf{LIBTEST} and \textbf{LIBTEST\_S} are the names for the profiling and testing library. The default is \textit{libtomcrypt\_prof.a} for
5086 \textbf{DESTDIR} is the prefix for the installation directories. It defaults to an empty string. \textbf{LIBPATH} is the prefix for the library
5087 directory which defaults to \textit{/usr/lib}. \textbf{INCPATH} is the prefix for the header file directory which defaults to \textit{/usr/include}.
5088 \textbf{DATADIR} is the prefix for the data (documentation) directory which defaults to \textit{/usr/share/doc/libtomcrypt/pdf}.
5090 All four can be used to create custom install locations depending on the nature of the OS and file system in use.
5097 This will build the library and install it to the directories under \textit{/home/tom/project/}. e.g.
5136 \textbf{EXTRALIBS} specifies any extra libraries required to link the test programs and shared libraries. They are specified in the notation
5144 This will install the library using the TomsFastMath library and link the \textit{libtfm.a} library out of the default library search path. The two
5146 the \textbf{EXTRALIBS} variable by separating them by a space.
5148 Note that \textbf{EXTRALIBS} is not required if you are only making and installing the static library but none of the test programs.
5152 Building a static library is fairly trivial as it only requires one invocation of the GNU make command.
5158 That will build LibTomCrypt (including the TomsFastMath descriptor), and install it in the default locations indicated previously. You can enable
5159 the built--in LibTomMath descriptor as well (or in place of the TomsFastMath descriptor). Similarly, you can build the library with no built--in
5166 In this case, no math descriptors are present in the library and they will have to be made available at build or run time before you can use any of the
5169 Note that even if you include the built--in descriptors you must link against the source library as well.
5175 This will compile \textit{myprogram} and link it against the LibTomCrypt library as well as TomsFastMath (which must have been previously installed). Note that
5176 we define \textbf{TFM\_DESC} for compilation. This is so that the TFM descriptor symbol will be defined for the client application to make use of without
5181 LibTomCrypt can also be built as a shared library through the \textit{makefile.shared} make script. It is similar to use as the static script except
5182 that you \textbf{must} specify the \textbf{EXTRALIBS} variable at install time.
5188 This will build and install the library and link the shared object against the TomsFastMath library (which must be installed as a shared object as well). The
5192 The file \textit{tomcrypt\_cfg.h} is what lets you control various high level macros which control the behaviour of the library. Build options are also
5193 stored in \textit{tomcrypt\_custom.h} which allow the enabling and disabling of various algorithms.
5196 This lets you control how the LTC\_ARGCHK macro will behave. The macro is used to check pointers inside the functions against
5197 NULL. There are four settings for ARGTYPE. When set to 0, it will have the default behaviour of printing a message to
5199 similarly. When set to 1, it will simply pass on to the assert() macro. When set to 2, the macro will display the error to
5200 stderr then return execution to the caller. This could lead to a segmentation fault (e.g. when a pointer is \textbf{NULL}) but is useful
5202 to 4, it will return CRYPT\_INVALID\_ARG to the caller.
5206 platforms define \textbf{ENDIAN\_BIG}. Similarly when the default word size of an \textit{unsigned long} is 32-bits define \textbf{ENDIAN\_32BITWORD}
5207 or define \textbf{ENDIAN\_64BITWORD} when its 64-bits. If you do not define any of them the library will automatically use \textbf{ENDIAN\_NEUTRAL}
5212 \mysection{The Configure Script}
5213 There are also options you can specify from the \textit{tomcrypt\_custom.h} header file.
5217 At the top of tomcrypt\_custom.h are a series of macros denoted as XMALLOC, XCALLOC, XREALLOC, XFREE, and so on. They resolve to
5218 the name of the respective functions from the standard C library by default. This lets you substitute in your own memory routines.
5219 If you substitute in your own functions they must behave like the standard C library functions in terms of what they expect as input and
5222 These macros are handy for working with platforms which do not have a standard C library. For instance, the OLPC\footnote{See http://dev.laptop.org/git?p=bios-crypto;a=summary}
5226 The rng\_get\_bytes() function can call a function that requires the clock() function. These macros let you override
5227 the default clock() used with a replacement. By default the standard C library clock() function is used.
5230 During the build if LTC\_NO\_FILE is defined then any function in the library that uses file I/O will not call the file I/O
5235 When this functions is defined the functions that store key material on the stack will clean up afterwards.
5236 Assumes that you have no memory paging with the stack.
5239 When this has been defined the various self--test functions (for ciphers, hashes, prngs, etc) are included in the build. This is the default configuration.
5240 If LTC\_NO\_TEST has been defined, the testing routines will be compacted and only return CRYPT\_NOP.
5243 When this has been defined the library will not use faster word oriented operations. By default, they are only enabled for platforms
5248 cbc\_encrypt() that it can safely XOR multiple octets in one step by using a larger data type. This has the benefit of
5249 cutting down the overhead of the respective functions.
5251 This mode does have one downside. It can cause unaligned reads from memory if you are not careful with the functions. This is why
5252 it has been enabled by default only for the x86 class of processors where unaligned accesses are allowed. Technically LTC\_FAST
5253 is not \textit{portable} since unaligned accesses are not covered by the ISO C specifications.
5257 By design the \textit{fast} mode functions won't get unaligned on their own. For instance, if you call ctr\_encrypt() right after calling
5258 ctr\_start() and all the inputs you gave are aligned than ctr\_encrypt() will perform aligned memory operations only. However, if you
5259 call ctr\_encrypt() with an odd amount of plaintext then call it again the CTR pad (the IV) will be partially used. This will
5260 cause the ctr routine to first use up the remaining pad bytes. Then if there are enough plaintext bytes left it will use
5263 The simplest precaution is to make sure you process all data in power of two blocks and handle \textit{remainder} at the end. e.g. If you are
5264 CTR'ing a long stream process it in blocks of (say) four kilobytes and handle any remaining incomplete blocks at the end of the stream.
5267 If you do plan on using the \textit{LTC\_FAST} mode you have to also define a \textit{LTC\_FAST\_TYPE} macro which resolves to an optimal sized
5268 data type you can perform integer operations with. Ideally it should be four or eight bytes since it must properly divide the size
5273 When this has been defined the library will not use any inline assembler. Only a few platforms support assembler inlines but various versions of ICC and GCC
5274 cannot handle all of the assembler functions.
5277 There are a plethora of macros for the ciphers, hashes, PRNGs and public key functions which are fairly
5278 self-explanatory. When they are defined the functionality is included otherwise it is not. There are some
5279 dependency issues which are noted in the file. For instance, Yarrow requires CTR chaining mode, a block
5285 When defined the library is configured to build fewer algorithms and modes. Mostly it sticks to NIST and ANSI approved algorithms. See
5286 the header file \textit{tomcrypt\_custom.h} for more details. It is meant to provide literally an easy method of trimming the library
5287 build to the most minimum of useful functionality.
5290 Twofish is a 128-bit symmetric block cipher that is provided within the library. The cipher itself is flexible enough
5291 to allow some trade-offs in the implementation. When TWOFISH\_SMALL is defined the scheduled symmetric key for Twofish
5292 requires only 200 bytes of memory. This is achieved by not pre-computing the substitution boxes. Having this
5293 defined will also greatly slow down the cipher. When this macro is not defined Twofish will pre-compute the
5294 tables at a cost of 4KB of memory. The cipher will be much faster as a result.
5296 When TWOFISH\_TABLES is defined the cipher will use pre-computed (and fixed in code) tables required to work. This is
5297 useful when TWOFISH\_SMALL is defined as the table values are computed on the fly. When this is defined the code size
5298 will increase by approximately 500 bytes. If this is defined but TWOFISH\_SMALL is not the cipher will still work but
5299 it will not speed up the encryption or decryption functions.
5302 When defined GCM will use a 64KB table (per GCM state) which will greatly speed up the per--packet latency.
5303 It also increases the initialization time and is not suitable when you are going to use a key a few times only.
5307 When defined GCM will use the SSE2 instructions to perform the $GF(2^x)$ multiply using 16 128--bit XOR operations. It shaves a few cycles per byte
5308 of GCM output on both the AMD64 and Intel Pentium 4 platforms. Requires GCC and an SSE2 equipped platform.
5311 When this is defined some of the code such as the Rijndael and SAFER+ ciphers are replaced with smaller code variants.
5315 When this is activated all of the descriptor table functions will use pthread locking to ensure thread safe updates to the tables. Note that
5316 it doesn't prevent a thread that is passively using a table from being messed up by another thread that updates the table.
5318 Generally the rule of thumb is to setup the tables once at startup and then leave them be. This added build flag simply makes updating
5319 the tables safer.
5322 When this has been defined the ECC point multiplier (built--in to the library) will use a timing resistant point multiplication
5323 algorithm which prevents leaking key bits of the private key (scalar). It is a slower algorithm but useful for situations
5327 The library comes with three math descriptors that allow you to interface the public key cryptography API to freely available math
5329 descriptors for the respective library are built and included in the library as \textit{gmp\_desc}, \textit{ltm\_desc}, or \textit{tfm\_desc} respectively.
5331 In the test demos that use the libraries the additional flags \textbf{USE\_GMP}, \textbf{USE\_LTM}, and \textbf{USE\_TFM} can be defined
5332 to tell the program which library to use. Only one of the USE flags can be defined at once.
5342 That will build and install the library with all descriptors (and link against all), but only use TomsFastMath in the timing demo.
5346 The entire API was designed with plug and play in mind at the low level. That is you can swap out any cipher, hash, PRNG or bignum library and the dependent API will not
5347 require updating. This has the nice benefit that one can add ciphers (etc.) not have to re--write portions of the API. For the most part, LibTomCrypt has also been written
5348 to be highly portable and easy to build out of the box on pretty much any platform. As such there are no assembler inlines throughout the code, I make no assumptions
5349 about the platform, etc...
5351 That works well for most cases but there are times where performance is of the essence. This API allows optimized routines to be dropped in--place of the existing
5352 portable routines. For instance, hand optimized assembler versions of AES could be provided. Any existing function that uses the cipher could automatically use
5353 the optimized code without re--writing. This also paves the way for hardware drivers that can access hardware accelerated cryptographic devices.
5355 At the heart of this flexibility is the \textit{descriptor} system. A descriptor is essentially just a C \textit{struct} which describes the algorithm and provides pointers
5356 to functions that do the required work. For a given class of operation (e.g. cipher, hash, prng, bignum) the functions of a descriptor have identical prototypes which makes
5357 development simple. In most dependent routines all an end developer has to do is register\_XXX() the descriptor and they are set.
5360 The ciphers in LibTomCrypt are accessed through the ltc\_cipher\_descriptor structure.
5384 /** Setup the cipher
5385 @param key The input symmetric key
5386 @param keylen The length of the input key (octets)
5387 @param num_rounds The requested number of rounds (0==default)
5388 @param skey [out] The destination of the scheduled key
5397 @param pt The plaintext
5398 @param ct [out] The ciphertext
5399 @param skey The scheduled key
5407 @param ct The ciphertext
5408 @param pt [out] The plaintext
5409 @param skey The scheduled key
5416 /** Test the block cipher
5422 /** Terminate the context
5423 @param skey The scheduled key
5428 @param keysize [in/out] The size of the key desired
5429 The suggested size
5438 @param blocks The number of complete blocks to process
5439 @param skey The scheduled key context
5450 @param blocks The number of complete blocks to process
5451 @param skey The scheduled key context
5462 @param blocks The number of complete blocks to process
5463 @param IV The initial value (input/output)
5464 @param skey The scheduled key context
5476 @param blocks The number of complete blocks to process
5477 @param IV The initial value (input/output)
5478 @param skey The scheduled key context
5490 @param blocks The number of complete blocks to process
5491 @param IV The initial value (input/output)
5493 @param skey The scheduled key context
5506 @param blocks The number of complete blocks to process
5507 @param IV The initial value (input/output)
5508 @param tweak The LRW tweak
5509 @param skey The scheduled key context
5522 @param blocks The number of complete blocks to process
5523 @param IV The initial value (input/output)
5524 @param tweak The LRW tweak
5525 @param skey The scheduled key context
5536 @param key The secret key to use
5537 @param keylen The length of the secret key (octets)
5539 @param nonce The session nonce [use once]
5540 @param noncelen The length of the nonce
5541 @param header The header for the session
5542 @param headerlen The length of the header (octets)
5543 @param pt [out] The plaintext
5544 @param ptlen The length of the plaintext (octets)
5545 @param ct [out] The ciphertext
5546 @param tag [out] The destination tag
5547 @param taglen [in/out] The max size and resulting size
5548 of the authentication tag
5563 @param key The secret key
5564 @param keylen The length of the secret key
5565 @param IV The initial vector
5566 @param IVlen The length of the initial vector
5567 @param adata The additional authentication data (header)
5568 @param adatalen The length of the adata
5569 @param pt The plaintext
5570 @param ptlen The length of the plaintext/ciphertext
5571 @param ct The ciphertext
5572 @param tag [out] The MAC tag
5573 @param taglen [in/out] The MAC tag length
5587 @param key The secret key
5588 @param keylen The key length (octets)
5589 @param in The message
5601 @param key The secret key
5602 @param keylen The key length (octets)
5603 @param in The message
5615 @param key The secret key
5616 @param keylen The key length (octets)
5617 @param in The message
5634 The \textit{name} parameter specifies the name of the cipher. This is what a developer would pass to find\_cipher() to find the cipher in the descriptor
5641 The minimum key length is \textit{min\_key\_length} and is measured in octets. Similarly the maximum key length is \textit{max\_key\_length}. They can be equal
5642 and both must valid key sizes for the cipher. Values in between are not assumed to be valid though they may be.
5645 The size of the ciphers plaintext or ciphertext is \textit{block\_length} and is measured in octets.
5648 Some ciphers allow different number of rounds to be used. Usually you just use the default. The default round count is \textit{default\_rounds}.
5651 To initialize a cipher (for ECB mode) the function setup() was provided. It accepts an array of key octets \textit{key} of length \textit{keylen} octets. The user
5652 can specify the number of rounds they want through \textit{num\_rounds} where $num\_rounds = 0$ means use the default. The destination of a scheduled key is stored
5655 Inside the \textit{symmetric\_key} union there is a \textit{void *data} which you can use to allocate data if you need a data structure that does not fit with the existing
5656 ones provided. Just make sure in your \textit{done()} function that you free the allocated memory.
5659 To process a single block in ECB mode the ecb\_encrypt() and ecb\_decrypt() functions were provided. The plaintext and ciphertext buffers are allowed to overlap so you
5660 must make sure you do not overwrite the output before you are finished with the input.
5663 The test() function is used to self--test the \textit{device}. It takes no arguments and returns \textbf{CRYPT\_OK} if all is working properly. You may return
5667 Occasionally, a function will want to find a suitable key size to use since the input is oddly sized. The keysize() function is for this case. It accepts a
5668 pointer to an integer which represents the desired size. The function then has to match it to thethe cipher. For
5669 example, if the input is $25$ and $24$ is valid then it stores $24$ back in the pointed to integer. It must not round up and must return an error if the keysize
5670 cannot be mapped to a valid key size for the cipher.
5673 The next set of functions cover the accelerated functionality of the cipher descriptor. Any combination of these functions may be set to \textbf{NULL} to indicate
5674 it is not supported. In those cases the software defaults are used (using the single ECB block routines).
5678 through the accel\_ecb\_encrypt and accel\_ecb\_decrypt pointers. The \textit{blocks} count is the number of complete blocks to process.
5681 These two functions are meant for accelerated CBC encryption. These functions are accessed through the accel\_cbc\_encrypt and accel\_cbc\_decrypt pointers.
5682 The \textit{blocks} value is the number of complete blocks to process. The \textit{IV} is the CBC initial vector. It is an input upon calling this function and must be
5683 updated by the function before returning.
5686 This function is meant for accelerated CTR encryption. It is accessible through the accel\_ctr\_encrypt pointer.
5687 The \textit{blocks} value is the number of complete blocks to process. The \textit{IV} is the CTR counter vector. It is an input upon calling this function and must be
5688 updated by the function before returning. The \textit{mode} value indicates whether the counter is big (mode = CTR\_COUNTER\_BIG\_ENDIAN) or
5691 This function (and the way it's called) differs from the other two since ctr\_encrypt() allows any size input plaintext. The accelerator will only be
5692 called if the following conditions are met.
5695 \item The accelerator is present
5696 \item The CTR pad is empty
5697 \item The remaining length of the input to process is greater than or equal to the block size.
5700 The \textit{CTR pad} is empty when a multiple (including zero) blocks of text have been processed. That is, if you pass in seven bytes to AES--CTR mode you would have to
5701 pass in a minimum of nine extra bytes before the accelerator could be called. The CTR accelerator must increment the counter (and store it back into the
5702 buffer provided) before encrypting it to create the pad.
5704 The accelerator will only be used to encrypt whole blocks. Partial blocks are always handled in software.
5707 These functions are meant for accelerated LRW. They process blocks of input in lengths of multiples of 16 octets. They must accept the \textit{IV} and \textit{tweak}
5713 Note that calling lrw\_done() will only invoke the cipher\_descriptor[].done() function on the \textit{symmetric\_key} parameter of the LRW state. That means
5714 if your device requires any (LRW specific) resources you should free them in your ciphers() done function. The simplest way to think of it is to write
5715 the plugin solely to do LRW with the cipher. That way cipher\_descriptor[].setup() means to init LRW resources and cipher\_descriptor[].done() means to
5719 This function is meant for accelerated CCM encryption or decryption. It processes the entire packet in one call. You can optimize the work flow somewhat
5720 by allowing the caller to call the setup() function first to schedule the key if your accelerator cannot do the key schedule on the fly (for instance). This
5736 \index{ccm\_memory()} This function is called when the user calls ccm\_memory().
5740 This function is meant for accelerated GCM encryption or decryption. It processes the entire packet in one call. Note that the setup() function will not
5741 be called prior to this. This function must handle scheduling the key provided on its own. It is called when the user calls gcm\_memory().
5745 This function is meant to perform an optimized OMAC1 (CMAC) message authentication code computation when the user calls omac\_memory().
5749 This function is meant to perform an optimized XCBC-MAC message authentication code computation when the user calls xcbc\_memory().
5753 This function is meant to perform an optimized F9 message authentication code computation when the user calls f9\_memory(). Like f9\_memory(), it requires
5754 the caller to perform any 3GPP related padding before calling in order to ensure proper compliance with F9.
5758 The hash functions are accessed through the ltc\_hash\_descriptor structure.
5782 @param hash The hash to initialize
5788 @param hash The hash state
5789 @param in The data to hash
5790 @param inlen The length of the data (octets)
5797 /** Produce the digest and store it
5798 @param hash The hash state
5799 @param out [out] The destination of the digest
5812 multiple packets just use the generic hmac_memory
5826 This is the name the hash is known by and what find\_hash() will look for.
5829 This is the internal ID byte used to distinguish the hash from other hashes.
5832 The \textit{hashsize} variable indicates the length of the output in octets.
5835 The \textit{blocksize} variable indicates the length of input (in octets) that the hash processes in a given
5839 This is the universal ASN.1 Object Identifier for the hash.
5842 The init function initializes the hash and prepares it to process message bytes.
5845 This processes message bytes. The algorithm must accept any length of input that the hash would allow. The input is not
5846 guaranteed to be a multiple of the block size in length.
5849 The done function terminates the hash and returns the message digest.
5852 A compatible accelerator must allow processing data in any granularity which may require internal padding on the driver side.
5855 The hmac\_block() callback is meant for single--shot optimized HMAC implementations. It is called directly by hmac\_memory() if present. If you need
5859 The pseudo--random number generators are accessible through the ltc\_prng\_descriptor structure.
5864 /** Name of the PRNG */
5871 @param prng [out] The state to initialize
5876 /** Add entropy to the PRNG
5877 @param in The entropy
5878 @param inlen Length of the entropy (octets)
5879 @param prng The PRNG state
5887 @param prng The PRNG state to ready
5892 /** Read from the PRNG
5893 @param out [out] Where to store the data
5895 @param prng The PRNG state to read from
5903 @param prng The PRNG state to terminate
5909 @param out [out] The destination for the state
5910 @param outlen [in/out] The max size and resulting size
5911 @param prng The PRNG to export
5919 @param in The data to import
5920 @param inlen The length of the data to import (octets)
5921 @param prng The PRNG to initialize/import
5928 /** Self-test the PRNG
5938 The name by which find\_prng() will find the PRNG.
5941 When an PRNG state is to be exported for future use you specify the space required in this variable.
5944 Initialize the PRNG and make it ready to accept entropy.
5947 Add entropy to the PRNG state. The exact behaviour of this function depends on the particulars of the PRNG.
5950 This function makes the PRNG ready to read from by processing the entropy added. The behaviour of this function depends
5951 on the specific PRNG used.
5954 Read from the PRNG and return the number of bytes read. This function does not have to fill the buffer but it is best
5955 if it does as many protocols do not retry reads and will fail on the first try.
5958 Terminate a PRNG state. The behaviour of this function depends on the particular PRNG used.
5961 An exported PRNG state is data that the PRNG can later import to resume activity. They're not meant to resume \textit{the same session}
5962 but should at least maintain the same level of state entropy.
5965 The library also makes use of the math descriptors to access math functions. While bignum math libraries usually differ in implementation
5966 it hasn't proven hard to write \textit{glue} to use math libraries so far. The basic descriptor looks like.
5972 /** Name of the math provider */
5981 @param a The number to initialize
5987 @param dst The number to initialize and write to
5988 @param src The number to copy from
5994 @param a The number to free
6002 @param src The number to copy from
6003 @param dst The number to write to
6019 @return The lower bits_per_digit of the integer (unsigned)
6024 @param a The number to read from
6025 @param n The number of the digit to fetch
6026 @return The bits_per_digit sized n'th digit of a
6030 /** Get the number of digits that represent the number
6031 @param a The number to count
6032 @return The number of digits used to represent the number
6037 @param a The left side integer
6038 @param b The right side integer
6046 @param a The left side integer
6047 @param b The right side integer (upto bits_per_digit)
6054 /** Count the number of bits used to represent the integer
6055 @param a The integer to count
6056 @return The number of bits required to represent the integer
6060 /** Count the number of LSB bits which are zero
6061 @param a The integer to count
6062 @return The number of contiguous zero LSB bits
6067 @param a The integer to store the power in
6068 @param n The power of two you want to store (a = 2^n)
6076 @param a The integer to store into
6077 @param str The string to read
6078 @param radix The radix the integer has been represented in (2-64)
6084 @param a The integer to store
6085 @param str The destination for the string
6086 @param radix The radix the integer is to be represented in (2-64)
6092 @param a The integer to get the size
6093 @return The length of the integer in octets
6098 @param src The integer to store
6099 @param dst The buffer to store the integer in
6105 @param dst The integer to load
6106 @param src The array of octets
6107 @param len The number of octets
6117 @param a The first source integer
6118 @param b The second source integer
6119 @param c The destination of "a + b"
6125 @param a The first source integer
6126 @param b The second source integer
6128 @param c The destination of "a + b"
6134 @param a The first source integer
6135 @param b The second source integer
6136 @param c The destination of "a - b"
6142 @param a The first source integer
6143 @param b The second source integer
6145 @param c The destination of "a - b"
6151 @param a The first source integer
6152 @param b The second source integer
6154 @param c The destination of "a * b"
6160 @param a The first source integer
6161 @param b The second source integer
6163 @param c The destination of "a * b"
6169 @param a The integer to square
6170 @param b The destination
6176 @param a The dividend
6177 @param b The divisor
6178 @param c The quotient (can be NULL to signify don't care)
6179 @param d The remainder (can be NULL to signify don't care)
6185 @param a The integer to divide (shift right)
6186 @param b The destination
6192 @param a The integer to reduce
6193 @param b The modulus (upto bits_per_digit in length)
6194 @param c The destination for the residue
6200 @param a The first integer
6201 @param b The second integer
6202 @param c The destination for (a, b)
6208 @param a The first integer
6209 @param b The second integer
6210 @param c The destination for [a, b]
6216 @param a The first source
6217 @param b The second source
6218 @param c The modulus
6219 @param d The destination (a*b mod c)
6225 @param a The first source
6226 @param b The modulus
6227 @param c The destination (a*a mod b)
6233 @param a The value to invert
6234 @param b The modulus
6235 @param c The destination (1/a mod b)
6243 @param a The modulus
6244 @param b The destination for the reduction digit
6250 @param a The destination for the normalization value
6251 @param b The modulus
6257 @param a The number [and dest] to reduce
6258 @param b The modulus
6259 @param c The value "b" from montgomery_setup()
6265 @param a The value "b" from montgomery_setup()
6273 @param a The base integer
6274 @param b The power (can be negative) integer
6275 @param c The modulus integer
6276 @param d The destination
6282 @param a The integer to test
6283 @param b The destination of the result (FP_YES if prime)
6290 /** ECC GF(p) point multiplication (from the NIST curves)
6291 @param k The integer to multiply the point by
6292 @param G The point to multiply
6293 @param R The destination for kG
6294 @param modulus The modulus for the field
6306 @param P The first point
6307 @param Q The second point
6308 @param R The destination of P + Q
6309 @param modulus The modulus
6310 @param mp The "b" value from montgomery_setup()
6320 @param P The first point
6321 @param R The destination of 2P
6322 @param modulus The modulus
6323 @param mp The "b" value from montgomery_setup()
6333 @param P The point to map
6334 @param modulus The modulus
6335 @param mp The "b" value from montgomery_setup()
6337 @remark The mapping can be different but keep in mind a
6362 @param wprng The index of the PRNG desired
6363 @param size The size of the key in octets
6364 @param e The "e" value (public key).
6376 @param in The octet array representing the base
6377 @param inlen The length of the input
6378 @param out The destination (to be stored in an octet array format)
6379 @param outlen The length of the output buffer and the resulting size
6380 (zero padded to the size of the modulus)
6382 @param key The RSA key to use
6392 Most of the functions are fairly straightforward and do not need documentation. We'll cover the basic conventions of the API and then explain the accelerated functions.
6396 All \textit{bignums} are accessed through an opaque \textit{void *} data type. You must internally cast the pointer if you need to access members of your bignum structure. During
6397 the init calls a \textit{void **} will be passed where you allocate your structure and set the pointer then initialize the number to zero. During the deinit calls you must
6398 free the bignum as well as the structure you allocated to place it in.
6400 All functions except the Montgomery reductions work from left to right with the arguments. For example, mul(a, b, c) computes $c \leftarrow ab$.
6404 The digit routines (including functions with the \textit{i} suffix) use a \textit{unsigned long} to represent the digit. If your internal digit is larger than this you must
6405 then partition your digits. Normally this does not matter as \textit{unsigned long} will be the same size as your register size. Note that if your digit is smaller
6406 than an \textit{unsigned long} that is also acceptable as the \textit{bits\_per\_digit} parameter will specify this.
6409 The ECC system in LibTomCrypt is based off of the NIST recommended curves over $GF(p)$ and is used to implement EC-DSA and EC-DH. The ECC functions work with
6410 the \textbf{ecc\_point} structure and assume the points are stored in Jacobian projective format.
6416 /** The x co-ordinate */
6418 /** The y co-ordinate */
6420 /** The z co-ordinate */
6425 All ECC functions must use this mapping system. The only exception is when you remap all ECC callbacks which will allow you to have more control
6426 over how the ECC math will be implemented. Out of the box you only have three parameters per point to use $(x, y, z)$ however, these are just void pointers. They
6427 could point to anything you want. The only further exception is the export functions which expects the values to be in affine format.
6430 This will multiply the point $G$ by the scalar $k$ and store the result in the point $R$. The value should be mapped to affine only if $map$ is set to one.
6433 This will add the point $P$ to the point $Q$ and store it in the point $R$. The $mp$ parameter is the \textit{b} value from the montgomery\_setup() call. The input points
6434 may be in either affine (with $z = 1$) or projective format and the output point is always projective.
6437 This will map the point $P$ back from projective to affine. The output point $P$ must be of the form $(x, y, 1)$.
6442 To accelerate EC--DSA verification the library provides a built--in function called ltc\_ecc\_mul2add(). This performs two point multiplications and an addition in
6443 roughly the time of one point multiplication. It is called from ecc\_verify\_hash() if an accelerator is not present. The acclerator function must allow the points to
6444 overlap (e.g., $A \leftarrow k_1A + k_2B$) and must return the final point in affine format.
6448 The RSA Modular Exponentiation (ME) function is used by the RSA API to perform exponentiations for private and public key operations. In particular for
6449 private key operations it uses the CRT approach to lower the time required. It is passed an RSA key with the following format.
6456 /** The public exponent */
6458 /** The private exponent */
6460 /** The modulus */
6462 /** The p factor of N */
6464 /** The q factor of N */
6466 /** The 1/q mod p CRT param */
6468 /** The d mod (p - 1) CRT param */
6470 /** The d mod (q - 1) CRT param */
6475 The call reads the \textit{in} buffer as an unsigned char array in big endian format. Then it performs the exponentiation and stores the output in big endian format
6476 to the \textit{out} buffer. The output must be zero padded (leading bytes) so that the length of the output matches the length of the modulus (in bytes). For example,
6477 for RSA--1024 the output is always 128 bytes regardless of how small the numerical value of the exponentiation is.
6479 Since the function is given the entire RSA key (for private keys only) CRT is possible as prescribed in the PKCS \#1 v2.1 specification.