I need to securely store a username and password in Python, what are my options? [closed] Ask Question

I need to securely store a username and password in Python, what are my options? [closed] Ask Question

I'm writing a small Python script which will periodically pull information from a 3rd party service using a username and password combo. I don't need to create something that is 100% bulletproof (does 100% even exist?), but I would like to involve a good measure of security so at the very least it would take a long time for someone to break it.

This script won't have a GUI and will be run periodically by cron, so entering a password each time it's run to decrypt things won't really work, and I'll have to store the username and password in either an encrypted file or encrypted in a SQLite database, which would be preferable as I'll be using SQLite anyway, and I might need to edit the password at some point. In addition, I'll probably be wrapping the whole program in an EXE, as it's exclusively for Windows at this point.

How can I securely store the username and password combo to be used periodically via a cron job?

ベストアンサー1

The python keyring library integrates with the CryptProtectDataユーザーのログオン資格情報を使用してデータを暗号化する Windows 上の API (および Mac と Linux 上の関連 API)。

簡単な使い方:

import keyring

# the service is just a namespace for your app
service_id = 'IM_YOUR_APP!'

keyring.set_password(service_id, 'dustin', 'my secret password')
password = keyring.get_password(service_id, 'dustin') # retrieve password

キーリングにユーザー名を保存する場合の使用方法:

import keyring

MAGIC_USERNAME_KEY = 'im_the_magic_username_key'

# the service is just a namespace for your app
service_id = 'IM_YOUR_APP!'  

username = 'dustin'

# save password
keyring.set_password(service_id, username, "password")

# optionally, abuse `set_password` to save username onto keyring
# we're just using some known magic string in the username field
keyring.set_password(service_id, MAGIC_USERNAME_KEY, username)

後でキーリングから情報を取得する

# again, abusing `get_password` to get the username.
# after all, the keyring is just a key-value store
username = keyring.get_password(service_id, MAGIC_USERNAME_KEY)
password = keyring.get_password(service_id, username)  

アイテムはユーザーのオペレーティング システムの資格情報を使用して暗号化されるため、ユーザー アカウントで実行されている他のアプリケーションがパスワードにアクセスできるようになります。

この脆弱性を少しでも隠すには、パスワードをキーリングに保存する前に、何らかの方法で暗号化/難読化することができます。もちろん、スクリプトをターゲットにしている人は誰でもソースを見て、パスワードの暗号化/難読化を解除する方法を見つけることができますが、少なくとも、何らかのアプリケーションがボールト内のすべてのパスワードを吸い上げて、あなたのパスワードも取得するのを防ぐことができます。

おすすめ記事