pw_encrypt.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routine.
  4. *
  5. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  8. */
  9. #include "libbb.h"
  10. #if ENABLE_USE_BB_CRYPT
  11. /*
  12. * DES and MD5 crypt implementations are taken from uclibc.
  13. * They were modified to not use static buffers.
  14. */
  15. /* Common for them */
  16. static const uint8_t ascii64[] = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  17. #include "pw_encrypt_des.c"
  18. #include "pw_encrypt_md5.c"
  19. /* Other advanced crypt ids: */
  20. /* $2$ or $2a$: Blowfish */
  21. /* $5$: SHA-256 */
  22. /* $6$: SHA-512 */
  23. /* TODO: implement SHA - http://people.redhat.com/drepper/SHA-crypt.txt */
  24. static struct const_des_ctx *des_cctx;
  25. static struct des_ctx *des_ctx;
  26. /* my_crypt returns malloc'ed data */
  27. static char *my_crypt(const char *key, const char *salt)
  28. {
  29. /* First, check if we are supposed to be using the MD5 replacement
  30. * instead of DES... */
  31. if (salt[0] == '$' && salt[1] == '1' && salt[2] == '$') {
  32. return md5_crypt(xzalloc(MD5_OUT_BUFSIZE), (unsigned char*)key, (unsigned char*)salt);
  33. }
  34. {
  35. if (!des_cctx)
  36. des_cctx = const_des_init();
  37. des_ctx = des_init(des_ctx, des_cctx);
  38. return des_crypt(des_ctx, xzalloc(DES_OUT_BUFSIZE), (unsigned char*)key, (unsigned char*)salt);
  39. }
  40. }
  41. /* So far nobody wants to have it public */
  42. static void my_crypt_cleanup(void)
  43. {
  44. free(des_cctx);
  45. free(des_ctx);
  46. des_cctx = NULL;
  47. des_ctx = NULL;
  48. }
  49. char* FAST_FUNC pw_encrypt(const char *clear, const char *salt, int cleanup)
  50. {
  51. char *encrypted;
  52. encrypted = my_crypt(clear, salt);
  53. if (cleanup)
  54. my_crypt_cleanup();
  55. return encrypted;
  56. }
  57. #else /* if !ENABLE_USE_BB_CRYPT */
  58. char* FAST_FUNC pw_encrypt(const char *clear, const char *salt, int cleanup)
  59. {
  60. return xstrdup(crypt(clear, salt));
  61. }
  62. #endif