Skip to main content

Store and access your passwords safely.

Project description

Installing and Using Python Keyring Lib

What is Python keyring lib?

The Python keyring lib provides a easy way to access the system keyring service from python. It can be used in any application that needs safe password storage.

The keyring services supported by the Python keyring lib:

  • OSXKeychain: supports the Keychain service in Mac OS X.

  • KDEKWallet: supports the KDE’s Kwallet service.

  • GnomeKeyring: for Gnome 2 environment.

  • SecretServiceKeyring: for newer GNOME and KDE environments.

Besides these native password storing services provided by operating systems. Python keyring lib also provides following build-in keyrings.

  • Win32CryptoKeyring: for Windows 2k+.

  • CryptedFileKeyring: a command line interface keyring base on PyCrypto.

  • UncryptedFileKeyring: a keyring which leaves passwords directly in file.

Installation Instructions

easy_install or pip

Run easy_install or pip:

$ easy_install keyring
$ pip install keyring

Source installation

Download the source tarball, and uncompress it, then run the install command:

$ wget
$ tar -xzvf keyring-0.3.tar.gz
$ cd keyring-0.3
$ python install

Configure your keyring lib

The python keyring lib contains implementations for several backends, including OSX Keychain, Gnome Keyring, KDE Kwallet and etc. The lib will automatically choose the keyring that is most suitable for your current environment. You can also specify the keyring you like to be used in the config file or by calling the set_keyring() function.

Customize your keyring by config file

This section is about how to change your option in the config file.

Config file path

The configuration of the lib is stored in a file named “keyringrc.cfg”. The file can be stored in either of following two paths.

  1. The working directory of the python

  2. The home directory for current user

The lib will first look for the config file in the working directory. If no config file exists or the config file cannot be written properly, keyring will reference the config in the home directory.

Beginning with keyring 0.8, the config root is platform specific. To determine where in the home directory the config file (and other data files) are stored, run the following:

python -c "import keyring.util.platform; print(keyring.util.platform.data_root())"
Config file content

To specify a keyring backend, you need tell the lib the module name of the backend, such as keyring.backend.OSXKeychain. If the backend is not shipped with the lib, in another word, is made by you own, you need also tell the lib the path of your own backend module. The module name should be written after the default-keyring option, while the module path belongs the keyring-path option.

