Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_crypt.py

raw
1 # Copyright (c) 2026, Alexei Znamensky <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 __all__ = ["CryptContext", "has_crypt_context"]
11
12 has_crypt_context = True
13 try:
14 from passlib.context import CryptContext
15
16 except ImportError:
17 try:
18 try:
19 import crypt as _crypt_mod
20 except ImportError:
21 import legacycrypt as _crypt_mod
22
23 _SCHEME_TO_METHOD = {
24 "sha512_crypt": _crypt_mod.METHOD_SHA512,
25 "sha256_crypt": _crypt_mod.METHOD_SHA256,
26 "md5_crypt": _crypt_mod.METHOD_MD5,
27 "des_crypt": _crypt_mod.METHOD_CRYPT,
28 }
29
30 class CryptContext: # type: ignore[no-redef]
31 @staticmethod
32 def verify(password, password_hash):
33 return _crypt_mod.crypt(password, password_hash) == password_hash
34
35 @staticmethod
36 def hash(password, scheme="sha512_crypt", rounds=10000):
37 method = _SCHEME_TO_METHOD.get(scheme)
38 if method is None:
39 raise ValueError(f"Unsupported scheme: {scheme}")
40 salt = _crypt_mod.mksalt(method, rounds=rounds)
41 return _crypt_mod.crypt(password, salt)
42
43 except ImportError:
44
45 class CryptContext: # type: ignore[no-redef]
46 pass
47
48 has_crypt_context = False