passtokey.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include <errno.h>
  2. #include <fcntl.h>
  3. #include <stdarg.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <termios.h>
  8. #include <unistd.h>
  9. #include "util.h"
  10. char *readpass(char *pw, int n);
  11. void setecho(int);
  12. static void
  13. usage(void)
  14. {
  15. fprint(2, "usage: passtokey\n");
  16. exit(1);
  17. }
  18. int
  19. main(int argc, char *argv[])
  20. {
  21. int c;
  22. char pw0[28+1], pw1[28+1];
  23. uchar key[Deskeylen];
  24. char *err;
  25. while((c = getopt(argc, argv, "")) != -1)
  26. switch(c) {
  27. default:
  28. usage();
  29. }
  30. argc -= optind;
  31. argv += optind;
  32. if(argc != 0)
  33. usage();
  34. setecho(0);
  35. for(;;) {
  36. fprintf(stderr, "password: ");
  37. fflush(stderr);
  38. if((err = readpass(pw0, sizeof pw0)) != nil) {
  39. fprintf(stderr, "\nbad password (%s), try again\n", err);
  40. continue;
  41. }
  42. fprintf(stderr, "\nconfirm: ");
  43. readpass(pw1, sizeof pw1);
  44. if(strcmp(pw0, pw1) == 0)
  45. break;
  46. fprintf(stderr, "\nmismatch, try again\n");
  47. }
  48. setecho(1);
  49. fprintf(stderr, "\n");
  50. passtokey(key, pw0);
  51. if(write(1, key, sizeof key) != sizeof key) {
  52. fprintf(stderr, "writing key: %s\n", strerror(errno));
  53. exit(1);
  54. }
  55. exit(0);
  56. }
  57. void
  58. setecho(int on)
  59. {
  60. struct termios term;
  61. tcgetattr(0, &term);
  62. if(on)
  63. term.c_lflag |= (ECHO|ECHOE|ECHOK|ECHONL);
  64. else
  65. term.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL);
  66. tcsetattr(0, TCSAFLUSH, &term);
  67. }
  68. char *
  69. readpass(char *pw, int n)
  70. {
  71. size_t len;
  72. char buf[64];
  73. if(fgets(buf, sizeof buf, stdin) == nil)
  74. return "read error";
  75. len = strlen(buf);
  76. if(buf[len-1] == '\n')
  77. buf[--len] = '\0';
  78. if(len < 6)
  79. return "too short";
  80. if(len >= n)
  81. return "too long";
  82. memmove(pw, buf, len+1);
  83. return nil;
  84. }