pbkdf2.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* $OpenBSD: pbkdf2.c,v 1.1 2012/10/09 12:36:50 jsing Exp $ */
  2. /*-
  3. * Copyright (c) 2008 Damien Bergamini <damien.bergamini@free.fr>
  4. *
  5. * Permission to use, copy, modify, and distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  12. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  15. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. */
  17. #include <sys/param.h>
  18. #include <lib/libsa/stand.h>
  19. #include "pbkdf2.h"
  20. #include "hmac_sha1.h"
  21. /*
  22. * Password-Based Key Derivation Function 2 (PKCS #5 v2.0).
  23. * Code based on IEEE Std 802.11-2007, Annex H.4.2.
  24. */
  25. int
  26. pkcs5_pbkdf2(const char *pass, size_t pass_len, const char *salt,
  27. size_t salt_len, u_int8_t *key, size_t key_len, u_int rounds)
  28. {
  29. u_int8_t *asalt, obuf[SHA1_DIGEST_LENGTH];
  30. u_int8_t d1[SHA1_DIGEST_LENGTH], d2[SHA1_DIGEST_LENGTH];
  31. u_int i, j;
  32. u_int count;
  33. size_t r;
  34. if (rounds < 1 || key_len == 0)
  35. return -1;
  36. if (salt_len == 0 || salt_len > SIZE_MAX - 1)
  37. return -1;
  38. if ((asalt = alloca(salt_len + 4)) == NULL)
  39. return -1;
  40. memcpy(asalt, salt, salt_len);
  41. for (count = 1; key_len > 0; count++) {
  42. asalt[salt_len + 0] = (count >> 24) & 0xff;
  43. asalt[salt_len + 1] = (count >> 16) & 0xff;
  44. asalt[salt_len + 2] = (count >> 8) & 0xff;
  45. asalt[salt_len + 3] = count & 0xff;
  46. hmac_sha1(asalt, salt_len + 4, pass, pass_len, d1);
  47. memcpy(obuf, d1, sizeof(obuf));
  48. for (i = 1; i < rounds; i++) {
  49. hmac_sha1(d1, sizeof(d1), pass, pass_len, d2);
  50. memcpy(d1, d2, sizeof(d1));
  51. for (j = 0; j < sizeof(obuf); j++)
  52. obuf[j] ^= d1[j];
  53. }
  54. r = MIN(key_len, SHA1_DIGEST_LENGTH);
  55. memcpy(key, obuf, r);
  56. key += r;
  57. key_len -= r;
  58. };
  59. explicit_bzero(asalt, salt_len + 4);
  60. explicit_bzero(d1, sizeof(d1));
  61. explicit_bzero(d2, sizeof(d2));
  62. explicit_bzero(obuf, sizeof(obuf));
  63. return 0;
  64. }