2
0

rsa_export.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* LibTomCrypt, modular cryptographic library -- Tom St Denis
  2. *
  3. * LibTomCrypt is a library that provides various cryptographic
  4. * algorithms in a highly modular and flexible manner.
  5. *
  6. * The library is free for all purposes without any express
  7. * guarantee it works.
  8. *
  9. * Tom St Denis, [email protected], http://libtomcrypt.org
  10. */
  11. #include "mycrypt.h"
  12. #ifdef MRSA
  13. /* Export an RSA key */
  14. int rsa_export(unsigned char *out, unsigned long *outlen, int type, rsa_key *key)
  15. {
  16. unsigned long y, z;
  17. int err;
  18. _ARGCHK(out != NULL);
  19. _ARGCHK(outlen != NULL);
  20. _ARGCHK(key != NULL);
  21. /* can we store the static header? */
  22. if (*outlen < (PACKET_SIZE + 1)) {
  23. return CRYPT_BUFFER_OVERFLOW;
  24. }
  25. /* type valid? */
  26. if (!(key->type == PK_PRIVATE || key->type == PK_PRIVATE_OPTIMIZED) &&
  27. (type == PK_PRIVATE || type == PK_PRIVATE_OPTIMIZED)) {
  28. return CRYPT_PK_INVALID_TYPE;
  29. }
  30. /* start at offset y=PACKET_SIZE */
  31. y = PACKET_SIZE;
  32. /* output key type */
  33. out[y++] = type;
  34. /* output modulus */
  35. OUTPUT_BIGNUM(&key->N, out, y, z);
  36. /* output public key */
  37. OUTPUT_BIGNUM(&key->e, out, y, z);
  38. if (type == PK_PRIVATE || type == PK_PRIVATE_OPTIMIZED) {
  39. OUTPUT_BIGNUM(&key->d, out, y, z);
  40. }
  41. if (type == PK_PRIVATE_OPTIMIZED) {
  42. OUTPUT_BIGNUM(&key->dQ, out, y, z);
  43. OUTPUT_BIGNUM(&key->dP, out, y, z);
  44. OUTPUT_BIGNUM(&key->pQ, out, y, z);
  45. OUTPUT_BIGNUM(&key->qP, out, y, z);
  46. OUTPUT_BIGNUM(&key->p, out, y, z);
  47. OUTPUT_BIGNUM(&key->q, out, y, z);
  48. }
  49. /* store packet header */
  50. packet_store_header(out, PACKET_SECT_RSA, PACKET_SUB_KEY);
  51. /* copy to the user buffer */
  52. *outlen = y;
  53. /* clear stack and return */
  54. return CRYPT_OK;
  55. }
  56. #endif /* MRSA */