The Wayback Machine - https://web.archive.org/web/20240626005821/https://www.geeksforgeeks.org/hiding-and-encrypting-passwords-in-python/
Open In App

Hiding and encrypting passwords in Python?

Last Updated : 16 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

There are various Python modules that are used to hide the user’s inputted password, among them one is maskpass() module. In Python with the help of maskpass() module and base64() module we can hide the password of users with asterisk(*) during input time and then with the help of base64() module it can be encrypted.

maskpass()

maskpass() is a Python module that can be used to hide passwords of users during the input time. The maskpass() modules also provides a secure way to handle the password prompt where programs interact with the users via terminal.

Installation:

Use pip to install maskpass in the command prompt.

pip install maskpass

These modules have 2 types of functions/methods:

  • askpass()
  • advpass()

askpass():

askpass uses the standard library to get non-blocking input and returns the password.

import maskpass
pwd = maskpass.askpass()

The above code execution will return the entered password in a string format. There are 2 optional arguments in askpass() method, which are ‘prompt’ and ‘mask’. The default value for the prompt is ‘Enter password :’ and the default value for the mask is asterisk(*).

Note: If you want to mask your password with a string, number or symbol then just pass that value in the mask. For example, if you want to mask your password with hashtag(#) then pass hashtag in mask i.e., mask=”#”, now when the user will enter the password then that password will be hidden with hashtag(#).  

Example 1: Without echoing the password of a user in a prompt

Python3




# User's password without echoing
import maskpass  # to hide the password
 
# masking the password
pwd = maskpass.askpass(mask="") 
print(pwd)


Output:

F:\files>python password.py
Enter Password :
greeksforgreeks

In the above example, the user’s password is not echoed in a prompt while inputting the password because the value assigned in the mask is null i.e. mask=””(no spacing) hence the password is hidden without any string, symbol.

Example 2: Echoing password of user in a prompt

Python3




# Echoing password and masked with hashtag(#)
import maskpass  # importing maskpass library
 
# prompt msg = Password and
# masking password with hashtag(#)
pwd = maskpass.askpass(prompt="Password:", mask="#")
print(pwd)


Output:

F:\files>python password.py
Password:###############
greeksforgreeks

In the above example, user’s password will be echoed in a prompt while inputting the password because the value assigned in the mask is hashtag(#) i.e. mask=”#” therefore when the user will enter the password, it will be hidden with a hashtag(#). 

advpass():

advpass uses pynput to get text and returns the password. advpass works in both console and also in Spyder.

import maskpass
pwd = maskpass.advpass()

Here also above code execution will return the entered password in a string format. There are 4 optional arguments in advpass() method, they are ‘prompt’, ‘mask’, ‘ide’, and ‘suppress’.

  • Here also default value for prompt is ‘Enter password:’
  • The default value for mask is asterisk(*).
  • Here ide expects a boolean value i.e., true or false, the default value of ide is False. There is no need to change the value of ide because it’s automatically checked whether it’s running on IDE or terminal.
  • suppress also expects a boolean value i.e., true or false, is used only in Spyder IDE. Setting this as True prevents the input from being passed to the rest of the system. This prevents the Spyder console from jumping down when space bar is pressed. The default value for suppress is True.

advpass() method has a revealing feature that will toggle the visibility of the user’s entered password when the Left-Ctrl key is pressed. Press the Left-Ctrl key again to mask/hide the password. Note: This works only with advpass() and needs pynput.

Example 1: Without press of left ctrl key while inputting the password

Python3




# Type password without left CTRL press key
import maskpass  # importing maskpass library
 
# masking the password
pwd = maskpass.advpass() 
print('Password : ', pwd)


Output:

F:\files>python password.py
Enter Password: ***************
Password : greeksforgreeks

In the above output the password is hidden with asterisk(*) symbol because a user has not pressed the left ctrl key on the keyboard.

Example 2: With press of left ctrl key while inputting the password:

Python3




# Type password without left CTRL press key
import maskpass  # importing maskpass library
 
pwd = maskpass.advpass()  # masking the password
print('Password : ', pwd)


Output:

F:\files>python password.py
Enter Password: greeksforgreeks
Password : greeksforgreeks

In the above output, the password is not hidden because a user has pressed the left ctrl key on the keyboard.

base64()

The base64 encode and decode function both require a byte-like object. To convert a string into bytes, we must encode a string using Python’s built-in encode function. Mostly UTF-8 encoding is used, you can also use ‘ASCII’ to encode but I recommend using UTF-8 encoding.

Python3




# encoding the string
string = "greeksforgreek"
 
# encoding string with utf-8
b = string.encode("UTF-8") 
print(b)


Output:

F:\files>python strencode.py
b'greeksforgreek'

here b prefix denotes that the value is a byte object.

Encoding the string using base64() module:

To encode the string i.e. to convert the string into byte-code, use the following method:

base64.b64encode(‘string’.encode(“utf-8”))  

Decoding the byte-code using base64() module:

To decode the byte-code i.e. to convert the byte-code again into a string, use the following method:

base64.b64decode(‘byte-code’).decode(“utf-8”)

Example:

Python3




# importing base64 modules for
# encoding & decoding string
import base64
 
string = "GreeksforGreeks"
 
# Encoding the string
encode = base64.b64encode(string.encode("utf-8"))
print("str-byte : ", encode)
 
# Decoding the string
decode = base64.b64decode(encode).decode("utf-8")
print("byte-str : ", decode)


Output:

F:\files>python base64.py
str-byte : b'R3JlZWtzZm9yR3JlZWtz'
byte-str : GreeksforGreeks

In the above example, “GreeksforGreeks” the string is firstly encoded using base64 module i.e. string is converted into byte-code and then with help of base64 module again the byte-code is decoded into its original string i.e. “GreeksforGreeks”.

Hide the user’s password during the input time

Python3




# Hiding the inputted password with maskpass()
# and encrypting it with use of base64()
import maskpass  # to hide the password
import base64  # to encode and decode the password
 
# dictionary with username
# as key & password as value
dict = {'Rahul': b'cmFodWw=',
        'Sandeep': b'U2FuZGVlcA=='}
 
# function to create password
def createpwd():
    print("\n========Create Account=========")
    name = input("Username : ")
     
    # masking password with prompt msg 'Password :'
    pwd = maskpass.askpass("Password : ")
     
    # encoding the entered password
    encpwd = base64.b64encode(pwd.encode("utf-8"))
 
    # appending username and password in dict
    dict[name] = encpwd 
    # print(dict)
 
# function for sign-in
def sign_in():
    print("\n\n=========Login Page===========")
    name = input("Username : ")
     
    # masking password with prompt msg 'Password :'
    pwd = maskpass.askpass("Password : ")
     
    # encoding the entered password
    encpwd = base64.b64encode(pwd.encode("utf-8"))
 
    # fetching password with
    # username as key in dict
    password = dict[name] 
    if(encpwd == password):
        print("Successfully logged in.")
    else:
        print("Login Failed")
 
# calling function
createpwd()
sign_in()


Output:

F:\files>python "userLogin.py"
========Create Account=========
Username : Rahulraj
Password : *****

=========Login Page===========
Username : Rahulraj
Password : *****
Successfully logged in.


Similar Reads

Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)
Prerequisite: Object-Oriented Programming in Python | Set 1 (Class, Object and Members) Data hiding In Python, we use double underscore (Or __) before the attributes name and those attributes will not be directly visible outside. Python Code class MyClass: # Hidden member of MyClass __hiddenVariable = 0 # A member method that changes # __hiddenVari
3 min read
Python PyQt5 - Hiding the Progress Bar ?
In this article we will see how to hide the progress bar in PyQt5 application. There two ways in which we can hide the progress - Using hide method.Setting visibility status of progress bar to False. Method #1 : With the help of hide method, we can hide the progress bar. Below is the implementation. C/C++ Code # importing libraries from PyQt5.QtWid
2 min read
Data Hiding in Python
In this article, we will discuss data hiding in Python, starting from data hiding in general to data hiding in Python, along with the advantages and disadvantages of using data hiding in python. What is Data Hiding? Data hiding is a concept which underlines the hiding of data or information from the user. It is one of the key aspects of Object-Orie
3 min read
PyQt5 - Hiding the radio button
In this article we will see how we can hide the radio button, when we create a GUI(Graphical User Interface) we creates radio button but when their uses get complete there is a need to make these radio button hide so that user cant make them check or uncheck any more. In order to do to this we have to do the following: 1. Create radio button 2. Cre
2 min read
PyQt5 QSpinBox – Hiding the spin box
In this article we will see how we can hide the spin box, while making GUI(Graphical User Interface) when the use of widget get completed there is a need to remove the widget from the screen in order to do this we can hide the spin box. In order to do this we will use hide() method. Syntax : spin_box.hide() Argument : It takes no argument Return :
2 min read
PyQt5 QSpinBox – Hiding it using setHidden method
In this article we will see how we can make the spin box hidden with the help of sethidden method. We can hide the spin box using hide method as well but setHidden method takes bool as argument which determine whether it should hide the spin box or not when called. In order to do so we use setHidden method. Syntax : spin_box.setHidden(bool) Argumen
2 min read
PyQt5 QCalendarWidget - Hiding according to the user
In this article we will see how we can hide the QCalendarWidget according to the user, hiding is exactly opposite of showing the QCalendarWidget. Calendar widget is a big widget therefore there is need to hide it when user don't need it. In order to do this we will use hide method with the QCalendarWidget object.Syntax : calendar.hide()Argument : I
2 min read
PyQt5 QCalendarWidget - Hiding the Navigation Bar
In this article we will see how we can hide the navigation bar of the QCalendarWidget. Navigation bar is the top section of the calendar which is used to change the next month, previous month, month selection, year selection. By default navigation bar is visible although we can hide it any time, below is the representation of navigation bar of QCal
1 min read
Remember and copy passwords to clipboard using Pyperclip module in Python
It is always a difficult job to remember all our passwords for different accounts. So this is a really simple Python program which uses sys module to obtain account name as argument from the command terminal and pyperclip module to paste the respective account's password to the clipboard. Pyperclip module does not come pre-installed with Python. To
2 min read
GUI to generate and store passwords in SQLite using Python
In this century there are many social media accounts, websites, or any online account that needs a secure password. Often we use the same password for multiple accounts and the basic drawback to that is if somebody gets to know about your password then he/she has the access to all your accounts. It is hard to remember all the distinct passwords. We
8 min read
Practice Tags :
three90RightbarBannerImg