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