mkpasswd.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* mkpasswd.c - encrypt the given passwd using salt
  2. *
  3. * Copyright 2013 Ashwini Kumar <ak.ashwini@gmail.com>
  4. * Copyright 2013 Kyungwan Han <asura321@gmail.com>
  5. *
  6. * No Standard
  7. USE_MKPASSWD(NEWTOY(mkpasswd, ">2S:m:P#=0<0", TOYFLAG_USR|TOYFLAG_BIN))
  8. config MKPASSWD
  9. bool "mkpasswd"
  10. default y
  11. depends on !TOYBOX_ON_ANDROID
  12. help
  13. usage: mkpasswd [-P FD] [-m TYPE] [-S SALT] [PASSWORD] [SALT]
  14. Crypt PASSWORD using crypt(3)
  15. -P FD Read password from file descriptor FD
  16. -m TYPE Encryption method (des, md5, sha256, or sha512; default is des)
  17. -S SALT
  18. */
  19. #define FOR_mkpasswd
  20. #include "toys.h"
  21. GLOBALS(
  22. long P;
  23. char *m, *S;
  24. )
  25. void mkpasswd_main(void)
  26. {
  27. char salt[MAX_SALT_LEN] = {0,};
  28. int i;
  29. if (!TT.m) TT.m = "des";
  30. if (toys.optc == 2) {
  31. if (TT.S) error_exit("duplicate salt");
  32. TT.S = toys.optargs[1];
  33. }
  34. if (-1 == (i = get_salt(salt, TT.m))) error_exit("bad -m");
  35. if (TT.S) {
  36. char *s = TT.S;
  37. // In C locale, isalnum() means [A-Za-Z0-0]
  38. while (isalnum(*s) || *s == '.' || *s == '/') s++;
  39. if (*s) error_exit("salt not in [./A-Za-z0-9]");
  40. snprintf(salt+i, sizeof(salt)-i, "%s", TT.S);
  41. }
  42. // Because read_password() doesn't have an fd argument
  43. if (TT.P) {
  44. if (dup2(TT.P, 0) == -1) perror_exit("fd");
  45. close(TT.P);
  46. }
  47. // If we haven't got a password on the command line, read it from tty or FD
  48. if (!*toys.optargs) {
  49. // Prompt and read interactively?
  50. if (isatty(0)) {
  51. if (read_password(toybuf, sizeof(toybuf), "Password: "))
  52. perror_exit("password read failed");
  53. } else {
  54. for (i = 0; i<sizeof(toybuf)-1; i++) {
  55. if (!xread(0, toybuf+i, 1)) break;
  56. if (toybuf[i] == '\n' || toybuf[i] == '\r') break;
  57. }
  58. toybuf[i] = 0;
  59. }
  60. }
  61. // encrypt & print the password
  62. xprintf("%s\n",crypt(*toys.optargs ? *toys.optargs : toybuf, salt));
  63. }