rsa_v15_decrypt_key.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. /* decrypt then PKCS #1 v1.5 depad */
  14. int rsa_v15_decrypt_key(const unsigned char *in, unsigned long inlen,
  15. unsigned char *outkey, unsigned long keylen,
  16. prng_state *prng, int prng_idx,
  17. int *res, rsa_key *key)
  18. {
  19. unsigned long modulus_bitlen, modulus_bytelen, x;
  20. int err;
  21. unsigned char *tmp;
  22. _ARGCHK(outkey != NULL);
  23. _ARGCHK(key != NULL);
  24. _ARGCHK(res != NULL);
  25. /* default to invalid */
  26. *res = 0;
  27. /* valid prng ? */
  28. if ((err = prng_is_valid(prng_idx)) != CRYPT_OK) {
  29. return err;
  30. }
  31. /* get modulus len in bits */
  32. modulus_bitlen = mp_count_bits(&(key->N));
  33. /* outlen must be at least the size of the modulus */
  34. modulus_bytelen = mp_unsigned_bin_size(&(key->N));
  35. if (modulus_bytelen != inlen) {
  36. return CRYPT_INVALID_PACKET;
  37. }
  38. /* allocate ram */
  39. tmp = XMALLOC(inlen);
  40. if (tmp == NULL) {
  41. return CRYPT_MEM;
  42. }
  43. /* rsa decode the packet */
  44. x = inlen;
  45. if ((err = rsa_exptmod(in, inlen, tmp, &x, PK_PRIVATE, prng, prng_idx, key)) != CRYPT_OK) {
  46. XFREE(tmp);
  47. return err;
  48. }
  49. /* PKCS #1 v1.5 depad */
  50. err = pkcs_1_v15_es_decode(tmp, x, modulus_bitlen, outkey, keylen, res);
  51. XFREE(tmp);
  52. return err;
  53. }
  54. #endif