Secure Password Storage in Python: A Guide to Keyring

TechSwitchTechSwitch
1 min read
import os
import keyring


def set_password(service_name, username, password):
    try:
        # Set the password in the keyring
        keyring.set_password(service_name, username, password)
        print("Password set for service '{}' and username '{}'".format(service_name, username))
    except keyring.errors.KeyringError as e:
        # Handle any errors that occur during password setting
        print("Error setting password: '{}'".format(str(e)))


def get_password(service_name, username):
    try:
        # Retrieve the password from the keyring
        password = keyring.get_password(service_name, username)
        if password:
              print("Password set for service '{}' and username '{}'".format(service_name, username))
        else:
            print("No password found '{}' and username '{}'".format(service_name, username))
    except keyring.errors.KeyringError as e:
        # Handle any errors that occur during password retrieval
        print("Error retrieving password: '{}'".format(str(e)))


# Usage example
service_name = 'test_svcaccount'
username = 'test-user'
pssword = os.environ['SECRET_PARAM']
#pssword = 'fhvjh'

# Set the password
set_password(service_name, username, pssword)

# Get the password
get_password(service_name, username)
0
Subscribe to my newsletter

Read articles from TechSwitch directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

TechSwitch
TechSwitch