pkcs_5_1.c 2.2 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. /* 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. if ((err = hash_descriptor[hash_idx].init(md)) != CRYPT_OK) {
  45. goto __ERR;
  46. }
  47. if ((err = hash_descriptor[hash_idx].process(md, password, password_len)) != CRYPT_OK) {
  48. goto __ERR;
  49. }
  50. if ((err = hash_descriptor[hash_idx].process(md, salt, 8)) != CRYPT_OK) {
  51. goto __ERR;
  52. }
  53. if ((err = hash_descriptor[hash_idx].done(md, buf)) != CRYPT_OK) {
  54. goto __ERR;
  55. }
  56. while (--iteration_count) {
  57. // code goes here.
  58. x = MAXBLOCKSIZE;
  59. if ((err = hash_memory(hash_idx, buf, hash_descriptor[hash_idx].hashsize, buf, &x)) != CRYPT_OK) {
  60. goto __ERR;
  61. }
  62. }
  63. /* copy upto outlen bytes */
  64. for (x = 0; x < hash_descriptor[hash_idx].hashsize && x < *outlen; x++) {
  65. out[x] = buf[x];
  66. }
  67. *outlen = x;
  68. err = CRYPT_OK;
  69. __ERR:
  70. #ifdef CLEAN_STACK
  71. zeromem(buf, MAXBLOCKSIZE);
  72. zeromem(md, sizeof(hash_state));
  73. #endif
  74. XFREE(buf);
  75. XFREE(md);
  76. return err;
  77. }
  78. #endif