1
0

secure_input.c 820 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #include "secure_input.h"
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #ifndef WIN32
  5. # include <termios.h>
  6. # include <sys/ioctl.h>
  7. #endif
  8. void
  9. secure_input(char *buf, size_t buf_size)
  10. {
  11. #ifndef WIN32
  12. struct termio ttymode;
  13. #endif
  14. int pos;
  15. int ch;
  16. #ifndef WIN32
  17. // hide input
  18. ioctl(STDIN_FILENO, TCGETA, &ttymode);
  19. ttymode.c_lflag &= ~( ECHO | ECHOE | ECHONL );
  20. ioctl(STDIN_FILENO, TCSETAF, &ttymode);
  21. #endif
  22. pos=0;
  23. ch=fgetc(stdin);
  24. while (pos < buf_size-1 && ch != '\n' && ch != EOF) {
  25. buf[pos] = ch;
  26. pos++;
  27. ch=fgetc(stdin);
  28. }
  29. buf[pos] = '\0';
  30. // flush the stdin buffer of remaining unused characters
  31. while (ch != '\n' && ch != EOF)
  32. ch = fgetc(stdin);
  33. #ifndef WIN32
  34. // unhide input
  35. ttymode.c_lflag |= ECHO | ECHOE | ECHONL;
  36. ioctl(STDIN_FILENO, TCSETAF, &ttymode);
  37. fputc('\n', stdout);
  38. #endif
  39. }