Skip to main content

Modules/_cryptmodule.c

Source:

cpython 3.14 @ ab2d84fe1023/Modules/_cryptmodule.c

crypt wraps the POSIX crypt(3) function for password hashing. Deprecated in 3.13 and removed in 3.13. Available only on Unix.

Map

LinesSymbolRole
1-50crypt_cryptCall system crypt() with word and salt
51-100mksaltGenerate a random salt string for a given method
101-150METHOD_*METHOD_SHA512, METHOD_SHA256, METHOD_MD5, METHOD_CRYPT

Reading

crypt.crypt()

// CPython: Modules/_cryptmodule.c:38 crypt_crypt_impl
static PyObject *
crypt_crypt_impl(PyObject *module, const char *word, const char *salt)
{
/* crypt(3) is not thread-safe; use the reentrant crypt_r if available */
#ifdef HAVE_CRYPT_R
struct crypt_data data;
memset(&data, 0, sizeof(data));
Py_BEGIN_ALLOW_THREADS
char *r = crypt_r(word, salt, &data);
Py_END_ALLOW_THREADS
#else
Py_BEGIN_ALLOW_THREADS
char *r = crypt(word, salt);
Py_END_ALLOW_THREADS
#endif
if (r == NULL) return PyErr_SetFromErrno(PyExc_OSError);
return PyUnicode_DecodeASCII(r, strlen(r), NULL);
}

Salt prefixes for method selection

// CPython: Modules/_cryptmodule.c:85 method constants
/* METHOD_SHA512: salt prefix '$6$rounds=N$' → SHA-512 with N rounds */
/* METHOD_SHA256: salt prefix '$5$rounds=N$' → SHA-256 with N rounds */
/* METHOD_MD5: salt prefix '$1$' → MD5-crypt */
/* METHOD_CRYPT: 2-char salt → traditional DES */
/* Example: crypt.crypt('password', crypt.mksalt(crypt.METHOD_SHA512)) */

mksalt

# CPython: Lib/crypt.py:82 mksalt
def mksalt(method=None, *, rounds=None):
"""Generate a random salt of the given method."""
if method is None: method = methods[0]
s = method.prefix
if method.ident in ('5', '6') and rounds is not None:
s += 'rounds=%d$' % rounds
# Append random characters from the base64 alphabet
s += ''.join(_saltchars[os.urandom(1)[0] % len(_saltchars)]
for _ in range(method.salt_chars))
return s

gopy notes

crypt was removed in Python 3.13 and is not in gopy's stdlib. For password hashing, hashlib provides PBKDF2 and bcrypt alternatives. The annotation covers the C module for completeness.