loadrsa.c 1.2 KB

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