OpenSSL  1.0.1c
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Macros
loadrsa.c
Go to the documentation of this file.
1 #include <stdio.h>
2 #include <openssl/rsa.h>
3 
4 /* This is a simple program to generate an RSA private key. It then
5  * saves both the public and private key into a char array, then
6  * re-reads them. It saves them as DER encoded binary data.
7  */
8 
9 void callback(stage,count,arg)
10 int stage,count;
11 char *arg;
12  {
13  FILE *out;
14 
15  out=(FILE *)arg;
16  fprintf(out,"%d",stage);
17  if (stage == 3)
18  fprintf(out,"\n");
19  fflush(out);
20  }
21 
23  {
24  RSA *rsa,*pub_rsa,*priv_rsa;
25  int len;
26  unsigned char buf[1024],*p;
27 
28  rsa=RSA_generate_key(512,RSA_F4,callback,(char *)stdout);
29 
30  p=buf;
31 
32  /* Save the public key into buffer, we know it will be big enough
33  * but we should really check how much space we need by calling the
34  * i2d functions with a NULL second parameter */
35  len=i2d_RSAPublicKey(rsa,&p);
36  len+=i2d_RSAPrivateKey(rsa,&p);
37 
38  printf("The public and private key are now both in a char array\n");
39  printf("and are taking up %d bytes\n",len);
40 
41  RSA_free(rsa);
42 
43  p=buf;
44  pub_rsa=d2i_RSAPublicKey(NULL,&p,(long)len);
45  len-=(p-buf);
46  priv_rsa=d2i_RSAPrivateKey(NULL,&p,(long)len);
47 
48  if ((pub_rsa == NULL) || (priv_rsa == NULL))
49  ERR_print_errors_fp(stderr);
50 
51  RSA_free(pub_rsa);
52  RSA_free(priv_rsa);
53  }