Hiding and encrypting passwords in Python? - GeeksforGeeks (2024)

Last Updated : 16 Feb, 2022

Summarize

Comments

Improve

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 maskpasspwd = 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.pyEnter 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.pyPassword:###############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 maskpasspwd = 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.pyEnter 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.pyEnter Password: greeksforgreeksPassword : 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

See Also
rsa

# encoding the string

string = "greeksforgreek"

# encoding string with utf-8

b = string.encode("UTF-8")

print(b)

Output:

F:\files>python strencode.pyb'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.pystr-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 : RahulrajPassword : *****=========Login Page===========Username : RahulrajPassword : *****Successfully logged in.


yadavrahulraj

Hiding and encrypting passwords in Python? - GeeksforGeeks (2)

Improve

Next Article

Hashing Passwords in Python with BCrypt

Please Login to comment...

Hiding and encrypting passwords in Python? - GeeksforGeeks (2024)
Top Articles
ESG Reporting 101: What You Need To Know
Send Money Abroad with your Credit Card
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
Things To Do In Atlanta Tomorrow Night
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Dmv In Anoka
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Rogold Extension
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Weekly Math Review Q4 3
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
Selly Medaline
Latest Posts
Article information

Author: Ray Christiansen

Last Updated:

Views: 5939

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Ray Christiansen

Birthday: 1998-05-04

Address: Apt. 814 34339 Sauer Islands, Hirtheville, GA 02446-8771

Phone: +337636892828

Job: Lead Hospitality Designer

Hobby: Urban exploration, Tai chi, Lockpicking, Fashion, Gunsmithing, Pottery, Geocaching

Introduction: My name is Ray Christiansen, I am a fair, good, cute, gentle, vast, glamorous, excited person who loves writing and wants to share my knowledge and understanding with you.