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