pkcs_1_v15_es_encode.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. /* v1.5 Encryption Padding for PKCS #1 -- Tom St Denis */
  13. #ifdef PKCS_1
  14. int pkcs_1_v15_es_encode(const unsigned char *msg, unsigned long msglen,
  15. unsigned long modulus_bitlen,
  16. prng_state *prng, int prng_idx,
  17. unsigned char *out, unsigned long *outlen)
  18. {
  19. unsigned long modulus_bytelen, x, y;
  20. _ARGCHK(msg != NULL);
  21. _ARGCHK(out != NULL);
  22. _ARGCHK(outlen != NULL);
  23. /* get modulus len */
  24. modulus_bytelen = (modulus_bitlen >> 3) + (modulus_bitlen & 7 ? 1 : 0);
  25. if (modulus_bytelen < 12) {
  26. return CRYPT_INVALID_ARG;
  27. }
  28. /* verify length */
  29. if (msglen > (modulus_bytelen - 11) || *outlen < modulus_bytelen) {
  30. return CRYPT_PK_INVALID_SIZE;
  31. }
  32. /* 0x00 0x02 PS 0x00 M */
  33. x = 0;
  34. out[x++] = 0x00;
  35. out[x++] = 0x02;
  36. y = modulus_bytelen - msglen - 3;
  37. if (prng_descriptor[prng_idx].read(out+x, y, prng) != y) {
  38. return CRYPT_ERROR_READPRNG;
  39. }
  40. x += y;
  41. out[x++] = 0x00;
  42. XMEMCPY(out+x, msg, msglen);
  43. *outlen = modulus_bytelen;
  44. return CRYPT_OK;
  45. }
  46. #endif /* PKCS_1 */