Sunday, November 17, 2024
Google search engine
HomeLanguagesStoring passwords with Python keyring

Storing passwords with Python keyring

In this article, we will see how to store and retrieve passwords securely using Python’s keyring package.

What is a keyring package?

keyring package is a module specifically designed to securely store and retrieve passwords. It is like the keychain of MacOS, using this module and Python code we can access the system keyring service.

Only authorized users who know about the service name and the username can retrieve the password.

We will install keyring module. Write the below command in your terminal to install it.

pip install keyring

 

Implementation 

The only work of the keyring module is to store passwords securely so that an unauthorized person who doesn’t know the username and service names can’t retrieve the password.

Python3




import keyring as kr
  
# User can use the alias if they want


Saving passwords

To save a password we will use the set_password() method which takes 3 parameters –

  • servicename – The name of the service i.e to a certain organization with which the person is related to.
  • username – Username of the person.
  • password – Password associated with that username.

Python3




kr.set_password("Lazyroar","Dwaipayan","Geeks@123")


Retrieving password 

To retrieve the saved password we will use the get_password() method. It takes two parameters.

  • Servicename
  • Username

Python3




print(kr.get_password("Lazyroar","Dwaipayan"))


Output:

 

Deleting a Password 

To delete a password we will use the delete_password() method. It also takes two parameters – Servicename and username.

Python3




import keyring as kr
  
kr.set_password("Lazyroar"
                "Dwaipayan"
                "Geeks@123")
  
print("Before deleting password ",
      kr.get_password("Lazyroar"
                      "Dwaipayan"))
  
kr.delete_password("Lazyroar", "Dwaipayan")
  
print("After deleting Password"
      kr.get_password("Lazyroar", "Dwaipayan"))


Output:

 

Retrieving stored username and password

Alternatively, we can retrieve both the stored username and the password using an alternative way by just passing the service name. Using the get_credential() method we can retrieve both the username and the password. Now the get_credential method doesn’t return any value so we first have to store the result in a variable and using that variable we need to call username and password.

If we pass a blank string as the username of the get_credential() method with just the Service name, then it will return both the username and the password.

Python3




import keyring as kr
  
kr.set_password("Lazyroar","Dwaipayan","Geeks@123")
  
cred = kr.get_credential("Lazyroar","")
  
print("Username : ",cred.username)
print("Password : ",cred.password)


Output:

 

RELATED ARTICLES

Most Popular

Recent Comments