pkcs_5_1.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. /* PKCS #5, Algorithm #1 */
  13. #ifdef PKCS_5
  14. int pkcs_5_alg1(const unsigned char *password, unsigned long password_len,
  15. const unsigned char *salt,
  16. int iteration_count, int hash_idx,
  17. unsigned char *out, unsigned long *outlen)
  18. {
  19. int err;
  20. unsigned long x;
  21. hash_state *md;
  22. unsigned char *buf;
  23. _ARGCHK(password != NULL);
  24. _ARGCHK(salt != NULL);
  25. _ARGCHK(out != NULL);
  26. _ARGCHK(outlen != NULL);
  27. /* test hash IDX */
  28. if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {
  29. return err;
  30. }
  31. /* allocate memory */
  32. md = XMALLOC(sizeof(hash_state));
  33. buf = XMALLOC(MAXBLOCKSIZE);
  34. if (md == NULL || buf == NULL) {
  35. if (md != NULL) {
  36. XFREE(md);
  37. }
  38. if (buf != NULL) {
  39. XFREE(buf);
  40. }
  41. return CRYPT_MEM;
  42. }
  43. /* hash initial password + salt */
  44. hash_descriptor[hash_idx].init(md);
  45. if ((err = hash_descriptor[hash_idx].process(md, password, password_len)) != CRYPT_OK) {
  46. goto __ERR;
  47. }
  48. if ((err = hash_descriptor[hash_idx].process(md, salt, 8)) != CRYPT_OK) {
  49. goto __ERR;
  50. }
  51. if ((err = hash_descriptor[hash_idx].done(md, buf)) != CRYPT_OK) {
  52. goto __ERR;
  53. }
  54. while (--iteration_count) {
  55. // code goes here.
  56. x = MAXBLOCKSIZE;
  57. if ((err = hash_memory(hash_idx, buf, hash_descriptor[hash_idx].hashsize, buf, &x)) != CRYPT_OK) {
  58. goto __ERR;
  59. }
  60. }
  61. /* copy upto outlen bytes */
  62. for (x = 0; x < hash_descriptor[hash_idx].hashsize && x < *outlen; x++) {
  63. out[x] = buf[x];
  64. }
  65. *outlen = x;
  66. err = CRYPT_OK;
  67. __ERR:
  68. #ifdef CLEAN_STACK
  69. zeromem(buf, MAXBLOCKSIZE);
  70. zeromem(md, sizeof(hash_state));
  71. #endif
  72. XFREE(buf);
  73. XFREE(md);
  74. return err;
  75. }
  76. #endif