crypt_pwd.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /** BEGIN COPYRIGHT BLOCK
  2. * Copyright 2001 Sun Microsystems, Inc.
  3. * Portions copyright 1999, 2001-2003 Netscape Communications Corporation.
  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_malloc( 3 + CRYPT_NAME_LEN + strlen( cry ));
  71. if ( enc != NULL )
  72. {
  73. sprintf( enc, "%c%s%c%s", PWD_HASH_PREFIX_START, CRYPT_SCHEME_NAME, PWD_HASH_PREFIX_END, cry );
  74. }
  75. }
  76. PR_Unlock(cryptlock);
  77. return( enc );
  78. }