forked from libtom/libtommath
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bn.tex
1835 lines (1460 loc) · 66.3 KB
/
bn.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass[synpaper]{book}
\usepackage{hyperref}
\usepackage{makeidx}
\usepackage{amssymb}
\usepackage{color}
\usepackage{alltt}
\usepackage{graphicx}
\usepackage{layout}
\def\union{\cup}
\def\intersect{\cap}
\def\getsrandom{\stackrel{\rm R}{\gets}}
\def\cross{\times}
\def\cat{\hspace{0.5em} \| \hspace{0.5em}}
\def\catn{$\|$}
\def\divides{\hspace{0.3em} | \hspace{0.3em}}
\def\nequiv{\not\equiv}
\def\approx{\raisebox{0.2ex}{\mbox{\small $\sim$}}}
\def\lcm{{\rm lcm}}
\def\gcd{{\rm gcd}}
\def\log{{\rm log}}
\def\ord{{\rm ord}}
\def\abs{{\mathit abs}}
\def\rep{{\mathit rep}}
\def\mod{{\mathit\ mod\ }}
\renewcommand{\pmod}[1]{\ ({\rm mod\ }{#1})}
\newcommand{\floor}[1]{\left\lfloor{#1}\right\rfloor}
\newcommand{\ceil}[1]{\left\lceil{#1}\right\rceil}
\def\Or{{\rm\ or\ }}
\def\And{{\rm\ and\ }}
\def\iff{\hspace{1em}\Longleftrightarrow\hspace{1em}}
\def\implies{\Rightarrow}
\def\undefined{{\rm ``undefined"}}
\def\Proof{\vspace{1ex}\noindent {\bf Proof:}\hspace{1em}}
\let\oldphi\phi
\def\phi{\varphi}
\def\Pr{{\rm Pr}}
\newcommand{\str}[1]{{\mathbf{#1}}}
\def\F{{\mathbb F}}
\def\N{{\mathbb N}}
\def\Z{{\mathbb Z}}
\def\R{{\mathbb R}}
\def\C{{\mathbb C}}
\def\Q{{\mathbb Q}}
\definecolor{DGray}{gray}{0.5}
\newcommand{\emailaddr}[1]{\mbox{$<${#1}$>$}}
\def\twiddle{\raisebox{0.3ex}{\mbox{\tiny $\sim$}}}
\def\gap{\vspace{0.5ex}}
\makeindex
\begin{document}
\frontmatter
\pagestyle{empty}
\title{LibTomMath User Manual \\ v0.42.0}
\author{Tom St Denis \\ [email protected]}
\maketitle
This text, the library and the accompanying textbook are all hereby placed in the public domain. This book has been
formatted for B5 [176x250] paper using the \LaTeX{} {\em book} macro package.
\vspace{10cm}
\begin{flushright}Open Source. Open Academia. Open Minds.
\mbox{ }
Tom St Denis,
Ontario, Canada
\end{flushright}
\tableofcontents
\listoffigures
\mainmatter
\pagestyle{headings}
\chapter{Introduction}
\section{What is LibTomMath?}
LibTomMath is a library of source code which provides a series of efficient and carefully written functions for manipulating
large integer numbers. It was written in portable ISO C source code so that it will build on any platform with a conforming
C compiler.
In a nutshell the library was written from scratch with verbose comments to help instruct computer science students how
to implement ``bignum'' math. However, the resulting code has proven to be very useful. It has been used by numerous
universities, commercial and open source software developers. It has been used on a variety of platforms ranging from
Linux and Windows based x86 to ARM based Gameboys and PPC based MacOS machines.
\section{License}
As of the v0.25 the library source code has been placed in the public domain with every new release. As of the v0.28
release the textbook ``Implementing Multiple Precision Arithmetic'' has been placed in the public domain with every new
release as well. This textbook is meant to compliment the project by providing a more solid walkthrough of the development
algorithms used in the library.
Since both\footnote{Note that the MPI files under mtest/ are copyrighted by Michael Fromberger. They are not required to use LibTomMath.} are in the
public domain everyone is entitled to do with them as they see fit.
\section{Building LibTomMath}
LibTomMath is meant to be very ``GCC friendly'' as it comes with a makefile well suited for GCC. However, the library will
also build in MSVC, Borland C out of the box. For any other ISO C compiler a makefile will have to be made by the end
developer.
\subsection{Static Libraries}
To build as a static library for GCC issue the following
\begin{alltt}
make
\end{alltt}
command. This will build the library and archive the object files in ``libtommath.a''. Now you link against
that and include ``tommath.h'' within your programs. Alternatively to build with MSVC issue the following
\begin{alltt}
nmake -f makefile.msvc
\end{alltt}
This will build the library and archive the object files in ``tommath.lib''. This has been tested with MSVC
version 6.00 with service pack 5.
\subsection{Shared Libraries}
To build as a shared library for GCC issue the following
\begin{alltt}
make -f makefile.shared
\end{alltt}
This requires the ``libtool'' package (common on most Linux/BSD systems). It will build LibTomMath as both shared
and static then install (by default) into /usr/lib as well as install the header files in /usr/include. The shared
library (resource) will be called ``libtommath.la'' while the static library called ``libtommath.a''. Generally
you use libtool to link your application against the shared object.
There is limited support for making a ``DLL'' in windows via the ``makefile.cygwin\_dll'' makefile. It requires
Cygwin to work with since it requires the auto-export/import functionality. The resulting DLL and import library
``libtommath.dll.a'' can be used to link LibTomMath dynamically to any Windows program using Cygwin.
\subsection{Testing}
To build the library and the test harness type
\begin{alltt}
make test
\end{alltt}
This will build the library, ``test'' and ``mtest/mtest''. The ``test'' program will accept test vectors and verify the
results. ``mtest/mtest'' will generate test vectors using the MPI library by Michael Fromberger\footnote{A copy of MPI
is included in the package}. Simply pipe mtest into test using
\begin{alltt}
mtest/mtest | test
\end{alltt}
If you do not have a ``/dev/urandom'' style RNG source you will have to write your own PRNG and simply pipe that into
mtest. For example, if your PRNG program is called ``myprng'' simply invoke
\begin{alltt}
myprng | mtest/mtest | test
\end{alltt}
This will output a row of numbers that are increasing. Each column is a different test (such as addition, multiplication, etc)
that is being performed. The numbers represent how many times the test was invoked. If an error is detected the program
will exit with a dump of the relevent numbers it was working with.
\section{Build Configuration}
LibTomMath can configured at build time in three phases we shall call ``depends'', ``tweaks'' and ``trims''.
Each phase changes how the library is built and they are applied one after another respectively.
To make the system more powerful you can tweak the build process. Classes are defined in the file
``tommath\_superclass.h''. By default, the symbol ``LTM\_ALL'' shall be defined which simply
instructs the system to build all of the functions. This is how LibTomMath used to be packaged. This will give you
access to every function LibTomMath offers.
However, there are cases where such a build is not optional. For instance, you want to perform RSA operations. You
don't need the vast majority of the library to perform these operations. Aside from LTM\_ALL there is
another pre--defined class ``SC\_RSA\_1'' which works in conjunction with the RSA from LibTomCrypt. Additional
classes can be defined base on the need of the user.
\subsection{Build Depends}
In the file tommath\_class.h you will see a large list of C ``defines'' followed by a series of ``ifdefs''
which further define symbols. All of the symbols (technically they're macros $\ldots$) represent a given C source
file. For instance, BN\_MP\_ADD\_C represents the file ``bn\_mp\_add.c''. When a define has been enabled the
function in the respective file will be compiled and linked into the library. Accordingly when the define
is absent the file will not be compiled and not contribute any size to the library.
You will also note that the header tommath\_class.h is actually recursively included (it includes itself twice).
This is to help resolve as many dependencies as possible. In the last pass the symbol LTM\_LAST will be defined.
This is useful for ``trims''.
\subsection{Build Tweaks}
A tweak is an algorithm ``alternative''. For example, to provide tradeoffs (usually between size and space).
They can be enabled at any pass of the configuration phase.
\begin{small}
\begin{center}
\begin{tabular}{|l|l|}
\hline \textbf{Define} & \textbf{Purpose} \\
\hline BN\_MP\_DIV\_SMALL & Enables a slower, smaller and equally \\
& functional mp\_div() function \\
\hline
\end{tabular}
\end{center}
\end{small}
\subsection{Build Trims}
A trim is a manner of removing functionality from a function that is not required. For instance, to perform
RSA cryptography you only require exponentiation with odd moduli so even moduli support can be safely removed.
Build trims are meant to be defined on the last pass of the configuration which means they are to be defined
only if LTM\_LAST has been defined.
\subsubsection{Moduli Related}
\begin{small}
\begin{center}
\begin{tabular}{|l|l|}
\hline \textbf{Restriction} & \textbf{Undefine} \\
\hline Exponentiation with odd moduli only & BN\_S\_MP\_EXPTMOD\_C \\
& BN\_MP\_REDUCE\_C \\
& BN\_MP\_REDUCE\_SETUP\_C \\
& BN\_S\_MP\_MUL\_HIGH\_DIGS\_C \\
& BN\_FAST\_S\_MP\_MUL\_HIGH\_DIGS\_C \\
\hline Exponentiation with random odd moduli & (The above plus the following) \\
& BN\_MP\_REDUCE\_2K\_C \\
& BN\_MP\_REDUCE\_2K\_SETUP\_C \\
& BN\_MP\_REDUCE\_IS\_2K\_C \\
& BN\_MP\_DR\_IS\_MODULUS\_C \\
& BN\_MP\_DR\_REDUCE\_C \\
& BN\_MP\_DR\_SETUP\_C \\
\hline Modular inverse odd moduli only & BN\_MP\_INVMOD\_SLOW\_C \\
\hline Modular inverse (both, smaller/slower) & BN\_FAST\_MP\_INVMOD\_C \\
\hline
\end{tabular}
\end{center}
\end{small}
\subsubsection{Operand Size Related}
\begin{small}
\begin{center}
\begin{tabular}{|l|l|}
\hline \textbf{Restriction} & \textbf{Undefine} \\
\hline Moduli $\le 2560$ bits & BN\_MP\_MONTGOMERY\_REDUCE\_C \\
& BN\_S\_MP\_MUL\_DIGS\_C \\
& BN\_S\_MP\_MUL\_HIGH\_DIGS\_C \\
& BN\_S\_MP\_SQR\_C \\
\hline Polynomial Schmolynomial & BN\_MP\_KARATSUBA\_MUL\_C \\
& BN\_MP\_KARATSUBA\_SQR\_C \\
& BN\_MP\_TOOM\_MUL\_C \\
& BN\_MP\_TOOM\_SQR\_C \\
\hline
\end{tabular}
\end{center}
\end{small}
\section{Purpose of LibTomMath}
Unlike GNU MP (GMP) Library, LIP, OpenSSL or various other commercial kits (Miracl), LibTomMath was not written with
bleeding edge performance in mind. First and foremost LibTomMath was written to be entirely open. Not only is the
source code public domain (unlike various other GPL/etc licensed code), not only is the code freely downloadable but the
source code is also accessible for computer science students attempting to learn ``BigNum'' or multiple precision
arithmetic techniques.
LibTomMath was written to be an instructive collection of source code. This is why there are many comments, only one
function per source file and often I use a ``middle-road'' approach where I don't cut corners for an extra 2\% speed
increase.
Source code alone cannot really teach how the algorithms work which is why I also wrote a textbook that accompanies
the library (beat that!).
So you may be thinking ``should I use LibTomMath?'' and the answer is a definite maybe. Let me tabulate what I think
are the pros and cons of LibTomMath by comparing it to the math routines from GnuPG\footnote{GnuPG v1.2.3 versus LibTomMath v0.28}.
\newpage\begin{figure}[here]
\begin{small}
\begin{center}
\begin{tabular}{|l|c|c|l|}
\hline \textbf{Criteria} & \textbf{Pro} & \textbf{Con} & \textbf{Notes} \\
\hline Few lines of code per file & X & & GnuPG $ = 300.9$, LibTomMath $ = 71.97$ \\
\hline Commented function prototypes & X && GnuPG function names are cryptic. \\
\hline Speed && X & LibTomMath is slower. \\
\hline Totally free & X & & GPL has unfavourable restrictions.\\
\hline Large function base & X & & GnuPG is barebones. \\
\hline Five modular reduction algorithms & X & & Faster modular exponentiation for a variety of moduli. \\
\hline Portable & X & & GnuPG requires configuration to build. \\
\hline
\end{tabular}
\end{center}
\end{small}
\caption{LibTomMath Valuation}
\end{figure}
It may seem odd to compare LibTomMath to GnuPG since the math in GnuPG is only a small portion of the entire application.
However, LibTomMath was written with cryptography in mind. It provides essentially all of the functions a cryptosystem
would require when working with large integers.
So it may feel tempting to just rip the math code out of GnuPG (or GnuMP where it was taken from originally) in your
own application but I think there are reasons not to. While LibTomMath is slower than libraries such as GnuMP it is
not normally significantly slower. On x86 machines the difference is normally a factor of two when performing modular
exponentiations. It depends largely on the processor, compiler and the moduli being used.
Essentially the only time you wouldn't use LibTomMath is when blazing speed is the primary concern. However,
on the other side of the coin LibTomMath offers you a totally free (public domain) well structured math library
that is very flexible, complete and performs well in resource contrained environments. Fast RSA for example can
be performed with as little as 8KB of ram for data (again depending on build options).
\chapter{Getting Started with LibTomMath}
\section{Building Programs}
In order to use LibTomMath you must include ``tommath.h'' and link against the appropriate library file (typically
libtommath.a). There is no library initialization required and the entire library is thread safe.
\section{Return Codes}
There are three possible return codes a function may return.
\index{MP\_OKAY}\index{MP\_YES}\index{MP\_NO}\index{MP\_VAL}\index{MP\_MEM}
\begin{figure}[here!]
\begin{center}
\begin{small}
\begin{tabular}{|l|l|}
\hline \textbf{Code} & \textbf{Meaning} \\
\hline MP\_OKAY & The function succeeded. \\
\hline MP\_VAL & The function input was invalid. \\
\hline MP\_MEM & Heap memory exhausted. \\
\hline &\\
\hline MP\_YES & Response is yes. \\
\hline MP\_NO & Response is no. \\
\hline
\end{tabular}
\end{small}
\end{center}
\caption{Return Codes}
\end{figure}
The last two codes listed are not actually ``return'ed'' by a function. They are placed in an integer (the caller must
provide the address of an integer it can store to) which the caller can access. To convert one of the three return codes
to a string use the following function.
\index{mp\_error\_to\_string}
\begin{alltt}
char *mp_error_to_string(int code);
\end{alltt}
This will return a pointer to a string which describes the given error code. It will not work for the return codes
MP\_YES and MP\_NO.
\section{Data Types}
The basic ``multiple precision integer'' type is known as the ``mp\_int'' within LibTomMath. This data type is used to
organize all of the data required to manipulate the integer it represents. Within LibTomMath it has been prototyped
as the following.
\index{mp\_int}
\begin{alltt}
typedef struct \{
int used, alloc, sign;
mp_digit *dp;
\} mp_int;
\end{alltt}
Where ``mp\_digit'' is a data type that represents individual digits of the integer. By default, an mp\_digit is the
ISO C ``unsigned long'' data type and each digit is $28-$bits long. The mp\_digit type can be configured to suit other
platforms by defining the appropriate macros.
All LTM functions that use the mp\_int type will expect a pointer to mp\_int structure. You must allocate memory to
hold the structure itself by yourself (whether off stack or heap it doesn't matter). The very first thing that must be
done to use an mp\_int is that it must be initialized.
\section{Function Organization}
The arithmetic functions of the library are all organized to have the same style prototype. That is source operands
are passed on the left and the destination is on the right. For instance,
\begin{alltt}
mp_add(&a, &b, &c); /* c = a + b */
mp_mul(&a, &a, &c); /* c = a * a */
mp_div(&a, &b, &c, &d); /* c = [a/b], d = a mod b */
\end{alltt}
Another feature of the way the functions have been implemented is that source operands can be destination operands as well.
For instance,
\begin{alltt}
mp_add(&a, &b, &b); /* b = a + b */
mp_div(&a, &b, &a, &c); /* a = [a/b], c = a mod b */
\end{alltt}
This allows operands to be re-used which can make programming simpler.
\section{Initialization}
\subsection{Single Initialization}
A single mp\_int can be initialized with the ``mp\_init'' function.
\index{mp\_init}
\begin{alltt}
int mp_init (mp_int * a);
\end{alltt}
This function expects a pointer to an mp\_int structure and will initialize the members of the structure so the mp\_int
represents the default integer which is zero. If the functions returns MP\_OKAY then the mp\_int is ready to be used
by the other LibTomMath functions.
\begin{small} \begin{alltt}
int main(void)
\{
mp_int number;
int result;
if ((result = mp_init(&number)) != MP_OKAY) \{
printf("Error initializing the number. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
/* use the number */
return EXIT_SUCCESS;
\}
\end{alltt} \end{small}
\subsection{Single Free}
When you are finished with an mp\_int it is ideal to return the heap it used back to the system. The following function
provides this functionality.
\index{mp\_clear}
\begin{alltt}
void mp_clear (mp_int * a);
\end{alltt}
The function expects a pointer to a previously initialized mp\_int structure and frees the heap it uses. It sets the
pointer\footnote{The ``dp'' member.} within the mp\_int to \textbf{NULL} which is used to prevent double free situations.
Is is legal to call mp\_clear() twice on the same mp\_int in a row.
\begin{small} \begin{alltt}
int main(void)
\{
mp_int number;
int result;
if ((result = mp_init(&number)) != MP_OKAY) \{
printf("Error initializing the number. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
/* use the number */
/* We're done with it. */
mp_clear(&number);
return EXIT_SUCCESS;
\}
\end{alltt} \end{small}
\subsection{Multiple Initializations}
Certain algorithms require more than one large integer. In these instances it is ideal to initialize all of the mp\_int
variables in an ``all or nothing'' fashion. That is, they are either all initialized successfully or they are all
not initialized.
The mp\_init\_multi() function provides this functionality.
\index{mp\_init\_multi} \index{mp\_clear\_multi}
\begin{alltt}
int mp_init_multi(mp_int *mp, ...);
\end{alltt}
It accepts a \textbf{NULL} terminated list of pointers to mp\_int structures. It will attempt to initialize them all
at once. If the function returns MP\_OKAY then all of the mp\_int variables are ready to use, otherwise none of them
are available for use. A complementary mp\_clear\_multi() function allows multiple mp\_int variables to be free'd
from the heap at the same time.
\begin{small} \begin{alltt}
int main(void)
\{
mp_int num1, num2, num3;
int result;
if ((result = mp_init_multi(&num1,
&num2,
&num3, NULL)) != MP\_OKAY) \{
printf("Error initializing the numbers. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
/* use the numbers */
/* We're done with them. */
mp_clear_multi(&num1, &num2, &num3, NULL);
return EXIT_SUCCESS;
\}
\end{alltt} \end{small}
\subsection{Other Initializers}
To initialized and make a copy of an mp\_int the mp\_init\_copy() function has been provided.
\index{mp\_init\_copy}
\begin{alltt}
int mp_init_copy (mp_int * a, mp_int * b);
\end{alltt}
This function will initialize $a$ and make it a copy of $b$ if all goes well.
\begin{small} \begin{alltt}
int main(void)
\{
mp_int num1, num2;
int result;
/* initialize and do work on num1 ... */
/* We want a copy of num1 in num2 now */
if ((result = mp_init_copy(&num2, &num1)) != MP_OKAY) \{
printf("Error initializing the copy. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
/* now num2 is ready and contains a copy of num1 */
/* We're done with them. */
mp_clear_multi(&num1, &num2, NULL);
return EXIT_SUCCESS;
\}
\end{alltt} \end{small}
Another less common initializer is mp\_init\_size() which allows the user to initialize an mp\_int with a given
default number of digits. By default, all initializers allocate \textbf{MP\_PREC} digits. This function lets
you override this behaviour.
\index{mp\_init\_size}
\begin{alltt}
int mp_init_size (mp_int * a, int size);
\end{alltt}
The $size$ parameter must be greater than zero. If the function succeeds the mp\_int $a$ will be initialized
to have $size$ digits (which are all initially zero).
\begin{small} \begin{alltt}
int main(void)
\{
mp_int number;
int result;
/* we need a 60-digit number */
if ((result = mp_init_size(&number, 60)) != MP_OKAY) \{
printf("Error initializing the number. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
/* use the number */
return EXIT_SUCCESS;
\}
\end{alltt} \end{small}
\section{Maintenance Functions}
\subsection{Reducing Memory Usage}
When an mp\_int is in a state where it won't be changed again\footnote{A Diffie-Hellman modulus for instance.} excess
digits can be removed to return memory to the heap with the mp\_shrink() function.
\index{mp\_shrink}
\begin{alltt}
int mp_shrink (mp_int * a);
\end{alltt}
This will remove excess digits of the mp\_int $a$. If the operation fails the mp\_int should be intact without the
excess digits being removed. Note that you can use a shrunk mp\_int in further computations, however, such operations
will require heap operations which can be slow. It is not ideal to shrink mp\_int variables that you will further
modify in the system (unless you are seriously low on memory).
\begin{small} \begin{alltt}
int main(void)
\{
mp_int number;
int result;
if ((result = mp_init(&number)) != MP_OKAY) \{
printf("Error initializing the number. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
/* use the number [e.g. pre-computation] */
/* We're done with it for now. */
if ((result = mp_shrink(&number)) != MP_OKAY) \{
printf("Error shrinking the number. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
/* use it .... */
/* we're done with it. */
mp_clear(&number);
return EXIT_SUCCESS;
\}
\end{alltt} \end{small}
\subsection{Adding additional digits}
Within the mp\_int structure are two parameters which control the limitations of the array of digits that represent
the integer the mp\_int is meant to equal. The \textit{used} parameter dictates how many digits are significant, that is,
contribute to the value of the mp\_int. The \textit{alloc} parameter dictates how many digits are currently available in
the array. If you need to perform an operation that requires more digits you will have to mp\_grow() the mp\_int to
your desired size.
\index{mp\_grow}
\begin{alltt}
int mp_grow (mp_int * a, int size);
\end{alltt}
This will grow the array of digits of $a$ to $size$. If the \textit{alloc} parameter is already bigger than
$size$ the function will not do anything.
\begin{small} \begin{alltt}
int main(void)
\{
mp_int number;
int result;
if ((result = mp_init(&number)) != MP_OKAY) \{
printf("Error initializing the number. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
/* use the number */
/* We need to add 20 digits to the number */
if ((result = mp_grow(&number, number.alloc + 20)) != MP_OKAY) \{
printf("Error growing the number. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
/* use the number */
/* we're done with it. */
mp_clear(&number);
return EXIT_SUCCESS;
\}
\end{alltt} \end{small}
\chapter{Basic Operations}
\section{Small Constants}
Setting mp\_ints to small constants is a relatively common operation. To accomodate these instances there are two
small constant assignment functions. The first function is used to set a single digit constant while the second sets
an ISO C style ``unsigned long'' constant. The reason for both functions is efficiency. Setting a single digit is quick but the
domain of a digit can change (it's always at least $0 \ldots 127$).
\subsection{Single Digit}
Setting a single digit can be accomplished with the following function.
\index{mp\_set}
\begin{alltt}
void mp_set (mp_int * a, mp_digit b);
\end{alltt}
This will zero the contents of $a$ and make it represent an integer equal to the value of $b$. Note that this
function has a return type of \textbf{void}. It cannot cause an error so it is safe to assume the function
succeeded.
\begin{small} \begin{alltt}
int main(void)
\{
mp_int number;
int result;
if ((result = mp_init(&number)) != MP_OKAY) \{
printf("Error initializing the number. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
/* set the number to 5 */
mp_set(&number, 5);
/* we're done with it. */
mp_clear(&number);
return EXIT_SUCCESS;
\}
\end{alltt} \end{small}
\subsection{Long Constants}
To set a constant that is the size of an ISO C ``unsigned long'' and larger than a single digit the following function
can be used.
\index{mp\_set\_int}
\begin{alltt}
int mp_set_int (mp_int * a, unsigned long b);
\end{alltt}
This will assign the value of the 32-bit variable $b$ to the mp\_int $a$. Unlike mp\_set() this function will always
accept a 32-bit input regardless of the size of a single digit. However, since the value may span several digits
this function can fail if it runs out of heap memory.
To get the ``unsigned long'' copy of an mp\_int the following function can be used.
\index{mp\_get\_int}
\begin{alltt}
unsigned long mp_get_int (mp_int * a);
\end{alltt}
This will return the 32 least significant bits of the mp\_int $a$.
\begin{small} \begin{alltt}
int main(void)
\{
mp_int number;
int result;
if ((result = mp_init(&number)) != MP_OKAY) \{
printf("Error initializing the number. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
/* set the number to 654321 (note this is bigger than 127) */
if ((result = mp_set_int(&number, 654321)) != MP_OKAY) \{
printf("Error setting the value of the number. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
printf("number == \%lu", mp_get_int(&number));
/* we're done with it. */
mp_clear(&number);
return EXIT_SUCCESS;
\}
\end{alltt} \end{small}
This should output the following if the program succeeds.
\begin{alltt}
number == 654321
\end{alltt}
\subsection{Initialize and Setting Constants}
To both initialize and set small constants the following two functions are available.
\index{mp\_init\_set} \index{mp\_init\_set\_int}
\begin{alltt}
int mp_init_set (mp_int * a, mp_digit b);
int mp_init_set_int (mp_int * a, unsigned long b);
\end{alltt}
Both functions work like the previous counterparts except they first mp\_init $a$ before setting the values.
\begin{alltt}
int main(void)
\{
mp_int number1, number2;
int result;
/* initialize and set a single digit */
if ((result = mp_init_set(&number1, 100)) != MP_OKAY) \{
printf("Error setting number1: \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
/* initialize and set a long */
if ((result = mp_init_set_int(&number2, 1023)) != MP_OKAY) \{
printf("Error setting number2: \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
/* display */
printf("Number1, Number2 == \%lu, \%lu",
mp_get_int(&number1), mp_get_int(&number2));
/* clear */
mp_clear_multi(&number1, &number2, NULL);
return EXIT_SUCCESS;
\}
\end{alltt}
If this program succeeds it shall output.
\begin{alltt}
Number1, Number2 == 100, 1023
\end{alltt}
\section{Comparisons}
Comparisons in LibTomMath are always performed in a ``left to right'' fashion. There are three possible return codes
for any comparison.
\index{MP\_GT} \index{MP\_EQ} \index{MP\_LT}
\begin{figure}[here]
\begin{center}
\begin{tabular}{|c|c|}
\hline \textbf{Result Code} & \textbf{Meaning} \\
\hline MP\_GT & $a > b$ \\
\hline MP\_EQ & $a = b$ \\
\hline MP\_LT & $a < b$ \\
\hline
\end{tabular}
\end{center}
\caption{Comparison Codes for $a, b$}
\label{fig:CMP}
\end{figure}
In figure \ref{fig:CMP} two integers $a$ and $b$ are being compared. In this case $a$ is said to be ``to the left'' of
$b$.
\subsection{Unsigned comparison}
An unsigned comparison considers only the digits themselves and not the associated \textit{sign} flag of the
mp\_int structures. This is analogous to an absolute comparison. The function mp\_cmp\_mag() will compare two
mp\_int variables based on their digits only.
\index{mp\_cmp\_mag}
\begin{alltt}
int mp_cmp_mag(mp_int * a, mp_int * b);
\end{alltt}
This will compare $a$ to $b$ placing $a$ to the left of $b$. This function cannot fail and will return one of the
three compare codes listed in figure \ref{fig:CMP}.
\begin{small} \begin{alltt}
int main(void)
\{
mp_int number1, number2;
int result;
if ((result = mp_init_multi(&number1, &number2, NULL)) != MP_OKAY) \{
printf("Error initializing the numbers. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
/* set the number1 to 5 */
mp_set(&number1, 5);
/* set the number2 to -6 */
mp_set(&number2, 6);
if ((result = mp_neg(&number2, &number2)) != MP_OKAY) \{
printf("Error negating number2. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
switch(mp_cmp_mag(&number1, &number2)) \{
case MP_GT: printf("|number1| > |number2|"); break;
case MP_EQ: printf("|number1| = |number2|"); break;
case MP_LT: printf("|number1| < |number2|"); break;
\}
/* we're done with it. */
mp_clear_multi(&number1, &number2, NULL);
return EXIT_SUCCESS;
\}
\end{alltt} \end{small}
If this program\footnote{This function uses the mp\_neg() function which is discussed in section \ref{sec:NEG}.} completes
successfully it should print the following.
\begin{alltt}
|number1| < |number2|
\end{alltt}
This is because $\vert -6 \vert = 6$ and obviously $5 < 6$.
\subsection{Signed comparison}
To compare two mp\_int variables based on their signed value the mp\_cmp() function is provided.
\index{mp\_cmp}
\begin{alltt}
int mp_cmp(mp_int * a, mp_int * b);
\end{alltt}
This will compare $a$ to the left of $b$. It will first compare the signs of the two mp\_int variables. If they
differ it will return immediately based on their signs. If the signs are equal then it will compare the digits
individually. This function will return one of the compare conditions codes listed in figure \ref{fig:CMP}.
\begin{small} \begin{alltt}
int main(void)
\{
mp_int number1, number2;
int result;
if ((result = mp_init_multi(&number1, &number2, NULL)) != MP_OKAY) \{
printf("Error initializing the numbers. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
/* set the number1 to 5 */
mp_set(&number1, 5);
/* set the number2 to -6 */
mp_set(&number2, 6);
if ((result = mp_neg(&number2, &number2)) != MP_OKAY) \{
printf("Error negating number2. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
switch(mp_cmp(&number1, &number2)) \{
case MP_GT: printf("number1 > number2"); break;
case MP_EQ: printf("number1 = number2"); break;
case MP_LT: printf("number1 < number2"); break;
\}
/* we're done with it. */
mp_clear_multi(&number1, &number2, NULL);
return EXIT_SUCCESS;
\}
\end{alltt} \end{small}
If this program\footnote{This function uses the mp\_neg() function which is discussed in section \ref{sec:NEG}.} completes
successfully it should print the following.
\begin{alltt}
number1 > number2
\end{alltt}
\subsection{Single Digit}
To compare a single digit against an mp\_int the following function has been provided.
\index{mp\_cmp\_d}
\begin{alltt}
int mp_cmp_d(mp_int * a, mp_digit b);
\end{alltt}
This will compare $a$ to the left of $b$ using a signed comparison. Note that it will always treat $b$ as
positive. This function is rather handy when you have to compare against small values such as $1$ (which often
comes up in cryptography). The function cannot fail and will return one of the tree compare condition codes
listed in figure \ref{fig:CMP}.
\begin{small} \begin{alltt}
int main(void)
\{
mp_int number;
int result;
if ((result = mp_init(&number)) != MP_OKAY) \{
printf("Error initializing the number. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}
/* set the number to 5 */
mp_set(&number, 5);
switch(mp_cmp_d(&number, 7)) \{
case MP_GT: printf("number > 7"); break;
case MP_EQ: printf("number = 7"); break;
case MP_LT: printf("number < 7"); break;
\}
/* we're done with it. */
mp_clear(&number);
return EXIT_SUCCESS;
\}
\end{alltt} \end{small}
If this program functions properly it will print out the following.
\begin{alltt}
number < 7
\end{alltt}
\section{Logical Operations}
Logical operations are operations that can be performed either with simple shifts or boolean operators such as
AND, XOR and OR directly. These operations are very quick.
\subsection{Multiplication by two}
Multiplications and divisions by any power of two can be performed with quick logical shifts either left or
right depending on the operation.
When multiplying or dividing by two a special case routine can be used which are as follows.
\index{mp\_mul\_2} \index{mp\_div\_2}
\begin{alltt}
int mp_mul_2(mp_int * a, mp_int * b);
int mp_div_2(mp_int * a, mp_int * b);
\end{alltt}
The former will assign twice $a$ to $b$ while the latter will assign half $a$ to $b$. These functions are fast
since the shift counts and maskes are hardcoded into the routines.
\begin{small} \begin{alltt}
int main(void)
\{
mp_int number;
int result;
if ((result = mp_init(&number)) != MP_OKAY) \{
printf("Error initializing the number. \%s",
mp_error_to_string(result));
return EXIT_FAILURE;
\}