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