• 0

[C++] Displaying Asterisk's for Password Characters ("*")?


Question

I have recently been developing a program incorporating all the theory we learnt in the first year of university & it is going really well. However, I have a problem with my username & password code (something we never did in my first year).

I have a couple of minor problems but the only one I think I need help with is getting the password characters to all display as "*", in order to maintain privacy. I would like them to behave like actual characters so, for example, if I pressed backspace, I would want it to delete the last character & not display another asterisks.

I have not been able to find a solution to my problem anywhere. So please may somebody help?

I'd rather not change the whole code of my username & password function as I am happy with it at the moment, so would somebody please help me with how to implement this within my current code?

If I have to change the username & password function then I am willing to do so. Also, would anybody like me to display more of my code on this matter?

The following is the function which allows the user to enter the password (but not the whole of my username & password code as that is scattered around the program). I would assume it would have something to do with this line:

 cin >> password;

The whole function works perfectly as it should, I'd just like the password to be displayed with asterisk's :)

Here is my code anyway:

void authorisation(int& keyPressed, int& currentMonth, int& currentYear)
{
	 int getKeyPress();
	 void displayHeaderFooter( int& currentMonth, int& currentYear);
	 void loginSuccess(int& keyPressed, int& currentMonth, int& currentYear);

	 CLEAR_SCREEN();

	 displayHeaderFooter(currentMonth, currentYear);

	 ifstream Passfile("password.txt", ios::in);
	 Passfile >> inputPassword;
	 ifstream Userfile("username.txt", ios::in);
	 Userfile >> inputUsername;
   	 Gotoxy(24, 12);
	 SelectTextColour( clCyan);
	 cout << "Please enter your username.";
	 Gotoxy(42, 10);
	 cin >> username;
	 Gotoxy(24, 13);
	 SelectTextColour( clDarkCyan);
	 cout << "Please enter your password.";
	 Gotoxy(42, 11);
	 cin >> password;
	 Userfile.close();
	 Passfile.close();

	 userHeader = 1;

	 while (username == inputUsername && password == inputPassword)
	 {
		if (userHeader == 1)
		{
		Gotoxy(0, 0);
		SelectTextColour( clGrey);
		SelectBackColour( clDarkCyan);
		cout << "		" << username << "		  ";
		}

		 Gotoxy(23, 18);
		 SelectTextColour( clGreen);
		 SelectBackColour( clBlack);
		 cout << "You have logged in successfully.";
		 Gotoxy(15, 19);
		 cout << "Please press the 'M' key to display the Main Menu.";
		 loginSuccess(keyPressed, currentMonth, currentYear);
	 }


	 if (username != inputUsername || password != inputPassword)
	 {
		 Gotoxy(16, 18);
		 SelectTextColour( clRed);
		 cout << "\a";
		 cout << "The username or password you entered is invalid.";
		 Gotoxy(21, 19);
		 cout << "Please press the 'L' key to try again.";
		 keyPressed = getKeyPress();
		 if (keyPressed == 'L')
		 {
			 authorisation(keyPressed, currentMonth, currentYear);
		 }
		 else
		 {
			Gotoxy(16, 18);
			SelectTextColour( clRed);
			cout << "\a";
			cout << "	" << "The command you entered is invalid." << "	";
			Gotoxy(21, 19);
			cout << "	" << "Please press the 'L' key to login." << "	";
		 }
	 }

}

Thank you in advance. I would be very grateful for any help :)

Edited by cJr.

8 answers to this question

Recommended Posts

  • 0

cin is buffered so you'll have to use the raw file description functions to get the effect you want. Unfortunately, this type of stuff is non-standard, so you'll have to specify which OS your compiling/running this code on for us to better help you.

  • 0

Thank you for your help & advice, although I don't really understand what you said (I'm still a beginner :()

I am using Windows Vista & at the moment I'm looking to make this application Windows only. It is a Win32 console application & I am using Visual Studio 2005 (rather than DevC++ or anything which sometimes have their own libraries).

Is there any more information you need?

  • 0

Here is how to do it on windows, with example code:

http://msdn.microsoft.com/en-us/library/078sfkak.aspx

----------------------

When I say cin is buffered, it means that when you press a key, the stuff your typing is stored in a buffer until you press the enter key.

An unbuffered input means that when you press a key, that value goes straight into the variable your using to store what's inputted.

A file descriptor is simply an integer that points to some input or output in the file descriptor table in the kernel, which has the actually address of the file (on disk or in memory) and other options

For example,

when you do something like:

FILE *j;

j = fopen('abc.txt', 'r');

You are essentially get back a integer, like 3. Then in the kernel there is a structure that has something like:

0 stdin 0x00203040

1 stdout 0x02340230

2 stderr 0x23423409234

3 "abc.txt" 0x20340304

This is a very simplistic view, but I think you'll get the idea.

  • 0

