rsa_v15_encrypt_key.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. /* PKCS #1 v1.5 pad then encrypt */
  14. int rsa_v15_encrypt_key(const unsigned char *inkey, unsigned long inlen,
  15. unsigned char *outkey, unsigned long *outlen,
  16. prng_state *prng, int prng_idx,
  17. 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? */
  26. if ((err = prng_is_valid(prng_idx)) != CRYPT_OK) {
  27. return err;
  28. }
  29. /* get modulus len in bits */
  30. modulus_bitlen = mp_count_bits(&(key->N));
  31. /* outlen must be at least the size of the modulus */
  32. modulus_bytelen = mp_unsigned_bin_size(&(key->N));
  33. if (modulus_bytelen > *outlen) {
  34. return CRYPT_BUFFER_OVERFLOW;
  35. }
  36. /* pad it */
  37. x = *outlen;
  38. if ((err = pkcs_1_v15_es_encode(inkey, inlen, modulus_bitlen, prng, prng_idx, outkey, &x)) != CRYPT_OK) {
  39. return err;
  40. }
  41. /* encrypt it */
  42. return rsa_exptmod(outkey, x, outkey, outlen, PK_PUBLIC, prng, prng_idx, key);
  43. }
  44. #endif