#include <stdio.h>
#include <string.h>
#include <openssl/err.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
 
int main(int argc, char **argv)
{
  FILE		*fp;
  RSA		*rsa=NULL;
  EVP_CIPHER_CTX  ctx;
  EVP_CIPHER	*enc=NULL;
  unsigned char *pvk_buf = NULL;
  int		pvk_len, result;
  
  ERR_load_crypto_strings();

  rsa = RSA_generate_key(1024, RSA_F4, NULL, NULL);
  if (rsa == NULL)
  {
	ERR_print_errors_fp(stderr);
	exit(1);
  }
  result = RSA_check_key(rsa);
  if (result <= 0)
  {
	ERR_print_errors_fp(stderr);
	exit(1);
  }

  pvk_len = i2d_RSAPrivateKey(rsa, NULL);
  pvk_buf = (unsigned char *)malloc(pvk_len);
  pvk_len = i2d_RSAPrivateKey(rsa, &pvk_buf);

  fp = fopen("privkey.der", "wb");
/*
  // this write the key in valid PEM format
  result = PEM_ASN1_write((int (*)())i2d_RSAPrivateKey,
			  PEM_STRING_RSA,
			  fp,
			  (char *)rsa,
			  enc,NULL,0,NULL,NULL);
*/
  fwrite(pvk_buf,pvk_len,1,fp);  
  free(pvk_buf);

  fclose(fp);
  RSA_free(rsa);
  
  ERR_free_strings();
  return 0;
}
