1

I am writing a Linux CLI program. I need to get a password from the user and, obviously, I don't want the password to be echoed to the console.

There are several solutions available here, but they are all for plain C. C command-line password input
How to mask password in c?
Getting a password in C without using getpass (3)?

How can those be adapted for C++, using std::string instead of char[]?

What would be the most elegant C++ solution?

Community
  • 1
  • 1
augustin
  • 14,373
  • 13
  • 66
  • 79
  • 1
    If you have a `char x[]`, you can create `std::string s(x);`. – Tony Delroy Oct 29 '10 at 09:57
  • 2
    If you care about security, then don't use `std::string`, use a plain old `char` buffer in an `mlock`'d region to avoid the password being copied all over memory and ending up in the swap file. Erase it with `memset` as soon as you're done with it. – Fred Foo Oct 29 '10 at 10:56
  • @Tony: thanks. I'm still struggling with the basics, so I don't yet think about simple things like this. – augustin Oct 29 '10 at 14:24
  • @larsmans: thanks. I do care about security and study about it a bit every day. Your advice is useful. +1 as well. – augustin Oct 29 '10 at 14:24
  • possible duplicate of [Read a password from std::cin](http://stackoverflow.com/questions/1413445/read-a-password-from-stdcin) – jww Oct 06 '14 at 04:34

2 Answers2

2

Linux itself is written (mostly) in C, so anything you could find in C++ would only be an abstraction around a single C routine. Better to call the routine yourself, converting the input and result.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2

Use any of the plain C solutions:

std::string pass (100);  // size the string at your max password size (minus one)

func_to_get_pass(&pass[0], pass.size());
// function takes a char* and the max size to write (including a null char)

pass.resize(pass.find('\0'));

cout << "Your password is " << pass << ".\n"; // oops! don't show it ;)