rsa_encrypt_key.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. /* OAEP pad then encrypt */
  14. int rsa_encrypt_key(const unsigned char *inkey, unsigned long inlen,
  15. unsigned char *outkey, unsigned long *outlen,
  16. const unsigned char *lparam, unsigned long lparamlen,
  17. prng_state *prng, int prng_idx, int hash_idx, rsa_key *key)
  18. {
  19. unsigned long modulus_bitlen, modulus_bytelen, x;
  20. int err;
  21. _ARGCHK(inkey != NULL);
  22. _ARGCHK(outkey != NULL);
  23. _ARGCHK(outlen != NULL);
  24. _ARGCHK(key != NULL);
  25. /* valid prng and hash ? */
  26. if ((err = prng_is_valid(prng_idx)) != CRYPT_OK) {
  27. return err;
  28. }
  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 > *outlen) {
  37. return CRYPT_BUFFER_OVERFLOW;
  38. }
  39. /* OAEP pad the key */
  40. x = *outlen;
  41. if ((err = pkcs_1_oaep_encode(inkey, inlen, lparam,
  42. lparamlen, modulus_bitlen, prng, prng_idx, hash_idx,
  43. outkey, &x)) != CRYPT_OK) {
  44. return err;
  45. }
  46. /* rsa exptmod the OAEP pad */
  47. return rsa_exptmod(outkey, x, outkey, outlen, PK_PUBLIC, prng, prng_idx, key);
  48. }
  49. #endif /* MRSA */