pkcs_1_mgf1.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. /* The Mask Generation Function (MGF1) for PKCS #1 -- Tom St Denis */
  13. #ifdef PKCS_1
  14. int pkcs_1_mgf1(const unsigned char *seed, unsigned long seedlen,
  15. int hash_idx,
  16. unsigned char *mask, unsigned long masklen)
  17. {
  18. unsigned long hLen, counter, x;
  19. int err;
  20. hash_state *md;
  21. unsigned char *buf;
  22. _ARGCHK(seed != NULL);
  23. _ARGCHK(mask != NULL);
  24. /* ensure valid hash */
  25. if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {
  26. return err;
  27. }
  28. /* get hash output size */
  29. hLen = hash_descriptor[hash_idx].hashsize;
  30. /* allocate memory */
  31. md = XMALLOC(sizeof(hash_state));
  32. buf = XMALLOC(hLen);
  33. if (md == NULL || buf == NULL) {
  34. if (md != NULL) {
  35. XFREE(md);
  36. }
  37. if (buf != NULL) {
  38. XFREE(buf);
  39. }
  40. return CRYPT_MEM;
  41. }
  42. /* start counter */
  43. counter = 0;
  44. while (masklen > 0) {
  45. /* handle counter */
  46. STORE32H(counter, buf);
  47. ++counter;
  48. /* get hash of seed || counter */
  49. hash_descriptor[hash_idx].init(md);
  50. if ((err = hash_descriptor[hash_idx].process(md, seed, seedlen)) != CRYPT_OK) {
  51. goto __ERR;
  52. }
  53. if ((err = hash_descriptor[hash_idx].process(md, buf, 4)) != CRYPT_OK) {
  54. goto __ERR;
  55. }
  56. if ((err = hash_descriptor[hash_idx].done(md, buf)) != CRYPT_OK) {
  57. goto __ERR;
  58. }
  59. /* store it */
  60. for (x = 0; x < hLen && masklen > 0; x++, masklen--) {
  61. *mask++ = buf[x];
  62. }
  63. }
  64. err = CRYPT_OK;
  65. __ERR:
  66. #ifdef CLEAN_STACK
  67. zeromem(buf, hLen);
  68. zeromem(md, sizeof(hash_state));
  69. #endif
  70. XFREE(buf);
  71. XFREE(md);
  72. return err;
  73. }
  74. #endif /* PKCS_1 */