/*
Algoritmo RSA utilizando SSL en C
Daniel Lerch Hostalot  
http://daniellerch.com/papers/html/algoritmo_rsa.html
http://glo.org.mx/~patux/crypto/
Modificado por: Geronimo Orozco, para aceptar diferentes cadenas e imprimir el texto cifrado :)
Modo de compilar
gcc -lssl -o rsa rsa.c 

*/
#include <stdio.h>
#include <openssl/rsa.h>
#include <openssl/engine.h>

int main(int argc, char *argv[])
{

  RSA *keypair;
  char *cleartext;
  char *ciphertext;
  char *cleartext2;

  int car, ind=0, nbytes = 256;

  cleartext = (char *) malloc (nbytes + 1);
  getline (&cleartext, &nbytes, stdin);

  keypair = RSA_new();

  /* Generamos un par de claves de 1024 bits */
  keypair = RSA_generate_key (1024, 17, NULL, NULL);
  ciphertext = malloc(RSA_size(keypair));

  RSA_public_encrypt (strlen(cleartext)+1, cleartext, ciphertext, keypair,RSA_PKCS1_PADDING);
  cleartext2 = malloc(RSA_size(keypair));

  RSA_private_decrypt (RSA_size(keypair), ciphertext, cleartext2, keypair,RSA_PKCS1_PADDING);

//  printf("CipherText: %x\n", ciphertext);
  printf ("CipherText: ");
  while (ciphertext[ind] !='\0')
  {
   car=ciphertext[ind++];
   putchar(car);
  }
  printf("\nClearText: %s\n", cleartext2);

  RSA_free(keypair);
  return 0;
}