rsa_export.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. /* This will export either an RSAPublicKey or RSAPrivateKey [defined in PKCS #1 v2.1] */
  14. int rsa_export(unsigned char *out, unsigned long *outlen, int type, rsa_key *key)
  15. {
  16. int err;
  17. _ARGCHK(out != NULL);
  18. _ARGCHK(outlen != NULL);
  19. _ARGCHK(key != NULL);
  20. /* type valid? */
  21. if (!(key->type == PK_PRIVATE) && (type == PK_PRIVATE)) {
  22. return CRYPT_PK_INVALID_TYPE;
  23. }
  24. if (type == PK_PRIVATE) {
  25. /* private key */
  26. mp_int zero;
  27. /* first INTEGER == 0 to signify two-prime RSA */
  28. if ((err = mp_init(&zero)) != MP_OKAY) {
  29. return mpi_to_ltc_error(err);
  30. }
  31. /* output is
  32. Version, n, e, d, p, q, d mod (p-1), d mod (q - 1), 1/q mod p
  33. */
  34. err = der_put_multi_integer(out, outlen, &zero, &key->N, &key->e,
  35. &key->d, &key->p, &key->q, &key->dP,
  36. &key->dQ, &key->qP, NULL);
  37. /* clear zero and return */
  38. mp_clear(&zero);
  39. return err;
  40. } else {
  41. /* public key */
  42. return der_put_multi_integer(out, outlen, &key->N, &key->e, NULL);
  43. }
  44. }
  45. #endif /* MRSA */