rsa_decrypt_key.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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/prng ? */
  29. if ((err = prng_is_valid(prng_idx)) != CRYPT_OK) {
  30. return err;
  31. }
  32. if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {
  33. return err;
  34. }
  35. /* get modulus len in bits */
  36. modulus_bitlen = mp_count_bits(&(key->N));
  37. /* outlen must be at least the size of the modulus */
  38. modulus_bytelen = mp_unsigned_bin_size(&(key->N));
  39. if (modulus_bytelen != inlen) {
  40. return CRYPT_INVALID_PACKET;
  41. }
  42. /* allocate ram */
  43. tmp = XMALLOC(inlen);
  44. if (tmp == NULL) {
  45. return CRYPT_MEM;
  46. }
  47. /* rsa decode the packet */
  48. x = inlen;
  49. if ((err = rsa_exptmod(in, inlen, tmp, &x, PK_PRIVATE, prng, prng_idx, key)) != CRYPT_OK) {
  50. XFREE(tmp);
  51. return err;
  52. }
  53. /* now OAEP decode the packet */
  54. err = pkcs_1_oaep_decode(tmp, x, lparam, lparamlen, modulus_bitlen, hash_idx,
  55. outkey, keylen, res);
  56. XFREE(tmp);
  57. return err;
  58. }
  59. #endif /* MRSA */