rsa_export.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. int rsa_export(unsigned char *out, unsigned long *outlen, int type, rsa_key *key)
  14. {
  15. unsigned long y, z;
  16. int err;
  17. _ARGCHK(out != NULL);
  18. _ARGCHK(outlen != NULL);
  19. _ARGCHK(key != NULL);
  20. /* can we store the static header? */
  21. if (*outlen < (PACKET_SIZE + 1)) {
  22. return CRYPT_BUFFER_OVERFLOW;
  23. }
  24. /* type valid? */
  25. if (!(key->type == PK_PRIVATE || key->type == PK_PRIVATE_OPTIMIZED) &&
  26. (type == PK_PRIVATE || type == PK_PRIVATE_OPTIMIZED)) {
  27. return CRYPT_PK_INVALID_TYPE;
  28. }
  29. /* start at offset y=PACKET_SIZE */
  30. y = PACKET_SIZE;
  31. /* output key type */
  32. out[y++] = type;
  33. /* output modulus */
  34. OUTPUT_BIGNUM(&key->N, out, y, z);
  35. /* output public key */
  36. OUTPUT_BIGNUM(&key->e, out, y, z);
  37. if (type == PK_PRIVATE || type == PK_PRIVATE_OPTIMIZED) {
  38. OUTPUT_BIGNUM(&key->d, out, y, z);
  39. }
  40. if (type == PK_PRIVATE_OPTIMIZED) {
  41. OUTPUT_BIGNUM(&key->dQ, out, y, z);
  42. OUTPUT_BIGNUM(&key->dP, out, y, z);
  43. OUTPUT_BIGNUM(&key->pQ, out, y, z);
  44. OUTPUT_BIGNUM(&key->qP, out, y, z);
  45. OUTPUT_BIGNUM(&key->p, out, y, z);
  46. OUTPUT_BIGNUM(&key->q, out, y, z);
  47. }
  48. /* store packet header */
  49. packet_store_header(out, PACKET_SECT_RSA, PACKET_SUB_KEY);
  50. /* copy to the user buffer */
  51. *outlen = y;
  52. /* clear stack and return */
  53. return CRYPT_OK;
  54. }
  55. #endif /* MRSA */