new polarssl
[syren.git] / src / libpolarssl / bignum.c
blob2432d9d24a41e907c72a2796525c65470561ac3b
1 /*
2 * Multi-precision integer library
4 * Copyright (C) 2006-2014, Brainspark B.V.
6 * This file is part of PolarSSL (http://www.polarssl.org)
7 * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
9 * All rights reserved.
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, write to the Free Software Foundation, Inc.,
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * This MPI implementation is based on:
28 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
29 * http://www.stillhq.com/extracted/gnupg-api/mpi/
30 * http://math.libtomcrypt.com/files/tommath.pdf
33 #if !defined(POLARSSL_CONFIG_FILE)
34 #include "config.h"
35 #else
36 #include POLARSSL_CONFIG_FILE
37 #endif
39 #if defined(POLARSSL_BIGNUM_C)
41 #include "bignum.h"
42 #include "bn_mul.h"
44 #if defined(POLARSSL_PLATFORM_C)
45 #include "platform.h"
46 #else
47 #define polarssl_printf printf
48 #define polarssl_malloc malloc
49 #define polarssl_free free
50 #endif
52 #include <stdlib.h>
54 #define ciL (sizeof(t_uint)) /* chars in limb */
55 #define biL (ciL << 3) /* bits in limb */
56 #define biH (ciL << 2) /* half limb size */
59 * Convert between bits/chars and number of limbs
61 #define BITS_TO_LIMBS(i) (((i) + biL - 1) / biL)
62 #define CHARS_TO_LIMBS(i) (((i) + ciL - 1) / ciL)
65 * Initialize one MPI
67 void mpi_init( mpi *X )
69 if( X == NULL )
70 return;
72 X->s = 1;
73 X->n = 0;
74 X->p = NULL;
78 * Unallocate one MPI
80 void mpi_free( mpi *X )
82 if( X == NULL )
83 return;
85 if( X->p != NULL )
87 memset( X->p, 0, X->n * ciL );
88 polarssl_free( X->p );
91 X->s = 1;
92 X->n = 0;
93 X->p = NULL;
97 * Enlarge to the specified number of limbs
99 int mpi_grow( mpi *X, size_t nblimbs )
101 t_uint *p;
103 if( nblimbs > POLARSSL_MPI_MAX_LIMBS )
104 return( POLARSSL_ERR_MPI_MALLOC_FAILED );
106 if( X->n < nblimbs )
108 if( ( p = (t_uint *) polarssl_malloc( nblimbs * ciL ) ) == NULL )
109 return( POLARSSL_ERR_MPI_MALLOC_FAILED );
111 memset( p, 0, nblimbs * ciL );
113 if( X->p != NULL )
115 memcpy( p, X->p, X->n * ciL );
116 memset( X->p, 0, X->n * ciL );
117 polarssl_free( X->p );
120 X->n = nblimbs;
121 X->p = p;
124 return( 0 );
128 * Resize down as much as possible,
129 * while keeping at least the specified number of limbs
131 int mpi_shrink( mpi *X, size_t nblimbs )
133 t_uint *p;
134 size_t i;
136 /* Actually resize up in this case */
137 if( X->n <= nblimbs )
138 return( mpi_grow( X, nblimbs ) );
140 for( i = X->n - 1; i > 0; i-- )
141 if( X->p[i] != 0 )
142 break;
143 i++;
145 if( i < nblimbs )
146 i = nblimbs;
148 if( ( p = (t_uint *) polarssl_malloc( i * ciL ) ) == NULL )
149 return( POLARSSL_ERR_MPI_MALLOC_FAILED );
151 memset( p, 0, i * ciL );
153 if( X->p != NULL )
155 memcpy( p, X->p, i * ciL );
156 memset( X->p, 0, X->n * ciL );
157 polarssl_free( X->p );
160 X->n = i;
161 X->p = p;
163 return( 0 );
167 * Copy the contents of Y into X
169 int mpi_copy( mpi *X, const mpi *Y )
171 int ret;
172 size_t i;
174 if( X == Y )
175 return( 0 );
177 if( Y->p == NULL )
179 mpi_free( X );
180 return( 0 );
183 for( i = Y->n - 1; i > 0; i-- )
184 if( Y->p[i] != 0 )
185 break;
186 i++;
188 X->s = Y->s;
190 MPI_CHK( mpi_grow( X, i ) );
192 memset( X->p, 0, X->n * ciL );
193 memcpy( X->p, Y->p, i * ciL );
195 cleanup:
197 return( ret );
201 * Swap the contents of X and Y
203 void mpi_swap( mpi *X, mpi *Y )
205 mpi T;
207 memcpy( &T, X, sizeof( mpi ) );
208 memcpy( X, Y, sizeof( mpi ) );
209 memcpy( Y, &T, sizeof( mpi ) );
213 * Conditionally assign X = Y, without leaking information
214 * about whether the assignment was made or not.
215 * (Leaking information about the respective sizes of X and Y is ok however.)
217 int mpi_safe_cond_assign( mpi *X, const mpi *Y, unsigned char assign )
219 int ret = 0;
220 size_t i;
222 /* make sure assign is 0 or 1 */
223 assign = ( assign != 0 );
225 MPI_CHK( mpi_grow( X, Y->n ) );
227 X->s = X->s * (1 - assign) + Y->s * assign;
229 for( i = 0; i < Y->n; i++ )
230 X->p[i] = X->p[i] * (1 - assign) + Y->p[i] * assign;
232 for( ; i < X->n; i++ )
233 X->p[i] *= (1 - assign);
235 cleanup:
236 return( ret );
240 * Conditionally swap X and Y, without leaking information
241 * about whether the swap was made or not.
242 * Here it is not ok to simply swap the pointers, which whould lead to
243 * different memory access patterns when X and Y are used afterwards.
245 int mpi_safe_cond_swap( mpi *X, mpi *Y, unsigned char swap )
247 int ret, s;
248 size_t i;
249 t_uint tmp;
251 if( X == Y )
252 return( 0 );
254 /* make sure swap is 0 or 1 */
255 swap = ( swap != 0 );
257 MPI_CHK( mpi_grow( X, Y->n ) );
258 MPI_CHK( mpi_grow( Y, X->n ) );
260 s = X->s;
261 X->s = X->s * (1 - swap) + Y->s * swap;
262 Y->s = Y->s * (1 - swap) + s * swap;
265 for( i = 0; i < X->n; i++ )
267 tmp = X->p[i];
268 X->p[i] = X->p[i] * (1 - swap) + Y->p[i] * swap;
269 Y->p[i] = Y->p[i] * (1 - swap) + tmp * swap;
272 cleanup:
273 return( ret );
277 * Set value from integer
279 int mpi_lset( mpi *X, t_sint z )
281 int ret;
283 MPI_CHK( mpi_grow( X, 1 ) );
284 memset( X->p, 0, X->n * ciL );
286 X->p[0] = ( z < 0 ) ? -z : z;
287 X->s = ( z < 0 ) ? -1 : 1;
289 cleanup:
291 return( ret );
295 * Get a specific bit
297 int mpi_get_bit( const mpi *X, size_t pos )
299 if( X->n * biL <= pos )
300 return( 0 );
302 return ( X->p[pos / biL] >> ( pos % biL ) ) & 0x01;
306 * Set a bit to a specific value of 0 or 1
308 int mpi_set_bit( mpi *X, size_t pos, unsigned char val )
310 int ret = 0;
311 size_t off = pos / biL;
312 size_t idx = pos % biL;
314 if( val != 0 && val != 1 )
315 return POLARSSL_ERR_MPI_BAD_INPUT_DATA;
317 if( X->n * biL <= pos )
319 if( val == 0 )
320 return ( 0 );
322 MPI_CHK( mpi_grow( X, off + 1 ) );
325 X->p[off] &= ~( (t_uint) 0x01 << idx );
326 X->p[off] |= (t_uint) val << idx;
328 cleanup:
330 return( ret );
334 * Return the number of least significant bits
336 size_t mpi_lsb( const mpi *X )
338 size_t i, j, count = 0;
340 for( i = 0; i < X->n; i++ )
341 for( j = 0; j < biL; j++, count++ )
342 if( ( ( X->p[i] >> j ) & 1 ) != 0 )
343 return( count );
345 return( 0 );
349 * Return the number of most significant bits
351 size_t mpi_msb( const mpi *X )
353 size_t i, j;
355 for( i = X->n - 1; i > 0; i-- )
356 if( X->p[i] != 0 )
357 break;
359 for( j = biL; j > 0; j-- )
360 if( ( ( X->p[i] >> ( j - 1 ) ) & 1 ) != 0 )
361 break;
363 return( ( i * biL ) + j );
367 * Return the total size in bytes
369 size_t mpi_size( const mpi *X )
371 return( ( mpi_msb( X ) + 7 ) >> 3 );
375 * Convert an ASCII character to digit value
377 static int mpi_get_digit( t_uint *d, int radix, char c )
379 *d = 255;
381 if( c >= 0x30 && c <= 0x39 ) *d = c - 0x30;
382 if( c >= 0x41 && c <= 0x46 ) *d = c - 0x37;
383 if( c >= 0x61 && c <= 0x66 ) *d = c - 0x57;
385 if( *d >= (t_uint) radix )
386 return( POLARSSL_ERR_MPI_INVALID_CHARACTER );
388 return( 0 );
392 * Import from an ASCII string
394 int mpi_read_string( mpi *X, int radix, const char *s )
396 int ret;
397 size_t i, j, slen, n;
398 t_uint d;
399 mpi T;
401 if( radix < 2 || radix > 16 )
402 return( POLARSSL_ERR_MPI_BAD_INPUT_DATA );
404 mpi_init( &T );
406 slen = strlen( s );
408 if( radix == 16 )
410 n = BITS_TO_LIMBS( slen << 2 );
412 MPI_CHK( mpi_grow( X, n ) );
413 MPI_CHK( mpi_lset( X, 0 ) );
415 for( i = slen, j = 0; i > 0; i--, j++ )
417 if( i == 1 && s[i - 1] == '-' )
419 X->s = -1;
420 break;
423 MPI_CHK( mpi_get_digit( &d, radix, s[i - 1] ) );
424 X->p[j / (2 * ciL)] |= d << ( (j % (2 * ciL)) << 2 );
427 else
429 MPI_CHK( mpi_lset( X, 0 ) );
431 for( i = 0; i < slen; i++ )
433 if( i == 0 && s[i] == '-' )
435 X->s = -1;
436 continue;
439 MPI_CHK( mpi_get_digit( &d, radix, s[i] ) );
440 MPI_CHK( mpi_mul_int( &T, X, radix ) );
442 if( X->s == 1 )
444 MPI_CHK( mpi_add_int( X, &T, d ) );
446 else
448 MPI_CHK( mpi_sub_int( X, &T, d ) );
453 cleanup:
455 mpi_free( &T );
457 return( ret );
461 * Helper to write the digits high-order first
463 static int mpi_write_hlp( mpi *X, int radix, char **p )
465 int ret;
466 t_uint r;
468 if( radix < 2 || radix > 16 )
469 return( POLARSSL_ERR_MPI_BAD_INPUT_DATA );
471 MPI_CHK( mpi_mod_int( &r, X, radix ) );
472 MPI_CHK( mpi_div_int( X, NULL, X, radix ) );
474 if( mpi_cmp_int( X, 0 ) != 0 )
475 MPI_CHK( mpi_write_hlp( X, radix, p ) );
477 if( r < 10 )
478 *(*p)++ = (char)( r + 0x30 );
479 else
480 *(*p)++ = (char)( r + 0x37 );
482 cleanup:
484 return( ret );
488 * Export into an ASCII string
490 int mpi_write_string( const mpi *X, int radix, char *s, size_t *slen )
492 int ret = 0;
493 size_t n;
494 char *p;
495 mpi T;
497 if( radix < 2 || radix > 16 )
498 return( POLARSSL_ERR_MPI_BAD_INPUT_DATA );
500 n = mpi_msb( X );
501 if( radix >= 4 ) n >>= 1;
502 if( radix >= 16 ) n >>= 1;
503 n += 3;
505 if( *slen < n )
507 *slen = n;
508 return( POLARSSL_ERR_MPI_BUFFER_TOO_SMALL );
511 p = s;
512 mpi_init( &T );
514 if( X->s == -1 )
515 *p++ = '-';
517 if( radix == 16 )
519 int c;
520 size_t i, j, k;
522 for( i = X->n, k = 0; i > 0; i-- )
524 for( j = ciL; j > 0; j-- )
526 c = ( X->p[i - 1] >> ( ( j - 1 ) << 3) ) & 0xFF;
528 if( c == 0 && k == 0 && ( i + j + 3 ) != 0 )
529 continue;
531 *(p++) = "0123456789ABCDEF" [c / 16];
532 *(p++) = "0123456789ABCDEF" [c % 16];
533 k = 1;
537 else
539 MPI_CHK( mpi_copy( &T, X ) );
541 if( T.s == -1 )
542 T.s = 1;
544 MPI_CHK( mpi_write_hlp( &T, radix, &p ) );
547 *p++ = '\0';
548 *slen = p - s;
550 cleanup:
552 mpi_free( &T );
554 return( ret );
557 #if defined(POLARSSL_FS_IO)
559 * Read X from an opened file
561 int mpi_read_file( mpi *X, int radix, FILE *fin )
563 t_uint d;
564 size_t slen;
565 char *p;
567 * Buffer should have space for (short) label and decimal formatted MPI,
568 * newline characters and '\0'
570 char s[ POLARSSL_MPI_RW_BUFFER_SIZE ];
572 memset( s, 0, sizeof( s ) );
573 if( fgets( s, sizeof( s ) - 1, fin ) == NULL )
574 return( POLARSSL_ERR_MPI_FILE_IO_ERROR );
576 slen = strlen( s );
577 if( slen == sizeof( s ) - 2 )
578 return( POLARSSL_ERR_MPI_BUFFER_TOO_SMALL );
580 if( s[slen - 1] == '\n' ) { slen--; s[slen] = '\0'; }
581 if( s[slen - 1] == '\r' ) { slen--; s[slen] = '\0'; }
583 p = s + slen;
584 while( --p >= s )
585 if( mpi_get_digit( &d, radix, *p ) != 0 )
586 break;
588 return( mpi_read_string( X, radix, p + 1 ) );
592 * Write X into an opened file (or stdout if fout == NULL)
594 int mpi_write_file( const char *p, const mpi *X, int radix, FILE *fout )
596 int ret;
597 size_t n, slen, plen;
599 * Buffer should have space for (short) label and decimal formatted MPI,
600 * newline characters and '\0'
602 char s[ POLARSSL_MPI_RW_BUFFER_SIZE ];
604 n = sizeof( s );
605 memset( s, 0, n );
606 n -= 2;
608 MPI_CHK( mpi_write_string( X, radix, s, (size_t *) &n ) );
610 if( p == NULL ) p = "";
612 plen = strlen( p );
613 slen = strlen( s );
614 s[slen++] = '\r';
615 s[slen++] = '\n';
617 if( fout != NULL )
619 if( fwrite( p, 1, plen, fout ) != plen ||
620 fwrite( s, 1, slen, fout ) != slen )
621 return( POLARSSL_ERR_MPI_FILE_IO_ERROR );
623 else
624 polarssl_printf( "%s%s", p, s );
626 cleanup:
628 return( ret );
630 #endif /* POLARSSL_FS_IO */
633 * Import X from unsigned binary data, big endian
635 int mpi_read_binary( mpi *X, const unsigned char *buf, size_t buflen )
637 int ret;
638 size_t i, j, n;
640 for( n = 0; n < buflen; n++ )
641 if( buf[n] != 0 )
642 break;
644 MPI_CHK( mpi_grow( X, CHARS_TO_LIMBS( buflen - n ) ) );
645 MPI_CHK( mpi_lset( X, 0 ) );
647 for( i = buflen, j = 0; i > n; i--, j++ )
648 X->p[j / ciL] |= ((t_uint) buf[i - 1]) << ((j % ciL) << 3);
650 cleanup:
652 return( ret );
656 * Export X into unsigned binary data, big endian
658 int mpi_write_binary( const mpi *X, unsigned char *buf, size_t buflen )
660 size_t i, j, n;
662 n = mpi_size( X );
664 if( buflen < n )
665 return( POLARSSL_ERR_MPI_BUFFER_TOO_SMALL );
667 memset( buf, 0, buflen );
669 for( i = buflen - 1, j = 0; n > 0; i--, j++, n-- )
670 buf[i] = (unsigned char)( X->p[j / ciL] >> ((j % ciL) << 3) );
672 return( 0 );
676 * Left-shift: X <<= count
678 int mpi_shift_l( mpi *X, size_t count )
680 int ret;
681 size_t i, v0, t1;
682 t_uint r0 = 0, r1;
684 v0 = count / (biL );
685 t1 = count & (biL - 1);
687 i = mpi_msb( X ) + count;
689 if( X->n * biL < i )
690 MPI_CHK( mpi_grow( X, BITS_TO_LIMBS( i ) ) );
692 ret = 0;
695 * shift by count / limb_size
697 if( v0 > 0 )
699 for( i = X->n; i > v0; i-- )
700 X->p[i - 1] = X->p[i - v0 - 1];
702 for( ; i > 0; i-- )
703 X->p[i - 1] = 0;
707 * shift by count % limb_size
709 if( t1 > 0 )
711 for( i = v0; i < X->n; i++ )
713 r1 = X->p[i] >> (biL - t1);
714 X->p[i] <<= t1;
715 X->p[i] |= r0;
716 r0 = r1;
720 cleanup:
722 return( ret );
726 * Right-shift: X >>= count
728 int mpi_shift_r( mpi *X, size_t count )
730 size_t i, v0, v1;
731 t_uint r0 = 0, r1;
733 v0 = count / biL;
734 v1 = count & (biL - 1);
736 if( v0 > X->n || ( v0 == X->n && v1 > 0 ) )
737 return mpi_lset( X, 0 );
740 * shift by count / limb_size
742 if( v0 > 0 )
744 for( i = 0; i < X->n - v0; i++ )
745 X->p[i] = X->p[i + v0];
747 for( ; i < X->n; i++ )
748 X->p[i] = 0;
752 * shift by count % limb_size
754 if( v1 > 0 )
756 for( i = X->n; i > 0; i-- )
758 r1 = X->p[i - 1] << (biL - v1);
759 X->p[i - 1] >>= v1;
760 X->p[i - 1] |= r0;
761 r0 = r1;
765 return( 0 );
769 * Compare unsigned values
771 int mpi_cmp_abs( const mpi *X, const mpi *Y )
773 size_t i, j;
775 for( i = X->n; i > 0; i-- )
776 if( X->p[i - 1] != 0 )
777 break;
779 for( j = Y->n; j > 0; j-- )
780 if( Y->p[j - 1] != 0 )
781 break;
783 if( i == 0 && j == 0 )
784 return( 0 );
786 if( i > j ) return( 1 );
787 if( j > i ) return( -1 );
789 for( ; i > 0; i-- )
791 if( X->p[i - 1] > Y->p[i - 1] ) return( 1 );
792 if( X->p[i - 1] < Y->p[i - 1] ) return( -1 );
795 return( 0 );
799 * Compare signed values
801 int mpi_cmp_mpi( const mpi *X, const mpi *Y )
803 size_t i, j;
805 for( i = X->n; i > 0; i-- )
806 if( X->p[i - 1] != 0 )
807 break;
809 for( j = Y->n; j > 0; j-- )
810 if( Y->p[j - 1] != 0 )
811 break;
813 if( i == 0 && j == 0 )
814 return( 0 );
816 if( i > j ) return( X->s );
817 if( j > i ) return( -Y->s );
819 if( X->s > 0 && Y->s < 0 ) return( 1 );
820 if( Y->s > 0 && X->s < 0 ) return( -1 );
822 for( ; i > 0; i-- )
824 if( X->p[i - 1] > Y->p[i - 1] ) return( X->s );
825 if( X->p[i - 1] < Y->p[i - 1] ) return( -X->s );
828 return( 0 );
832 * Compare signed values
834 int mpi_cmp_int( const mpi *X, t_sint z )
836 mpi Y;
837 t_uint p[1];
839 *p = ( z < 0 ) ? -z : z;
840 Y.s = ( z < 0 ) ? -1 : 1;
841 Y.n = 1;
842 Y.p = p;
844 return( mpi_cmp_mpi( X, &Y ) );
848 * Unsigned addition: X = |A| + |B| (HAC 14.7)
850 int mpi_add_abs( mpi *X, const mpi *A, const mpi *B )
852 int ret;
853 size_t i, j;
854 t_uint *o, *p, c;
856 if( X == B )
858 const mpi *T = A; A = X; B = T;
861 if( X != A )
862 MPI_CHK( mpi_copy( X, A ) );
865 * X should always be positive as a result of unsigned additions.
867 X->s = 1;
869 for( j = B->n; j > 0; j-- )
870 if( B->p[j - 1] != 0 )
871 break;
873 MPI_CHK( mpi_grow( X, j ) );
875 o = B->p; p = X->p; c = 0;
877 for( i = 0; i < j; i++, o++, p++ )
879 *p += c; c = ( *p < c );
880 *p += *o; c += ( *p < *o );
883 while( c != 0 )
885 if( i >= X->n )
887 MPI_CHK( mpi_grow( X, i + 1 ) );
888 p = X->p + i;
891 *p += c; c = ( *p < c ); i++; p++;
894 cleanup:
896 return( ret );
900 * Helper for mpi subtraction
902 static void mpi_sub_hlp( size_t n, t_uint *s, t_uint *d )
904 size_t i;
905 t_uint c, z;
907 for( i = c = 0; i < n; i++, s++, d++ )
909 z = ( *d < c ); *d -= c;
910 c = ( *d < *s ) + z; *d -= *s;
913 while( c != 0 )
915 z = ( *d < c ); *d -= c;
916 c = z; i++; d++;
921 * Unsigned subtraction: X = |A| - |B| (HAC 14.9)
923 int mpi_sub_abs( mpi *X, const mpi *A, const mpi *B )
925 mpi TB;
926 int ret;
927 size_t n;
929 if( mpi_cmp_abs( A, B ) < 0 )
930 return( POLARSSL_ERR_MPI_NEGATIVE_VALUE );
932 mpi_init( &TB );
934 if( X == B )
936 MPI_CHK( mpi_copy( &TB, B ) );
937 B = &TB;
940 if( X != A )
941 MPI_CHK( mpi_copy( X, A ) );
944 * X should always be positive as a result of unsigned subtractions.
946 X->s = 1;
948 ret = 0;
950 for( n = B->n; n > 0; n-- )
951 if( B->p[n - 1] != 0 )
952 break;
954 mpi_sub_hlp( n, B->p, X->p );
956 cleanup:
958 mpi_free( &TB );
960 return( ret );
964 * Signed addition: X = A + B
966 int mpi_add_mpi( mpi *X, const mpi *A, const mpi *B )
968 int ret, s = A->s;
970 if( A->s * B->s < 0 )
972 if( mpi_cmp_abs( A, B ) >= 0 )
974 MPI_CHK( mpi_sub_abs( X, A, B ) );
975 X->s = s;
977 else
979 MPI_CHK( mpi_sub_abs( X, B, A ) );
980 X->s = -s;
983 else
985 MPI_CHK( mpi_add_abs( X, A, B ) );
986 X->s = s;
989 cleanup:
991 return( ret );
995 * Signed subtraction: X = A - B
997 int mpi_sub_mpi( mpi *X, const mpi *A, const mpi *B )
999 int ret, s = A->s;
1001 if( A->s * B->s > 0 )
1003 if( mpi_cmp_abs( A, B ) >= 0 )
1005 MPI_CHK( mpi_sub_abs( X, A, B ) );
1006 X->s = s;
1008 else
1010 MPI_CHK( mpi_sub_abs( X, B, A ) );
1011 X->s = -s;
1014 else
1016 MPI_CHK( mpi_add_abs( X, A, B ) );
1017 X->s = s;
1020 cleanup:
1022 return( ret );
1026 * Signed addition: X = A + b
1028 int mpi_add_int( mpi *X, const mpi *A, t_sint b )
1030 mpi _B;
1031 t_uint p[1];
1033 p[0] = ( b < 0 ) ? -b : b;
1034 _B.s = ( b < 0 ) ? -1 : 1;
1035 _B.n = 1;
1036 _B.p = p;
1038 return( mpi_add_mpi( X, A, &_B ) );
1042 * Signed subtraction: X = A - b
1044 int mpi_sub_int( mpi *X, const mpi *A, t_sint b )
1046 mpi _B;
1047 t_uint p[1];
1049 p[0] = ( b < 0 ) ? -b : b;
1050 _B.s = ( b < 0 ) ? -1 : 1;
1051 _B.n = 1;
1052 _B.p = p;
1054 return( mpi_sub_mpi( X, A, &_B ) );
1058 * Helper for mpi multiplication
1060 static
1061 #if defined(__APPLE__) && defined(__arm__)
1063 * Apple LLVM version 4.2 (clang-425.0.24) (based on LLVM 3.2svn)
1064 * appears to need this to prevent bad ARM code generation at -O3.
1066 __attribute__ ((noinline))
1067 #endif
1068 void mpi_mul_hlp( size_t i, t_uint *s, t_uint *d, t_uint b )
1070 t_uint c = 0, t = 0;
1072 #if defined(MULADDC_HUIT)
1073 for( ; i >= 8; i -= 8 )
1075 MULADDC_INIT
1076 MULADDC_HUIT
1077 MULADDC_STOP
1080 for( ; i > 0; i-- )
1082 MULADDC_INIT
1083 MULADDC_CORE
1084 MULADDC_STOP
1086 #else /* MULADDC_HUIT */
1087 for( ; i >= 16; i -= 16 )
1089 MULADDC_INIT
1090 MULADDC_CORE MULADDC_CORE
1091 MULADDC_CORE MULADDC_CORE
1092 MULADDC_CORE MULADDC_CORE
1093 MULADDC_CORE MULADDC_CORE
1095 MULADDC_CORE MULADDC_CORE
1096 MULADDC_CORE MULADDC_CORE
1097 MULADDC_CORE MULADDC_CORE
1098 MULADDC_CORE MULADDC_CORE
1099 MULADDC_STOP
1102 for( ; i >= 8; i -= 8 )
1104 MULADDC_INIT
1105 MULADDC_CORE MULADDC_CORE
1106 MULADDC_CORE MULADDC_CORE
1108 MULADDC_CORE MULADDC_CORE
1109 MULADDC_CORE MULADDC_CORE
1110 MULADDC_STOP
1113 for( ; i > 0; i-- )
1115 MULADDC_INIT
1116 MULADDC_CORE
1117 MULADDC_STOP
1119 #endif /* MULADDC_HUIT */
1121 t++;
1123 do {
1124 *d += c; c = ( *d < c ); d++;
1126 while( c != 0 );
1130 * Baseline multiplication: X = A * B (HAC 14.12)
1132 int mpi_mul_mpi( mpi *X, const mpi *A, const mpi *B )
1134 int ret;
1135 size_t i, j;
1136 mpi TA, TB;
1138 mpi_init( &TA ); mpi_init( &TB );
1140 if( X == A ) { MPI_CHK( mpi_copy( &TA, A ) ); A = &TA; }
1141 if( X == B ) { MPI_CHK( mpi_copy( &TB, B ) ); B = &TB; }
1143 for( i = A->n; i > 0; i-- )
1144 if( A->p[i - 1] != 0 )
1145 break;
1147 for( j = B->n; j > 0; j-- )
1148 if( B->p[j - 1] != 0 )
1149 break;
1151 MPI_CHK( mpi_grow( X, i + j ) );
1152 MPI_CHK( mpi_lset( X, 0 ) );
1154 for( i++; j > 0; j-- )
1155 mpi_mul_hlp( i - 1, A->p, X->p + j - 1, B->p[j - 1] );
1157 X->s = A->s * B->s;
1159 cleanup:
1161 mpi_free( &TB ); mpi_free( &TA );
1163 return( ret );
1167 * Baseline multiplication: X = A * b
1169 int mpi_mul_int( mpi *X, const mpi *A, t_sint b )
1171 mpi _B;
1172 t_uint p[1];
1174 _B.s = 1;
1175 _B.n = 1;
1176 _B.p = p;
1177 p[0] = b;
1179 return( mpi_mul_mpi( X, A, &_B ) );
1183 * Division by mpi: A = Q * B + R (HAC 14.20)
1185 int mpi_div_mpi( mpi *Q, mpi *R, const mpi *A, const mpi *B )
1187 int ret;
1188 size_t i, n, t, k;
1189 mpi X, Y, Z, T1, T2;
1191 if( mpi_cmp_int( B, 0 ) == 0 )
1192 return( POLARSSL_ERR_MPI_DIVISION_BY_ZERO );
1194 mpi_init( &X ); mpi_init( &Y ); mpi_init( &Z );
1195 mpi_init( &T1 ); mpi_init( &T2 );
1197 if( mpi_cmp_abs( A, B ) < 0 )
1199 if( Q != NULL ) MPI_CHK( mpi_lset( Q, 0 ) );
1200 if( R != NULL ) MPI_CHK( mpi_copy( R, A ) );
1201 return( 0 );
1204 MPI_CHK( mpi_copy( &X, A ) );
1205 MPI_CHK( mpi_copy( &Y, B ) );
1206 X.s = Y.s = 1;
1208 MPI_CHK( mpi_grow( &Z, A->n + 2 ) );
1209 MPI_CHK( mpi_lset( &Z, 0 ) );
1210 MPI_CHK( mpi_grow( &T1, 2 ) );
1211 MPI_CHK( mpi_grow( &T2, 3 ) );
1213 k = mpi_msb( &Y ) % biL;
1214 if( k < biL - 1 )
1216 k = biL - 1 - k;
1217 MPI_CHK( mpi_shift_l( &X, k ) );
1218 MPI_CHK( mpi_shift_l( &Y, k ) );
1220 else k = 0;
1222 n = X.n - 1;
1223 t = Y.n - 1;
1224 MPI_CHK( mpi_shift_l( &Y, biL * (n - t) ) );
1226 while( mpi_cmp_mpi( &X, &Y ) >= 0 )
1228 Z.p[n - t]++;
1229 MPI_CHK( mpi_sub_mpi( &X, &X, &Y ) );
1231 MPI_CHK( mpi_shift_r( &Y, biL * (n - t) ) );
1233 for( i = n; i > t ; i-- )
1235 if( X.p[i] >= Y.p[t] )
1236 Z.p[i - t - 1] = ~0;
1237 else
1240 * The version of Clang shipped by Apple with Mavericks around
1241 * 2014-03 can't handle 128-bit division properly. Disable
1242 * 128-bits division for this version. Let's be optimistic and
1243 * assume it'll be fixed in the next minor version (next
1244 * patchlevel is probably a bit too optimistic).
1246 #if defined(POLARSSL_HAVE_UDBL) && \
1247 ! ( defined(__x86_64__) && defined(__APPLE__) && \
1248 defined(__clang_major__) && __clang_major__ == 5 && \
1249 defined(__clang_minor__) && __clang_minor__ == 0 )
1250 t_udbl r;
1252 r = (t_udbl) X.p[i] << biL;
1253 r |= (t_udbl) X.p[i - 1];
1254 r /= Y.p[t];
1255 if( r > ((t_udbl) 1 << biL) - 1)
1256 r = ((t_udbl) 1 << biL) - 1;
1258 Z.p[i - t - 1] = (t_uint) r;
1259 #else
1261 * __udiv_qrnnd_c, from gmp/longlong.h
1263 t_uint q0, q1, r0, r1;
1264 t_uint d0, d1, d, m;
1266 d = Y.p[t];
1267 d0 = ( d << biH ) >> biH;
1268 d1 = ( d >> biH );
1270 q1 = X.p[i] / d1;
1271 r1 = X.p[i] - d1 * q1;
1272 r1 <<= biH;
1273 r1 |= ( X.p[i - 1] >> biH );
1275 m = q1 * d0;
1276 if( r1 < m )
1278 q1--, r1 += d;
1279 while( r1 >= d && r1 < m )
1280 q1--, r1 += d;
1282 r1 -= m;
1284 q0 = r1 / d1;
1285 r0 = r1 - d1 * q0;
1286 r0 <<= biH;
1287 r0 |= ( X.p[i - 1] << biH ) >> biH;
1289 m = q0 * d0;
1290 if( r0 < m )
1292 q0--, r0 += d;
1293 while( r0 >= d && r0 < m )
1294 q0--, r0 += d;
1296 r0 -= m;
1298 Z.p[i - t - 1] = ( q1 << biH ) | q0;
1299 #endif
1302 Z.p[i - t - 1]++;
1305 Z.p[i - t - 1]--;
1307 MPI_CHK( mpi_lset( &T1, 0 ) );
1308 T1.p[0] = (t < 1) ? 0 : Y.p[t - 1];
1309 T1.p[1] = Y.p[t];
1310 MPI_CHK( mpi_mul_int( &T1, &T1, Z.p[i - t - 1] ) );
1312 MPI_CHK( mpi_lset( &T2, 0 ) );
1313 T2.p[0] = (i < 2) ? 0 : X.p[i - 2];
1314 T2.p[1] = (i < 1) ? 0 : X.p[i - 1];
1315 T2.p[2] = X.p[i];
1317 while( mpi_cmp_mpi( &T1, &T2 ) > 0 );
1319 MPI_CHK( mpi_mul_int( &T1, &Y, Z.p[i - t - 1] ) );
1320 MPI_CHK( mpi_shift_l( &T1, biL * (i - t - 1) ) );
1321 MPI_CHK( mpi_sub_mpi( &X, &X, &T1 ) );
1323 if( mpi_cmp_int( &X, 0 ) < 0 )
1325 MPI_CHK( mpi_copy( &T1, &Y ) );
1326 MPI_CHK( mpi_shift_l( &T1, biL * (i - t - 1) ) );
1327 MPI_CHK( mpi_add_mpi( &X, &X, &T1 ) );
1328 Z.p[i - t - 1]--;
1332 if( Q != NULL )
1334 MPI_CHK( mpi_copy( Q, &Z ) );
1335 Q->s = A->s * B->s;
1338 if( R != NULL )
1340 MPI_CHK( mpi_shift_r( &X, k ) );
1341 X.s = A->s;
1342 MPI_CHK( mpi_copy( R, &X ) );
1344 if( mpi_cmp_int( R, 0 ) == 0 )
1345 R->s = 1;
1348 cleanup:
1350 mpi_free( &X ); mpi_free( &Y ); mpi_free( &Z );
1351 mpi_free( &T1 ); mpi_free( &T2 );
1353 return( ret );
1357 * Division by int: A = Q * b + R
1359 int mpi_div_int( mpi *Q, mpi *R, const mpi *A, t_sint b )
1361 mpi _B;
1362 t_uint p[1];
1364 p[0] = ( b < 0 ) ? -b : b;
1365 _B.s = ( b < 0 ) ? -1 : 1;
1366 _B.n = 1;
1367 _B.p = p;
1369 return( mpi_div_mpi( Q, R, A, &_B ) );
1373 * Modulo: R = A mod B
1375 int mpi_mod_mpi( mpi *R, const mpi *A, const mpi *B )
1377 int ret;
1379 if( mpi_cmp_int( B, 0 ) < 0 )
1380 return POLARSSL_ERR_MPI_NEGATIVE_VALUE;
1382 MPI_CHK( mpi_div_mpi( NULL, R, A, B ) );
1384 while( mpi_cmp_int( R, 0 ) < 0 )
1385 MPI_CHK( mpi_add_mpi( R, R, B ) );
1387 while( mpi_cmp_mpi( R, B ) >= 0 )
1388 MPI_CHK( mpi_sub_mpi( R, R, B ) );
1390 cleanup:
1392 return( ret );
1396 * Modulo: r = A mod b
1398 int mpi_mod_int( t_uint *r, const mpi *A, t_sint b )
1400 size_t i;
1401 t_uint x, y, z;
1403 if( b == 0 )
1404 return( POLARSSL_ERR_MPI_DIVISION_BY_ZERO );
1406 if( b < 0 )
1407 return POLARSSL_ERR_MPI_NEGATIVE_VALUE;
1410 * handle trivial cases
1412 if( b == 1 )
1414 *r = 0;
1415 return( 0 );
1418 if( b == 2 )
1420 *r = A->p[0] & 1;
1421 return( 0 );
1425 * general case
1427 for( i = A->n, y = 0; i > 0; i-- )
1429 x = A->p[i - 1];
1430 y = ( y << biH ) | ( x >> biH );
1431 z = y / b;
1432 y -= z * b;
1434 x <<= biH;
1435 y = ( y << biH ) | ( x >> biH );
1436 z = y / b;
1437 y -= z * b;
1441 * If A is negative, then the current y represents a negative value.
1442 * Flipping it to the positive side.
1444 if( A->s < 0 && y != 0 )
1445 y = b - y;
1447 *r = y;
1449 return( 0 );
1453 * Fast Montgomery initialization (thanks to Tom St Denis)
1455 static void mpi_montg_init( t_uint *mm, const mpi *N )
1457 t_uint x, m0 = N->p[0];
1458 unsigned int i;
1460 x = m0;
1461 x += ( ( m0 + 2 ) & 4 ) << 1;
1463 for( i = biL; i >= 8; i /= 2 )
1464 x *= ( 2 - ( m0 * x ) );
1466 *mm = ~x + 1;
1470 * Montgomery multiplication: A = A * B * R^-1 mod N (HAC 14.36)
1472 static void mpi_montmul( mpi *A, const mpi *B, const mpi *N, t_uint mm,
1473 const mpi *T )
1475 size_t i, n, m;
1476 t_uint u0, u1, *d;
1478 memset( T->p, 0, T->n * ciL );
1480 d = T->p;
1481 n = N->n;
1482 m = ( B->n < n ) ? B->n : n;
1484 for( i = 0; i < n; i++ )
1487 * T = (T + u0*B + u1*N) / 2^biL
1489 u0 = A->p[i];
1490 u1 = ( d[0] + u0 * B->p[0] ) * mm;
1492 mpi_mul_hlp( m, B->p, d, u0 );
1493 mpi_mul_hlp( n, N->p, d, u1 );
1495 *d++ = u0; d[n + 1] = 0;
1498 memcpy( A->p, d, (n + 1) * ciL );
1500 if( mpi_cmp_abs( A, N ) >= 0 )
1501 mpi_sub_hlp( n, N->p, A->p );
1502 else
1503 /* prevent timing attacks */
1504 mpi_sub_hlp( n, A->p, T->p );
1508 * Montgomery reduction: A = A * R^-1 mod N
1510 static void mpi_montred( mpi *A, const mpi *N, t_uint mm, const mpi *T )
1512 t_uint z = 1;
1513 mpi U;
1515 U.n = U.s = (int) z;
1516 U.p = &z;
1518 mpi_montmul( A, &U, N, mm, T );
1522 * Sliding-window exponentiation: X = A^E mod N (HAC 14.85)
1524 int mpi_exp_mod( mpi *X, const mpi *A, const mpi *E, const mpi *N, mpi *_RR )
1526 int ret;
1527 size_t wbits, wsize, one = 1;
1528 size_t i, j, nblimbs;
1529 size_t bufsize, nbits;
1530 t_uint ei, mm, state;
1531 mpi RR, T, W[ 2 << POLARSSL_MPI_WINDOW_SIZE ], Apos;
1532 int neg;
1534 if( mpi_cmp_int( N, 0 ) < 0 || ( N->p[0] & 1 ) == 0 )
1535 return( POLARSSL_ERR_MPI_BAD_INPUT_DATA );
1537 if( mpi_cmp_int( E, 0 ) < 0 )
1538 return( POLARSSL_ERR_MPI_BAD_INPUT_DATA );
1541 * Init temps and window size
1543 mpi_montg_init( &mm, N );
1544 mpi_init( &RR ); mpi_init( &T );
1545 mpi_init( &Apos );
1546 memset( W, 0, sizeof( W ) );
1548 i = mpi_msb( E );
1550 wsize = ( i > 671 ) ? 6 : ( i > 239 ) ? 5 :
1551 ( i > 79 ) ? 4 : ( i > 23 ) ? 3 : 1;
1553 if( wsize > POLARSSL_MPI_WINDOW_SIZE )
1554 wsize = POLARSSL_MPI_WINDOW_SIZE;
1556 j = N->n + 1;
1557 MPI_CHK( mpi_grow( X, j ) );
1558 MPI_CHK( mpi_grow( &W[1], j ) );
1559 MPI_CHK( mpi_grow( &T, j * 2 ) );
1562 * Compensate for negative A (and correct at the end)
1564 neg = ( A->s == -1 );
1565 if( neg )
1567 MPI_CHK( mpi_copy( &Apos, A ) );
1568 Apos.s = 1;
1569 A = &Apos;
1573 * If 1st call, pre-compute R^2 mod N
1575 if( _RR == NULL || _RR->p == NULL )
1577 MPI_CHK( mpi_lset( &RR, 1 ) );
1578 MPI_CHK( mpi_shift_l( &RR, N->n * 2 * biL ) );
1579 MPI_CHK( mpi_mod_mpi( &RR, &RR, N ) );
1581 if( _RR != NULL )
1582 memcpy( _RR, &RR, sizeof( mpi ) );
1584 else
1585 memcpy( &RR, _RR, sizeof( mpi ) );
1588 * W[1] = A * R^2 * R^-1 mod N = A * R mod N
1590 if( mpi_cmp_mpi( A, N ) >= 0 )
1591 MPI_CHK( mpi_mod_mpi( &W[1], A, N ) );
1592 else
1593 MPI_CHK( mpi_copy( &W[1], A ) );
1595 mpi_montmul( &W[1], &RR, N, mm, &T );
1598 * X = R^2 * R^-1 mod N = R mod N
1600 MPI_CHK( mpi_copy( X, &RR ) );
1601 mpi_montred( X, N, mm, &T );
1603 if( wsize > 1 )
1606 * W[1 << (wsize - 1)] = W[1] ^ (wsize - 1)
1608 j = one << (wsize - 1);
1610 MPI_CHK( mpi_grow( &W[j], N->n + 1 ) );
1611 MPI_CHK( mpi_copy( &W[j], &W[1] ) );
1613 for( i = 0; i < wsize - 1; i++ )
1614 mpi_montmul( &W[j], &W[j], N, mm, &T );
1617 * W[i] = W[i - 1] * W[1]
1619 for( i = j + 1; i < (one << wsize); i++ )
1621 MPI_CHK( mpi_grow( &W[i], N->n + 1 ) );
1622 MPI_CHK( mpi_copy( &W[i], &W[i - 1] ) );
1624 mpi_montmul( &W[i], &W[1], N, mm, &T );
1628 nblimbs = E->n;
1629 bufsize = 0;
1630 nbits = 0;
1631 wbits = 0;
1632 state = 0;
1634 while( 1 )
1636 if( bufsize == 0 )
1638 if( nblimbs == 0 )
1639 break;
1641 nblimbs--;
1643 bufsize = sizeof( t_uint ) << 3;
1646 bufsize--;
1648 ei = (E->p[nblimbs] >> bufsize) & 1;
1651 * skip leading 0s
1653 if( ei == 0 && state == 0 )
1654 continue;
1656 if( ei == 0 && state == 1 )
1659 * out of window, square X
1661 mpi_montmul( X, X, N, mm, &T );
1662 continue;
1666 * add ei to current window
1668 state = 2;
1670 nbits++;
1671 wbits |= (ei << (wsize - nbits));
1673 if( nbits == wsize )
1676 * X = X^wsize R^-1 mod N
1678 for( i = 0; i < wsize; i++ )
1679 mpi_montmul( X, X, N, mm, &T );
1682 * X = X * W[wbits] R^-1 mod N
1684 mpi_montmul( X, &W[wbits], N, mm, &T );
1686 state--;
1687 nbits = 0;
1688 wbits = 0;
1693 * process the remaining bits
1695 for( i = 0; i < nbits; i++ )
1697 mpi_montmul( X, X, N, mm, &T );
1699 wbits <<= 1;
1701 if( (wbits & (one << wsize)) != 0 )
1702 mpi_montmul( X, &W[1], N, mm, &T );
1706 * X = A^E * R * R^-1 mod N = A^E mod N
1708 mpi_montred( X, N, mm, &T );
1710 if( neg )
1712 X->s = -1;
1713 MPI_CHK( mpi_add_mpi( X, N, X ) );
1716 cleanup:
1718 for( i = (one << (wsize - 1)); i < (one << wsize); i++ )
1719 mpi_free( &W[i] );
1721 mpi_free( &W[1] ); mpi_free( &T ); mpi_free( &Apos );
1723 if( _RR == NULL || _RR->p == NULL )
1724 mpi_free( &RR );
1726 return( ret );
1730 * Greatest common divisor: G = gcd(A, B) (HAC 14.54)
1732 int mpi_gcd( mpi *G, const mpi *A, const mpi *B )
1734 int ret;
1735 size_t lz, lzt;
1736 mpi TG, TA, TB;
1738 mpi_init( &TG ); mpi_init( &TA ); mpi_init( &TB );
1740 MPI_CHK( mpi_copy( &TA, A ) );
1741 MPI_CHK( mpi_copy( &TB, B ) );
1743 lz = mpi_lsb( &TA );
1744 lzt = mpi_lsb( &TB );
1746 if ( lzt < lz )
1747 lz = lzt;
1749 MPI_CHK( mpi_shift_r( &TA, lz ) );
1750 MPI_CHK( mpi_shift_r( &TB, lz ) );
1752 TA.s = TB.s = 1;
1754 while( mpi_cmp_int( &TA, 0 ) != 0 )
1756 MPI_CHK( mpi_shift_r( &TA, mpi_lsb( &TA ) ) );
1757 MPI_CHK( mpi_shift_r( &TB, mpi_lsb( &TB ) ) );
1759 if( mpi_cmp_mpi( &TA, &TB ) >= 0 )
1761 MPI_CHK( mpi_sub_abs( &TA, &TA, &TB ) );
1762 MPI_CHK( mpi_shift_r( &TA, 1 ) );
1764 else
1766 MPI_CHK( mpi_sub_abs( &TB, &TB, &TA ) );
1767 MPI_CHK( mpi_shift_r( &TB, 1 ) );
1771 MPI_CHK( mpi_shift_l( &TB, lz ) );
1772 MPI_CHK( mpi_copy( G, &TB ) );
1774 cleanup:
1776 mpi_free( &TG ); mpi_free( &TA ); mpi_free( &TB );
1778 return( ret );
1782 * Fill X with size bytes of random.
1784 * Use a temporary bytes representation to make sure the result is the same
1785 * regardless of the platform endianness (useful when f_rng is actually
1786 * deterministic, eg for tests).
1788 int mpi_fill_random( mpi *X, size_t size,
1789 int (*f_rng)(void *, unsigned char *, size_t),
1790 void *p_rng )
1792 int ret;
1793 unsigned char buf[POLARSSL_MPI_MAX_SIZE];
1795 if( size > POLARSSL_MPI_MAX_SIZE )
1796 return( POLARSSL_ERR_MPI_BAD_INPUT_DATA );
1798 MPI_CHK( f_rng( p_rng, buf, size ) );
1799 MPI_CHK( mpi_read_binary( X, buf, size ) );
1801 cleanup:
1802 return( ret );
1806 * Modular inverse: X = A^-1 mod N (HAC 14.61 / 14.64)
1808 int mpi_inv_mod( mpi *X, const mpi *A, const mpi *N )
1810 int ret;
1811 mpi G, TA, TU, U1, U2, TB, TV, V1, V2;
1813 if( mpi_cmp_int( N, 0 ) <= 0 )
1814 return( POLARSSL_ERR_MPI_BAD_INPUT_DATA );
1816 mpi_init( &TA ); mpi_init( &TU ); mpi_init( &U1 ); mpi_init( &U2 );
1817 mpi_init( &G ); mpi_init( &TB ); mpi_init( &TV );
1818 mpi_init( &V1 ); mpi_init( &V2 );
1820 MPI_CHK( mpi_gcd( &G, A, N ) );
1822 if( mpi_cmp_int( &G, 1 ) != 0 )
1824 ret = POLARSSL_ERR_MPI_NOT_ACCEPTABLE;
1825 goto cleanup;
1828 MPI_CHK( mpi_mod_mpi( &TA, A, N ) );
1829 MPI_CHK( mpi_copy( &TU, &TA ) );
1830 MPI_CHK( mpi_copy( &TB, N ) );
1831 MPI_CHK( mpi_copy( &TV, N ) );
1833 MPI_CHK( mpi_lset( &U1, 1 ) );
1834 MPI_CHK( mpi_lset( &U2, 0 ) );
1835 MPI_CHK( mpi_lset( &V1, 0 ) );
1836 MPI_CHK( mpi_lset( &V2, 1 ) );
1840 while( ( TU.p[0] & 1 ) == 0 )
1842 MPI_CHK( mpi_shift_r( &TU, 1 ) );
1844 if( ( U1.p[0] & 1 ) != 0 || ( U2.p[0] & 1 ) != 0 )
1846 MPI_CHK( mpi_add_mpi( &U1, &U1, &TB ) );
1847 MPI_CHK( mpi_sub_mpi( &U2, &U2, &TA ) );
1850 MPI_CHK( mpi_shift_r( &U1, 1 ) );
1851 MPI_CHK( mpi_shift_r( &U2, 1 ) );
1854 while( ( TV.p[0] & 1 ) == 0 )
1856 MPI_CHK( mpi_shift_r( &TV, 1 ) );
1858 if( ( V1.p[0] & 1 ) != 0 || ( V2.p[0] & 1 ) != 0 )
1860 MPI_CHK( mpi_add_mpi( &V1, &V1, &TB ) );
1861 MPI_CHK( mpi_sub_mpi( &V2, &V2, &TA ) );
1864 MPI_CHK( mpi_shift_r( &V1, 1 ) );
1865 MPI_CHK( mpi_shift_r( &V2, 1 ) );
1868 if( mpi_cmp_mpi( &TU, &TV ) >= 0 )
1870 MPI_CHK( mpi_sub_mpi( &TU, &TU, &TV ) );
1871 MPI_CHK( mpi_sub_mpi( &U1, &U1, &V1 ) );
1872 MPI_CHK( mpi_sub_mpi( &U2, &U2, &V2 ) );
1874 else
1876 MPI_CHK( mpi_sub_mpi( &TV, &TV, &TU ) );
1877 MPI_CHK( mpi_sub_mpi( &V1, &V1, &U1 ) );
1878 MPI_CHK( mpi_sub_mpi( &V2, &V2, &U2 ) );
1881 while( mpi_cmp_int( &TU, 0 ) != 0 );
1883 while( mpi_cmp_int( &V1, 0 ) < 0 )
1884 MPI_CHK( mpi_add_mpi( &V1, &V1, N ) );
1886 while( mpi_cmp_mpi( &V1, N ) >= 0 )
1887 MPI_CHK( mpi_sub_mpi( &V1, &V1, N ) );
1889 MPI_CHK( mpi_copy( X, &V1 ) );
1891 cleanup:
1893 mpi_free( &TA ); mpi_free( &TU ); mpi_free( &U1 ); mpi_free( &U2 );
1894 mpi_free( &G ); mpi_free( &TB ); mpi_free( &TV );
1895 mpi_free( &V1 ); mpi_free( &V2 );
1897 return( ret );
1900 #if defined(POLARSSL_GENPRIME)
1902 static const int small_prime[] =
1904 3, 5, 7, 11, 13, 17, 19, 23,
1905 29, 31, 37, 41, 43, 47, 53, 59,
1906 61, 67, 71, 73, 79, 83, 89, 97,
1907 101, 103, 107, 109, 113, 127, 131, 137,
1908 139, 149, 151, 157, 163, 167, 173, 179,
1909 181, 191, 193, 197, 199, 211, 223, 227,
1910 229, 233, 239, 241, 251, 257, 263, 269,
1911 271, 277, 281, 283, 293, 307, 311, 313,
1912 317, 331, 337, 347, 349, 353, 359, 367,
1913 373, 379, 383, 389, 397, 401, 409, 419,
1914 421, 431, 433, 439, 443, 449, 457, 461,
1915 463, 467, 479, 487, 491, 499, 503, 509,
1916 521, 523, 541, 547, 557, 563, 569, 571,
1917 577, 587, 593, 599, 601, 607, 613, 617,
1918 619, 631, 641, 643, 647, 653, 659, 661,
1919 673, 677, 683, 691, 701, 709, 719, 727,
1920 733, 739, 743, 751, 757, 761, 769, 773,
1921 787, 797, 809, 811, 821, 823, 827, 829,
1922 839, 853, 857, 859, 863, 877, 881, 883,
1923 887, 907, 911, 919, 929, 937, 941, 947,
1924 953, 967, 971, 977, 983, 991, 997, -103
1928 * Small divisors test (X must be positive)
1930 * Return values:
1931 * 0: no small factor (possible prime, more tests needed)
1932 * 1: certain prime
1933 * POLARSSL_ERR_MPI_NOT_ACCEPTABLE: certain non-prime
1934 * other negative: error
1936 static int mpi_check_small_factors( const mpi *X )
1938 int ret = 0;
1939 size_t i;
1940 t_uint r;
1942 if( ( X->p[0] & 1 ) == 0 )
1943 return( POLARSSL_ERR_MPI_NOT_ACCEPTABLE );
1945 for( i = 0; small_prime[i] > 0; i++ )
1947 if( mpi_cmp_int( X, small_prime[i] ) <= 0 )
1948 return( 1 );
1950 MPI_CHK( mpi_mod_int( &r, X, small_prime[i] ) );
1952 if( r == 0 )
1953 return( POLARSSL_ERR_MPI_NOT_ACCEPTABLE );
1956 cleanup:
1957 return( ret );
1961 * Miller-Rabin pseudo-primality test (HAC 4.24)
1963 static int mpi_miller_rabin( const mpi *X,
1964 int (*f_rng)(void *, unsigned char *, size_t),
1965 void *p_rng )
1967 int ret;
1968 size_t i, j, n, s;
1969 mpi W, R, T, A, RR;
1971 mpi_init( &W ); mpi_init( &R ); mpi_init( &T ); mpi_init( &A );
1972 mpi_init( &RR );
1975 * W = |X| - 1
1976 * R = W >> lsb( W )
1978 MPI_CHK( mpi_sub_int( &W, X, 1 ) );
1979 s = mpi_lsb( &W );
1980 MPI_CHK( mpi_copy( &R, &W ) );
1981 MPI_CHK( mpi_shift_r( &R, s ) );
1983 i = mpi_msb( X );
1985 * HAC, table 4.4
1987 n = ( ( i >= 1300 ) ? 2 : ( i >= 850 ) ? 3 :
1988 ( i >= 650 ) ? 4 : ( i >= 350 ) ? 8 :
1989 ( i >= 250 ) ? 12 : ( i >= 150 ) ? 18 : 27 );
1991 for( i = 0; i < n; i++ )
1994 * pick a random A, 1 < A < |X| - 1
1996 MPI_CHK( mpi_fill_random( &A, X->n * ciL, f_rng, p_rng ) );
1998 if( mpi_cmp_mpi( &A, &W ) >= 0 )
2000 j = mpi_msb( &A ) - mpi_msb( &W );
2001 MPI_CHK( mpi_shift_r( &A, j + 1 ) );
2003 A.p[0] |= 3;
2006 * A = A^R mod |X|
2008 MPI_CHK( mpi_exp_mod( &A, &A, &R, X, &RR ) );
2010 if( mpi_cmp_mpi( &A, &W ) == 0 ||
2011 mpi_cmp_int( &A, 1 ) == 0 )
2012 continue;
2014 j = 1;
2015 while( j < s && mpi_cmp_mpi( &A, &W ) != 0 )
2018 * A = A * A mod |X|
2020 MPI_CHK( mpi_mul_mpi( &T, &A, &A ) );
2021 MPI_CHK( mpi_mod_mpi( &A, &T, X ) );
2023 if( mpi_cmp_int( &A, 1 ) == 0 )
2024 break;
2026 j++;
2030 * not prime if A != |X| - 1 or A == 1
2032 if( mpi_cmp_mpi( &A, &W ) != 0 ||
2033 mpi_cmp_int( &A, 1 ) == 0 )
2035 ret = POLARSSL_ERR_MPI_NOT_ACCEPTABLE;
2036 break;
2040 cleanup:
2041 mpi_free( &W ); mpi_free( &R ); mpi_free( &T ); mpi_free( &A );
2042 mpi_free( &RR );
2044 return( ret );
2048 * Pseudo-primality test: small factors, then Miller-Rabin
2050 int mpi_is_prime( mpi *X,
2051 int (*f_rng)(void *, unsigned char *, size_t),
2052 void *p_rng )
2054 int ret;
2055 const mpi XX = { 1, X->n, X->p }; /* Abs(X) */
2057 if( mpi_cmp_int( &XX, 0 ) == 0 ||
2058 mpi_cmp_int( &XX, 1 ) == 0 )
2059 return( POLARSSL_ERR_MPI_NOT_ACCEPTABLE );
2061 if( mpi_cmp_int( &XX, 2 ) == 0 )
2062 return( 0 );
2064 if( ( ret = mpi_check_small_factors( &XX ) ) != 0 )
2066 if( ret == 1 )
2067 return( 0 );
2069 return( ret );
2072 return( mpi_miller_rabin( &XX, f_rng, p_rng ) );
2076 * Prime number generation
2078 int mpi_gen_prime( mpi *X, size_t nbits, int dh_flag,
2079 int (*f_rng)(void *, unsigned char *, size_t),
2080 void *p_rng )
2082 int ret;
2083 size_t k, n;
2084 t_uint r;
2085 mpi Y;
2087 if( nbits < 3 || nbits > POLARSSL_MPI_MAX_BITS )
2088 return( POLARSSL_ERR_MPI_BAD_INPUT_DATA );
2090 mpi_init( &Y );
2092 n = BITS_TO_LIMBS( nbits );
2094 MPI_CHK( mpi_fill_random( X, n * ciL, f_rng, p_rng ) );
2096 k = mpi_msb( X );
2097 if( k < nbits ) MPI_CHK( mpi_shift_l( X, nbits - k ) );
2098 if( k > nbits ) MPI_CHK( mpi_shift_r( X, k - nbits ) );
2100 X->p[0] |= 3;
2102 if( dh_flag == 0 )
2104 while( ( ret = mpi_is_prime( X, f_rng, p_rng ) ) != 0 )
2106 if( ret != POLARSSL_ERR_MPI_NOT_ACCEPTABLE )
2107 goto cleanup;
2109 MPI_CHK( mpi_add_int( X, X, 2 ) );
2112 else
2115 * An necessary condition for Y and X = 2Y + 1 to be prime
2116 * is X = 2 mod 3 (which is equivalent to Y = 2 mod 3).
2117 * Make sure it is satisfied, while keeping X = 3 mod 4
2119 MPI_CHK( mpi_mod_int( &r, X, 3 ) );
2120 if( r == 0 )
2121 MPI_CHK( mpi_add_int( X, X, 8 ) );
2122 else if( r == 1 )
2123 MPI_CHK( mpi_add_int( X, X, 4 ) );
2125 /* Set Y = (X-1) / 2, which is X / 2 because X is odd */
2126 MPI_CHK( mpi_copy( &Y, X ) );
2127 MPI_CHK( mpi_shift_r( &Y, 1 ) );
2129 while( 1 )
2132 * First, check small factors for X and Y
2133 * before doing Miller-Rabin on any of them
2135 if( ( ret = mpi_check_small_factors( X ) ) == 0 &&
2136 ( ret = mpi_check_small_factors( &Y ) ) == 0 &&
2137 ( ret = mpi_miller_rabin( X, f_rng, p_rng ) ) == 0 &&
2138 ( ret = mpi_miller_rabin( &Y, f_rng, p_rng ) ) == 0 )
2140 break;
2143 if( ret != POLARSSL_ERR_MPI_NOT_ACCEPTABLE )
2144 goto cleanup;
2147 * Next candidates. We want to preserve Y = (X-1) / 2 and
2148 * Y = 1 mod 2 and Y = 2 mod 3 (eq X = 3 mod 4 and X = 2 mod 3)
2149 * so up Y by 6 and X by 12.
2151 MPI_CHK( mpi_add_int( X, X, 12 ) );
2152 MPI_CHK( mpi_add_int( &Y, &Y, 6 ) );
2156 cleanup:
2158 mpi_free( &Y );
2160 return( ret );
2163 #endif /* POLARSSL_GENPRIME */
2165 #if defined(POLARSSL_SELF_TEST)
2167 #define GCD_PAIR_COUNT 3
2169 static const int gcd_pairs[GCD_PAIR_COUNT][3] =
2171 { 693, 609, 21 },
2172 { 1764, 868, 28 },
2173 { 768454923, 542167814, 1 }
2177 * Checkup routine
2179 int mpi_self_test( int verbose )
2181 int ret, i;
2182 mpi A, E, N, X, Y, U, V;
2184 mpi_init( &A ); mpi_init( &E ); mpi_init( &N ); mpi_init( &X );
2185 mpi_init( &Y ); mpi_init( &U ); mpi_init( &V );
2187 MPI_CHK( mpi_read_string( &A, 16,
2188 "EFE021C2645FD1DC586E69184AF4A31E" \
2189 "D5F53E93B5F123FA41680867BA110131" \
2190 "944FE7952E2517337780CB0DB80E61AA" \
2191 "E7C8DDC6C5C6AADEB34EB38A2F40D5E6" ) );
2193 MPI_CHK( mpi_read_string( &E, 16,
2194 "B2E7EFD37075B9F03FF989C7C5051C20" \
2195 "34D2A323810251127E7BF8625A4F49A5" \
2196 "F3E27F4DA8BD59C47D6DAABA4C8127BD" \
2197 "5B5C25763222FEFCCFC38B832366C29E" ) );
2199 MPI_CHK( mpi_read_string( &N, 16,
2200 "0066A198186C18C10B2F5ED9B522752A" \
2201 "9830B69916E535C8F047518A889A43A5" \
2202 "94B6BED27A168D31D4A52F88925AA8F5" ) );
2204 MPI_CHK( mpi_mul_mpi( &X, &A, &N ) );
2206 MPI_CHK( mpi_read_string( &U, 16,
2207 "602AB7ECA597A3D6B56FF9829A5E8B85" \
2208 "9E857EA95A03512E2BAE7391688D264A" \
2209 "A5663B0341DB9CCFD2C4C5F421FEC814" \
2210 "8001B72E848A38CAE1C65F78E56ABDEF" \
2211 "E12D3C039B8A02D6BE593F0BBBDA56F1" \
2212 "ECF677152EF804370C1A305CAF3B5BF1" \
2213 "30879B56C61DE584A0F53A2447A51E" ) );
2215 if( verbose != 0 )
2216 polarssl_printf( " MPI test #1 (mul_mpi): " );
2218 if( mpi_cmp_mpi( &X, &U ) != 0 )
2220 if( verbose != 0 )
2221 polarssl_printf( "failed\n" );
2223 ret = 1;
2224 goto cleanup;
2227 if( verbose != 0 )
2228 polarssl_printf( "passed\n" );
2230 MPI_CHK( mpi_div_mpi( &X, &Y, &A, &N ) );
2232 MPI_CHK( mpi_read_string( &U, 16,
2233 "256567336059E52CAE22925474705F39A94" ) );
2235 MPI_CHK( mpi_read_string( &V, 16,
2236 "6613F26162223DF488E9CD48CC132C7A" \
2237 "0AC93C701B001B092E4E5B9F73BCD27B" \
2238 "9EE50D0657C77F374E903CDFA4C642" ) );
2240 if( verbose != 0 )
2241 polarssl_printf( " MPI test #2 (div_mpi): " );
2243 if( mpi_cmp_mpi( &X, &U ) != 0 ||
2244 mpi_cmp_mpi( &Y, &V ) != 0 )
2246 if( verbose != 0 )
2247 polarssl_printf( "failed\n" );
2249 ret = 1;
2250 goto cleanup;
2253 if( verbose != 0 )
2254 polarssl_printf( "passed\n" );
2256 MPI_CHK( mpi_exp_mod( &X, &A, &E, &N, NULL ) );
2258 MPI_CHK( mpi_read_string( &U, 16,
2259 "36E139AEA55215609D2816998ED020BB" \
2260 "BD96C37890F65171D948E9BC7CBAA4D9" \
2261 "325D24D6A3C12710F10A09FA08AB87" ) );
2263 if( verbose != 0 )
2264 polarssl_printf( " MPI test #3 (exp_mod): " );
2266 if( mpi_cmp_mpi( &X, &U ) != 0 )
2268 if( verbose != 0 )
2269 polarssl_printf( "failed\n" );
2271 ret = 1;
2272 goto cleanup;
2275 if( verbose != 0 )
2276 polarssl_printf( "passed\n" );
2278 MPI_CHK( mpi_inv_mod( &X, &A, &N ) );
2280 MPI_CHK( mpi_read_string( &U, 16,
2281 "003A0AAEDD7E784FC07D8F9EC6E3BFD5" \
2282 "C3DBA76456363A10869622EAC2DD84EC" \
2283 "C5B8A74DAC4D09E03B5E0BE779F2DF61" ) );
2285 if( verbose != 0 )
2286 polarssl_printf( " MPI test #4 (inv_mod): " );
2288 if( mpi_cmp_mpi( &X, &U ) != 0 )
2290 if( verbose != 0 )
2291 polarssl_printf( "failed\n" );
2293 ret = 1;
2294 goto cleanup;
2297 if( verbose != 0 )
2298 polarssl_printf( "passed\n" );
2300 if( verbose != 0 )
2301 polarssl_printf( " MPI test #5 (simple gcd): " );
2303 for ( i = 0; i < GCD_PAIR_COUNT; i++)
2305 MPI_CHK( mpi_lset( &X, gcd_pairs[i][0] ) );
2306 MPI_CHK( mpi_lset( &Y, gcd_pairs[i][1] ) );
2308 MPI_CHK( mpi_gcd( &A, &X, &Y ) );
2310 if( mpi_cmp_int( &A, gcd_pairs[i][2] ) != 0 )
2312 if( verbose != 0 )
2313 polarssl_printf( "failed at %d\n", i );
2315 ret = 1;
2316 goto cleanup;
2320 if( verbose != 0 )
2321 polarssl_printf( "passed\n" );
2323 cleanup:
2325 if( ret != 0 && verbose != 0 )
2326 polarssl_printf( "Unexpected error, return code = %08X\n", ret );
2328 mpi_free( &A ); mpi_free( &E ); mpi_free( &N ); mpi_free( &X );
2329 mpi_free( &Y ); mpi_free( &U ); mpi_free( &V );
2331 if( verbose != 0 )
2332 polarssl_printf( "\n" );
2334 return( ret );
2337 #endif /* POLARSSL_SELF_TEST */
2339 #endif /* POLARSSL_BIGNUM_C */