I guess that will need its own routine, which you'll call from the authorisation routine. You'll have a loop that goes over each character using the aforementionned _getch_, and which will use a buffer (hm... maybe a vector<char>?) to, well, buffer all the characters and return a string when the enter key is pressed. Then if you want asteriks you just have to display a number of asteriks equal to the length of the buffer.

I'm not sure how you would implement the backspace functionality though.

  • 0

Thank you both dduardo & Dr_Asik. There are a fair few things I don't understand completely in both your posts, however, I will have a look at them in detail when I get chance & research the parts I don't understand.

I will get back to you when I have had time to look at what you've said & try a few things (if I end up understanding how to implement the _getch(); code into my code lol :s)

  Joel said:
The word you were looking for is 'asterisk'. Asterix is a comic book character.

Thank you for informing me Joel. I'm surprised because my English is normally very good (especially as I didn't pick it up on Firefox's spell-checker either) :p

  • 0
  Dr_Asik said:
I'm not sure how you would implement the backspace functionality though.

The easiest way to implement a password protection system is to simply don't print anything and ask for the password two times. This is how 99.99% of the command-line utilities do it.

But if you really want the asterisk blocked password you see in web-browsers than things get a little bit more complicated.

You'll want to use setConsoleCursorPosition and include 'windows.h'

http://msdn.microsoft.com/en-us/library/ms686025(VS.85).aspx

And do something like this:

COORD coord;

coord.X = x; coord.Y = y;

SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);

COORD is just a struct with x and y members

When ever you get a backspace code you'll move the cursor position back one and then write a space, then move the cursor back to the space to overwrite it when the user enters another character.

It seems like +cJr. is using some other library that uses gotoxy and has other console functions, but those aren't windows.h stuff, atleast from what i've found on msdn.

