blob: 87737c8e793e7b65d5f6dc276b2876785d638794 [file] [log] [blame]
Paul Bakker5121ce52009-01-03 21:22:43 +00001/*
2 * Simple MPI demonstration program
3 *
4 * Copyright (C) 2006-2007 Christophe Devine
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21#ifndef _CRT_SECURE_NO_DEPRECATE
22#define _CRT_SECURE_NO_DEPRECATE 1
23#endif
24
25#include <stdio.h>
26
Paul Bakker40e46942009-01-03 21:51:57 +000027#include "polarssl/bignum.h"
Paul Bakker5121ce52009-01-03 21:22:43 +000028
29int main( void )
30{
31 mpi E, P, Q, N, H, D, X, Y, Z;
32
33 mpi_init( &E, &P, &Q, &N, &H,
34 &D, &X, &Y, &Z, NULL );
35
36 mpi_read_string( &P, 10, "2789" );
37 mpi_read_string( &Q, 10, "3203" );
38 mpi_read_string( &E, 10, "257" );
39 mpi_mul_mpi( &N, &P, &Q );
40
41 printf( "\n Public key:\n\n" );
42 mpi_write_file( " N = ", &N, 10, NULL );
43 mpi_write_file( " E = ", &E, 10, NULL );
44
45 printf( "\n Private key:\n\n" );
46 mpi_write_file( " P = ", &P, 10, NULL );
47 mpi_write_file( " Q = ", &Q, 10, NULL );
48
49 mpi_sub_int( &P, &P, 1 );
50 mpi_sub_int( &Q, &Q, 1 );
51 mpi_mul_mpi( &H, &P, &Q );
52 mpi_inv_mod( &D, &E, &H );
53
54 mpi_write_file( " D = E^-1 mod (P-1)*(Q-1) = ",
55 &D, 10, NULL );
56
57 mpi_read_string( &X, 10, "55555" );
58 mpi_exp_mod( &Y, &X, &E, &N, NULL );
59 mpi_exp_mod( &Z, &Y, &D, &N, NULL );
60
61 printf( "\n RSA operation:\n\n" );
62 mpi_write_file( " X (plaintext) = ", &X, 10, NULL );
63 mpi_write_file( " Y (ciphertext) = X^E mod N = ", &Y, 10, NULL );
64 mpi_write_file( " Z (decrypted) = Y^D mod N = ", &Z, 10, NULL );
65 printf( "\n" );
66
67 mpi_free( &Z, &Y, &X, &D, &H,
68 &N, &Q, &P, &E, NULL );
69
70#ifdef WIN32
71 printf( " Press Enter to exit this program.\n" );
72 fflush( stdout ); getchar();
73#endif
74
75 return( 0 );
76}