crypt_pwd.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /** BEGIN COPYRIGHT BLOCK
  2. * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission.
  3. * Copyright (C) 2005 Red Hat, Inc.
  4. * All rights reserved.
  5. * END COPYRIGHT BLOCK **/
  6. /*
  7. * slapd hashed password routines
  8. *
  9. */
  10. #include <stdio.h>
  11. #include <string.h>
  12. #include <sys/types.h>
  13. #ifdef _WIN32
  14. char *crypt(char *key, char *salt);
  15. #else
  16. #include <sys/socket.h>
  17. #if defined( hpux ) || defined ( AIX ) || defined (LINUX) || defined (OSF1)
  18. #define __USE_XOPEN /* linux */
  19. #include <unistd.h>
  20. #else /* hpux */
  21. #include <crypt.h>
  22. #endif /* hpux */
  23. #endif /* _WIN32 */
  24. #include "pwdstorage.h"
  25. static PRLock *cryptlock; /* Some implementations of crypt are not thread safe. ie. ours & Irix */
  26. /* characters used in crypt encoding */
  27. static unsigned char itoa64[] = /* 0 ... 63 => ascii - 64 */
  28. "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  29. void
  30. crypt_init()
  31. {
  32. cryptlock = PR_NewLock();
  33. }
  34. int
  35. crypt_pw_cmp( char *userpwd, char *dbpwd )
  36. {
  37. int rc;
  38. char *cp;
  39. PR_Lock(cryptlock);
  40. /* we use salt (first 2 chars) of encoded password in call to crypt() */
  41. cp = crypt( userpwd, dbpwd );
  42. if (cp) {
  43. rc= strcmp( dbpwd, cp);
  44. } else {
  45. rc = -1;
  46. }
  47. PR_Unlock(cryptlock);
  48. return rc;
  49. }
  50. char *
  51. crypt_pw_enc( char *pwd )
  52. {
  53. char *cry, salt[3];
  54. char *enc= NULL;
  55. long v;
  56. static unsigned int seed = 0;
  57. if ( seed == 0)
  58. {
  59. seed = (unsigned int)slapi_rand();
  60. }
  61. v = slapi_rand_r(&seed);
  62. salt[0] = itoa64[v & 0x3f];
  63. v >>= 6;
  64. salt[1] = itoa64[v & 0x3f];
  65. salt[2] = '\0';
  66. PR_Lock(cryptlock);
  67. cry = crypt( pwd, salt );
  68. if ( cry != NULL )
  69. {
  70. enc = slapi_ch_smprintf("%c%s%c%s", PWD_HASH_PREFIX_START, CRYPT_SCHEME_NAME, PWD_HASH_PREFIX_END, cry );
  71. }
  72. PR_Unlock(cryptlock);
  73. return( enc );
  74. }