Edited by dduardo
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Edge for Business gets secure password deployment for organizations by Paul Hill Microsoft Edge for Business now offers organizations secure password deployments as a generally available feature, the Redmond giant said. Instead of users sharing passwords on sticky notes or via email to access certain websites or tools, admins can deploy encrypted shared passwords to specific users within their organization. When a user receives a password, it is stored in their Edge password manager and can be used to log into websites seamlessly using autofill. Microsoft has made this enterprise-grade solution available to customers at no additional cost. How it works and the user experience Administrators have to manage the feature via the Microsoft Edge management service within the Microsoft 365 admin center. From there, they can add, update, and revoke credentials for specific user groups through configuration policies. Once an admin has set it up and shared passwords with users, the users will see the passwords in their Edge password manager and can be used with autofill on corresponding websites. The passwords are tied to work profiles in Edge on managed Windows devices to limit their misuse. Further boosting security, the shared passwords cannot actually be viewed, edited, or deleted (unless the website allows), or exported from the password manager. This is a good addition for security because if an unauthorized user gains physical access to the computer, they cannot learn what the password is. Administrators reading this do need to be aware of an important caveat related to developer tools. A motivated user who wants to reveal the passwords can do so by digging into the developer tools, for this reason, you should consider restricting access to the developer tools by configuring the DeveloperToolsAvailability policy. The underlying security and encryption Microsoft’s new secure passwords feature has been built using the Information Protection SDK. The passwords are encrypted and the encryption is tied to Entra identities which lets organizations enforce them without manual key management. The decryption of the passwords takes place at runtime using the same SDK, validating the user’s identity. Availability and getting started Secure password deployment is available through the Edge management service in the Microsoft 365 admin center. Once in the admin center, you should choose an existing configuration policy or create a new one. Inside the policy, go to the Customization Settings tab and then to the Secure password deployment page. To use this feature you must have a Microsoft 365 Business Premium, E3, or E5 subscription. The feature also requires the Edge admin or Global admin role. Source: Microsoft
    • Is it though?  I built a new rig a few months ago and it was literally impossible to get one without RGB, but within 10 minutes of setting it up, I turned all that crap off.  It was REALLY distracting, and who needs additional heat INSIDE a PC? It's popular on YouTube for sure, it's neat looking and whatnot, but it's about as practical as a coffee cup with a hole in it. As for the price, a non-enthusiast would just see something priced way above what they can get from a retailer brand new...
    • RollBack Rx Pro 12.9 Build 2710971022 by Razvan Serea RollBack Rx is a robust system restore utility that enables home users and IT professionals to easily restore a PC to a time before certain events occurred. In essence, it turns your PC into a Instant Time Machine. Regardless of what happens to your PC your can quickly and easily restore your PC to a previous time. Making it easy to rescue you from any PC disaster - saving time, money and PC trouble. Windows System Restore only restores Windows system files and some program files. In addition, if Windows crashes to a point were Windows itself can not boot up (ie. BSOD*) you would not be able to access your Windows System Restore points. In contrast, the RollBack Rx technology works at the sector level of the hard drive and restores everything! - right down to the last byte of data. It sits below Windows. So even if Windows crashes, there’s a sub-console (mini OS) that boots prior to windows. This allows you to access Rollback Rx and go back to a point in time when your system was working trouble-free. Key Features Go back to any previous point in time within seconds. Go back minutes, hours, days, weeks, or even months to any previous snapshot. Does not affect computer performance, uses minimal system resources. Supports unlimited snapshots. Creates a complete system snapshot without having to restart the system. Reverse any system crash within seconds (even if Windows cannot startup). Back out of any failed program, OS updates, and botched updates. Recover from any malware or virus attack within seconds. Works with VMWare and Virtual Machines, both as a host or within the virtual machine as a client. Supports Multi-boot, Multi OS workstations. Lock snapshots to prevent deletion. Intuitive GUI based snapshot manager. Explore, browse, and retrieve files and folders from any snapshot. Drag and drop them into your active system. Roll backwards as well as forwards to any available system snapshot. Allows users to safely test any software. Fast, 100% complete uninstaller. Retrieve files from a crashed PC, even if Windows cannot boot. Access control – manage levels of multiple user and administrative privileges. Automatically schedule snapshots to be taken on a fixed schedule or upon execution of specific files (ie. setup.exe) as well as manually. 256 bit AES snapshot encryption. Prevent unauthorized data theft in case of a stolen laptop. Group Management and Enterprise Network Administration Control (FREE utility). Comes with Stealth Mode where you can hide the RollBack Rx tray icon and splash screen (seen during bootup) Change the startup hotkey for sub-console access (default is HOME). Built-in snapshot defragmenter which will optimize system resources and recover free space. Option to keep files and folders unchanged when you roll-back. Advanced setup configuration wizard for system administrators which will set deployment options and predefined RollBack Rx settings. Offers detailed program operation logging. Supports all industry-standard deployment options including silent installations and pre-installation configuration. Explore RollBack Rx Pro with a 14-day trial, fully functional on Windows 11, 10, 8, and Windows 7 SP1** (32 and 64-bit). RollBack Rx Pro 12.9 Build 2710971022 changelog: General Add PnpLockdown in shieldm.inf Fix registry exclusion problem in Windows 11 24H2 release Add detailed logging for file filter driver Add detailed logging for Windows update Add time stamp to kernel drivers Change kernel driver and Win32 IRP structure Other small bug fixes / typos reported through tech support Endpoint Manager Add client report dashboard Add sound effect when receiving a EPM message. Keep EPM message history Fix bug that oversized Windows symbol files cannot be downloaded Download: RollBack Rx Pro 12.9 | 61.0 MB (Shareware) View: RollBack Rx Home Page Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Universal Media Server 14.12.1 by Razvan Serea Universal Media Server is a DLNA-compliant UPnP Media Server. UMS was started by SubJunk, an official developer of PMS, in order to ensure greater stability and file-compatibility. The program streams or transcodes many different media formats with little or no configuration. It is powered by MEncoder, FFmpeg, tsMuxeR, AviSynth, MediaInfo and more, which combine to offer support for a wide range of media formats. Because it is written in Java, Universal Media Server supports all major operating systems, with versions for Windows, Linux and Mac OS X. To see a comparison of popular media servers, click here. Universal Media Server 14.12.1 changelog: General Added status page to readme Fixed videos not being marked as fully played (#5373) (thanks, @Fredo1650!) Fixed adding YouTube channels from handle URLs (URLs with @ in them) Fixed handling special characters on Linux (#5100) (thanks, @LaTeteDansLesEtoiles!) Fixed directory browsing crash (#5189) (thanks, @jt-gilkeson!) Fixed FFmpeg on Linux x86_64 and arm64 (#5465) (thanks, @KanjiMonster!) Fixed logspam like "Could not hydrate device or its services from descriptor" (#5292) (thanks, MTOakey!) Fixed broken YouTube video playback Fixed web interface E2E testing on CI using outdated code because of overeager caching Fixed broken video playback when burning subtitles to H.265 via FFmpeg (#5486) Improved logging Translation updates via Crowdin Chinese (Simplified) (59%) (thanks, 無情天!) Dutch (41%) (thanks, Matthias!) Hungarian (86%) (thanks, Zoltán Rózsa!) Japanese (69%) (thanks, Yukihuru!) Download: Universal Media Server 14.12.1 | 203.0 MB (Open Source) Download: Other operating systems View: Universal Media Server Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • You sign your rights to reddit when you write on their platform. Free labour for them to make money. The AI companies should also take advantage of that free labour.
  • Recent Achievements

    • Week One Done
      somar86 earned a badge
      Week One Done
    • One Month Later
      somar86 earned a badge
      One Month Later
    • Apprentice
      Adrian Williams went up a rank
      Apprentice
    • Reacting Well
      BashOrgRu earned a badge
      Reacting Well
    • Collaborator
      CHUNWEI earned a badge
      Collaborator
  • Popular Contributors

    1. 1
      +primortal
      510
    2. 2
      ATLien_0
      260
    3. 3
      +Edouard
      190
    4. 4
      +FloatingFatMan
      175
    5. 5
      snowy owl
      133
  • Tell a friend

    Love Neowin? Tell a friend!