pkcs_1_mgf1.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. if ((err = hash_descriptor[hash_idx].init(md)) != CRYPT_OK) {
  50. goto __ERR;
  51. }
  52. if ((err = hash_descriptor[hash_idx].process(md, seed, seedlen)) != CRYPT_OK) {
  53. goto __ERR;
  54. }
  55. if ((err = hash_descriptor[hash_idx].process(md, buf, 4)) != CRYPT_OK) {
  56. goto __ERR;
  57. }
  58. if ((err = hash_descriptor[hash_idx].done(md, buf)) != CRYPT_OK) {
  59. goto __ERR;
  60. }
  61. /* store it */
  62. for (x = 0; x < hLen && masklen > 0; x++, masklen--) {
  63. *mask++ = buf[x];
  64. }
  65. }
  66. err = CRYPT_OK;
  67. __ERR:
  68. #ifdef CLEAN_STACK
  69. zeromem(buf, hLen);
  70. zeromem(md, sizeof(hash_state));
  71. #endif
  72. XFREE(buf);
  73. XFREE(md);
  74. return err;
  75. }
  76. #endif /* PKCS_1 */