Hola amigos estoy buscando ejemplos en c o c++ sobre rsa, he mirado su funcionamiento pero me gustaria saber si ya existe algun ejemplo que sea funcional, he encontrado algunos por la red pero no me son funcionales, como por ejemplo este, a ver si me podeis pasar algun ejemplo sencillo que sea funcional.
Saludos.
#include <math.h>
#include <stdio.h>
#include <string.h>
unsigned int pick_e ( unsigned int phi );
unsigned int inv ( unsigned int num, unsigned int phi );
unsigned int encrypt ( unsigned int num, unsigned int key, unsigned int n );
int main ( void )
{
char msg[] = "HELLO WORLD 21";
unsigned int cyphertext[sizeof(msg)];
unsigned int p = 3; // Too small for real security!
unsigned int q = 11; // Too small for real security!
unsigned int i, n, phi, e, d, result;
n = p * q; // This is the step that is hard to reverse!
phi = (p-1) * (q-1); // Euler's "totient" function.
e = pick_e( phi ); // pick one of the pair of keys, ...
d = inv( e, phi ); // ... and calculate the other.
printf( "p=%u, q=%u, n=%u, phi(n)=%u, e=%u, d=%u\n", p, q, n, phi, e, d );
// Encrypting the message:
printf( "\n\tEncrypt msg \"%s\" using key (%u,%u):\n", msg, e, n );
for ( i=0; i < strlen(msg); ++i )
{ cyphertext = encrypt( msg-64, e, n );
printf( "\t%c (%2u) --> %c (%2u)\n", msg, msg-64,
(char)(cyphertext+64), cyphertext );
}
// Decrypt that message:
printf( "\n\tDecrypt cyphertext using key (%u,%u):\n", d, n );
for ( i=0; i < strlen(msg); ++i )
{
result = encrypt( cyphertext, d, n );
printf( "\t%c (%2u)--> %c (%2u)\n", (char)(cyphertext+64),
cyphertext, (char)(result+64), result );
}
const char c = 0;
scanf(c);
return 0;
}
/* Return some integer relatively prime to phi
(should pick a random one, not the first one found! */
unsigned int pick_e ( unsigned int phi )
{
return 7; // The gcd code isn't worth implementing for this demo!
}
/* Compute the inverse of num modulus phi (Note there is a better way!) */
unsigned int inv ( unsigned int num, unsigned int phi )
{
unsigned int i = 0;
while ( (num * i ) % phi != 1 )
++i;
return i;
}
/* Compute the encryption of some num using key (key, n) */
unsigned int encrypt ( unsigned int num, unsigned int key, unsigned int n )
{
int result = (int) (fmodl( powl(num, key), n ) + 0.5);
if ( result < 0 ) result += n;
return (unsigned int) result;
}