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 P; 29 char *m, *S; 30) 31 32void mkpasswd_main(void) 33{ 34 char salt[MAX_SALT_LEN] = {0,}; 35 int i; 36 37 if (!TT.m) TT.m = "des"; 38 if (toys.optc == 2) { 39 if (TT.S) error_exit("duplicate salt"); 40 TT.S = toys.optargs[1]; 41 } 42 43 if (-1 == (i = get_salt(salt, TT.m))) error_exit("bad -m"); 44 if (TT.S) { 45 char *s = TT.S; 46 47 // In C locale, isalnum() means [A-Za-Z0-0] 48 while (isalnum(*s) || *s == '.' || *s == '/') s++; 49 if (*s) error_exit("salt not in [./A-Za-z0-9]"); 50 51 snprintf(salt+i, sizeof(salt)-i, "%s", TT.S); 52 } 53 54 // Because read_password() doesn't have an fd argument 55 if (TT.P) { 56 if (dup2(TT.P, 0) == -1) perror_exit("fd"); 57 close(TT.P); 58 } 59 60 // If we haven't got a password on the command line, read it from tty or FD 61 if (!*toys.optargs) { 62 // Prompt and read interactively? 63 if (isatty(0)) { 64 if (read_password(toybuf, sizeof(toybuf), "Password: ")) 65 perror_exit("password read failed"); 66 } else { 67 for (i = 0; i<sizeof(toybuf)-1; i++) { 68 if (!xread(0, toybuf+i, 1)) break; 69 if (toybuf[i] == '\n' || toybuf[i] == '\r') break; 70 } 71 toybuf[i] = 0; 72 } 73 } 74 75 // encrypt & print the password 76 xprintf("%s\n",crypt(*toys.optargs ? *toys.optargs : toybuf, salt)); 77} 78