在python hashlib中导入_sha

4 投票
2 回答
4884 浏览
提问于 2025-04-16 09:22

今天我在查看Python的hashlib模块时,发现了一些我还是搞不明白的事情。

在这个Python模块里,有一个我看不懂的导入,内容是这样的:

def __get_builtin_constructor(name):
    if name in ('SHA1', 'sha1'):
        import _sha
        return _sha.new

我试着从Python的命令行中导入_sha模块,但好像这样无法访问到。我的第一反应是它可能是一个C语言写的模块,但我不太确定。

所以,大家知道这个模块在哪里吗?他们是怎么导入它的呢?

2 个回答

5

看起来你的Python安装里有一个叫做_sha的模块,但实际上它应该是_haslib这个模块。它们都是用C语言写的模块。在Python 2.6的hashlib.py文件里有相关的内容:

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')
9

其实,_sha模块是由shamodule.c提供的,而_md5模块是由md5module.c和md5.c提供的。这两个模块只有在你的Python没有默认使用OpenSSL编译时才会被构建。

你可以在你的Python源代码压缩包里的setup.py文件中找到详细信息。

    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库本身提供的。

如果你想单独使用这些功能,你可以在没有OpenSSL的情况下构建你的Python,或者更好的是,你可以使用pydebug选项来构建,这样就能得到它们。

从你的Python源代码压缩包中:

./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]

撰写回答