_sha импорт в python hashlib
Вопрос
Ну, сегодня я проверял модуль hashlib в python, но потом я нашел кое-что, что до сих пор не могу понять.
Внутри этого модуля python есть импорт, за которым я не могу уследить.Я поступаю вот так:
def __get_builtin_constructor(name):
if name in ('SHA1', 'sha1'):
import _sha
return _sha.new
Я попытался импортировать модуль _sha из оболочки python, но, похоже, к нему невозможно добраться таким образом.Мое первое предположение заключается в том, что это модуль C, но я не уверен.
Итак, скажите мне, ребята, вы знаете, где находится этот модуль?Как они это импортируют?
Решение
На самом деле, модуль _SHA предоставляется shamodule.c, а _md5 предоставляется md5module.c и md5.c, и оба будут построены только тогда, когда ваш Python не будет составлен с OpenSSL по умолчанию.
Вы можете найти детали в setup.py
В вашем Python Source Tarball.
if COMPILED_WITH_PYDEBUG or not have_usable_openssl:
# The _sha module implements the SHA1 hash algorithm.
exts.append( Extension('_sha', ['shamodule.c']) )
# The _md5 module implements the RSA Data Security, Inc. MD5
# Message-Digest Algorithm, described in RFC 1321. The
# necessary files md5.c and md5.h are included here.
exts.append( Extension('_md5',
sources = ['md5module.c', 'md5.c'],
depends = ['md5.h']) )
Чаще всего ваш Python построен из библиотеки OpenSSL, и в этом случае эти функции обеспечиваются самими библиотеками OpenSSL.
Теперь, если вы хотите их отдельно, то вы можете построить свой Python без OpenSSL или, что еще лучше, вы можете построить с помощью опции PydeBug и получить их.
От вашего Python Source Tarball:
./configure --with-pydebug
make
И вот ты:
>>> import _sha
[38571 refs]
>>> _sha.__file__
'/home/senthil/python/release27-maint/build/lib.linux-i686-2.7-pydebug/_sha.so'
[38573 refs]
Другие советы
Похоже, что при установке python sha скомпилирован внутри _haslib вместо _sha (оба модуля C).Из hashlib.py на python 2.6:
import _haslib:
.....
except ImportError:
# We don't have the _hashlib OpenSSL module?
# use the built in legacy interfaces via a wrapper function
new = __py_new
# lookup the C function to use directly for the named constructors
md5 = __get_builtin_constructor('md5')
sha1 = __get_builtin_constructor('sha1')
sha224 = __get_builtin_constructor('sha224')
sha256 = __get_builtin_constructor('sha256')
sha384 = __get_builtin_constructor('sha384')
sha512 = __get_builtin_constructor('sha512')