好吧,今天我正在检查Python的Hashlib模块,但后来我发现了一些我仍然不知道的东西。

在此Python模块中,有一个我无法遵循的导入。我这样说:

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

我试图从python shell导入_sha模块,但似乎无法以这种方式达到。我的第一个猜测是它是一个C模块,但我不确定。

所以告诉我,你知道那个模块在哪里吗?他们如何导入它?

有帮助吗?

解决方案

实际上,_sha模块由shamodule.c和_md5提供,由md5module.c和md5.c提供,并且只有在默认情况下使用openssl编制python时,才能构建两者。

您可以在 setup.py 在您的python源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库本身提供。

现在,如果您希望它们单独使用,那么您可以在没有OpenSSL或更好的情况下构建Python,可以使用Pydebug选项构建并拥有它们。

从您的Python来源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安装已在_haslib内部编译了SHA,而不是_sha(两个C模块)。来自python的hashlib.py 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')
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top