rsa_decrypt_key.c 1.8 KB

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