Here’s a sample config file(The full demo can be accessed in the demo/


Write your own keyring backend

The interface for the backend is defined by keyring.backend.KeyringBackend. By extending this base class and implementing the three functions supported(), get_password() and set_password(), you can easily create your own backend for keyring lib.

The usage of the three functions:

  • supported(self) : Return if this backend is supported in current environment. The returned value can be 0, 1 , or -1. 0 means suitable; 1 means recommended and -1 means this backend is not available for current environment.

  • get_password(self, service, username) : Return the stored password for the username of the service.

  • set_password(self, service, username, password) : Store the password for username of the service in the backend.

For an instance, there’s the source code of the demo mentioned above. It’s a simple keyring which stores the password directly in memory.


A simple keyring class for the

Created by Kang Zhang on 2009-07-12
from keyring.backend import KeyringBackend

class SimpleKeyring(KeyringBackend):
    """Simple Keyring is a keyring which can store only one
    password in memory.
    def __init__(self):
        self.password = ''

    def supported(self):
        return 0

    def get_password(self, service, username):
        return self.password

    def set_password(self, service, username, password):
        self.password = password
        return 0

Set the keyring in runtime

Besides setting the backend through the config file, you can also set the backend to use by calling the api set_keyring(). The backend you passed in will be used to store the password in your application.

Here’s a code snippet from the It shows the usage of set_keyring()

# define a new keyring class which extends the KeyringBackend
import keyring.backend
class TestKeyring(keyring.backend.KeyringBackend):
    """A test keyring which always outputs same password
    def supported(self): return 0
    def set_password(self, servicename, username, password): return 0
    def get_password(self, servicename, username):
        return "password from TestKeyring"

# set the keyring for keyring lib
import keyring

# invoke the keyring lib
    keyring.set_password("demo-service", "tarek", "passexample")
    print "password stored sucessfully"
except keyring.backend.PasswordSetError:
    print "failed to store password"
print "password", keyring.get_password("demo-service", "tarek")

Integrate the keyring lib with your application

API interface

The keyring lib has two functions:

  • get_password(service, username) : Returns the password stored in keyring. If the password does not exist, it will return None.

  • set_password(service, username, password) : Store the password in the keyring.


Here’s an example of using keyring for application authorization. It can be found in the demo folder of the repository. Note that the faked auth function only returns true when the password equals to the username.


Created by Kang Zhang 2009-08-14

import keyring
import getpass
import ConfigParser

def auth(username, password):
    """A faked authorization function.
    return username == password

def main():
    """This scrip demos how to use keyring facilite the authorization. The
    username is stored in a config named 'auth_demo.cfg'
    # config file init
    config_file = 'auth_demo.cfg'
    config = ConfigParser.SafeConfigParser({
    if not config.has_section('auth_demo_login'):

    username = config.get('auth_demo_login','username')
    password = None
    if username != '':
        password = keyring.get_password('auth_demo_login', username)

    if password == None or not auth(username, password):

        while 1:
            username = raw_input("Username:\n")
            password = getpass.getpass("Password:\n")

            if auth(username, password):
                print "Authorization failed."

        # store the username
        config.set('auth_demo_login', 'username', username)
        config.write(open(config_file, 'w'))

        # store the password
        keyring.set_password('auth_demo_login', username, password)

    # the stuff that needs authorization here
    print "Authorization successful."

if __name__ == "__main__":

Get involved

Python keyring lib is an open community project and highly welcomes new contributors.

Running Tests

To run the tests, you’ll want keyring installed to some environment in which it can be tested. Two recommended techniques are described below.

Using virtualenv and pytest/nose/unittest2

Pytest and Nose are two popular test runners that will discover tests and run them. Unittest2 (also known as simply unittest in Python 3) also has a mode to discover tests.

First, however, these test runners typically need a test environment in which to run. It is recommended that you install keyring to a virtual environment to avoid interfering with your system environment. For more information, see the virtualenv homepage.

After you’ve created (or designated) your environment, install keyring into the environment by running:

python develop

Then, invoke your favorite test runner, e.g.:



Using buildout

The keyring repo bundles buildout’s bootstrap script as a subrepo, so using buildout is three easy steps:

1. python buildout/bootstrap  # bootstrap the buildout.
2. bin/buildout  # prepare the buildout.
3. bin/test  # execute the test runner.

For more information about the options that the script provides do execute:

python bin/test --help


The project was based on Tarek Ziade’s idea in this post. Kang Zhang initially carried it out as a Google Summer of Code project, and Tarek mentored Kang on this project.

See CONTRIBUTORS.txt for a complete list of contributors.



This backward-incompatible release attempts to remove some cruft from the codebase that’s accumulated over the versions.

  • Removed legacy file relocation support. keyring no longer supports loading configuration or file-based backends from ~. If upgrading from 0.8 or later, the files should already have been migrated to their new proper locations. If upgrading from 0.7.x or earlier, the files will have to be migrated manually.

  • Removed CryptedFileKeyring migration support. To maintain an existing CryptedFileKeyring, one must first upgrade to 0.9.2 or later and access the keyring before upgrading to 1.0 to retain the existing keyring.

  • File System backends now create files without group and world permissions. Fixes #67.


  • Merged 0.9.3 to include fix for #75.


  • Add support for using Keyczar to encrypt keyrings. Keyczar is “an open source cryptographic toolkit designed to make it easier and safer for developers to use cryptography in their applications.”

  • Added support for storing keyrings on Google Docs or any other filesystem supported by pyfilesystem.

  • Fixed issue in Gnome Keyring when unicode is passed as the service name, username, or password.

  • Tweaked SecretService code to pass unicode to DBus, as unicode is the preferred format.

  • Issue #71 - Fixed logic in CryptedFileKeyring.

  • Unencrypted keyring file will be saved with user read/write (and not group or world read/write).


  • Ensure migration is run when get_password is called. Fixes #75. Thanks to Marc Deslauriers for reporting the bug and supplying the patch.


  • Keyring 0.9.1 introduced a whole different storage format for the CryptedFileKeyring, but this introduced some potential compatibility issues. This release incorporates the security updates but reverts to the INI file format for storage, only encrypting the passwords and leaving the service and usernames in plaintext. Subsequent releases may incorporate a new keyring to implement a whole-file encrypted version. Fixes #64.

  • The CryptedFileKeyring now requires simplejson for Python 2.5 clients.


  • Fix for issue where SecretServiceBackend.set_password would raise a UnicodeError on Python 3 or when a unicode password was provided on Python 2.

  • CryptedFileKeyring now uses PBKDF2 to derive the key from the user’s password and a random hash. The IV is chosen randomly as well. All the stored passwords are encrypted at once. Any keyrings using the old format will be automatically converted to the new format (but will no longer be compatible with 0.9 and earlier). The user’s password is no longer limited to 32 characters. PyCrypto 2.5 or greater is now required for this keyring.


  • Add support for GTK 3 and secret service D-Bus. Fixes #52.

  • Issue #60 - Use correct method for decoding.


  • Fix regression in keyring lib on Windows XP where the LOCALAPPDATA environment variable is not present.


  • Mac OS X keyring backend now uses subprocess calls to the security command instead of calling the API, which with the latest updates, no longer allows Python to invoke from a virtualenv. Fixes issue #13.

  • When using file-based storage, the keyring files are no longer stored in the user’s home directory, but are instead stored in platform-friendly locations (%localappdata%Python Keyring on Windows and according to the Base Dir Specification ($XDG_DATA_HOME/python_keyring or $HOME/.local/share/python_keyring) on other operating systems). This fixes #21.

Backward Compatibility Notice

Due to the new storage location for file-based keyrings, keyring 0.8 supports backward compatibility by automatically moving the password files to the updated location. In general, users can upgrade to 0.8 and continue to operate normally. Any applications that customize the storage location or make assumptions about the storage location will need to take this change into consideration. Additionally, after upgrading to 0.8, it is not possible to downgrade to 0.7 without manually moving configuration files. In 1.0, the backward compatibilty will be removed.


  • Removed non-ASCII characters from README and CHANGES docs (required by distutils if we’re to include them in the long_description). Fixes #55.


  • Python 3 is now supported. All tests now pass under Python 3.2 on Windows and Linux (although Linux backend support is limited). Fixes #28.

  • Extension modules on Mac and Windows replaced by pure-Python ctypes implementations. Thanks to Jerome Laheurte.

  • WinVaultKeyring now supports multiple passwords for the same service. Fixes #47.

  • Most of the tests don’t require user interaction anymore.

  • Entries stored in Gnome Keyring appears now with a meaningful name if you try to browser your keyring (for ex. with Seahorse)

  • Tests from Gnome Keyring no longer pollute the user own keyring.

  • keyring.util.escape now accepts only unicode strings. Don’t try to encode strings passed to it.


  • fix compiling on OSX with XCode 4.0



  • Added keyring.http for facilitating HTTP Auth using keyring.

  • Add a utility to access the keyring from the command line.



  • Now using the existing Gnome and KDE python libs instead of custom C++ code.

  • Using the getpass module instead of custom code


  • Fixed the setup script (some subdirs were not included in the release.)


  • Fixed keyring.core when the user doesn’t have a cfg, or is not properly configured.

  • Fixed escaping issues for usernames with non-ascii characters


Project details

Release history Release notifications | RSS feed

This version


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution (61.4 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page