/
crypt_helper.py
69 lines (52 loc) · 1.79 KB
/
crypt_helper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# -*- coding: utf-8 -*-
"""
@file
@brief Encrypting, decrypting.
"""
import os
import pyquickhelper.loghelper as pl
def _default_name():
"""
Returns a default username.
::
os.environ.get('USERNAME', os.environ.get('NAME', 'unknown'))
"""
return os.environ.get('USERNAME', os.environ.get('NAME', 'unknown'))
def get_password(key, username=None):
"""
Retrieves a password assocatied to *key*.
Relies on module :epkg:`keyring`.
@param key key
@param username username or ``environ['USERNAME']`` if None
@return password
.. exref::
:title: Store and retrieve a password
Module :epkg:`keyring` can be used to store and retrieve a password.
It is an easy way to avoid letting clear password in the code.
To store a password:
.. runpython::
:showcode:
from pyquickhelper.loghelper import set_password
set_password("system", "username", "password")
And to retrieve it:
.. runpython::
:showcode:
from pyquickhelper.loghelper import get_password
pwd = get_password("system", "username")
print(pwd)
"""
if username is None:
username = _default_name()
return pl.get_password(key, username, ask=False) # pylint: disable=E1123
def set_password(pwd, key, username=None):
"""
Stores a password assocatied to *key*.
Relies on module :epkg:`keyring`.
@param pwd password
@param key key
@param username username or ``environ['USERNAME']`` if None
@return password
"""
if username is None:
username = _default_name()
pl.set_password(key, username, pwd, ask=False) # pylint: disable=E1123