rsa_import.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. /* import an RSAPublicKey or RSAPrivateKey [two-prime only, defined in PKCS #1 v2.1] */
  14. int rsa_import(const unsigned char *in, unsigned long inlen, rsa_key *key)
  15. {
  16. unsigned long x;
  17. int err;
  18. _ARGCHK(in != NULL);
  19. _ARGCHK(key != NULL);
  20. /* init key */
  21. if ((err = mp_init_multi(&key->e, &key->d, &key->N, &key->dQ, &key->dP, &key->qP,
  22. &key->p, &key->q, NULL)) != MP_OKAY) {
  23. return mpi_to_ltc_error(err);
  24. }
  25. /* read first number, it's either N or 0 [0 == private key] */
  26. x = inlen;
  27. if ((err = der_get_multi_integer(in, &x, &key->N, NULL)) != CRYPT_OK) {
  28. goto __ERR;
  29. }
  30. /* advance */
  31. inlen -= x;
  32. in += x;
  33. if (mp_cmp_d(&key->N, 0) == MP_EQ) {
  34. /* it's a private key */
  35. if ((err = der_get_multi_integer(in, &inlen, &key->N, &key->e,
  36. &key->d, &key->p, &key->q, &key->dP,
  37. &key->dQ, &key->qP, NULL)) != CRYPT_OK) {
  38. goto __ERR;
  39. }
  40. key->type = PK_PRIVATE;
  41. } else {
  42. /* it's a public key and we lack e */
  43. if ((err = der_get_multi_integer(in, &inlen, &key->e, NULL)) != CRYPT_OK) {
  44. goto __ERR;
  45. }
  46. /* free up some ram */
  47. mp_clear_multi(&key->p, &key->q, &key->qP, &key->dP, &key->dQ, NULL);
  48. key->type = PK_PUBLIC;
  49. }
  50. return CRYPT_OK;
  51. __ERR:
  52. mp_clear_multi(&key->d, &key->e, &key->N, &key->dQ, &key->dP,
  53. &key->qP, &key->p, &key->q, NULL);
  54. return err;
  55. }
  56. #endif /* MRSA */