Getting a Hidden Password Input
Safely get a password input in Python using getpass
. Just call the getpass.getpass()
function and your input will be nicely obscured:
The catch is, getpass
works smoothly in a terminal environment. Don't count on it too much in IDLE - it might throw a tantrum.
Alternative strategies
Asterisk masking with getch
If you fancy giving your users some visual feedback in the form of asterisks (*
) when they're typing a password, you can turn to msvcrt.getch()
. Here's how you can do it in Windows:
Authenticate with getch and pwinput
If you are looking for a solution that works like a charm regardless of the platform or need more flexibility with your input, you might want to check out the getch
module from PyPI or the pwinput
module:
pwinput
even allows you to modify the mask character:
Advocate for security
Keep the secrets safe
When handling sensitive data, it's best to tread with care. Keep the passwords in checks and balances - avoid storing in plain text or in places that shout 'here be secrets', like logs. Use them transiently and consider encryption for longer-term storage.
Use the right tools
Consider incorporating libraries such as PyCryptodome for additional security layers when handling passwords. Always hash the passwords before you lock them up and use a trusted library for hashing like bcrypt
or argon2
. They won't disappoint!
Enhancing the user experience
Although asterisks and other characters add an extra layer of user comfort, remember they are just for show. The key to successful password secrecy is the hidden data transfer to your application.
Building strong password policies
Don't just secure passwords, super-secure them. Make getpass
work hand in hand with strong cryptography libraries to maintain password integrity from the point of entry, during transfer and at restโend to end protection.
Was this article helpful?