comparison crypt.tex @ 15:6362d3854bb4 libtomcrypt-orig

0.96 release of LibTomCrypt
author Matt Johnston <matt@ucc.asn.au>
date Tue, 15 Jun 2004 14:07:21 +0000
parents 7faae8f46238
children 5d99163f7e32
comparison
equal deleted inserted replaced
3:7faae8f46238 15:6362d3854bb4
45 \def\twiddle{\raisebox{0.3ex}{\mbox{\tiny $\sim$}}} 45 \def\twiddle{\raisebox{0.3ex}{\mbox{\tiny $\sim$}}}
46 46
47 \def\gap{\vspace{0.5ex}} 47 \def\gap{\vspace{0.5ex}}
48 \makeindex 48 \makeindex
49 \begin{document} 49 \begin{document}
50 \title{A Tiny Crypto Library, \\ LibTomCrypt \\ Version 0.95} 50 \title{A Tiny Crypto Library, \\ LibTomCrypt \\ Version 0.96}
51 \author{Tom St Denis \\ 51 \author{Tom St Denis \\
52 \\ 52 \\
53 [email protected] \\ 53 [email protected] \\
54 http://libtomcrypt.org \\ \\ 54 http://libtomcrypt.org \\ \\
55 Phone: 1-613-836-3160\\ 55 Phone: 1-613-836-3160\\
101 Similarly SSL protocols could be formed on top of the low-level symmetric cipher functions. The goal of this package is 101 Similarly SSL protocols could be formed on top of the low-level symmetric cipher functions. The goal of this package is
102 to provide these low level core functions in a robust and easy to use fashion. 102 to provide these low level core functions in a robust and easy to use fashion.
103 103
104 The library also serves well as a toolkit for applications where they don't need to be OpenPGP, PKCS, etc. compliant. 104 The library also serves well as a toolkit for applications where they don't need to be OpenPGP, PKCS, etc. compliant.
105 Included are fully operational public key routines for encryption, decryption, signature generation and verification. 105 Included are fully operational public key routines for encryption, decryption, signature generation and verification.
106 These routines are fully portable but are not conformant to any known set of standards. They are all based on established 106 These routines are fully portable but are not conformant to any known set of standards\footnote{With the exception of
107 the RSA code which is based on the PKCS \#1 standards.}. They are all based on established
107 number theory and cryptography. 108 number theory and cryptography.
108 109
109 \subsection{What the library IS NOT for?} 110 \subsection{What the library IS NOT for?}
110 111
111 The library is not designed to be in anyway an implementation of the SSL or OpenPGP standards. The library 112 The library is not designed to be in anyway an implementation of the SSL or OpenPGP standards. The library
239 In general the API is very simple to memorize and use. Most of the functions return either {\bf void} or {\bf int}. Functions 240 In general the API is very simple to memorize and use. Most of the functions return either {\bf void} or {\bf int}. Functions
240 that return {\bf int} will return {\bf CRYPT\_OK} if the function was successful or one of the many error codes 241 that return {\bf int} will return {\bf CRYPT\_OK} if the function was successful or one of the many error codes
241 if it failed. Certain functions that return int will return $-1$ to indicate an error. These functions will be explicitly 242 if it failed. Certain functions that return int will return $-1$ to indicate an error. These functions will be explicitly
242 commented upon. When a function does return a CRYPT error code it can be translated into a string with 243 commented upon. When a function does return a CRYPT error code it can be translated into a string with
243 244
244 \begin{verbatim} 245 \index{error\_to\_string()}
245 const char *error_to_string(int errno); 246 \begin{verbatim}
247 const char *error_to_string(int err);
246 \end{verbatim} 248 \end{verbatim}
247 249
248 An example of handling an error is: 250 An example of handling an error is:
249 \begin{verbatim} 251 \begin{verbatim}
250 void somefunc(void) 252 void somefunc(void)
251 { 253 {
252 int errno; 254 int err;
253 255
254 /* call a cryptographic function */ 256 /* call a cryptographic function */
255 if ((errno = some_crypto_function(...)) != CRYPT_OK) { 257 if ((err = some_crypto_function(...)) != CRYPT_OK) {
256 printf("A crypto error occured, %s\n", error_to_string(errno)); 258 printf("A crypto error occured, %s\n", error_to_string(err));
257 /* perform error handling */ 259 /* perform error handling */
258 } 260 }
259 /* continue on if no error occured */ 261 /* continue on if no error occured */
260 } 262 }
261 \end{verbatim} 263 \end{verbatim}
318 #include <mycrypt.h> 320 #include <mycrypt.h>
319 int main(void) { 321 int main(void) {
320 rsa_key key; 322 rsa_key key;
321 unsigned char buffer[1024]; 323 unsigned char buffer[1024];
322 unsigned long x; 324 unsigned long x;
323 int errno; 325 int err;
324 326
325 /* ... Make up the RSA key somehow */ 327 /* ... Make up the RSA key somehow */
326 328
327 /* lets export the key, set x to the size of the output buffer */ 329 /* lets export the key, set x to the size of the output buffer */
328 x = sizeof(buffer); 330 x = sizeof(buffer);
329 if ((errno = rsa_export(buffer, &x, PK_PUBLIC, &key)) != CRYPT_OK) { 331 if ((err = rsa_export(buffer, &x, PK_PUBLIC, &key)) != CRYPT_OK) {
330 printf("Export error: %s\n", error_to_string(errno)); 332 printf("Export error: %s\n", error_to_string(err));
331 return -1; 333 return -1;
332 } 334 }
333 335
334 /* if rsa_export() was successful then x will have the size of the output */ 336 /* if rsa_export() was successful then x will have the size of the output */
335 printf("RSA exported key takes %d bytes\n", x); 337 printf("RSA exported key takes %d bytes\n", x);
409 \begin{small} 411 \begin{small}
410 \begin{verbatim} 412 \begin{verbatim}
411 #include <mycrypt.h> 413 #include <mycrypt.h>
412 int main(void) 414 int main(void)
413 { 415 {
414 int keysize, errno; 416 int keysize, err;
415 417
416 /* now given a 20 byte key what keysize does Twofish want to use? */ 418 /* now given a 20 byte key what keysize does Twofish want to use? */
417 keysize = 20; 419 keysize = 20;
418 if ((errno = twofish_keysize(&keysize)) != CRYPT_OK) { 420 if ((err = twofish_keysize(&keysize)) != CRYPT_OK) {
419 printf("Error getting key size: %s\n", error_to_string(errno)); 421 printf("Error getting key size: %s\n", error_to_string(err));
420 return -1; 422 return -1;
421 } 423 }
422 printf("Twofish suggested a key size of %d\n", keysize); 424 printf("Twofish suggested a key size of %d\n", keysize);
423 return 0; 425 return 0;
424 } 426 }
432 #include <mycrypt.h> 434 #include <mycrypt.h>
433 int main(void) 435 int main(void)
434 { 436 {
435 unsigned char pt[8], ct[8], key[8]; 437 unsigned char pt[8], ct[8], key[8];
436 symmetric_key skey; 438 symmetric_key skey;
437 int errno; 439 int err;
438 440
439 /* ... key is loaded appropriately in ``key'' ... */ 441 /* ... key is loaded appropriately in ``key'' ... */
440 /* ... load a block of plaintext in ``pt'' ... */ 442 /* ... load a block of plaintext in ``pt'' ... */
441 443
442 /* schedule the key */ 444 /* schedule the key */
443 if ((errno = blowfish_setup(key, 8, 0, &skey)) != CRYPT_OK) { 445 if ((err = blowfish_setup(key, /* the key we will use */
444 printf("Setup error: %s\n", error_to_string(errno)); 446 8, /* key is 8 bytes (64-bits) long */
447 0, /* 0 == use default # of rounds */
448 &skey) /* where to put the scheduled key */
449 ) != CRYPT_OK) {
450 printf("Setup error: %s\n", error_to_string(err));
445 return -1; 451 return -1;
446 } 452 }
447 453
448 /* encrypt the block */ 454 /* encrypt the block */
449 blowfish_ecb_encrypt(pt, ct, &skey); 455 blowfish_ecb_encrypt(pt, /* encrypt this 8-byte array */
456 ct, /* store encrypted data here */
457 &skey); /* our previously scheduled key */
450 458
451 /* decrypt the block */ 459 /* decrypt the block */
452 blowfish_ecb_decrypt(ct, pt, &skey); 460 blowfish_ecb_decrypt(ct, /* decrypt this 8-byte array */
461 pt, /* store decrypted data here */
462 &skey); /* our previously scheduled key */
453 463
454 return 0; 464 return 0;
455 } 465 }
456 \end{verbatim} 466 \end{verbatim}
457 \end{small} 467 \end{small}
499 The remaining fields are all pointers to the core functions for each cipher. The end of the cipher\_descriptor array is 509 The remaining fields are all pointers to the core functions for each cipher. The end of the cipher\_descriptor array is
500 marked when ``name'' equals {\bf NULL}. 510 marked when ``name'' equals {\bf NULL}.
501 511
502 As of this release the current cipher\_descriptors elements are 512 As of this release the current cipher\_descriptors elements are
503 513
514 \index{Cipher descriptor table}
504 \begin{small} 515 \begin{small}
505 \begin{center} 516 \begin{center}
506 \begin{tabular}{|c|c|c|c|c|c|} 517 \begin{tabular}{|c|c|c|c|c|c|}
507 \hline Name & Descriptor Name & Block Size & Key Range & Rounds \\ 518 \hline Name & Descriptor Name & Block Size & Key Range & Rounds \\
508 \hline Blowfish & blowfish\_desc & 8 & 8 $\ldots$ 56 & 16 \\ 519 \hline Blowfish & blowfish\_desc & 8 & 8 $\ldots$ 56 & 16 \\
514 \hline Safer K64 & safer\_k64\_desc & 8 & 8 & 6 $\ldots$ 13 \\ 525 \hline Safer K64 & safer\_k64\_desc & 8 & 8 & 6 $\ldots$ 13 \\
515 \hline Safer SK64 & safer\_sk64\_desc & 8 & 8 & 6 $\ldots$ 13 \\ 526 \hline Safer SK64 & safer\_sk64\_desc & 8 & 8 & 6 $\ldots$ 13 \\
516 \hline Safer K128 & safer\_k128\_desc & 8 & 16 & 6 $\ldots$ 13 \\ 527 \hline Safer K128 & safer\_k128\_desc & 8 & 16 & 6 $\ldots$ 13 \\
517 \hline Safer SK128 & safer\_sk128\_desc & 8 & 16 & 6 $\ldots$ 13 \\ 528 \hline Safer SK128 & safer\_sk128\_desc & 8 & 16 & 6 $\ldots$ 13 \\
518 \hline AES & aes\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\ 529 \hline AES & aes\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\
530 & aes\_enc\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\
519 \hline Twofish & twofish\_desc & 16 & 16, 24, 32 & 16 \\ 531 \hline Twofish & twofish\_desc & 16 & 16, 24, 32 & 16 \\
520 \hline DES & des\_desc & 8 & 7 & 16 \\ 532 \hline DES & des\_desc & 8 & 7 & 16 \\
521 \hline 3DES (EDE mode) & des3\_desc & 8 & 21 & 16 \\ 533 \hline 3DES (EDE mode) & des3\_desc & 8 & 21 & 16 \\
522 \hline CAST5 (CAST-128) & cast5\_desc & 8 & 5 $\ldots$ 16 & 12, 16 \\ 534 \hline CAST5 (CAST-128) & cast5\_desc & 8 & 5 $\ldots$ 16 & 12, 16 \\
523 \hline Noekeon & noekeon\_desc & 16 & 16 & 16 \\ 535 \hline Noekeon & noekeon\_desc & 16 & 16 & 16 \\
526 \end{tabular} 538 \end{tabular}
527 \end{center} 539 \end{center}
528 \end{small} 540 \end{small}
529 541
530 \subsection{Notes} 542 \subsection{Notes}
543 \begin{small}
544 \begin{enumerate}
545 \item
546 For AES (also known as Rijndael) there are four descriptors which complicate issues a little. The descriptors
547 rijndael\_desc and rijndael\_enc\_desc provide the cipher named ``rijndael''. The descriptors aes\_desc and
548 aes\_enc\_desc provide the cipher name ``aes''. Functionally both ``rijndael'' and ``aes'' are the same cipher. The
549 only difference is when you call find\_cipher() you have to pass the correct name. The cipher descriptors with ``enc''
550 in the middle (e.g. rijndael\_enc\_desc) are related to an implementation of Rijndael with only the encryption routine
551 and tables. The decryption and self--test function pointers of both ``encrypt only'' descriptors are set to \textbf{NULL} and
552 should not be called.
553
554 The ``encrypt only'' descriptors are useful for applications that only use the encryption function of the cipher. Algorithms such
555 as EAX, PMAC and OMAC only require the encryption function. So far this ``encrypt only'' functionality has only been implemented for
556 Rijndael as it makes the most sense for this cipher.
557
558 \item
531 For the 64-bit SAFER famliy of ciphers (e.g K64, SK64, K128, SK128) the ecb\_encrypt() and ecb\_decrypt() 559 For the 64-bit SAFER famliy of ciphers (e.g K64, SK64, K128, SK128) the ecb\_encrypt() and ecb\_decrypt()
532 functions are the same. So if you want to use those functions directly just call safer\_ecb\_encrypt() 560 functions are the same. So if you want to use those functions directly just call safer\_ecb\_encrypt()
533 or safer\_ecb\_decrypt() respectively. 561 or safer\_ecb\_decrypt() respectively.
534 562
563 \item
535 Note that for ``DES'' and ``3DES'' they use 8 and 24 byte keys but only 7 and 21 [respectively] bytes of the keys are in 564 Note that for ``DES'' and ``3DES'' they use 8 and 24 byte keys but only 7 and 21 [respectively] bytes of the keys are in
536 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 565 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
537 byte string from the real 7/21 byte key. 566 byte string from the real 7/21 byte key.
538 567
568 \item
539 Note that ``Twofish'' has additional configuration options that take place at build time. These options are found in 569 Note that ``Twofish'' has additional configuration options that take place at build time. These options are found in
540 the file ``mycrypt\_cfg.h''. The first option is ``TWOFISH\_SMALL'' which when defined will force the Twofish code 570 the file ``mycrypt\_cfg.h''. The first option is ``TWOFISH\_SMALL'' which when defined will force the Twofish code
541 to not pre-compute the Twofish ``$g(X)$'' function as a set of four $8 \times 32$ s-boxes. This means that a scheduled 571 to not pre-compute the Twofish ``$g(X)$'' function as a set of four $8 \times 32$ s-boxes. This means that a scheduled
542 key will require less ram but the resulting cipher will be slower. The second option is ``TWOFISH\_TABLES'' which when 572 key will require less ram but the resulting cipher will be slower. The second option is ``TWOFISH\_TABLES'' which when
543 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 573 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
544 by the polynomials 5B and EF used in the MDS multiplication. As a result the code is faster and slightly larger. The 574 by the polynomials 5B and EF used in the MDS multiplication. As a result the code is faster and slightly larger. The
545 speed increase is useful when ``TWOFISH\_SMALL'' is defined since the s-boxes and MDS multiply form the heart of the 575 speed increase is useful when ``TWOFISH\_SMALL'' is defined since the s-boxes and MDS multiply form the heart of the
546 Twofish round function. 576 Twofish round function.
547 577
578 \index{Twofish build options}
548 \begin{small} 579 \begin{small}
549 \begin{center} 580 \begin{center}
550 \begin{tabular}{|l|l|l|} 581 \begin{tabular}{|l|l|l|}
551 \hline TWOFISH\_SMALL & TWOFISH\_TABLES & Speed and Memory (per key) \\ 582 \hline TWOFISH\_SMALL & TWOFISH\_TABLES & Speed and Memory (per key) \\
552 \hline undefined & undefined & Very fast, 4.2KB of ram. \\ 583 \hline undefined & undefined & Very fast, 4.2KB of ram. \\
556 \hline 587 \hline
557 \end{tabular} 588 \end{tabular}
558 \end{center} 589 \end{center}
559 \end{small} 590 \end{small}
560 591
592 \end{enumerate}
593 \end{small}
594
561 To work with the cipher\_descriptor array there is a function: 595 To work with the cipher\_descriptor array there is a function:
596 \index{find\_cipher()}
562 \begin{verbatim} 597 \begin{verbatim}
563 int find_cipher(char *name) 598 int find_cipher(char *name)
564 \end{verbatim} 599 \end{verbatim}
565 Which will search for a given name in the array. It returns negative one if the cipher is not found, otherwise it returns 600 Which will search for a given name in the array. It returns negative one if the cipher is not found, otherwise it returns
566 the location in the array where the cipher was found. For example, to indirectly setup Blowfish you can also use: 601 the location in the array where the cipher was found. For example, to indirectly setup Blowfish you can also use:
569 #include <mycrypt.h> 604 #include <mycrypt.h>
570 int main(void) 605 int main(void)
571 { 606 {
572 unsigned char key[8]; 607 unsigned char key[8];
573 symmetric_key skey; 608 symmetric_key skey;
574 int errno; 609 int err;
575 610
576 /* you must register a cipher before you use it */ 611 /* you must register a cipher before you use it */
577 if (register_cipher(&blowfish_desc)) == -1) { 612 if (register_cipher(&blowfish_desc)) == -1) {
578 printf("Unable to register Blowfish cipher."); 613 printf("Unable to register Blowfish cipher.");
579 return -1; 614 return -1;
580 } 615 }
581 616
582 /* generic call to function (assuming the key in key[] was already setup) */ 617 /* generic call to function (assuming the key in key[] was already setup) */
583 if ((errno = cipher_descriptor[find_cipher("blowfish")].setup(key, 8, 0, &skey)) != CRYPT_OK) { 618 if ((err = cipher_descriptor[find_cipher("blowfish")].setup(key, 8, 0, &skey)) != CRYPT_OK) {
584 printf("Error setting up Blowfish: %s\n", error_to_string(errno)); 619 printf("Error setting up Blowfish: %s\n", error_to_string(err));
585 return -1; 620 return -1;
586 } 621 }
587 622
588 /* ... use cipher ... */ 623 /* ... use cipher ... */
589 } 624 }
590 \end{verbatim} 625 \end{verbatim}
591 \end{small} 626 \end{small}
592 627
593 A good safety would be to check the return value of ``find\_cipher()'' before accessing the desired function. In order 628 A good safety would be to check the return value of ``find\_cipher()'' before accessing the desired function. In order
594 to use a cipher with the descriptor table you must register it first using: 629 to use a cipher with the descriptor table you must register it first using:
630 \index{register\_cipher()}
595 \begin{verbatim} 631 \begin{verbatim}
596 int register_cipher(const struct _cipher_descriptor *cipher); 632 int register_cipher(const struct _cipher_descriptor *cipher);
597 \end{verbatim} 633 \end{verbatim}
598 Which accepts a pointer to a descriptor and returns the index into the global descriptor table. If an error occurs such 634 Which accepts a pointer to a descriptor and returns the index into the global descriptor table. If an error occurs such
599 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 635 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
600 than once it will just return the index of the first copy. To remove a cipher call: 636 than once it will just return the index of the first copy. To remove a cipher call:
637 \index{unregister\_cipher()}
601 \begin{verbatim} 638 \begin{verbatim}
602 int unregister_cipher(const struct _cipher_descriptor *cipher); 639 int unregister_cipher(const struct _cipher_descriptor *cipher);
603 \end{verbatim} 640 \end{verbatim}
604 Which returns {\bf CRYPT\_OK} if it removes it otherwise it returns {\bf CRYPT\_ERROR}. Consider: 641 Which returns {\bf CRYPT\_OK} if it removes it otherwise it returns {\bf CRYPT\_ERROR}. Consider:
605 \begin{small} 642 \begin{small}
606 \begin{verbatim} 643 \begin{verbatim}
607 #include <mycrypt.h> 644 #include <mycrypt.h>
608 int main(void) 645 int main(void)
609 { 646 {
610 int errno; 647 int err;
611 648
612 /* register the cipher */ 649 /* register the cipher */
613 if (register_cipher(&rijndael_desc) == -1) { 650 if (register_cipher(&rijndael_desc) == -1) {
614 printf("Error registering Rijndael\n"); 651 printf("Error registering Rijndael\n");
615 return -1; 652 return -1;
616 } 653 }
617 654
618 /* use Rijndael */ 655 /* use Rijndael */
619 656
620 /* remove it */ 657 /* remove it */
621 if ((errno = unregister_cipher(&rijndael_desc)) != CRYPT_OK) { 658 if ((err = unregister_cipher(&rijndael_desc)) != CRYPT_OK) {
622 printf("Error removing Rijndael: %s\n", error_to_string(errno)); 659 printf("Error removing Rijndael: %s\n", error_to_string(err));
623 return -1; 660 return -1;
624 } 661 }
625 662
626 return 0; 663 return 0;
627 } 664 }
634 A typical symmetric block cipher can be used in chaining modes to effectively encrypt messages larger than the block 671 A typical symmetric block cipher can be used in chaining modes to effectively encrypt messages larger than the block
635 size of the cipher. Given a key $k$, a plaintext $P$ and a cipher $E$ we shall denote the encryption of the block 672 size of the cipher. Given a key $k$, a plaintext $P$ and a cipher $E$ we shall denote the encryption of the block
636 $P$ under the key $k$ as $E_k(P)$. In some modes there exists an initial vector denoted as $C_{-1}$. 673 $P$ under the key $k$ as $E_k(P)$. In some modes there exists an initial vector denoted as $C_{-1}$.
637 674
638 \subsubsection{ECB Mode} 675 \subsubsection{ECB Mode}
676 \index{ECB mode}
639 ECB or Electronic Codebook Mode is the simplest method to use. It is given as: 677 ECB or Electronic Codebook Mode is the simplest method to use. It is given as:
640 \begin{equation} 678 \begin{equation}
641 C_i = E_k(P_i) 679 C_i = E_k(P_i)
642 \end{equation} 680 \end{equation}
643 This mode is very weak since it allows people to swap blocks and perform replay attacks if the same key is used more 681 This mode is very weak since it allows people to swap blocks and perform replay attacks if the same key is used more
644 than once. 682 than once.
645 683
646 \subsubsection{CBC Mode} 684 \subsubsection{CBC Mode}
685 \index{CBC mode}
647 CBC or Cipher Block Chaining mode is a simple mode designed to prevent trivial forms of replay and swap attacks on ciphers. 686 CBC or Cipher Block Chaining mode is a simple mode designed to prevent trivial forms of replay and swap attacks on ciphers.
648 It is given as: 687 It is given as:
649 \begin{equation} 688 \begin{equation}
650 C_i = E_k(P_i \oplus C_{i - 1}) 689 C_i = E_k(P_i \oplus C_{i - 1})
651 \end{equation} 690 \end{equation}
652 It is important that the initial vector be unique and preferably random for each message encrypted under the same key. 691 It is important that the initial vector be unique and preferably random for each message encrypted under the same key.
653 692
654 \subsubsection{CTR Mode} 693 \subsubsection{CTR Mode}
694 \index{CTR mode}
655 CTR or Counter Mode is a mode which only uses the encryption function of the cipher. Given a initial vector which is 695 CTR or Counter Mode is a mode which only uses the encryption function of the cipher. Given a initial vector which is
656 treated as a large binary counter the CTR mode is given as: 696 treated as a large binary counter the CTR mode is given as:
657 \begin{eqnarray} 697 \begin{eqnarray}
658 C_{-1} = C_{-1} + 1\mbox{ }(\mbox{mod }2^W) \nonumber \\ 698 C_{-1} = C_{-1} + 1\mbox{ }(\mbox{mod }2^W) \nonumber \\
659 C_i = P_i \oplus E_k(C_{-1}) 699 C_i = P_i \oplus E_k(C_{-1})
661 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 701 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
662 encrypted under the same key replay and swap attacks are infeasible. CTR mode may look simple but it is as secure 702 encrypted under the same key replay and swap attacks are infeasible. CTR mode may look simple but it is as secure
663 as the block cipher is under a chosen plaintext attack (provided the initial vector is unique). 703 as the block cipher is under a chosen plaintext attack (provided the initial vector is unique).
664 704
665 \subsubsection{CFB Mode} 705 \subsubsection{CFB Mode}
706 \index{CFB mode}
666 CFB or Ciphertext Feedback Mode is a mode akin to CBC. It is given as: 707 CFB or Ciphertext Feedback Mode is a mode akin to CBC. It is given as:
667 \begin{eqnarray} 708 \begin{eqnarray}
668 C_i = P_i \oplus C_{-1} \nonumber \\ 709 C_i = P_i \oplus C_{-1} \nonumber \\
669 C_{-1} = E_k(C_i) 710 C_{-1} = E_k(C_i)
670 \end{eqnarray} 711 \end{eqnarray}
671 Note that in this library the output feedback width is equal to the size of the block cipher. That is this mode is used 712 Note that in this library the output feedback width is equal to the size of the block cipher. That is this mode is used
672 to encrypt whole blocks at a time. However, the library will buffer data allowing the user to encrypt or decrypt partial 713 to encrypt whole blocks at a time. However, the library will buffer data allowing the user to encrypt or decrypt partial
673 blocks without a delay. When this mode is first setup it will initially encrypt the initial vector as required. 714 blocks without a delay. When this mode is first setup it will initially encrypt the initial vector as required.
674 715
675 \subsubsection{OFB Mode} 716 \subsubsection{OFB Mode}
717 \index{OFB mode}
676 OFB or Output Feedback Mode is a mode akin to CBC as well. It is given as: 718 OFB or Output Feedback Mode is a mode akin to CBC as well. It is given as:
677 \begin{eqnarray} 719 \begin{eqnarray}
678 C_{-1} = E_k(C_{-1}) \nonumber \\ 720 C_{-1} = E_k(C_{-1}) \nonumber \\
679 C_i = P_i \oplus C_{-1} 721 C_i = P_i \oplus C_{-1}
680 \end{eqnarray} 722 \end{eqnarray}
701 \index{CBC Mode} \index{CTR Mode} 743 \index{CBC Mode} \index{CTR Mode}
702 \index{OFB Mode} \index{CFB Mode} 744 \index{OFB Mode} \index{CFB Mode}
703 The library provides simple support routines for handling CBC, CTR, CFB, OFB and ECB encoded messages. Assuming the mode 745 The library provides simple support routines for handling CBC, CTR, CFB, OFB and ECB encoded messages. Assuming the mode
704 you want is XXX there is a structure called ``symmetric\_XXX'' that will contain the information required to 746 you want is XXX there is a structure called ``symmetric\_XXX'' that will contain the information required to
705 use that mode. They have identical setup routines (except ECB mode for obvious reasons): 747 use that mode. They have identical setup routines (except ECB mode for obvious reasons):
748 \index{ecb\_start()} \index{cfb\_start()} \index{cbc\_start()} \index{ofb\_start()} \index{ctr\_start()}
706 \begin{verbatim} 749 \begin{verbatim}
707 int XXX_start(int cipher, const unsigned char *IV, 750 int XXX_start(int cipher, const unsigned char *IV,
708 const unsigned char *key, int keylen, 751 const unsigned char *key, int keylen,
709 int num_rounds, symmetric_XXX *XXX); 752 int num_rounds, symmetric_XXX *XXX);
710 753
719 parameters ``key'', ``keylen'' and ``num\_rounds'' are the same as in the XXX\_setup() function call. The final parameter 762 parameters ``key'', ``keylen'' and ``num\_rounds'' are the same as in the XXX\_setup() function call. The final parameter
720 is a pointer to the structure you want to hold the information for the mode of operation. 763 is a pointer to the structure you want to hold the information for the mode of operation.
721 764
722 Both routines return {\bf CRYPT\_OK} if the cipher initialized correctly, otherwise they return an error code. To 765 Both routines return {\bf CRYPT\_OK} if the cipher initialized correctly, otherwise they return an error code. To
723 actually encrypt or decrypt the following routines are provided: 766 actually encrypt or decrypt the following routines are provided:
767 \index{ecb\_encrypt()} \index{ecb\_decrypt()} \index{cfb\_encrypt()} \index{cfb\_decrypt()}
768 \index{cbc\_encrypt()} \index{cbc\_decrypt()} \index{ofb\_encrypt()} \index{ofb\_decrypt()} \index{ctr\_encrypt()} \index{ctr\_decrypt()}
724 \begin{verbatim} 769 \begin{verbatim}
725 int XXX_encrypt(const unsigned char *pt, unsigned char *ct, 770 int XXX_encrypt(const unsigned char *pt, unsigned char *ct,
726 symmetric_XXX *XXX); 771 symmetric_XXX *XXX);
727 int XXX_decrypt(const unsigned char *ct, unsigned char *pt, 772 int XXX_decrypt(const unsigned char *ct, unsigned char *pt,
728 symmetric_XXX *XXX); 773 symmetric_XXX *XXX);
737 chunk sensitive. That is you can encrypt ``ABCDEF'' in three calls like ``AB'', ``CD'', ``EF'' or two like ``ABCDE'' and ``F'' 782 chunk sensitive. That is you can encrypt ``ABCDEF'' in three calls like ``AB'', ``CD'', ``EF'' or two like ``ABCDE'' and ``F''
738 and end up with the same ciphertext. However, encrypting ``ABC'' and ``DABC'' will result in different ciphertexts. All 783 and end up with the same ciphertext. However, encrypting ``ABC'' and ``DABC'' will result in different ciphertexts. All
739 five of the modes will return {\bf CRYPT\_OK} on success from the encrypt or decrypt functions. 784 five of the modes will return {\bf CRYPT\_OK} on success from the encrypt or decrypt functions.
740 785
741 To decrypt in either mode you simply perform the setup like before (recall you have to fetch the IV value you used) 786 To decrypt in either mode you simply perform the setup like before (recall you have to fetch the IV value you used)
742 and use the decrypt routine on all of the blocks. When you are done working with either mode you should wipe the 787 and use the decrypt routine on all of the blocks.
743 memory (using ``zeromem()'') to help prevent the key from leaking. For example: 788
789 To change or read the IV of a previously initialized chaining mode use the following two functions.
790
791 \index{cbc\_setiv()} \index{cbc\_getiv()} \index{ofb\_setiv()} \index{ofb\_getiv()} \index{cfb\_setiv()} \index{cfb\_getiv()}
792 \index{ctr\_setiv()} \index{ctr\_getiv()}
793 \begin{verbatim}
794 int XXX_getiv(unsigned char *IV, unsigned long *len, symmetric_XXX *XXX);
795 int XXX_setiv(const unsigned char *IV, unsigned long len, symmetric_XXX *XXX);
796 \end{verbatim}
797
798 The XXX\_getiv function will read the IV out of the chaining mode and store it into ``IV'' along with the length of the IV
799 stored in ``len''. The XXX\_setiv will initialize the chaining mode state as if the original IV were the new IV specified. The length
800 of the IV passed in must be the size of the ciphers block size.
801
802 The XXX\_setiv functions are handy if you wish to change the IV without re--keying the cipher.
803
744 \newpage 804 \newpage
745 \begin{small} 805 \begin{small}
746 \begin{verbatim} 806 \begin{verbatim}
747 #include <mycrypt.h> 807 #include <mycrypt.h>
748 int main(void) 808 int main(void)
749 { 809 {
750 unsigned char key[16], IV[16], buffer[512]; 810 unsigned char key[16], IV[16], buffer[512];
751 symmetric_CTR ctr; 811 symmetric_CTR ctr;
752 int x, errno; 812 int x, err;
753 813
754 /* register twofish first */ 814 /* register twofish first */
755 if (register_cipher(&twofish_desc) == -1) { 815 if (register_cipher(&twofish_desc) == -1) {
756 printf("Error registering cipher.\n"); 816 printf("Error registering cipher.\n");
757 return -1; 817 return -1;
758 } 818 }
759 819
760 /* somehow fill out key and IV */ 820 /* somehow fill out key and IV */
761 821
762 /* start up CTR mode */ 822 /* start up CTR mode */
763 if ((errno = ctr_start(find_cipher("twofish"), IV, key, 16, 0, &ctr)) != CRYPT_OK) { 823 if ((err = ctr_start(find_cipher("twofish"), /* index of desired cipher */
764 printf("ctr_start error: %s\n", error_to_string(errno)); 824 IV, /* the initial vector */
825 key, /* the secret key */
826 16, /* length of secret key (16 bytes, 128 bits) */
827 0, /* 0 == default # of rounds */
828 &ctr) /* where to store initialized CTR state */
829 ) != CRYPT_OK) {
830 printf("ctr_start error: %s\n", error_to_string(err));
765 return -1; 831 return -1;
766 } 832 }
767 833
768 /* somehow fill buffer than encrypt it */ 834 /* somehow fill buffer than encrypt it */
769 if ((errno = ctr_encrypt(buffer, buffer, sizeof(buffer), &ctr)) != CRYPT_OK) { 835 if ((err = ctr_encrypt( buffer, /* plaintext */
770 printf("ctr_encrypt error: %s\n", error_to_string(errno)); 836 buffer, /* ciphertext */
837 sizeof(buffer), /* length of data to encrypt */
838 &ctr) /* previously initialized CTR state */
839 ) != CRYPT_OK) {
840 printf("ctr_encrypt error: %s\n", error_to_string(err));
771 return -1; 841 return -1;
772 } 842 }
773 843
774 /* make use of ciphertext... */ 844 /* make use of ciphertext... */
845
846 /* now we want to decrypt so let's use ctr_setiv */
847 if ((err = ctr_setiv( IV, /* the initial IV we gave to ctr_start */
848 16, /* the IV is 16 bytes long */
849 &ctr) /* the ctr state we wish to modify */
850 ) != CRYPT_OK) {
851 printf("ctr_setiv error: %s\n", error_to_string(err));
852 return -1;
853 }
854
855 if ((err = ctr_decrypt( buffer, /* ciphertext */
856 buffer, /* plaintext */
857 sizeof(buffer), /* length of data to encrypt */
858 &ctr) /* previously initialized CTR state */
859 ) != CRYPT_OK) {
860 printf("ctr_decrypt error: %s\n", error_to_string(err));
861 return -1;
862 }
775 863
776 /* clear up and return */ 864 /* clear up and return */
777 zeromem(key, sizeof(key)); 865 zeromem(key, sizeof(key));
778 zeromem(&ctr, sizeof(ctr)); 866 zeromem(&ctr, sizeof(ctr));
779 867
785 \section{Encrypt and Authenticate Modes} 873 \section{Encrypt and Authenticate Modes}
786 874
787 \subsection{EAX Mode} 875 \subsection{EAX Mode}
788 LibTomCrypt provides support for a mode called EAX\footnote{See 876 LibTomCrypt provides support for a mode called EAX\footnote{See
789 M. Bellare, P. Rogaway, D. Wagner, A Conventional Authenticated-Encryption Mode.} in a manner similar to the 877 M. Bellare, P. Rogaway, D. Wagner, A Conventional Authenticated-Encryption Mode.} in a manner similar to the
790 way it was intended to be used. 878 way it was intended to be used by the designers. First a short description of what EAX mode is before I explain how to use it.
791 879 EAX is a mode that requires a cipher, CTR and OMAC support and provides encryption and authentication\footnote{Note that since EAX only requires OMAC and CTR you may use ``encrypt only'' cipher descriptors with this mode.}.
792 First a short description of what EAX mode is before I explain how to use it. EAX is a mode that requires a cipher, 880 It is initialized with a random ``nonce'' that can be shared publicly as well as a ``header'' which can be fixed and public as well as a random
793 CTR and OMAC support and provides encryption and authentication. It is initialized with a random ``nonce'' that can 881 secret symmetric key.
794 be shared publicly as well as a ``header'' which can be fixed and public as well as a random secret symmetric key.
795 882
796 The ``header'' data is meant to be meta-data associated with a stream that isn't private (e.g. protocol messages). It can 883 The ``header'' data is meant to be meta-data associated with a stream that isn't private (e.g. protocol messages). It can
797 be added at anytime during an EAX stream and is part of the authentication tag. That is, changes in the meta-data can 884 be added at anytime during an EAX stream and is part of the authentication tag. That is, changes in the meta-data can
798 be detected by an invalid output tag. 885 be detected by changes in the output tag.
799 886
800 The mode can then process plaintext producing ciphertext as well as compute a partial checksum. The actual checksum 887 The mode can then process plaintext producing ciphertext as well as compute a partial checksum. The actual checksum
801 called a ``tag'' is only emitted when the message is finished. In the interim though the user can process any arbitrary 888 called a ``tag'' is only emitted when the message is finished. In the interim though the user can process any arbitrary
802 sized message block to send to the recipient as ciphertext. This makes the EAX mode especially suited for streaming modes 889 sized message block to send to the recipient as ciphertext. This makes the EAX mode especially suited for streaming modes
803 of operation. 890 of operation.
804 891
805 The mode is initialized with the following function. 892 The mode is initialized with the following function.
893 \index{eax\_init()}
806 \begin{verbatim} 894 \begin{verbatim}
807 int eax_init(eax_state *eax, int cipher, 895 int eax_init(eax_state *eax, int cipher,
808 const unsigned char *key, unsigned long keylen, 896 const unsigned char *key, unsigned long keylen,
809 const unsigned char *nonce, unsigned long noncelen, 897 const unsigned char *nonce, unsigned long noncelen,
810 const unsigned char *header, unsigned long headerlen); 898 const unsigned char *header, unsigned long headerlen);
814 ``key'' is the shared secret symmetric key of length ``keylen''. ``nonce'' is the random public string of 902 ``key'' is the shared secret symmetric key of length ``keylen''. ``nonce'' is the random public string of
815 length ``noncelen''. ``header'' is the random (or fixed or \textbf{NULL}) header for the message of length 903 length ``noncelen''. ``header'' is the random (or fixed or \textbf{NULL}) header for the message of length
816 ``headerlen''. 904 ``headerlen''.
817 905
818 When this function completes ``eax'' will be initialized such that you can now either have data decrypted or 906 When this function completes ``eax'' will be initialized such that you can now either have data decrypted or
819 encrypted in EAX mode. Note that if ``headerlen'' is zero you may pass ``header'' as \textbf{NULL}. It will still 907 encrypted in EAX mode. Note that if ``headerlen'' is zero you may pass ``header'' as \textbf{NULL} to indicate
820 initialize the EAX ``H'' value to the correct value. 908 there is no initial header data.
821 909
822 To encrypt or decrypt data in a streaming mode use the following. 910 To encrypt or decrypt data in a streaming mode use the following.
911 \index{eax\_encrypt()} \index{eax\_decrypt()}
823 \begin{verbatim} 912 \begin{verbatim}
824 int eax_encrypt(eax_state *eax, const unsigned char *pt, 913 int eax_encrypt(eax_state *eax, const unsigned char *pt,
825 unsigned char *ct, unsigned long length); 914 unsigned char *ct, unsigned long length);
826 915
827 int eax_decrypt(eax_state *eax, const unsigned char *ct, 916 int eax_decrypt(eax_state *eax, const unsigned char *ct,
830 The function ``eax\_encrypt'' will encrypt the bytes in ``pt'' of ``length'' bytes and store the ciphertext in 919 The function ``eax\_encrypt'' will encrypt the bytes in ``pt'' of ``length'' bytes and store the ciphertext in
831 ``ct''. Note that ``ct'' and ``pt'' may be the same region in memory. This function will also send the ciphertext 920 ``ct''. Note that ``ct'' and ``pt'' may be the same region in memory. This function will also send the ciphertext
832 through the OMAC function. The function ``eax\_decrypt'' decrypts ``ct'' and stores it in ``pt''. This also allows 921 through the OMAC function. The function ``eax\_decrypt'' decrypts ``ct'' and stores it in ``pt''. This also allows
833 ``pt'' and ``ct'' to be the same region in memory. 922 ``pt'' and ``ct'' to be the same region in memory.
834 923
924 You cannot both encrypt or decrypt with the same ``eax'' context. For bi-directional communication you
925 will need to initialize two EAX contexts (preferably with different headers and nonces).
926
835 Note that both of these functions allow you to send the data in any granularity but the order is important. While 927 Note that both of these functions allow you to send the data in any granularity but the order is important. While
836 the eax\_init() function allows you to add initial header data to the stream you can also add header data during the 928 the eax\_init() function allows you to add initial header data to the stream you can also add header data during the
837 EAX stream with the following. 929 EAX stream with the following.
838 930
839 Also note that you cannot both encrypt or decrypt with the same ``eax'' context. For bi-directional communication you 931 \index{eax\_addheader()}
840 will need to initialize two EAX contexts (preferably with different headers and nonces).
841
842 \begin{verbatim} 932 \begin{verbatim}
843 int eax_addheader(eax_state *eax, 933 int eax_addheader(eax_state *eax,
844 const unsigned char *header, unsigned long length); 934 const unsigned char *header, unsigned long length);
845 \end{verbatim} 935 \end{verbatim}
846 936
847 This will add the ``length'' bytes from ``header'' to the given ``eax'' stream. Once the message is finished the 937 This will add the ``length'' bytes from ``header'' to the given ``eax'' stream. Once the message is finished the
848 ``tag'' (checksum) may be computed with the following function. 938 ``tag'' (checksum) may be computed with the following function.
849 939
940 \index{eax\_done()}
850 \begin{verbatim} 941 \begin{verbatim}
851 int eax_done(eax_state *eax, 942 int eax_done(eax_state *eax,
852 unsigned char *tag, unsigned long *taglen); 943 unsigned char *tag, unsigned long *taglen);
853 \end{verbatim} 944 \end{verbatim}
854 This will terminate the EAX state ``eax'' and store upto ``taglen'' bytes of the message tag in ``tag''. The function 945 This will terminate the EAX state ``eax'' and store upto ``taglen'' bytes of the message tag in ``tag''. The function
855 then stores how many bytes of the tag were written out back into ``taglen''. 946 then stores how many bytes of the tag were written out back into ``taglen''.
856 947
857 The EAX mode code can be tested to ensure it matches the test vectors by calling the following function. 948 The EAX mode code can be tested to ensure it matches the test vectors by calling the following function.
949 \index{eax\_test()}
858 \begin{verbatim} 950 \begin{verbatim}
859 int eax_test(void); 951 int eax_test(void);
860 \end{verbatim} 952 \end{verbatim}
861 This requires that the AES (or Rijndael) block cipher be registered with the cipher\_descriptor table first. 953 This requires that the AES (or Rijndael) block cipher be registered with the cipher\_descriptor table first.
954
955 \begin{verbatim}
956 #include <mycrypt.h>
957 int main(void)
958 {
959 int err;
960 eax_state eax;
961 unsigned char pt[64], ct[64], nonce[16], key[16], tag[16];
962 unsigned long taglen;
963
964 if (register_cipher(&rijndael_desc) == -1) {
965 printf("Error registering Rijndael");
966 return EXIT_FAILURE;
967 }
968
969 /* ... make up random nonce and key ... */
970
971 /* initialize context */
972 if ((err = eax_init( &eax, /* the context */
973 find_cipher("rijndael"), /* cipher we want to use */
974 nonce, /* our state nonce */
975 16, /* none is 16 bytes */
976 "TestApp", /* example header, identifies this program */
977 7) /* length of the header */
978 ) != CRYPT_OK) {
979 printf("Error eax_init: %s", error_to_string(err));
980 return EXIT_FAILURE;
981 }
982
983 /* now encrypt data, say in a loop or whatever */
984 if ((err = eax_encrypt( &eax, /* eax context */
985 pt, /* plaintext (source) */
986 ct, /* ciphertext (destination) */
987 sizeof(pt) /* size of plaintext */
988 ) != CRYPT_OK) {
989 printf("Error eax_encrypt: %s", error_to_string(err));
990 return EXIT_FAILURE;
991 }
992
993 /* finish message and get authentication tag */
994 taglen = sizeof(tag);
995 if ((err = eax_done( &eax, /* eax context */
996 tag, /* where to put tag */
997 &taglen /* length of tag space */
998 ) != CRYPT_OK) {
999 printf("Error eax_done: %s", error_to_string(err));
1000 return EXIT_FAILURE;
1001 }
1002
1003 /* now we have the authentication tag in "tag" and it's taglen bytes long */
1004
1005 }
1006 \end{verbatim}
1007
1008 You can also perform an entire EAX state on a block of memory in a single function call with the
1009 following functions.
1010
1011
1012 \index{eax\_encrypt\_authenticate\_memory} \index{eax\_decrypt\_verify\_memory}
1013 \begin{verbatim}
1014 int eax_encrypt_authenticate_memory(int cipher,
1015 const unsigned char *key, unsigned long keylen,
1016 const unsigned char *nonce, unsigned long noncelen,
1017 const unsigned char *header, unsigned long headerlen,
1018 const unsigned char *pt, unsigned long ptlen,
1019 unsigned char *ct,
1020 unsigned char *tag, unsigned long *taglen);
1021
1022 int eax_decrypt_verify_memory(int cipher,
1023 const unsigned char *key, unsigned long keylen,
1024 const unsigned char *nonce, unsigned long noncelen,
1025 const unsigned char *header, unsigned long headerlen,
1026 const unsigned char *ct, unsigned long ctlen,
1027 unsigned char *pt,
1028 unsigned char *tag, unsigned long taglen,
1029 int *res);
1030 \end{verbatim}
1031
1032 Both essentially just call eax\_init() followed by eax\_encrypt() (or eax\_decrypt() respectively) and eax\_done(). The parameters
1033 have the same meaning as with those respective functions.
1034
1035 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
1036 the tag it computed while decrypting the message. If the tags match then it stores a $1$ in ``res'', otherwise it stores a $0$.
862 1037
863 \subsection{OCB Mode} 1038 \subsection{OCB Mode}
864 LibTomCrypt provides support for a mode called OCB\footnote{See 1039 LibTomCrypt provides support for a mode called OCB\footnote{See
865 P. Rogaway, M. Bellare, J. Black, T. Krovetz, ``OCB: A Block Cipher Mode of Operation for Efficient Authenticated Encryption''.} 1040 P. Rogaway, M. Bellare, J. Black, T. Krovetz, ``OCB: A Block Cipher Mode of Operation for Efficient Authenticated Encryption''.}
866 in a mode somewhat similar to as it was meant to be used. 1041 . OCB is an encryption protocol that simultaneously provides authentication. It is slightly faster to use than EAX mode
867
868 OCB is an encryption protocol that simultaneously provides authentication. It is slightly faster to use than EAX mode
869 but is less flexible. Let's review how to initialize an OCB context. 1042 but is less flexible. Let's review how to initialize an OCB context.
870 1043
1044 \index{ocb\_init()}
871 \begin{verbatim} 1045 \begin{verbatim}
872 int ocb_init(ocb_state *ocb, int cipher, 1046 int ocb_init(ocb_state *ocb, int cipher,
873 const unsigned char *key, unsigned long keylen, 1047 const unsigned char *key, unsigned long keylen,
874 const unsigned char *nonce); 1048 const unsigned char *nonce);
875 \end{verbatim} 1049 \end{verbatim}
876 1050
877 This will initialize the ``ocb'' context using cipher descriptor ``cipher''. It will use a ``key'' of length ``keylen'' 1051 This will initialize the ``ocb'' context using cipher descriptor ``cipher''. It will use a ``key'' of length ``keylen''
878 and the random ``nonce''. Note that ``nonce'' must be a random (public) string the same length as the block ciphers 1052 and the random ``nonce''. Note that ``nonce'' must be a random (public) string the same length as the block ciphers
879 block size (e.g. 16 for AES). 1053 block size (e.g. 16 bytes for AES).
880 1054
881 This mode has no ``Associated Data'' like EAX mode does which means you cannot authenticate metadata along with the stream. 1055 This mode has no ``Associated Data'' like EAX mode does which means you cannot authenticate metadata along with the stream.
882 To encrypt or decrypt data use the following. 1056 To encrypt or decrypt data use the following.
883 1057
1058 \index{ocb\_encrypt()} \index{ocb\_decrypt()}
884 \begin{verbatim} 1059 \begin{verbatim}
885 int ocb_encrypt(ocb_state *ocb, const unsigned char *pt, unsigned char *ct); 1060 int ocb_encrypt(ocb_state *ocb, const unsigned char *pt, unsigned char *ct);
886 int ocb_decrypt(ocb_state *ocb, const unsigned char *ct, unsigned char *pt); 1061 int ocb_decrypt(ocb_state *ocb, const unsigned char *ct, unsigned char *pt);
887 \end{verbatim} 1062 \end{verbatim}
888 1063
891 both functions given a single ``ocb'' state. For bi-directional communication you will have to initialize two ``ocb'' 1066 both functions given a single ``ocb'' state. For bi-directional communication you will have to initialize two ``ocb''
892 states (with different nonces). Also ``pt'' and ``ct'' may point to the same location in memory. 1067 states (with different nonces). Also ``pt'' and ``ct'' may point to the same location in memory.
893 1068
894 When you are finished encrypting the message you call the following function to compute the tag. 1069 When you are finished encrypting the message you call the following function to compute the tag.
895 1070
1071 \index{ocb\_done\_encrypt()}
896 \begin{verbatim} 1072 \begin{verbatim}
897 int ocb_done_encrypt(ocb_state *ocb, 1073 int ocb_done_encrypt(ocb_state *ocb,
898 const unsigned char *pt, unsigned long ptlen, 1074 const unsigned char *pt, unsigned long ptlen,
899 unsigned char *ct, 1075 unsigned char *ct,
900 unsigned char *tag, unsigned long *taglen); 1076 unsigned char *tag, unsigned long *taglen);
907 Note that ``ptlen'' must be less than or equal to the block size of block cipher chosen. Also note that if you have 1083 Note that ``ptlen'' must be less than or equal to the block size of block cipher chosen. Also note that if you have
908 an input message equal to the length of the block size then you pass the data here (not to ocb\_encrypt()) only. 1084 an input message equal to the length of the block size then you pass the data here (not to ocb\_encrypt()) only.
909 1085
910 To terminate a decrypt stream and compared the tag you call the following. 1086 To terminate a decrypt stream and compared the tag you call the following.
911 1087
1088 \index{ocb\_done\_decrypt()}
912 \begin{verbatim} 1089 \begin{verbatim}
913 int ocb_done_decrypt(ocb_state *ocb, 1090 int ocb_done_decrypt(ocb_state *ocb,
914 const unsigned char *ct, unsigned long ctlen, 1091 const unsigned char *ct, unsigned long ctlen,
915 unsigned char *pt, 1092 unsigned char *pt,
916 const unsigned char *tag, unsigned long taglen, 1093 const unsigned char *tag, unsigned long taglen,
922 ``res'' is set to zero. If all ``taglen'' bytes of ``tag'' can be verified then ``res'' is set to one (authenticated 1099 ``res'' is set to zero. If all ``taglen'' bytes of ``tag'' can be verified then ``res'' is set to one (authenticated
923 message). 1100 message).
924 1101
925 To make life simpler the following two functions are provided for memory bound OCB. 1102 To make life simpler the following two functions are provided for memory bound OCB.
926 1103
1104 \index{ocb\_encrypt\_authenticate\_memory()}
927 \begin{verbatim} 1105 \begin{verbatim}
928 int ocb_encrypt_authenticate_memory(int cipher, 1106 int ocb_encrypt_authenticate_memory(int cipher,
929 const unsigned char *key, unsigned long keylen, 1107 const unsigned char *key, unsigned long keylen,
930 const unsigned char *nonce, 1108 const unsigned char *nonce,
931 const unsigned char *pt, unsigned long ptlen, 1109 const unsigned char *pt, unsigned long ptlen,
934 \end{verbatim} 1112 \end{verbatim}
935 1113
936 This will OCB encrypt the message ``pt'' of length ``ptlen'' and store the ciphertext in ``ct''. The length ``ptlen'' 1114 This will OCB encrypt the message ``pt'' of length ``ptlen'' and store the ciphertext in ``ct''. The length ``ptlen''
937 can be any arbitrary length. 1115 can be any arbitrary length.
938 1116
1117 \index{ocb\_decrypt\_verify\_memory()}
939 \begin{verbatim} 1118 \begin{verbatim}
940 int ocb_decrypt_verify_memory(int cipher, 1119 int ocb_decrypt_verify_memory(int cipher,
941 const unsigned char *key, unsigned long keylen, 1120 const unsigned char *key, unsigned long keylen,
942 const unsigned char *nonce, 1121 const unsigned char *nonce,
943 const unsigned char *ct, unsigned long ctlen, 1122 const unsigned char *ct, unsigned long ctlen,
947 \end{verbatim} 1126 \end{verbatim}
948 1127
949 Similarly this will OCB decrypt and compare the internally computed tag against the tag provided. ``res'' is set 1128 Similarly this will OCB decrypt and compare the internally computed tag against the tag provided. ``res'' is set
950 appropriately. 1129 appropriately.
951 1130
952
953
954 \chapter{One-Way Cryptographic Hash Functions} 1131 \chapter{One-Way Cryptographic Hash Functions}
955 \section{Core Functions} 1132 \section{Core Functions}
956 1133
957 Like the ciphers there are hash core functions and a universal data type to hold the hash state called ``hash\_state''. 1134 Like the ciphers there are hash core functions and a universal data type to hold the hash state called ``hash\_state''.
958 To initialize hash XXX (where XXX is the name) call: 1135 To initialize hash XXX (where XXX is the name) call:
1018 } 1195 }
1019 \end{verbatim} 1196 \end{verbatim}
1020 \end{small} 1197 \end{small}
1021 1198
1022 \section{Hash Descriptors} 1199 \section{Hash Descriptors}
1023 \index{Hash Descriptors}
1024 Like the set of ciphers the set of hashes have descriptors too. They are stored in an array called ``hash\_descriptor'' and 1200 Like the set of ciphers the set of hashes have descriptors too. They are stored in an array called ``hash\_descriptor'' and
1025 are defined by: 1201 are defined by:
1026 \begin{verbatim} 1202 \begin{verbatim}
1027 struct _hash_descriptor { 1203 struct _hash_descriptor {
1028 char *name; 1204 char *name;
1114 \begin{small} 1290 \begin{small}
1115 \begin{verbatim} 1291 \begin{verbatim}
1116 #include <mycrypt.h> 1292 #include <mycrypt.h>
1117 int main(void) 1293 int main(void)
1118 { 1294 {
1119 int idx, errno; 1295 int idx, err;
1120 unsigned long len; 1296 unsigned long len;
1121 unsigned char out[MAXBLOCKSIZE]; 1297 unsigned char out[MAXBLOCKSIZE];
1122 1298
1123 /* register the hash */ 1299 /* register the hash */
1124 if (register_hash(&md5_desc) == -1) { 1300 if (register_hash(&md5_desc) == -1) {
1129 /* get the index of the hash */ 1305 /* get the index of the hash */
1130 idx = find_hash("md5"); 1306 idx = find_hash("md5");
1131 1307
1132 /* call the hash */ 1308 /* call the hash */
1133 len = sizeof(out); 1309 len = sizeof(out);
1134 if ((errno = hash_memory(idx, "hello world", 11, out, &len)) != CRYPT_OK) { 1310 if ((err = hash_memory(idx, "hello world", 11, out, &len)) != CRYPT_OK) {
1135 printf("Error hashing data: %s\n", error_to_string(errno)); 1311 printf("Error hashing data: %s\n", error_to_string(err));
1136 return -1; 1312 return -1;
1137 } 1313 }
1138 return 0; 1314 return 0;
1139 } 1315 }
1140 \end{verbatim} 1316 \end{verbatim}
1141 \end{small} 1317 \end{small}
1142 1318
1143 The following hashes are provided as of this release: 1319 The following hashes are provided as of this release:
1320 \index{Hash descriptor table}
1144 \begin{center} 1321 \begin{center}
1145 \begin{tabular}{|c|c|c|} 1322 \begin{tabular}{|c|c|c|}
1146 \hline Name & Descriptor Name & Size of Message Digest (bytes) \\ 1323 \hline Name & Descriptor Name & Size of Message Digest (bytes) \\
1147 \hline WHIRLPOOL & whirlpool\_desc & 64 \\ 1324 \hline WHIRLPOOL & whirlpool\_desc & 64 \\
1148 \hline SHA-512 & sha512\_desc & 64 \\ 1325 \hline SHA-512 & sha512\_desc & 64 \\
1160 \end{tabular} 1337 \end{tabular}
1161 \end{center} 1338 \end{center}
1162 1339
1163 Similar to the cipher descriptor table you must register your hash algorithms before you can use them. These functions 1340 Similar to the cipher descriptor table you must register your hash algorithms before you can use them. These functions
1164 work exactly like those of the cipher registration code. The functions are: 1341 work exactly like those of the cipher registration code. The functions are:
1342 \index{register\_hash()} \index{unregister\_hash()}
1165 \begin{verbatim} 1343 \begin{verbatim}
1166 int register_hash(const struct _hash_descriptor *hash); 1344 int register_hash(const struct _hash_descriptor *hash);
1167 int unregister_hash(const struct _hash_descriptor *hash); 1345 int unregister_hash(const struct _hash_descriptor *hash);
1168 \end{verbatim} 1346 \end{verbatim}
1169 1347
1183 eavesdropper will not be able to verify the authenticity of a message. 1361 eavesdropper will not be able to verify the authenticity of a message.
1184 1362
1185 The HMAC support works much like the normal hash functions except that the initialization routine requires you to pass a key 1363 The HMAC support works much like the normal hash functions except that the initialization routine requires you to pass a key
1186 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 1364 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
1187 chars. The initialization routine is: 1365 chars. The initialization routine is:
1366 \index{hmac\_init()}
1188 \begin{verbatim} 1367 \begin{verbatim}
1189 int hmac_init(hmac_state *hmac, int hash, 1368 int hmac_init(hmac_state *hmac, int hash,
1190 const unsigned char *key, unsigned long keylen); 1369 const unsigned char *key, unsigned long keylen);
1191 \end{verbatim} 1370 \end{verbatim}
1192 The ``hmac'' parameter is the state for the HMAC code. ``hash'' is the index into the descriptor table of the hash you want 1371 The ``hmac'' parameter is the state for the HMAC code. ``hash'' is the index into the descriptor table of the hash you want
1193 to use to authenticate the message. ``key'' is the pointer to the array of chars that make up the key. ``keylen'' is the 1372 to use to authenticate the message. ``key'' is the pointer to the array of chars that make up the key. ``keylen'' is the
1194 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: 1373 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:
1374 \index{hmac\_process()}
1195 \begin{verbatim} 1375 \begin{verbatim}
1196 int hmac_process(hmac_state *hmac, const unsigned char *buf, 1376 int hmac_process(hmac_state *hmac, const unsigned char *buf,
1197 unsigned long len); 1377 unsigned long len);
1198 \end{verbatim} 1378 \end{verbatim}
1199 ``hmac'' is the HMAC state you are working with. ``buf'' is the array of octets to send into the HMAC process. ``len'' is the 1379 ``hmac'' is the HMAC state you are working with. ``buf'' is the array of octets to send into the HMAC process. ``len'' is the
1200 number of octets to process. Like the hash process routines you can send the data in arbitrarly sized chunks. When you 1380 number of octets to process. Like the hash process routines you can send the data in arbitrarly sized chunks. When you
1201 are finished with the HMAC process you must call the following function to get the HMAC code: 1381 are finished with the HMAC process you must call the following function to get the HMAC code:
1382 \index{hmac\_done()}
1202 \begin{verbatim} 1383 \begin{verbatim}
1203 int hmac_done(hmac_state *hmac, unsigned char *hashOut, 1384 int hmac_done(hmac_state *hmac, unsigned char *hashOut,
1204 unsigned long *outlen); 1385 unsigned long *outlen);
1205 \end{verbatim} 1386 \end{verbatim}
1206 ``hmac'' is the HMAC state you are working with. ``hashOut'' is the array of octets where the HMAC code should be stored. You must 1387 ``hmac'' is the HMAC state you are working with. ``hashOut'' is the array of octets where the HMAC code should be stored. You must
1210 1391
1211 There are two utility functions provided to make using HMACs easier todo. They accept the key and information about the 1392 There are two utility functions provided to make using HMACs easier todo. They accept the key and information about the
1212 message (file pointer, address in memory) and produce the HMAC result in one shot. These are useful if you want to avoid 1393 message (file pointer, address in memory) and produce the HMAC result in one shot. These are useful if you want to avoid
1213 calling the three step process yourself. 1394 calling the three step process yourself.
1214 1395
1396 \index{hmac\_memory()}
1215 \begin{verbatim} 1397 \begin{verbatim}
1216 int hmac_memory(int hash, const unsigned char *key, unsigned long keylen, 1398 int hmac_memory(int hash, const unsigned char *key, unsigned long keylen,
1217 const unsigned char *data, unsigned long len, 1399 const unsigned char *data, unsigned long len,
1218 unsigned char *dst, unsigned long *dstlen); 1400 unsigned char *dst, unsigned long *dstlen);
1219 \end{verbatim} 1401 \end{verbatim}
1220 This will produce an HMAC code for the array of octets in ``data'' of length ``len''. The index into the hash descriptor 1402 This will produce an HMAC code for the array of octets in ``data'' of length ``len''. The index into the hash descriptor
1221 table must be provided in ``hash''. It uses the key from ``key'' with a key length of ``keylen''. 1403 table must be provided in ``hash''. It uses the key from ``key'' with a key length of ``keylen''.
1222 The result is stored in the array of octets ``dst'' and the length in ``dstlen''. The value of ``dstlen'' must be set 1404 The result is stored in the array of octets ``dst'' and the length in ``dstlen''. The value of ``dstlen'' must be set
1223 to the size of the destination buffer before calling this function. Similarly for files there is the following function: 1405 to the size of the destination buffer before calling this function. Similarly for files there is the following function:
1406 \index{hmac\_file()}
1224 \begin{verbatim} 1407 \begin{verbatim}
1225 int hmac_file(int hash, const char *fname, const unsigned char *key, 1408 int hmac_file(int hash, const char *fname, const unsigned char *key,
1226 unsigned long keylen, 1409 unsigned long keylen,
1227 unsigned char *dst, unsigned long *dstlen); 1410 unsigned char *dst, unsigned long *dstlen);
1228 \end{verbatim} 1411 \end{verbatim}
1229 ``hash'' is the index into the hash descriptor table of the hash you want to use. ``fname'' is the filename to process. 1412 ``hash'' is the index into the hash descriptor table of the hash you want to use. ``fname'' is the filename to process.
1230 ``key'' is the array of octets to use as the key of length ``keylen''. ``dst'' is the array of octets where the 1413 ``key'' is the array of octets to use as the key of length ``keylen''. ``dst'' is the array of octets where the
1231 result should be stored. 1414 result should be stored.
1232 1415
1233 To test if the HMAC code is working there is the following function: 1416 To test if the HMAC code is working there is the following function:
1417 \index{hmac\_test()}
1234 \begin{verbatim} 1418 \begin{verbatim}
1235 int hmac_test(void); 1419 int hmac_test(void);
1236 \end{verbatim} 1420 \end{verbatim}
1237 Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code. Some example code for using the 1421 Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code. Some example code for using the
1238 HMAC system is given below. 1422 HMAC system is given below.
1240 \begin{small} 1424 \begin{small}
1241 \begin{verbatim} 1425 \begin{verbatim}
1242 #include <mycrypt.h> 1426 #include <mycrypt.h>
1243 int main(void) 1427 int main(void)
1244 { 1428 {
1245 int idx, errno; 1429 int idx, err;
1246 hmac_state hmac; 1430 hmac_state hmac;
1247 unsigned char key[16], dst[MAXBLOCKSIZE]; 1431 unsigned char key[16], dst[MAXBLOCKSIZE];
1248 unsigned long dstlen; 1432 unsigned long dstlen;
1249 1433
1250 /* register SHA-1 */ 1434 /* register SHA-1 */
1257 idx = find_hash("sha1"); 1441 idx = find_hash("sha1");
1258 1442
1259 /* we would make up our symmetric key in "key[]" here */ 1443 /* we would make up our symmetric key in "key[]" here */
1260 1444
1261 /* start the HMAC */ 1445 /* start the HMAC */
1262 if ((errno = hmac_init(&hmac, idx, key, 16)) != CRYPT_OK) { 1446 if ((err = hmac_init(&hmac, idx, key, 16)) != CRYPT_OK) {
1263 printf("Error setting up hmac: %s\n", error_to_string(errno)); 1447 printf("Error setting up hmac: %s\n", error_to_string(err));
1264 return -1; 1448 return -1;
1265 } 1449 }
1266 1450
1267 /* process a few octets */ 1451 /* process a few octets */
1268 if((errno = hmac_process(&hmac, "hello", 5) != CRYPT_OK) { 1452 if((err = hmac_process(&hmac, "hello", 5) != CRYPT_OK) {
1269 printf("Error processing hmac: %s\n", error_to_string(errno)); 1453 printf("Error processing hmac: %s\n", error_to_string(err));
1270 return -1; 1454 return -1;
1271 } 1455 }
1272 1456
1273 /* get result (presumably to use it somehow...) */ 1457 /* get result (presumably to use it somehow...) */
1274 dstlen = sizeof(dst); 1458 dstlen = sizeof(dst);
1275 if ((errno = hmac_done(&hmac, dst, &dstlen)) != CRYPT_OK) { 1459 if ((err = hmac_done(&hmac, dst, &dstlen)) != CRYPT_OK) {
1276 printf("Error finishing hmac: %s\n", error_to_string(errno)); 1460 printf("Error finishing hmac: %s\n", error_to_string(err));
1277 return -1; 1461 return -1;
1278 } 1462 }
1279 printf("The hmac is %lu bytes long\n", dstlen); 1463 printf("The hmac is %lu bytes long\n", dstlen);
1280 1464
1281 /* return */ 1465 /* return */
1288 OMAC\footnote{\url{http://crypt.cis.ibaraki.ac.jp/omac/omac.html}}, which stands for \textit{One-Key CBC MAC} is an 1472 OMAC\footnote{\url{http://crypt.cis.ibaraki.ac.jp/omac/omac.html}}, which stands for \textit{One-Key CBC MAC} is an
1289 algorithm which produces a Message Authentication Code (MAC) using only a block cipher such as AES. From an API 1473 algorithm which produces a Message Authentication Code (MAC) using only a block cipher such as AES. From an API
1290 standpoint the OMAC routines work much like the HMAC routines do. Instead in this case a cipher is used instead of a hash. 1474 standpoint the OMAC routines work much like the HMAC routines do. Instead in this case a cipher is used instead of a hash.
1291 1475
1292 To start an OMAC state you call 1476 To start an OMAC state you call
1293 1477 \index{omac\_init()}
1294 \begin{verbatim} 1478 \begin{verbatim}
1295 int omac_init(omac_state *omac, int cipher, 1479 int omac_init(omac_state *omac, int cipher,
1296 const unsigned char *key, unsigned long keylen); 1480 const unsigned char *key, unsigned long keylen);
1297 \end{verbatim} 1481 \end{verbatim}
1298 The ``omac'' variable is the state for the OMAC algorithm. ``cipher'' is the index into the cipher\_descriptor table 1482 The ``omac'' variable is the state for the OMAC algorithm. ``cipher'' is the index into the cipher\_descriptor table
1299 of the cipher\footnote{The cipher must have a 64 or 128 bit block size. Such as CAST5, Blowfish, DES, AES, Twofish, etc.} you 1483 of the cipher\footnote{The cipher must have a 64 or 128 bit block size. Such as CAST5, Blowfish, DES, AES, Twofish, etc.} you
1300 wish to use. ``key'' and ``keylen'' are the keys used to authenticate the data. 1484 wish to use. ``key'' and ``keylen'' are the keys used to authenticate the data.
1301 1485
1302 To send data through the algorithm call 1486 To send data through the algorithm call
1487 \index{omac\_process()}
1303 \begin{verbatim} 1488 \begin{verbatim}
1304 int omac_process(omac_state *state, 1489 int omac_process(omac_state *state,
1305 const unsigned char *buf, unsigned long len); 1490 const unsigned char *buf, unsigned long len);
1306 \end{verbatim} 1491 \end{verbatim}
1307 This will send ``len'' bytes from ``buf'' through the active OMAC state ``state''. Returns \textbf{CRYPT\_OK} if the 1492 This will send ``len'' bytes from ``buf'' through the active OMAC state ``state''. Returns \textbf{CRYPT\_OK} if the
1318 omac_process(&mystate, "hello world", 11); 1503 omac_process(&mystate, "hello world", 11);
1319 \end{verbatim} 1504 \end{verbatim}
1320 1505
1321 When you are done processing the message you can call the following to compute the message tag. 1506 When you are done processing the message you can call the following to compute the message tag.
1322 1507
1508 \index{omac\_done()}
1323 \begin{verbatim} 1509 \begin{verbatim}
1324 int omac_done(omac_state *state, 1510 int omac_done(omac_state *state,
1325 unsigned char *out, unsigned long *outlen); 1511 unsigned char *out, unsigned long *outlen);
1326 \end{verbatim} 1512 \end{verbatim}
1327 Which will terminate the OMAC and output the \textit{tag} (MAC) to ``out''. Note that unlike the HMAC and other code 1513 Which will terminate the OMAC and output the \textit{tag} (MAC) to ``out''. Note that unlike the HMAC and other code
1331 size to show how many bytes were actually used. 1517 size to show how many bytes were actually used.
1332 1518
1333 Similar to the HMAC code the file and memory functions are also provided. To OMAC a buffer of memory in one shot use the 1519 Similar to the HMAC code the file and memory functions are also provided. To OMAC a buffer of memory in one shot use the
1334 following function. 1520 following function.
1335 1521
1522 \index{omac\_memory()}
1336 \begin{verbatim} 1523 \begin{verbatim}
1337 int omac_memory(int cipher, 1524 int omac_memory(int cipher,
1338 const unsigned char *key, unsigned long keylen, 1525 const unsigned char *key, unsigned long keylen,
1339 const unsigned char *msg, unsigned long msglen, 1526 const unsigned char *msg, unsigned long msglen,
1340 unsigned char *out, unsigned long *outlen); 1527 unsigned char *out, unsigned long *outlen);
1342 This will compute the OMAC of ``msglen'' bytes of ``msg'' using the key ``key'' of length ``keylen'' bytes and the cipher 1529 This will compute the OMAC of ``msglen'' bytes of ``msg'' using the key ``key'' of length ``keylen'' bytes and the cipher
1343 specified by the ``cipher'''th entry in the cipher\_descriptor table. It will store the MAC in ``out'' with the same 1530 specified by the ``cipher'''th entry in the cipher\_descriptor table. It will store the MAC in ``out'' with the same
1344 rules as omac\_done. 1531 rules as omac\_done.
1345 1532
1346 To OMAC a file use 1533 To OMAC a file use
1534 \index{omac\_file()}
1347 \begin{verbatim} 1535 \begin{verbatim}
1348 int omac_file(int cipher, 1536 int omac_file(int cipher,
1349 const unsigned char *key, unsigned long keylen, 1537 const unsigned char *key, unsigned long keylen,
1350 const char *filename, 1538 const char *filename,
1351 unsigned char *out, unsigned long *outlen); 1539 unsigned char *out, unsigned long *outlen);
1354 Which will OMAC the entire contents of the file specified by ``filename'' using the key ``key'' of length ``keylen'' bytes 1542 Which will OMAC the entire contents of the file specified by ``filename'' using the key ``key'' of length ``keylen'' bytes
1355 and the cipher specified by the ``cipher'''th entry in the cipher\_descriptor table. It will store the MAC in ``out'' with 1543 and the cipher specified by the ``cipher'''th entry in the cipher\_descriptor table. It will store the MAC in ``out'' with
1356 the same rules as omac\_done. 1544 the same rules as omac\_done.
1357 1545
1358 To test if the OMAC code is working there is the following function: 1546 To test if the OMAC code is working there is the following function:
1547 \index{omac\_test()}
1359 \begin{verbatim} 1548 \begin{verbatim}
1360 int omac_test(void); 1549 int omac_test(void);
1361 \end{verbatim} 1550 \end{verbatim}
1362 Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code. Some example code for using the 1551 Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code. Some example code for using the
1363 OMAC system is given below. 1552 OMAC system is given below.
1414 protocol is another MAC algorithm that relies solely on a symmetric-key block cipher. It uses essentially the same 1603 protocol is another MAC algorithm that relies solely on a symmetric-key block cipher. It uses essentially the same
1415 API as the provided OMAC code. 1604 API as the provided OMAC code.
1416 1605
1417 A PMAC state is initialized with the following. 1606 A PMAC state is initialized with the following.
1418 1607
1608 \index{pmac\_init()}
1419 \begin{verbatim} 1609 \begin{verbatim}
1420 int pmac_init(pmac_state *pmac, int cipher, 1610 int pmac_init(pmac_state *pmac, int cipher,
1421 const unsigned char *key, unsigned long keylen); 1611 const unsigned char *key, unsigned long keylen);
1422 \end{verbatim} 1612 \end{verbatim}
1423 Which initializes the ``pmac'' state with the given ``cipher'' and ``key'' of length ``keylen'' bytes. The chosen cipher 1613 Which initializes the ``pmac'' state with the given ``cipher'' and ``key'' of length ``keylen'' bytes. The chosen cipher
1424 must have a 64 or 128 bit block size (e.x. AES). 1614 must have a 64 or 128 bit block size (e.x. AES).
1425 1615
1426 To MAC data simply send it through the process function. 1616 To MAC data simply send it through the process function.
1427 1617
1618 \index{pmac\_process()}
1428 \begin{verbatim} 1619 \begin{verbatim}
1429 int pmac_process(pmac_state *state, 1620 int pmac_process(pmac_state *state,
1430 const unsigned char *buf, unsigned long len); 1621 const unsigned char *buf, unsigned long len);
1431 \end{verbatim} 1622 \end{verbatim}
1432 This will process ``len'' bytes of ``buf'' in the given ``state''. The function is not sensitive to the granularity of the 1623 This will process ``len'' bytes of ``buf'' in the given ``state''. The function is not sensitive to the granularity of the
1443 pmac_process(&mystate, "hello world", 11); 1634 pmac_process(&mystate, "hello world", 11);
1444 \end{verbatim} 1635 \end{verbatim}
1445 1636
1446 When a complete message has been processed the following function can be called to compute the message tag. 1637 When a complete message has been processed the following function can be called to compute the message tag.
1447 1638
1639 \index{pmac\_done()}
1448 \begin{verbatim} 1640 \begin{verbatim}
1449 int pmac_done(pmac_state *state, 1641 int pmac_done(pmac_state *state,
1450 unsigned char *out, unsigned long *outlen); 1642 unsigned char *out, unsigned long *outlen);
1451 \end{verbatim} 1643 \end{verbatim}
1452 This will store upto ``outlen'' bytes of the tag for the given ``state'' into ``out''. Note that if ``outlen'' is larger 1644 This will store upto ``outlen'' bytes of the tag for the given ``state'' into ``out''. Note that if ``outlen'' is larger
1453 than the size of the tag it is set to the amount of bytes stored in ``out''. 1645 than the size of the tag it is set to the amount of bytes stored in ``out''.
1454 1646
1455 Similar to the PMAC code the file and memory functions are also provided. To PMAC a buffer of memory in one shot use the 1647 Similar to the PMAC code the file and memory functions are also provided. To PMAC a buffer of memory in one shot use the
1456 following function. 1648 following function.
1457 1649
1650 \index{pmac\_memory()}
1458 \begin{verbatim} 1651 \begin{verbatim}
1459 int pmac_memory(int cipher, 1652 int pmac_memory(int cipher,
1460 const unsigned char *key, unsigned long keylen, 1653 const unsigned char *key, unsigned long keylen,
1461 const unsigned char *msg, unsigned long msglen, 1654 const unsigned char *msg, unsigned long msglen,
1462 unsigned char *out, unsigned long *outlen); 1655 unsigned char *out, unsigned long *outlen);
1464 This will compute the PMAC of ``msglen'' bytes of ``msg'' using the key ``key'' of length ``keylen'' bytes and the cipher 1657 This will compute the PMAC of ``msglen'' bytes of ``msg'' using the key ``key'' of length ``keylen'' bytes and the cipher
1465 specified by the ``cipher'''th entry in the cipher\_descriptor table. It will store the MAC in ``out'' with the same 1658 specified by the ``cipher'''th entry in the cipher\_descriptor table. It will store the MAC in ``out'' with the same
1466 rules as omac\_done. 1659 rules as omac\_done.
1467 1660
1468 To PMAC a file use 1661 To PMAC a file use
1662 \index{pmac\_file()}
1469 \begin{verbatim} 1663 \begin{verbatim}
1470 int pmac_file(int cipher, 1664 int pmac_file(int cipher,
1471 const unsigned char *key, unsigned long keylen, 1665 const unsigned char *key, unsigned long keylen,
1472 const char *filename, 1666 const char *filename,
1473 unsigned char *out, unsigned long *outlen); 1667 unsigned char *out, unsigned long *outlen);
1714 } 1908 }
1715 \end{verbatim} 1909 \end{verbatim}
1716 \end{small} 1910 \end{small}
1717 1911
1718 \chapter{RSA Public Key Cryptography} 1912 \chapter{RSA Public Key Cryptography}
1719 \textbf{Note: } \textit{This chapter on PKCS \#1 RSA will replace the older chapter on RSA (The current chapter nine) in subsequent 1913
1720 releases of the library. Users are encouraged to stop using the LibTomCrypt style padding functions.} 1914 \section{Introduction}
1915 RSA wrote the PKCS \#1 specifications which detail RSA Public Key Cryptography. In the specifications are
1916 padding algorithms for encryption and signatures. The standard includes ``v1.5'' and ``v2.0'' algorithms.
1917 To simplify matters a little the v2.0 encryption and signature padding algorithms are called OAEP and PSS
1918 respectively.
1721 1919
1722 \section{PKCS \#1 Encryption} 1920 \section{PKCS \#1 Encryption}
1723 1921
1724 PKCS \#1 RSA Encryption amounts to OAEP padding of the input message followed by the modular exponentiation. As far as this portion of 1922 PKCS \#1 RSA Encryption amounts to OAEP padding of the input message followed by the modular exponentiation. As far as this portion of
1725 the library is concerned we are only dealing with th OAEP padding of the message. 1923 the library is concerned we are only dealing with th OAEP padding of the message.
1726 1924
1727 \subsection{OAEP Encoding} 1925 \subsection{OAEP Encoding}
1728 1926
1927 \index{pkcs\_1\_oaep\_encode()}
1729 \begin{alltt} 1928 \begin{alltt}
1730 int pkcs_1_oaep_encode(const unsigned char *msg, unsigned long msglen, 1929 int pkcs_1_oaep_encode(const unsigned char *msg, unsigned long msglen,
1731 const unsigned char *lparam, unsigned long lparamlen, 1930 const unsigned char *lparam, unsigned long lparamlen,
1732 unsigned long modulus_bitlen, int hash_idx, 1931 unsigned long modulus_bitlen, prng_state *prng,
1733 int prng_idx, prng_state *prng, 1932 int prng_idx, int hash_idx,
1734 unsigned char *out, unsigned long *outlen); 1933 unsigned char *out, unsigned long *outlen);
1735 \end{alltt} 1934 \end{alltt}
1736 1935
1737 This accepts ``msg'' as input of length ``msglen'' which will be OAEP padded. The ``lparam'' variable is an additional system specific 1936 This accepts ``msg'' as input of length ``msglen'' which will be OAEP padded. The ``lparam'' variable is an additional system specific
1738 tag that can be applied to the encoding. This is useful to identify which system encoded the message. If no variance is desired then 1937 tag that can be applied to the encoding. This is useful to identify which system encoded the message. If no variance is desired then
1750 Note that when the message is padded it still has not been RSA encrypted. You must pass the output of this function to 1949 Note that when the message is padded it still has not been RSA encrypted. You must pass the output of this function to
1751 rsa\_exptmod() to encrypt it. 1950 rsa\_exptmod() to encrypt it.
1752 1951
1753 \subsection{OAEP Decoding} 1952 \subsection{OAEP Decoding}
1754 1953
1954 \index{pkcs\_1\_oaep\_decode()}
1755 \begin{alltt} 1955 \begin{alltt}
1756 int pkcs_1_oaep_decode(const unsigned char *msg, unsigned long msglen, 1956 int pkcs_1_oaep_decode(const unsigned char *msg, unsigned long msglen,
1757 const unsigned char *lparam, unsigned long lparamlen, 1957 const unsigned char *lparam, unsigned long lparamlen,
1758 unsigned long modulus_bitlen, int hash_idx, 1958 unsigned long modulus_bitlen, int hash_idx,
1759 unsigned char *out, unsigned long *outlen); 1959 unsigned char *out, unsigned long *outlen,
1960 int *res);
1760 \end{alltt} 1961 \end{alltt}
1761 1962
1762 This function decodes an OAEP encoded message and outputs the original message that was passed to the OAEP encoder. ``msg'' is the 1963 This function decodes an OAEP encoded message and outputs the original message that was passed to the OAEP encoder. ``msg'' is the
1763 output of pkcs\_1\_oaep\_encode() of length ``msglen''. ``lparam'' is the same system variable passed to the OAEP encoder. If it does not 1964 output of pkcs\_1\_oaep\_encode() of length ``msglen''. ``lparam'' is the same system variable passed to the OAEP encoder. If it does not
1764 match what was used during encoding this function will not decode the packet. ``modulus\_bitlen'' is the size of the RSA modulus in bits 1965 match what was used during encoding this function will not decode the packet. ``modulus\_bitlen'' is the size of the RSA modulus in bits
1765 and must match what was used during encoding. Similarly the ``hash\_idx'' index into the hash descriptor table must match what was used 1966 and must match what was used during encoding. Similarly the ``hash\_idx'' index into the hash descriptor table must match what was used
1766 during encoding. 1967 during encoding.
1767 1968
1768 If the function succeeds it decodes the OAEP encoded message into ``out'' of length ``outlen''. 1969 If the function succeeds it decodes the OAEP encoded message into ``out'' of length ``outlen'' and stores a
1970 $1$ in ``res''. If the packet is invalid it stores $0$ in ``res'' and if the function fails for another reason
1971 it returns an error code.
1972
1973 \subsection{PKCS \#1 v1.5 Encoding}
1974
1975 \index{pkcs\_1\_v15\_es\_encode()}
1976 \begin{verbatim}
1977 int pkcs_1_v15_es_encode(const unsigned char *msg, unsigned long msglen,
1978 unsigned long modulus_bitlen,
1979 prng_state *prng, int prng_idx,
1980 unsigned char *out, unsigned long *outlen);
1981 \end{verbatim}
1982
1983 This will PKCS v1.5 encode the data in ``msg'' of length ``msglen''. Pass the length (in bits) of your
1984 RSA modulus in ``modulus\_bitlen''. The encoded data will be stored in ``out'' of length ``outlen''.
1985
1986 \subsection{PKCS \#1 v1.5 Decoding}
1987 \index{pkcs\_1\_v15\_es\_decode()}
1988 \begin{verbatim}
1989 int pkcs_1_v15_es_decode(const unsigned char *msg, unsigned long msglen,
1990 unsigned long modulus_bitlen,
1991 unsigned char *out, unsigned long outlen,
1992 int *res);
1993 \end{verbatim}
1994
1995 This will PKCS v1.5 decode the message in ``msg'' of length ``msglen''. It will store the output in ``out''. Note
1996 that the length of the output ``outlen'' is a constant. This decoder cannot determine the original message
1997 length. If the data in ``msg'' is a valid packet then a $1$ is stored in ``res'', otherwise a $0$ is
1998 stored.
1769 1999
1770 \section{PKCS \#1 Digital Signatures} 2000 \section{PKCS \#1 Digital Signatures}
1771 2001
1772 \subsection{PSS Encoding} 2002 \subsection{PSS Encoding}
1773 PSS encoding is the second half of the PKCS \#1 standard which is padding to be applied to messages that are signed. 2003 PSS encoding is the second half of the PKCS \#1 standard which is padding to be applied to messages that are signed.
1774 2004
2005 \index{pkcs\_1\_pss\_encode()}
1775 \begin{alltt} 2006 \begin{alltt}
1776 int pkcs_1_pss_encode(const unsigned char *msghash, unsigned long msghashlen, 2007 int pkcs_1_pss_encode(const unsigned char *msghash, unsigned long msghashlen,
1777 unsigned long saltlen, int hash_idx, 2008 unsigned long saltlen, prng_state *prng,
1778 int prng_idx, prng_state *prng, 2009 int prng_idx, int hash_idx,
1779 unsigned long modulus_bitlen, 2010 unsigned long modulus_bitlen,
1780 unsigned char *out, unsigned long *outlen); 2011 unsigned char *out, unsigned long *outlen);
1781 \end{alltt} 2012 \end{alltt}
1782 2013
1783 This function assumes the message to be PSS encoded has previously been hashed. The input hash ``msghash'' is of length 2014 This function assumes the message to be PSS encoded has previously been hashed. The input hash ``msghash'' is of length
1784 ``msghashlen''. PSS allows a variable length random salt (it can be zero length) to be introduced in the signature process. 2015 ``msghashlen''. PSS allows a variable length random salt (it can be zero length) to be introduced in the signature process.
1785 ``hash\_idx'' is the index into the hash descriptor table of the hash to use. ``prng\_idx'' and ``prng'' are the random 2016 ``hash\_idx'' is the index into the hash descriptor table of the hash to use. ``prng\_idx'' and ``prng'' are the random
1786 number generator information required for the salt. 2017 number generator information required for the salt.
1787 2018
1788 Similar to OAEP encoding ``modulus\_bitlen'' is the size of the RSA modulus. It limits the size of the salt. If $m$ is the length 2019 Similar to OAEP encoding ``modulus\_bitlen'' is the size of the RSA modulus (in bits). It limits the size of the salt. If $m$ is the length
1789 of the modulus $h$ the length of the hash output (in octets) then there can be $m - h - 2$ bytes of salt. 2020 of the modulus $h$ the length of the hash output (in octets) then there can be $m - h - 2$ bytes of salt.
1790 2021
1791 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(). 2022 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().
1792 2023
1793 \subsection{PSS Decoding} 2024 \subsection{PSS Decoding}
1794 2025
1795 To decode a PSS encoded signature block you have to use the following. 2026 To decode a PSS encoded signature block you have to use the following.
1796 2027
2028 \index{pkcs\_1\_pss\_decode()}
1797 \begin{alltt} 2029 \begin{alltt}
1798 int pkcs_1_pss_decode(const unsigned char *msghash, unsigned long msghashlen, 2030 int pkcs_1_pss_decode(const unsigned char *msghash, unsigned long msghashlen,
1799 const unsigned char *sig, unsigned long siglen, 2031 const unsigned char *sig, unsigned long siglen,
1800 unsigned long saltlen, int hash_idx, 2032 unsigned long saltlen, int hash_idx,
1801 unsigned long modulus_bitlen, int *res); 2033 unsigned long modulus_bitlen, int *res);
1804 ``msghashlen''. If the block is a valid PSS block and the decoded hash equals the hash supplied ``res'' is set to non--zero. Otherwise, 2036 ``msghashlen''. If the block is a valid PSS block and the decoded hash equals the hash supplied ``res'' is set to non--zero. Otherwise,
1805 it is set to zero. The rest of the parameters are as in the PSS encode call. 2037 it is set to zero. The rest of the parameters are as in the PSS encode call.
1806 2038
1807 It's important to use the same ``saltlen'' and hash for both encoding and decoding as otherwise the procedure will not work. 2039 It's important to use the same ``saltlen'' and hash for both encoding and decoding as otherwise the procedure will not work.
1808 2040
2041 \subsection{PKCS \#1 v1.5 Encoding}
2042
2043 \index{pkcs\_1\_v15\_sa\_encode()}
2044 \begin{verbatim}
2045 int pkcs_1_v15_sa_encode(const unsigned char *msghash, unsigned long msghashlen,
2046 int hash_idx, unsigned long modulus_bitlen,
2047 unsigned char *out, unsigned long *outlen);
2048 \end{verbatim}
2049
2050 This will PKCS \#1 v1.5 signature encode the message hash ``msghash'' of length ``msghashlen''. You have
2051 to tell this routine which hash produced the message hash in ``hash\_idx''. The encoded hash is stored
2052 in ``out'' of length ``outlen''.
2053
2054 \subsection{PKCS \#1 v1.5 Decoding}
2055
2056 \index{pkcs\_1\_v15\_sa\_decode()}
2057 \begin{verbatim}
2058 int pkcs_1_v15_sa_decode(const unsigned char *msghash, unsigned long msghashlen,
2059 const unsigned char *sig, unsigned long siglen,
2060 int hash_idx, unsigned long modulus_bitlen,
2061 int *res);
2062 \end{verbatim}
2063
2064 This will PKCS \#1 v1.5 signature decode the data in ``sig'' of length ``siglen'' and compare the extracted
2065 hash against ``msghash'' of length ``msghashlen''. You have to tell this routine which hash produced the
2066 message digest in ``hash\_idx''. If the packet is valid and the hashes match ``res'' is set to $1$. Otherwise,
2067 it is set to $0$.
2068
2069 \section{RSA Operations}
2070 \subsection{Background}
2071
2072 RSA is a public key algorithm that is based on the inability to find the ``e-th'' root modulo a composite of unknown
2073 factorization. Normally the difficulty of breaking RSA is associated with the integer factoring problem but they are
2074 not strictly equivalent.
2075
2076 The system begins with with two primes $p$ and $q$ and their product $N = pq$. The order or ``Euler totient'' of the
2077 multiplicative sub-group formed modulo $N$ is given as $\phi(N) = (p - 1)(q - 1)$ which can be reduced to
2078 $\mbox{lcm}(p - 1, q - 1)$. The public key consists of the composite $N$ and some integer $e$ such that
2079 $\mbox{gcd}(e, \phi(N)) = 1$. The private key consists of the composite $N$ and the inverse of $e$ modulo $\phi(N)$
2080 often simply denoted as $de \equiv 1\mbox{ }(\mbox{mod }\phi(N))$.
2081
2082 A person who wants to encrypt with your public key simply forms an integer (the plaintext) $M$ such that
2083 $1 < M < N-2$ and computes the ciphertext $C = M^e\mbox{ }(\mbox{mod }N)$. Since finding the inverse exponent $d$
2084 given only $N$ and $e$ appears to be intractable only the owner of the private key can decrypt the ciphertext and compute
2085 $C^d \equiv \left (M^e \right)^d \equiv M^1 \equiv M\mbox{ }(\mbox{mod }N)$. Similarly the owner of the private key
2086 can sign a message by ``decrypting'' it. Others can verify it by ``encrypting'' it.
2087
2088 Currently RSA is a difficult system to cryptanalyze provided that both primes are large and not close to each other.
2089 Ideally $e$ should be larger than $100$ to prevent direct analysis. For example, if $e$ is three and you do not pad
2090 the plaintext to be encrypted than it is possible that $M^3 < N$ in which case finding the cube-root would be trivial.
2091 The most often suggested value for $e$ is $65537$ since it is large enough to make such attacks impossible and also well
2092 designed for fast exponentiation (requires 16 squarings and one multiplication).
2093
2094 It is important to pad the input to RSA since it has particular mathematical structure. For instance
2095 $M_1^dM_2^d = (M_1M_2)^d$ which can be used to forge a signature. Suppose $M_3 = M_1M_2$ is a message you want
2096 to have a forged signature for. Simply get the signatures for $M_1$ and $M_2$ on their own and multiply the result
2097 together. Similar tricks can be used to deduce plaintexts from ciphertexts. It is important not only to sign
2098 the hash of documents only but also to pad the inputs with data to remove such structure.
2099
2100 \subsection{RSA Key Generation}
2101
2102 For RSA routines a single ``rsa\_key'' structure is used. To make a new RSA key call:
2103 \index{rsa\_make\_key()}
2104 \begin{verbatim}
2105 int rsa_make_key(prng_state *prng,
2106 int wprng, int size,
2107 long e, rsa_key *key);
2108 \end{verbatim}
2109
2110 Where ``wprng'' is the index into the PRNG descriptor array. ``size'' is the size in bytes of the RSA modulus desired.
2111 ``e'' is the encryption exponent desired, typical values are 3, 17, 257 and 65537. I suggest you stick with 65537 since its big
2112 enough to prevent trivial math attacks and not super slow. ``key'' is where the key is placed. All keys must be at
2113 least 128 bytes and no more than 512 bytes in size (\textit{that is from 1024 to 4096 bits}).
2114
2115 Note that the ``rsa\_make\_key()'' function allocates memory at runtime when you make the key. Make sure to call
2116 ``rsa\_free()'' (see below) when you are finished with the key. If ``rsa\_make\_key()'' fails it will automatically
2117 free the ram allocated itself.
2118
2119 There are three types of RSA keys. The types are {\bf PK\_PRIVATE\_OPTIMIZED}, {\bf PK\_PRIVATE} and {\bf PK\_PUBLIC}. The first
2120 two are private keys where the ``optimized'' type uses the Chinese Remainder Theorem to speed up decryption/signatures. By
2121 default all new keys are of the ``optimized'' type. The non-optimized private type is provided for backwards compatibility
2122 as well as to save space since the optimized key requires about four times as much memory.
2123
2124 \subsection{RSA Exponentiation}
2125
2126 To do raw work with the RSA function call:
2127 \index{rsa\_exptmod()}
2128 \begin{verbatim}
2129 int rsa_exptmod(const unsigned char *in, unsigned long inlen,
2130 unsigned char *out, unsigned long *outlen, int which,
2131 prng_state *prng, int prng_idx,
2132 rsa_key *key);
2133 \end{verbatim}
2134 This loads the bignum from ``in'' as a big endian word in the format PKCS specifies, raises it to either ``e'' or ``d'' and stores the result
2135 in ``out'' and the size of the result in ``outlen''. ``which'' is set to {\bf PK\_PUBLIC} to use ``e''
2136 (i.e. for encryption/verifying) and set to {\bf PK\_PRIVATE} to use ``d'' as the exponent (i.e. for decrypting/signing).
2137
2138 Note that the output of his function is zero-padded as per PKCS \#1 specifications. This allows this routine to
2139 interoprate with PKCS \#1 padding functions properly.
2140
2141 \subsection{RSA Key Encryption}
2142 Normally RSA is used to encrypt short symmetric keys which are then used in block ciphers to encrypt a message.
2143 To facilitate encrypting short keys the following functions have been provided.
2144
2145 \index{rsa\_encrypt\_key()}
2146 \begin{verbatim}
2147 int rsa_encrypt_key(const unsigned char *inkey, unsigned long inlen,
2148 unsigned char *outkey, unsigned long *outlen,
2149 const unsigned char *lparam, unsigned long lparamlen,
2150 prng_state *prng, int prng_idx, int hash_idx, rsa_key *key);
2151 \end{verbatim}
2152 This function will OAEP pad ``inkey'' of length inlen bytes then RSA encrypt it and store the ciphertext
2153 in ``outkey'' of length ``outlen''. The ``lparam'' and ``lparamlen'' are the same parameters you would pass
2154 to pkcs\_1\_oaep\_encode().
2155
2156 \index{rsa\_decrypt\_key()}
2157 \begin{verbatim}
2158 int rsa_decrypt_key(const unsigned char *in, unsigned long inlen,
2159 unsigned char *outkey, unsigned long *keylen,
2160 const unsigned char *lparam, unsigned long lparamlen,
2161 prng_state *prng, int prng_idx,
2162 int hash_idx, int *res,
2163 rsa_key *key);
2164 \end{verbatim}
2165 This function will RSA decrypt ``in'' of length ``inlen'' then OAEP depad the resulting data and store it in
2166 ``outkey'' of length ``outlen''. The ``lparam'' and ``lparamlen'' are the same parameters you would pass
2167 to pkcs\_1\_oaep\_decode().
2168
2169 If the RSA decrypted data isn't a valid OAEP packet then ``res'' is set to $0$. Otherwise, it is set to $1$.
2170
2171 \subsection{RSA Hash Signatures}
2172 Similar to RSA key encryption RSA is also used to ``digitally sign'' message digests (hashes). To facilitate this
2173 process the following functions have been provided.
2174
2175 \index{rsa\_sign\_hash()}
2176 \begin{verbatim}
2177 int rsa_sign_hash(const unsigned char *msghash, unsigned long msghashlen,
2178 unsigned char *sig, unsigned long *siglen,
2179 prng_state *prng, int prng_idx,
2180 int hash_idx, unsigned long saltlen,
2181 rsa_key *key);
2182 \end{verbatim}
2183
2184 This will PSS encode the message hash ``msghash'' of length ``msghashlen''. Next the PSS encoded message is
2185 RSA ``signed'' and the output is stored in ``sig'' of length ``siglen''.
2186
2187
2188 \index{rsa\_verify\_hash()}
2189 \begin{verbatim}
2190 int rsa_verify_hash(const unsigned char *sig, unsigned long siglen,
2191 const unsigned char *msghash, unsigned long msghashlen,
2192 prng_state *prng, int prng_idx,
2193 int hash_idx, unsigned long saltlen,
2194 int *stat, rsa_key *key);
2195 \end{verbatim}
2196
2197 This will RSA ``verify'' the signature in ``sig'' of length ``siglen''. Next the RSA decoded data is PSS decoded
2198 and the extracted hash is compared against the message hash ``msghash'' of length ``msghashlen''.
2199
2200 If the RSA decoded data is not a valid PSS message or if the PSS decoded hash does not match the ``msghash''
2201 the value ``res'' is set to $0$. Otherwise, if the function succeeds and signature is valid ``res'' is set
2202 to $1$.
2203
2204 \begin{verbatim}
2205 #include <mycrypt.h>
2206 int main(void)
2207 {
2208 int err, hash_idx, prng_idx, res;
2209 unsigned long l1, l2;
2210 unsigned char pt[16], pt2[16], out[1024];
2211 rsa_key key;
2212
2213 /* register prng/hash */
2214 if (register_prng(&sprng_desc) == -1) {
2215 printf("Error registering sprng");
2216 return EXIT_FAILURE;
2217 }
2218
2219 if (register_hash(&sha1_desc) == -1) {
2220 printf("Error registering sha1");
2221 return EXIT_FAILURE;
2222 }
2223 hash_idx = find_hash("sha1");
2224 prng_idx = find_prng("sprng");
2225
2226 /* make an RSA-1024 key */
2227 if ((err = rsa_make_key(NULL, /* PRNG state */
2228 prng_idx, /* PRNG idx */
2229 1024/8, /* 1024-bit key */
2230 65537, /* we like e=65537 */
2231 &key) /* where to store the key */
2232 ) != CRYPT_OK) {
2233 printf("rsa_make_key %s", error_to_string(err));
2234 return EXIT_FAILURE;
2235 }
2236
2237 /* fill in pt[] with a key we want to send ... */
2238 l1 = sizeof(out);
2239 if ((err = rsa_encrypt_key(pt, /* data we wish to encrypt */
2240 16, /* data is 16 bytes long */
2241 out, /* where to store ciphertext */
2242 &l1, /* length of ciphertext */
2243 "TestApp", /* our lparam for this program */
2244 7, /* lparam is 7 bytes long */
2245 NULL, /* PRNG state */
2246 prng_idx, /* prng idx */
2247 hash_idx, /* hash idx */
2248 &key) /* our RSA key */
2249 ) != CRYPT_OK) {
2250 printf("rsa_encrypt_key %s", error_to_string(err));
2251 return EXIT_FAILURE;
2252 }
2253
2254 /* now let's decrypt the encrypted key */
2255 l2 = sizeof(pt2);
2256 if ((err = rsa_decrypt_key(out, /* encrypted data */
2257 l1, /* length of ciphertext */
2258 pt2, /* where to put plaintext */
2259 &l2, /* plaintext length */
2260 "TestApp", /* lparam for this program */
2261 7, /* lparam is 7 bytes long */
2262 NULL, /* PRNG state */
2263 prng_idx, /* prng idx */
2264 hash_idx, /* hash idx */
2265 &res, /* validity of data */
2266 &key) /* our RSA key */
2267 ) != CRYPT_OK) {
2268 printf("rsa_decrypt_key %s", error_to_string(err));
2269 return EXIT_FAILURE;
2270 }
2271 /* if all went well pt == pt2, l2 == 16, res == 1 */
2272 }
2273 \end{verbatim}
2274
1809 \chapter{Password Based Cryptography} 2275 \chapter{Password Based Cryptography}
1810 \section{PKCS \#5} 2276 \section{PKCS \#5}
1811 In order to securely handle user passwords for the purposes of creating session keys and chaining IVs the PKCS \#5 was drafted. PKCS \#5 2277 In order to securely handle user passwords for the purposes of creating session keys and chaining IVs the PKCS \#5 was drafted. PKCS \#5
1812 is made up of two algorithms, Algorithm One and Algorithm Two. Algorithm One is the older fairly limited algorithm which has been implemented 2278 is made up of two algorithms, Algorithm One and Algorithm Two. Algorithm One is the older fairly limited algorithm which has been implemented
1813 for completeness. Algorithm Two is a bit more modern and more flexible to work with. 2279 for completeness. Algorithm Two is a bit more modern and more flexible to work with.
1815 \section{Algorithm One} 2281 \section{Algorithm One}
1816 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 2282 Algorithm One accepts as input a password, an 8--byte salt and an iteration counter. The iteration counter is meant to act as delay for
1817 people trying to brute force guess the password. The higher the iteration counter the longer the delay. This algorithm also requires a hash 2283 people trying to brute force guess the password. The higher the iteration counter the longer the delay. This algorithm also requires a hash
1818 algorithm and produces an output no longer than the output of the hash. 2284 algorithm and produces an output no longer than the output of the hash.
1819 2285
2286 \index{pkcs\_5\_alg1()}
1820 \begin{alltt} 2287 \begin{alltt}
1821 int pkcs_5_alg1(const unsigned char *password, unsigned long password_len, 2288 int pkcs_5_alg1(const unsigned char *password, unsigned long password_len,
1822 const unsigned char *salt, 2289 const unsigned char *salt,
1823 int iteration_count, int hash_idx, 2290 int iteration_count, int hash_idx,
1824 unsigned char *out, unsigned long *outlen) 2291 unsigned char *out, unsigned long *outlen)
1834 2301
1835 Algorithm Two is the recommended algorithm for this task. It allows variable length salts and can produce outputs larger than the 2302 Algorithm Two is the recommended algorithm for this task. It allows variable length salts and can produce outputs larger than the
1836 hash functions output. As such it can easily be used to derive session keys for ciphers and MACs as well initial vectors as required 2303 hash functions output. As such it can easily be used to derive session keys for ciphers and MACs as well initial vectors as required
1837 from a single password and invokation of this algorithm. 2304 from a single password and invokation of this algorithm.
1838 2305
2306 \index{pkcs\_5\_alg2()}
1839 \begin{alltt} 2307 \begin{alltt}
1840 int pkcs_5_alg2(const unsigned char *password, unsigned long password_len, 2308 int pkcs_5_alg2(const unsigned char *password, unsigned long password_len,
1841 const unsigned char *salt, unsigned long salt_len, 2309 const unsigned char *salt, unsigned long salt_len,
1842 int iteration_count, int hash_idx, 2310 int iteration_count, int hash_idx,
1843 unsigned char *out, unsigned long *outlen) 2311 unsigned char *out, unsigned long *outlen)
1875 memcpy(mac_key, outbuf+32, 16); 2343 memcpy(mac_key, outbuf+32, 16);
1876 2344
1877 /* use material (recall to store the salt in the output) */ 2345 /* use material (recall to store the salt in the output) */
1878 \} 2346 \}
1879 \end{alltt} 2347 \end{alltt}
1880
1881 \chapter{RSA Routines}
1882
1883 \textbf{Note: } \textit{This chapter has been marked for removal. In particular any function that uses the LibTomCrypt style
1884 RSA padding (e.g. rsa\_pad() rsa\_signpad()) will be removed in the v0.96 release cycle. The functions like rsa\_make\_key() and
1885 rsa\_exptmod() will stay but may be slightly modified. }
1886
1887 \section{Background}
1888
1889 RSA is a public key algorithm that is based on the inability to find the ``e-th'' root modulo a composite of unknown
1890 factorization. Normally the difficulty of breaking RSA is associated with the integer factoring problem but they are
1891 not strictly equivalent.
1892
1893 The system begins with with two primes $p$ and $q$ and their product $N = pq$. The order or ``Euler totient'' of the
1894 multiplicative sub-group formed modulo $N$ is given as $\phi(N) = (p - 1)(q - 1)$ which can be reduced to
1895 $\mbox{lcm}(p - 1, q - 1)$. The public key consists of the composite $N$ and some integer $e$ such that
1896 $\mbox{gcd}(e, \phi(N)) = 1$. The private key consists of the composite $N$ and the inverse of $e$ modulo $\phi(N)$
1897 often simply denoted as $de \equiv 1\mbox{ }(\mbox{mod }\phi(N))$.
1898
1899 A person who wants to encrypt with your public key simply forms an integer (the plaintext) $M$ such that
1900 $1 < M < N-2$ and computes the ciphertext $C = M^e\mbox{ }(\mbox{mod }N)$. Since finding the inverse exponent $d$
1901 given only $N$ and $e$ appears to be intractable only the owner of the private key can decrypt the ciphertext and compute
1902 $C^d \equiv \left (M^e \right)^d \equiv M^1 \equiv M\mbox{ }(\mbox{mod }N)$. Similarly the owner of the private key
1903 can sign a message by ``decrypting'' it. Others can verify it by ``encrypting'' it.
1904
1905 Currently RSA is a difficult system to cryptanalyze provided that both primes are large and not close to each other.
1906 Ideally $e$ should be larger than $100$ to prevent direct analysis. For example, if $e$ is three and you do not pad
1907 the plaintext to be encrypted than it is possible that $M^3 < N$ in which case finding the cube-root would be trivial.
1908 The most often suggested value for $e$ is $65537$ since it is large enough to make such attacks impossible and also well
1909 designed for fast exponentiation (requires 16 squarings and one multiplication).
1910
1911 It is important to pad the input to RSA since it has particular mathematical structure. For instance
1912 $M_1^dM_2^d = (M_1M_2)^d$ which can be used to forge a signature. Suppose $M_3 = M_1M_2$ is a message you want
1913 to have a forged signature for. Simply get the signatures for $M_1$ and $M_2$ on their own and multiply the result
1914 together. Similar tricks can be used to deduce plaintexts from ciphertexts. It is important not only to sign
1915 the hash of documents only but also to pad the inputs with data to remove such structure.
1916
1917 \section{Core Functions}
1918
1919 For RSA routines a single ``rsa\_key'' structure is used. To make a new RSA key call:
1920 \index{rsa\_make\_key()}
1921 \begin{verbatim}
1922 int rsa_make_key(prng_state *prng,
1923 int wprng, int size,
1924 long e, rsa_key *key);
1925 \end{verbatim}
1926
1927 Where ``wprng'' is the index into the PRNG descriptor array. ``size'' is the size in bytes of the RSA modulus desired.
1928 ``e'' is the encryption exponent desired, typical values are 3, 17, 257 and 65537. I suggest you stick with 65537 since its big
1929 enough to prevent trivial math attacks and not super slow. ``key'' is where the key is placed. All keys must be at
1930 least 128 bytes and no more than 512 bytes in size (\textit{that is from 1024 to 4096 bits}).
1931
1932 Note that the ``rsa\_make\_key()'' function allocates memory at runtime when you make the key. Make sure to call
1933 ``rsa\_free()'' (see below) when you are finished with the key. If ``rsa\_make\_key()'' fails it will automatically
1934 free the ram allocated itself.
1935
1936 There are three types of RSA keys. The types are {\bf PK\_PRIVATE\_OPTIMIZED}, {\bf PK\_PRIVATE} and {\bf PK\_PUBLIC}. The first
1937 two are private keys where the ``optimized'' type uses the Chinese Remainder Theorem to speed up decryption/signatures. By
1938 default all new keys are of the ``optimized'' type. The non-optimized private type is provided for backwards compatibility
1939 as well as to save space since the optimized key requires about four times as much memory.
1940
1941 To do raw work with the RSA function call:
1942 \index{rsa\_exptmod()}
1943 \begin{verbatim}
1944 int rsa_exptmod(const unsigned char *in, unsigned long inlen,
1945 unsigned char *out, unsigned long *outlen,
1946 int which, rsa_key *key);
1947 \end{verbatim}
1948 This loads the bignum from ``in'' as a big endian word in the format PKCS specifies, raises it to either ``e'' or ``d'' and stores the result
1949 in ``out'' and the size of the result in ``outlen''. ``which'' is set to {\bf PK\_PUBLIC} to use ``e''
1950 (i.e. for encryption/verifying) and set to {\bf PK\_PRIVATE} to use ``d'' as the exponent (i.e. for decrypting/signing).
1951
1952 Note that this function does not perform padding on the input (as per PKCS). So if you send in ``0000001'' you will
1953 get ``01'' back (when you do the opposite operation). Make sure you pad properly which usually involves setting the msb to
1954 a non-zero value.
1955
1956 \section{Packet Routines}
1957 To encrypt or decrypt a symmetric key using RSA the following functions are provided. The idea is that you make up
1958 a random symmetric key and use that to encode your message. By RSA encrypting the symmetric key you can send it to a
1959 recipient who can RSA decrypt it and symmetrically decrypt the message.
1960 \begin{verbatim}
1961 int rsa_encrypt_key(const unsigned char *inkey, unsigned long inlen,
1962 unsigned char *outkey, unsigned long *outlen,
1963 prng_state *prng, int wprng, rsa_key *key);
1964 \end{verbatim}
1965 This function is used to RSA encrypt a symmetric to share with another user. The symmetric key and its length are
1966 passed as ``inkey'' and ``inlen'' respectively. The symmetric key is limited to a range of 8 to 32 bytes
1967 (\textit{64 to 256 bits}). The RSA encrypted packet is stored in ``outkey'' and will be of length ``outlen'' bytes. The
1968 value of ``outlen'' must be originally set to the size of the output buffer.
1969
1970 \begin{verbatim}
1971 int rsa_decrypt_key(const unsigned char *in, unsigned long inlen,
1972 unsigned char *outkey, unsigned long *keylen,
1973 rsa_key *key);
1974 \end{verbatim}
1975
1976 This function will decrypt an RSA packet to retrieve the original symmetric key encrypted with rsa\_encrypt\_key().
1977 Similarly to sign or verify a hash of a message the following two messages are provided. The idea is to hash your message
1978 then use these functions to RSA sign the hash.
1979 \begin{verbatim}
1980 int rsa_sign_hash(const unsigned char *in, unsigned long inlen,
1981 unsigned char *out, unsigned long *outlen,
1982 rsa_key *key);
1983
1984 int rsa_verify_hash(const unsigned char *sig, unsigned long siglen,
1985 const unsigned char *hash, int *stat, rsa_key *key);
1986 \end{verbatim}
1987 For ``rsa\_sign\_hash'' the input is intended to be the hash of a message the user wants to sign. The output is the
1988 RSA signed packet which ``rsa\_verify\_hash'' can verify. For the verification function ``sig'' is the RSA signature
1989 and ``hash'' is the hash of the message. The integer ``stat'' is set to non-zero if the signature is valid or zero
1990 otherwise.
1991
1992 To import/export RSA keys as a memory buffer (e.g. to store them to disk) call:
1993 \begin{verbatim}
1994 int rsa_export(unsigned char *out, unsigned long *outlen,
1995 int type, rsa_key *key);
1996
1997 int rsa_import(const unsigned char *in, unsigned long inlen, rsa_key *key);
1998 \end{verbatim}
1999
2000 The ``type'' parameter is {\bf PK\_PUBLIC}, {\bf PK\_PRIVATE} or {\bf PK\_PRIVATE\_OPTIMIZED} to export either a public or
2001 private key. The latter type will export a key with the optimized parameters. To free the memory used by an RSA key call:
2002 \index{rsa\_free()}
2003 \begin{verbatim}
2004 void rsa_free(rsa_key *key);
2005 \end{verbatim}
2006
2007 Note that if the key fails to ``rsa\_import()'' you do not have to free the memory allocated for it.
2008
2009 \section{Remarks}
2010 It is important that you match your RSA key size with the function you are performing. The internal padding for both
2011 signatures and encryption triple the size of the plaintext. This means to encrypt or sign
2012 a message of N bytes you must have a modulus of 1+3N bytes. Note that this doesn't affect the length of the plaintext
2013 you pass into functions like rsa\_encrypt(). This restriction applies only to data that is passed through the
2014 internal RSA routines directly directly.
2015
2016 The following table gives the size requirements for various hashes.
2017 \begin{center}
2018 \begin{tabular}{|c|c|c|}
2019 \hline Name & Size of Message Digest (bytes) & RSA Key Size (bits)\\
2020 \hline SHA-512 & 64 & 1544\\
2021 \hline SHA-384 & 48 & 1160 \\
2022 \hline SHA-256 & 32 & 776\\
2023 \hline TIGER-192 & 24 & 584\\
2024 \hline SHA-1 & 20 & 488\\
2025 \hline MD5 & 16 & 392\\
2026 \hline MD4 & 16 & 392\\
2027 \hline
2028 \end{tabular}
2029 \end{center}
2030
2031 The symmetric ciphers will use at a maximum a 256-bit key which means at the least a 776-bit RSA key is
2032 required to use all of the symmetric ciphers with the RSA routines. If you want to use any of the large size
2033 message digests (SHA-512 or SHA-384) you will have to use a larger key. Or to be simple just make 2048-bit or larger
2034 keys. None of the hashes will have problems with such key sizes.
2035 2348
2036 \chapter{Diffie-Hellman Key Exchange} 2349 \chapter{Diffie-Hellman Key Exchange}
2037 2350
2038 \section{Background} 2351 \section{Background}
2039 2352
2222 Which stores the smallest and largest key sizes support into the two variables. 2535 Which stores the smallest and largest key sizes support into the two variables.
2223 2536
2224 \section{DH Packet} 2537 \section{DH Packet}
2225 Similar to the RSA related functions there are functions to encrypt or decrypt symmetric keys using the DH public key 2538 Similar to the RSA related functions there are functions to encrypt or decrypt symmetric keys using the DH public key
2226 algorithms. 2539 algorithms.
2540 \index{dh\_encrypt\_key()} \index{dh\_decrypt\_key()}
2227 \begin{verbatim} 2541 \begin{verbatim}
2228 int dh_encrypt_key(const unsigned char *inkey, unsigned long keylen, 2542 int dh_encrypt_key(const unsigned char *inkey, unsigned long keylen,
2229 unsigned char *out, unsigned long *len, 2543 unsigned char *out, unsigned long *len,
2230 prng_state *prng, int wprng, int hash, 2544 prng_state *prng, int wprng, int hash,
2231 dh_key *key); 2545 dh_key *key);
2238 and find the hash of the shared secret. The message digest is than XOR'ed against the symmetric key. All of the 2552 and find the hash of the shared secret. The message digest is than XOR'ed against the symmetric key. All of the
2239 required data is placed in ``out'' by ``dh\_encrypt\_key()''. The hash must produce a message digest at least as large 2553 required data is placed in ``out'' by ``dh\_encrypt\_key()''. The hash must produce a message digest at least as large
2240 as the symmetric key you are trying to share. 2554 as the symmetric key you are trying to share.
2241 2555
2242 Similar to the RSA system you can sign and verify a hash of a message. 2556 Similar to the RSA system you can sign and verify a hash of a message.
2557 \index{dh\_sign\_hash()} \index{dh\_verify\_hash()}
2243 \begin{verbatim} 2558 \begin{verbatim}
2244 int dh_sign_hash(const unsigned char *in, unsigned long inlen, 2559 int dh_sign_hash(const unsigned char *in, unsigned long inlen,
2245 unsigned char *out, unsigned long *outlen, 2560 unsigned char *out, unsigned long *outlen,
2246 prng_state *prng, int wprng, dh_key *key); 2561 prng_state *prng, int wprng, dh_key *key);
2247 2562
2332 Which both work like their DH counterparts. 2647 Which both work like their DH counterparts.
2333 2648
2334 \section{ECC Packet} 2649 \section{ECC Packet}
2335 Similar to the RSA API there are two functions which encrypt and decrypt symmetric keys using the ECC public key 2650 Similar to the RSA API there are two functions which encrypt and decrypt symmetric keys using the ECC public key
2336 algorithms. 2651 algorithms.
2652
2653 \index{ecc\_encrypt\_key()} \index{ecc\_decrypt\_key()}
2337 \begin{verbatim} 2654 \begin{verbatim}
2338 int ecc_encrypt_key(const unsigned char *inkey, unsigned long keylen, 2655 int ecc_encrypt_key(const unsigned char *inkey, unsigned long keylen,
2339 unsigned char *out, unsigned long *len, 2656 unsigned char *out, unsigned long *len,
2340 prng_state *prng, int wprng, int hash, 2657 prng_state *prng, int wprng, int hash,
2341 ecc_key *key); 2658 ecc_key *key);
2349 and find the hash of the shared secret. The message digest is than XOR'ed against the symmetric key. All of the required 2666 and find the hash of the shared secret. The message digest is than XOR'ed against the symmetric key. All of the required
2350 data is placed in ``out'' by ``ecc\_encrypt\_key()''. The hash chosen must produce a message digest at least as large 2667 data is placed in ``out'' by ``ecc\_encrypt\_key()''. The hash chosen must produce a message digest at least as large
2351 as the symmetric key you are trying to share. 2668 as the symmetric key you are trying to share.
2352 2669
2353 There are also functions to sign and verify the hash of a message. 2670 There are also functions to sign and verify the hash of a message.
2671 \index{ecc\_sign\_hash()} \index{ecc\_verify\_hash()}
2354 \begin{verbatim} 2672 \begin{verbatim}
2355 int ecc_sign_hash(const unsigned char *in, unsigned long inlen, 2673 int ecc_sign_hash(const unsigned char *in, unsigned long inlen,
2356 unsigned char *out, unsigned long *outlen, 2674 unsigned char *out, unsigned long *outlen,
2357 prng_state *prng, int wprng, ecc_key *key); 2675 prng_state *prng, int wprng, ecc_key *key);
2358 2676
2407 \hline 2725 \hline
2408 \end{tabular} 2726 \end{tabular}
2409 \end{center} 2727 \end{center}
2410 2728
2411 When you are finished with a DSA key you can call the following function to free the memory used. 2729 When you are finished with a DSA key you can call the following function to free the memory used.
2730 \index{dsa\_free()}
2412 \begin{verbatim} 2731 \begin{verbatim}
2413 void dsa_free(dsa_key *key); 2732 void dsa_free(dsa_key *key);
2414 \end{verbatim} 2733 \end{verbatim}
2415 2734
2416 \section{Key Verification} 2735 \section{Key Verification}
2445 is within range and belongs to a group of prime order. Note that test eight does not prove that $g$ generated $y$ only 2764 is within range and belongs to a group of prime order. Note that test eight does not prove that $g$ generated $y$ only
2446 that $y$ belongs to a multiplicative sub-group of order $q$. 2765 that $y$ belongs to a multiplicative sub-group of order $q$.
2447 2766
2448 The following function will perform these tests. 2767 The following function will perform these tests.
2449 2768
2769 \index{dsa\_verify\_key()}
2450 \begin{verbatim} 2770 \begin{verbatim}
2451 int dsa_verify_key(dsa_key *key, int *stat); 2771 int dsa_verify_key(dsa_key *key, int *stat);
2452 \end{verbatim} 2772 \end{verbatim}
2453 2773
2454 This will test ``key'' and store the result in ``stat''. If the result is $stat = 0$ the DSA key failed one of the tests 2774 This will test ``key'' and store the result in ``stat''. If the result is $stat = 0$ the DSA key failed one of the tests
2457 2777
2458 2778
2459 \section{Signatures} 2779 \section{Signatures}
2460 To generate a DSA signature call the following function 2780 To generate a DSA signature call the following function
2461 2781
2782 \index{dsa\_sign\_hash()}
2462 \begin{verbatim} 2783 \begin{verbatim}
2463 int dsa_sign_hash(const unsigned char *in, unsigned long inlen, 2784 int dsa_sign_hash(const unsigned char *in, unsigned long inlen,
2464 unsigned char *out, unsigned long *outlen, 2785 unsigned char *out, unsigned long *outlen,
2465 prng_state *prng, int wprng, dsa_key *key); 2786 prng_state *prng, int wprng, dsa_key *key);
2466 \end{verbatim} 2787 \end{verbatim}
2469 of the signature in ``outlen''. If the signature is longer than the size you initially specify in ``outlen'' nothing 2790 of the signature in ``outlen''. If the signature is longer than the size you initially specify in ``outlen'' nothing
2470 is stored and the function returns an error code. The DSA ``key'' must be of the \textbf{PK\_PRIVATE} persuasion. 2791 is stored and the function returns an error code. The DSA ``key'' must be of the \textbf{PK\_PRIVATE} persuasion.
2471 2792
2472 To verify a hash created with that function use the following function 2793 To verify a hash created with that function use the following function
2473 2794
2795 \index{dsa\_verify\_hash()}
2474 \begin{verbatim} 2796 \begin{verbatim}
2475 int dsa_verify_hash(const unsigned char *sig, unsigned long siglen, 2797 int dsa_verify_hash(const unsigned char *sig, unsigned long siglen,
2476 const unsigned char *hash, unsigned long inlen, 2798 const unsigned char *hash, unsigned long inlen,
2477 int *stat, dsa_key *key); 2799 int *stat, dsa_key *key);
2478 \end{verbatim} 2800 \end{verbatim}
2480 It will set ``stat'' to $1$ if the signature is valid, otherwise it sets ``stat'' to $0$. 2802 It will set ``stat'' to $1$ if the signature is valid, otherwise it sets ``stat'' to $0$.
2481 2803
2482 \section{Import and Export} 2804 \section{Import and Export}
2483 2805
2484 To export a DSA key so that it can be transported use the following function 2806 To export a DSA key so that it can be transported use the following function
2807 \index{dsa\_export()}
2485 \begin{verbatim} 2808 \begin{verbatim}
2486 int dsa_export(unsigned char *out, unsigned long *outlen, 2809 int dsa_export(unsigned char *out, unsigned long *outlen,
2487 int type, 2810 int type,
2488 dsa_key *key); 2811 dsa_key *key);
2489 \end{verbatim} 2812 \end{verbatim}
2491 initialized to the maximum buffer size). The ``type`` variable may be either \textbf{PK\_PRIVATE} or \textbf{PK\_PUBLIC} 2814 initialized to the maximum buffer size). The ``type`` variable may be either \textbf{PK\_PRIVATE} or \textbf{PK\_PUBLIC}
2492 depending on whether you want to export a private or public copy of the DSA key. 2815 depending on whether you want to export a private or public copy of the DSA key.
2493 2816
2494 To import an exported DSA key use the following function 2817 To import an exported DSA key use the following function
2495 2818
2819 \index{dsa\_import()}
2496 \begin{verbatim} 2820 \begin{verbatim}
2497 int dsa_import(const unsigned char *in, unsigned long inlen, 2821 int dsa_import(const unsigned char *in, unsigned long inlen,
2498 dsa_key *key); 2822 dsa_key *key);
2499 \end{verbatim} 2823 \end{verbatim}
2500 2824
2501 This will import the DSA key from the buffer ``in'' of length ``inlen'' to the ``key''. If the process fails the function 2825 This will import the DSA key from the buffer ``in'' of length ``inlen'' to the ``key''. If the process fails the function
2502 will automatically free all of the heap allocated in the process (you don't have to call dsa\_free()). 2826 will automatically free all of the heap allocated in the process (you don't have to call dsa\_free()).
2503
2504 \chapter{Public Keyrings}
2505 \section{Introduction}
2506 In order to simplify the usage of the public key algorithms a set of keyring routines have been developed. They let the
2507 developer manage asymmetric keys by providing load, save, export, import routines as well as encrypt, decrypt, sign, verify
2508 routines in a unified API. That is all three types of PK systems can be used within the same keyring with the same API.
2509
2510 To define types of keys there are four enumerations used globaly:
2511 \begin{verbatim}
2512 enum {
2513 NON_KEY=0,
2514 RSA_KEY,
2515 DH_KEY,
2516 ECC_KEY
2517 };
2518 \end{verbatim}
2519
2520 To make use of the system the developer has to know how link-lists work. The main structure that the keyring routines use
2521 is the ``pk\_key'' defined as:
2522 \begin{small}
2523 \begin{verbatim}
2524 typedef struct Pk_key {
2525 int key_type, /* PUBLIC, PRIVATE, PRIVATE_OPTIMIZED */
2526 system; /* RSA, ECC or DH ? */
2527
2528 char name[MAXLEN], /* various info's about this key */
2529 email[MAXLEN],
2530 description[MAXLEN];
2531
2532 unsigned long ID; /* CRC32 of the name/email/description together */
2533
2534 _pk_key key;
2535
2536 struct Pk_key *next; /* linked list chain */
2537 } pk_key;
2538 \end{verbatim}
2539 \end{small}
2540
2541 The list is chained via the ``next'' member and terminated with the node of the list that has ``system'' equal to
2542 {\bf NON\_KEY}.
2543
2544 \section{The Keyring API}
2545 To initialize a blank keyring the function ``kr\_init()'' is used.
2546 \begin{verbatim}
2547 int kr_init(pk_key **pk);
2548 \end{verbatim}
2549 You pass it a pointer to a pointer of type ``pk\_key'' where it will allocate ram for one node of the keyring and sets the
2550 pointer.
2551
2552 Now instead of calling the PK specific ``make\_key'' functions there is one function that can make all three types of keys.
2553 \begin{verbatim}
2554 int kr_make_key(pk_key *pk, prng_state *prng, int wprng,
2555 int system, int keysize, const char *name,
2556 const char *email, const char *description);
2557 \end{verbatim}
2558 The ``name'', ``email'' and ``description'' parameters are simply little pieces of information that you can tag along with a
2559 key. They can each be either blank or any string less than 256 bytes. ``system'' is one of the enumeration elements, that
2560 is {\bf RSA\_KEY}, {\bf DH\_KEY} or {\bf ECC\_KEY}. ``keysize'' is the size of the key you desire which is regulated by
2561 the individual systems, for example, RSA keys are limited in keysize from 128 to 512 bytes.
2562
2563 To find keys along a keyring there are two functions provided:
2564 \begin{verbatim}
2565 pk_key *kr_find(pk_key *pk, unsigned long ID);
2566
2567 pk_key *kr_find_name(pk_key *pk, const char *name);
2568 \end{verbatim}
2569 The first searches by the 32-bit ID provided and the latter checks the name against the keyring. They both return a pointer
2570 to the node in the ring of a match or {\bf NULL} if no match is found.
2571
2572 To export or import a single node of a keyring the two functions are provided:
2573 \begin{verbatim}
2574 int kr_export(pk_key *pk, unsigned long ID, int key_type,
2575 unsigned char *out, unsigned long *outlen);
2576
2577 int kr_import(pk_key *pk, const unsigned char *in);
2578 \end{verbatim}
2579 The export function exports the key with an ID provided and of a specific type much like the normal PK export routines. The
2580 ``key\_type'' is one of {\bf PK\_PUBLIC} or {\bf PK\_PRIVATE}. In this function with RSA keys the type
2581 {\bf PK\_PRIVATE\_OPTIMIZED} is the same as the {\bf PK\_PRIVATE} type. The import function will read in a packet and
2582 add it to the keyring.
2583
2584 To load and save whole keyrings from disk:
2585 \begin{verbatim}
2586 int kr_load(pk_key **pk, FILE *in, symmetric_CTR *ctr);
2587
2588 int kr_save(pk_key *pk, FILE *out, symmetric_CTR *ctr);
2589 \end{verbatim}
2590 Both take file pointers to allow the user to pre-append data to the stream. The ``ctr'' parameter should be setup with
2591 ``ctr\_start'' or set to NULL. This parameter lets the user encrypt the keyring as its written to disk, if it is set
2592 to NULL the data is written without being encrypted. The load function assumes the list has not been initialized yet
2593 and will reset the pointer given to it.
2594
2595 There are the four encrypt, decrypt, sign and verify functions as well
2596 \begin{verbatim}
2597 int kr_encrypt_key(pk_key *pk, unsigned long ID,
2598 const unsigned char *in, unsigned long inlen,
2599 unsigned char *out, unsigned long *outlen,
2600 prng_state *prng, int wprng, int hash);
2601
2602 int kr_decrypt_key(pk_key *pk, const unsigned char *in,
2603 unsigned char *out, unsigned long *outlen);
2604 \end{verbatim}
2605
2606 The kr\_encrypt\_key() routine is designed to encrypt a symmetric key with a specified users public key. The symmetric
2607 key is then used with a block cipher to encode the message. The recipient can call kr\_decrypt\_key() to get the original
2608 symmetric key back and decode the message. The hash specified must produce a message digest longer than symmetric key
2609 provided.
2610
2611 \begin{verbatim}
2612 int kr_sign_hash(pk_key *pk, unsigned long ID,
2613 const unsigned char *in, unsigned long inlen,
2614 unsigned char *out, unsigned long *outlen,
2615 prng_state *prng, int wprng);
2616
2617 int kr_verify_hash(pk_key *pk, const unsigned char *in,
2618 const unsigned char *hash, unsigned long hashlen,
2619 int *stat);
2620 \end{verbatim}
2621
2622 Similar to the two previous these are used to sign a message digest or verify one. This requires hashing the message
2623 first then passing the output in.
2624
2625 To delete keys and clear rings there are:
2626 \begin{verbatim}
2627 int kr_del(pk_key **_pk, unsigned long ID);
2628 int kr_clear(pk_key **pk);
2629 \end{verbatim}
2630 ``kr\_del'' will try to remove a key with a given ID from the ring and ``kr\_clear'' will completely empty a list and free
2631 the memory associated with it. Below is small example using the keyring API:
2632
2633 \begin{small}
2634 \begin{verbatim}
2635 #include <mycrypt.h>
2636 int main(void)
2637 {
2638 pk_key *kr;
2639 unsigned char buf[4096], buf2[4096];
2640 unsigned long len;
2641 int err;
2642
2643 /* make a new list */
2644 if ((err = kr_init(&kr)) != CRYPT_OK) {
2645 printf("kr_init: %s\n", error_to_string(err));
2646 exit(-1);
2647 }
2648
2649 /* add a key to it */
2650 register_prng(&sprng_desc);
2651 if ((err = kr_make_key(kr, NULL, find_prng("sprng"), RSA_KEY, 128,
2652 "TomBot", "[email protected]", "test key")) == CRYPT_OK) {
2653 printf("kr_make_key: %s\n", error_to_string(err));
2654 exit(-1);
2655 }
2656
2657 /* export the first key */
2658 len = sizeof(buf);
2659 if ((err = kr_export(kr, kr->ID, PK_PRIVATE, buf, &len)) != CRYPT_OK) {
2660 printf("kr_export: %s\n", error_to_string(err));
2661 exit(-1);
2662 }
2663
2664 /* ... */
2665 }
2666 \end{verbatim}
2667 \end{small}
2668
2669 \chapter{$GF(2^w)$ Math Routines}
2670
2671 The library provides a set of polynomial-basis $GF(2^w)$ routines to help facilitate algorithms such as ECC over such
2672 fields. Note that the current implementation of ECC in the library is strictly over the integers only. The routines
2673 are simple enough to use for other purposes outside of ECC.
2674
2675 At the heart of all of the GF routines is the data type ``gf\_int'. It is simply a type definition for an array of
2676 $L$ 32-bit words. You can configure the maximum size $L$ of the ``gf\_int'' type by opening the file ``mycrypt.h'' and
2677 changing ``LSIZE''. Note that if you set it to $n$ then you can only multiply upto two $n \over 2$ bit polynomials without
2678 an overflow. The type ``gf\_intp'' is associated with a pointer to an ``unsigned long'' as required in the algorithms.
2679
2680 There are no initialization routines for ``gf\_int'' variables and you can simply use them after declaration. There are five
2681 low level functions:
2682 \index{gf\_copy()} \index{gf\_zero()} \index{gf\_iszero()} \index{gf\_isone()}
2683 \index{gf\_deg()}
2684 \begin{verbatim}
2685 void gf_copy(gf_intp a, gf_intp b);
2686 void gf_zero(gf_intp a);
2687 int gf_iszero(gf_intp a);
2688 int gf_isone(gf_intp a);
2689 int gf_deg(gf_intp a);
2690 \end{verbatim}
2691 There are all fairly self-explanatory. ``gf\_copy(a, b)'' copies the contents of ``a'' into ``b''. ``gf\_zero()'' simply
2692 zeroes the entire polynomial. ``gf\_iszero()'' tests to see if the polynomial is all zero and ``gf\_isone()'' tests to see
2693 if the polynomial is equal to the multiplicative identity. ``gf\_deg()'' returns the degree of the polynomial or $-1$ if its
2694 a zero polynomial.
2695
2696 There are five core math routines as well:
2697 \index{gf\_shl()} \index{gf\_shr()} \index{gf\_add()} \index{gf\_mul()} \index{gf\_div()}
2698 \begin{verbatim}
2699 void gf_shl(gf_intp a, gf_intp b);
2700 void gf_shr(gf_intp a, gf_intp b);
2701 void gf_add(gf_intp a, gf_intp b, gf_intp c);
2702 void gf_mul(gf_intp a, gf_intp b, gf_intp c);
2703 void gf_div(gf_intp a, gf_intp b, gf_intp q, gf_intp r);
2704 \end{verbatim}
2705
2706 Which are all fairly obvious. ``gf\_shl(a,b)'' multiplies the polynomial ``a'' by $x$ and stores it in ``b''.
2707 ``gf\_shl(a,b)'' divides the polynomial ``a'' by $x$ and stores it in ``b''. ``gf\_add(a,b,c)'' adds the polynomial
2708 ``a'' to ``b'' and stores the sum in ``c''. Similarly for ``gf\_mul(a,b,c)''. The ``gf\_div(a,b,q,r)'' function divides
2709 ``a'' by ``b'' and stores the quotient in ``q'' and the remainder in ``r''.
2710
2711 There are six number theoretic functions as well:
2712 \index{gf\_mod()} \index{gf\_mulmod()} \index{gf\_invmod()} \index{gf\_gcd()} \index{gf\_is\_prime()}
2713 \index{gf\_sqrt()}
2714 \begin{verbatim}
2715 void gf_mod(gf_intp a, gf_intp m, gf_intp b);
2716 void gf_mulmod(gf_intp a, gf_intp b, gf_intp m, gf_intp c);
2717 void gf_invmod(gf_intp A, gf_intp M, gf_intp B);
2718 void gf_sqrt(gf_intp a, gf_intp m, gf_intp b);
2719 void gf_gcd(gf_intp A, gf_intp B, gf_intp c);
2720 int gf_is_prime(gf_intp a);
2721 \end{verbatim}
2722
2723 Which all work similarly except for ``gf\_mulmod(a,b,m,c)'' which computes $c = ab\mbox{ }(\mbox{mod }m)$. The
2724 ``gf\_is\_prime()'' function returns one if the polynomial is primitive, otherwise it returns zero.
2725
2726 Finally to read/store a ``gf\_int'' in a binary string use:
2727 \index{gf\_size()} \index{gf\_toraw()} \index{gf\_readraw()}
2728 \begin{verbatim}
2729 int gf_size(gf_intp a);
2730 void gf_toraw(gf_intp a, unsigned char *dst);
2731 void gf_readraw(gf_intp a, unsigned char *str, int len);
2732 \end{verbatim}
2733 Where ``gf\_size()'' returns the size in bytes required for the data. ``gf\_toraw(a,b)'' stores the polynomial in ``b''
2734 in binary format (endian neutral). ``gf\_readraw(a,b,c)'' reads the binary string in ``b'' back. Note that the length
2735 you pass it must be the same as returned by ``gf\_size()'' or it will not load correctly.
2736 2827
2737 \chapter{Miscellaneous} 2828 \chapter{Miscellaneous}
2738 \section{Base64 Encoding and Decoding} 2829 \section{Base64 Encoding and Decoding}
2739 The library provides functions to encode and decode a RFC1521 base64 coding scheme. This means that it can decode what it 2830 The library provides functions to encode and decode a RFC1521 base64 coding scheme. This means that it can decode what it
2740 encodes but the format used does not comply to any known standard. The characters used in the mappings are: 2831 encodes but the format used does not comply to any known standard. The characters used in the mappings are:
3035 3126
3036 \subsubsection{SMALL\_CODE} 3127 \subsubsection{SMALL\_CODE}
3037 When this is defined some of the code such as the Rijndael and SAFER+ ciphers are replaced with smaller code variants. 3128 When this is defined some of the code such as the Rijndael and SAFER+ ciphers are replaced with smaller code variants.
3038 These variants are slower but can save quite a bit of code space. 3129 These variants are slower but can save quite a bit of code space.
3039 3130
3131 \input{crypt.ind}
3132
3040 \end{document} 3133 \end{document}