Python passlib.context.CryptContext() Examples
The following are 30
code examples of passlib.context.CryptContext().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
passlib.context
, or try the search function
.
Example #1
Source File: core.py From flask-security with MIT License | 6 votes |
def _get_pwd_context(app): pw_hash = cv("PASSWORD_HASH", app=app) schemes = cv("PASSWORD_SCHEMES", app=app) deprecated = cv("DEPRECATED_PASSWORD_SCHEMES", app=app) if pw_hash not in schemes: allowed = ", ".join(schemes[:-1]) + " and " + schemes[-1] raise ValueError( "Invalid password hashing scheme %r. Allowed values are %s" % (pw_hash, allowed) ) cc = CryptContext( schemes=schemes, default=pw_hash, deprecated=deprecated, **cv("PASSWORD_HASH_PASSLIB_OPTIONS", app=app), ) return cc
Example #2
Source File: test_context_deprecated.py From jarvis with GNU General Public License v2.0 | 6 votes |
def test_22_to_string(self): """test to_string() method""" pa = CryptPolicy(**self.sample_config_5pd) s = pa.to_string() # NOTE: can't compare string directly, ordering etc may not match pb = CryptPolicy.from_string(s) self.assertEqual(pb.to_dict(), self.sample_config_5pd) s = pa.to_string(encoding="latin-1") self.assertIsInstance(s, bytes) #=================================================================== # #=================================================================== #============================================================================= # CryptContext #=============================================================================
Example #3
Source File: test_context_deprecated.py From jarvis with GNU General Public License v2.0 | 6 votes |
def test_01_replace(self): """test replace()""" cc = CryptContext(["md5_crypt", "bsdi_crypt", "des_crypt"]) self.assertIs(cc.policy.get_handler(), hash.md5_crypt) cc2 = cc.replace() self.assertIsNot(cc2, cc) # NOTE: was not able to maintain backward compatibility with this... ##self.assertIs(cc2.policy, cc.policy) cc3 = cc.replace(default="bsdi_crypt") self.assertIsNot(cc3, cc) # NOTE: was not able to maintain backward compatibility with this... ##self.assertIs(cc3.policy, cc.policy) self.assertIs(cc3.policy.get_handler(), hash.bsdi_crypt)
Example #4
Source File: test_context_deprecated.py From jarvis with GNU General Public License v2.0 | 6 votes |
def test_12_hash_needs_update(self): """test hash_needs_update() method""" cc = CryptContext(**self.sample_policy_1) # check deprecated scheme self.assertTrue(cc.hash_needs_update('9XXD4trGYeGJA')) self.assertFalse(cc.hash_needs_update('$1$J8HC2RCr$HcmM.7NxB2weSvlw2FgzU0')) # check min rounds self.assertTrue(cc.hash_needs_update('$5$rounds=1999$jD81UCoo.zI.UETs$Y7qSTQ6mTiU9qZB4fRr43wRgQq4V.5AAf7F97Pzxey/')) self.assertFalse(cc.hash_needs_update('$5$rounds=2000$228SSRje04cnNCaQ$YGV4RYu.5sNiBvorQDlO0WWQjyJVGKBcJXz3OtyQ2u8')) # check max rounds self.assertFalse(cc.hash_needs_update('$5$rounds=3000$fS9iazEwTKi7QPW4$VasgBC8FqlOvD7x2HhABaMXCTh9jwHclPA9j5YQdns.')) self.assertTrue(cc.hash_needs_update('$5$rounds=3001$QlFHHifXvpFX4PLs$/0ekt7lSs/lOikSerQ0M/1porEHxYq7W/2hdFpxA3fA')) #=================================================================== # border cases #===================================================================
Example #5
Source File: password_manager.py From Flask-User with MIT License | 6 votes |
def __init__(self, app): """ Create a passlib CryptContext. Args: password_hash(str): The name of a valid passlib password hash. Examples: ``'bcrypt', 'pbkdf2_sha512', 'sha512_crypt' or 'argon2'``. Example: ``password_manager = PasswordManager('bcrypt')`` """ self.app = app self.user_manager = app.user_manager # Create a passlib CryptContext self.password_crypt_context = CryptContext( schemes=self.user_manager.USER_PASSLIB_CRYPTCONTEXT_SCHEMES, **self.user_manager.USER_PASSLIB_CRYPTCONTEXT_KEYWORDS)
Example #6
Source File: utils.py From jarvis with GNU General Public License v2.0 | 6 votes |
def get_user_category(self, user): """ Helper for hashing passwords per-user -- figure out the CryptContext category for specified Django user object. .. note:: This may be overridden via PASSLIB_GET_CATEGORY django setting """ if user.is_superuser: return "superuser" elif user.is_staff: return "staff" else: return None #============================================================================= # patch control #=============================================================================
Example #7
Source File: db_account_users.py From anchore-engine with Apache License 2.0 | 6 votes |
def hash(self, password): """ Hash the password to store it. If not configured for hashes, this is a no-op. :param password: :return: """ logger.info('Checking hash on password') if self.do_hash: logger.info('Hashing password prior to storage') context = dict(schemes=['argon2']) cc = CryptContext(**context) password = cc.hash(password) else: logger.info('No hash requirement set in config') return password
Example #8
Source File: utils.py From jarvis with GNU General Public License v2.0 | 5 votes |
def __init__(self, context=None, get_user_category=None, **kwds): # init log self.log = logging.getLogger(__name__ + ".DjangoContextAdapter") # init parent, filling in default context object if context is None: context = CryptContext() super(DjangoContextAdapter, self).__init__(context=context, **kwds) # setup user category if get_user_category: assert callable(get_user_category) self.get_user_category = get_user_category # install lru cache wrappers from django.utils.lru_cache import lru_cache self.get_hashers = lru_cache()(self.get_hashers) # get copy of original make_password from django.contrib.auth.hashers import make_password if make_password.__module__.startswith("passlib."): make_password = _PatchManager.peek_unpatched_func(make_password) self._orig_make_password = make_password # get other django helpers from django.contrib.auth.hashers import is_password_usable self.is_password_usable = is_password_usable # init manager mlog = logging.getLogger(__name__ + ".DjangoContextAdapter._manager") self._manager = _PatchManager(log=mlog)
Example #9
Source File: apache.py From jarvis with GNU General Public License v2.0 | 5 votes |
def check_password(self, user, realm=None, password=_UNSET): """Verify password for specified user + realm. If ``self.default_realm`` has been set, this may be called with the syntax ``check_password(user, password)``, otherwise it must be called with all three arguments: ``check_password(user, realm, password)``. :returns: * ``None`` if user or realm not found. * ``False`` if user found, but password does not match. * ``True`` if user found and password matches. .. versionchanged:: 1.6 This method was previously called ``verify``, it was renamed to prevent ambiguity with the :class:`!CryptContext` method. The old alias is deprecated, and will be removed in Passlib 1.8. """ if password is _UNSET: # called w/ two args - (user, password), use default realm realm, password = None, realm user = self._encode_user(user) realm = self._encode_realm(realm) hash = self._records.get((user,realm)) if hash is None: return None return htdigest.verify(password, hash, user, realm, encoding=self.encoding)
Example #10
Source File: apache.py From jarvis with GNU General Public License v2.0 | 5 votes |
def _init_htpasswd_context(): # start with schemes built into apache schemes = [ # builtin support added in apache 2.4 # (https://bz.apache.org/bugzilla/show_bug.cgi?id=49288) "bcrypt", # support not "builtin" to apache, instead it requires support through host's crypt(). # adding them here to allow editing htpasswd under windows and then deploying under unix. "sha256_crypt", "sha512_crypt", "des_crypt", # apache default as of 2.2.18, and still default in 2.4 "apr_md5_crypt", # NOTE: apache says ONLY intended for transitioning htpasswd <-> ldap "ldap_sha1", # NOTE: apache says ONLY supported on Windows, Netware, TPF "plaintext" ] # apache can verify anything supported by the native crypt(), # though htpasswd tool can only generate a limited set of hashes. # (this list may overlap w/ builtin apache schemes) schemes.extend(registry.get_supported_os_crypt_schemes()) # hack to remove dups and sort into preferred order preferred = schemes[:3] + ["apr_md5_crypt"] + schemes schemes = sorted(set(schemes), key=preferred.index) # NOTE: default will change to "portable" in passlib 2.0 return CryptContext(schemes, default=htpasswd_defaults['portable_apache_22']) #: CryptContext configured to match htpasswd
Example #11
Source File: test_utils.py From jarvis with GNU General Public License v2.0 | 5 votes |
def test_is_crypt_context(self): """test is_crypt_context()""" from passlib.utils import is_crypt_context from passlib.context import CryptContext cc = CryptContext(["des_crypt"]) self.assertTrue(is_crypt_context(cc)) self.assertFalse(not is_crypt_context(cc))
Example #12
Source File: test_context_deprecated.py From jarvis with GNU General Public License v2.0 | 5 votes |
def setUp(self): TestCase.setUp(self) # make sure this isn't registered before OR after unload_handler_name("dummy_2") self.addCleanup(unload_handler_name, "dummy_2") # silence some warnings warnings.filterwarnings("ignore", r"CryptContext\(\)\.replace\(\) has been deprecated") warnings.filterwarnings("ignore", ".*(CryptPolicy|context\.policy).*(has|have) been deprecated.*")
Example #13
Source File: test_context_deprecated.py From jarvis with GNU General Public License v2.0 | 5 votes |
def test_30_nonstring_hash(self): """test non-string hash values cause error""" warnings.filterwarnings("ignore", ".*needs_update.*'scheme' keyword is deprecated.*") # # test hash=None or some other non-string causes TypeError # and that explicit-scheme code path behaves the same. # cc = CryptContext(["des_crypt"]) for hash, kwds in [ (None, {}), # NOTE: 'scheme' kwd is deprecated... (None, {"scheme": "des_crypt"}), (1, {}), ((), {}), ]: self.assertRaises(TypeError, cc.hash_needs_update, hash, **kwds) cc2 = CryptContext(["mysql323"]) self.assertRaises(TypeError, cc2.hash_needs_update, None) #=================================================================== # eoc #=================================================================== #============================================================================= # LazyCryptContext #=============================================================================
Example #14
Source File: web_interface.py From FACT_core with GNU General Public License v3.0 | 5 votes |
def password_is_legal(pw: str) -> bool: if not pw: return False schemes = ['bcrypt', 'des_crypt', 'pbkdf2_sha256', 'pbkdf2_sha512', 'sha256_crypt', 'sha512_crypt', 'plaintext'] ctx = CryptContext(schemes=schemes) return ctx.identify(pw) == 'plaintext'
Example #15
Source File: test_context_deprecated.py From jarvis with GNU General Public License v2.0 | 5 votes |
def test_00_constructor(self): """test constructor""" # create crypt context using handlers cc = CryptContext([hash.md5_crypt, hash.bsdi_crypt, hash.des_crypt]) c,b,a = cc.policy.iter_handlers() self.assertIs(a, hash.des_crypt) self.assertIs(b, hash.bsdi_crypt) self.assertIs(c, hash.md5_crypt) # create context using names cc = CryptContext(["md5_crypt", "bsdi_crypt", "des_crypt"]) c,b,a = cc.policy.iter_handlers() self.assertIs(a, hash.des_crypt) self.assertIs(b, hash.bsdi_crypt) self.assertIs(c, hash.md5_crypt) # policy kwd policy = cc.policy cc = CryptContext(policy=policy) self.assertEqual(cc.to_dict(), policy.to_dict()) cc = CryptContext(policy=policy, default="bsdi_crypt") self.assertNotEqual(cc.to_dict(), policy.to_dict()) self.assertEqual(cc.to_dict(), dict(schemes=["md5_crypt","bsdi_crypt","des_crypt"], default="bsdi_crypt")) self.assertRaises(TypeError, setattr, cc, 'policy', None) self.assertRaises(TypeError, CryptContext, policy='x')
Example #16
Source File: test_context_deprecated.py From jarvis with GNU General Public License v2.0 | 5 votes |
def setUp(self): TestCase.setUp(self) warnings.filterwarnings("ignore", r"CryptContext\(\)\.replace\(\) has been deprecated.*") warnings.filterwarnings("ignore", r"The CryptContext ``policy`` keyword has been deprecated.*") warnings.filterwarnings("ignore", ".*(CryptPolicy|context\.policy).*(has|have) been deprecated.*") warnings.filterwarnings("ignore", r"the method.*hash_needs_update.*is deprecated") #=================================================================== # constructor #===================================================================
Example #17
Source File: core.py From flask-security with MIT License | 5 votes |
def _get_hashing_context(app): schemes = cv("HASHING_SCHEMES", app=app) deprecated = cv("DEPRECATED_HASHING_SCHEMES", app=app) return CryptContext(schemes=schemes, deprecated=deprecated)
Example #18
Source File: test_handlers_pbkdf2.py From jarvis with GNU General Public License v2.0 | 5 votes |
def test_95_context_algs(self): """test handling of 'algs' in context object""" handler = self.handler from passlib.context import CryptContext c1 = CryptContext(["scram"], scram__algs="sha1,md5") h = c1.hash("dummy") self.assertEqual(handler.extract_digest_algs(h), ["md5", "sha-1"]) self.assertFalse(c1.needs_update(h)) c2 = c1.copy(scram__algs="sha1") self.assertFalse(c2.needs_update(h)) c2 = c1.copy(scram__algs="sha1,sha256") self.assertTrue(c2.needs_update(h))
Example #19
Source File: test_sessions.py From amivapi with GNU Affero General Public License v3.0 | 5 votes |
def _get_weak_hash(self, plaintext): """Create a weaker CryptContext and hash plaintext. (Weaker as in weaker than default context) """ weak_context = CryptContext( schemes=["pbkdf2_sha256"], pbkdf2_sha256__default_rounds=5, ) return weak_context.hash(plaintext)
Example #20
Source File: password_manager.py From Flask-User with MIT License | 5 votes |
def verify_password(self, password, password_hash): """Verify plaintext ``password`` against ``hashed password``. Args: password(str): Plaintext password that the user types in. password_hash(str): Password hash generated by a previous call to ``hash_password()``. Returns: | True when ``password`` matches ``password_hash``. | False otherwise. Example: :: if verify_password('mypassword', user.password): login_user(user) """ # Print deprecation warning if called with (password, user) instead of (password, user.password) if isinstance(password_hash, self.user_manager.db_manager.UserClass): print( 'Deprecation warning: verify_password(password, user) has been changed'\ ' to: verify_password(password, password_hash). The user param will be deprecated.'\ ' Please change your call with verify_password(password, user) into'\ ' a call with verify_password(password, user.password)' ' as soon as possible.') password_hash = password_hash.password # effectively user.password # Use passlib's CryptContext to verify a password return self.password_crypt_context.verify(password, password_hash)
Example #21
Source File: password_manager.py From Flask-User with MIT License | 5 votes |
def hash_password(self, password): """Hash plaintext ``password`` using the ``password_hash`` specified in the constructor. Args: password(str): Plaintext password that the user types in. Returns: hashed password. Example: ``user.password = hash_password('mypassword')`` """ # Use passlib's CryptContext to hash a password password_hash = self.password_crypt_context.hash(password) return password_hash
Example #22
Source File: fastapi_login.py From fastapi_login with MIT License | 5 votes |
def __init__(self, secret: str, tokenUrl: str, algorithm="HS256"): """ :param str secret: Secret key used to sign and decrypt the JWT :param str algorithm: Should be "HS256" or "RS256" used to decrypt the JWT :param str tokenUrl: the url where the user can login to get the token """ self.secret = Secret(secret) self._user_callback = None self.algorithm = algorithm self.pwd_context = CryptContext(schemes=["bcrypt"]) # this is not mandatory as they user may want to user their own # function to get the token and pass it to the get_current_user method self.tokenUrl = tokenUrl self.oauth_scheme = None self._not_authenticated_exception = None
Example #23
Source File: security.py From flask-unchained with MIT License | 5 votes |
def _get_pwd_context(self, app: FlaskUnchained) -> CryptContext: """ Get the password hashing context. """ pw_hash = app.config.SECURITY_PASSWORD_HASH schemes = app.config.SECURITY_PASSWORD_SCHEMES if pw_hash not in schemes: allowed = (', '.join(schemes[:-1]) + ' and ' + schemes[-1]) raise ValueError(f'Invalid password hashing scheme {pw_hash}. ' f'Allowed values are {allowed}.') return CryptContext(schemes=schemes, default=pw_hash, deprecated=app.config.SECURITY_DEPRECATED_PASSWORD_SCHEMES)
Example #24
Source File: security.py From flask-unchained with MIT License | 5 votes |
def _get_hashing_context(self, app: FlaskUnchained) -> CryptContext: """ Get the token hashing (and verifying) context. """ return CryptContext(schemes=app.config.SECURITY_HASHING_SCHEMES, deprecated=app.config.SECURITY_DEPRECATED_HASHING_SCHEMES)
Example #25
Source File: crypt.py From signac with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_crypt_context(): "Return the default signac crypto context." return CryptContext(schemes=('bcrypt', ))
Example #26
Source File: User.py From Flask-GraphQL-Graphene-MySQL-Docker-StarterKit with MIT License | 5 votes |
def _verify_password(self, password): userctx = CryptContext(schemes=["sha256_crypt", "md5_crypt"]) return userctx.verify(password, self.password)
Example #27
Source File: User.py From Flask-GraphQL-Graphene-MySQL-Docker-StarterKit with MIT License | 5 votes |
def _hash_password(self, password): userctx = CryptContext(schemes=["sha256_crypt", "md5_crypt"]) self.password = userctx.hash(password)
Example #28
Source File: conftest.py From yosai with Apache License 2.0 | 5 votes |
def crypt_context(): return CryptContext(schemes=['sha256_crypt'])
Example #29
Source File: credential.py From yosai with Apache License 2.0 | 5 votes |
def create_password_crypt_context(self, authc_settings): context = dict(schemes=[authc_settings.preferred_algorithm]) context.update(authc_settings.preferred_algorithm_context) return CryptContext(**context)
Example #30
Source File: authc.py From yosai with Apache License 2.0 | 5 votes |
def create_password_crypt_context(self, authc_settings): context = dict(schemes=[authc_settings.preferred_algorithm]) context.update(authc_settings.preferred_algorithm_context) return CryptContext(**context)