在Python中使用hashlib的_sha模块导入问题

4

今天我在查看Python的hashlib模块时发现了一些问题,但是我仍然无法弄清楚。

在这个Python模块中,有一个我无法跟踪的导入。它像这样:

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

我尝试从Python shell导入_sha模块,但似乎无法通过这种方式访问。我的第一个猜测是它是一个C模块,但我不确定。

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

2个回答

9

实际上,_sha模块是由shamodule.c提供的,而_md5则是由md5module.c和md5.c提供的。只有当你的Python默认未使用OpenSSL编译时,两者才会被构建。

你可以在Python源代码tarball中的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源代码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]

5

看起来你的 Python 安装中,_hashlib 内部包含了 sha 编译而不是 _sha(两个 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')

那么,我能否从hashlib之外导入该模块的方式? - FernandoEscher
是的,导入_hashlib(注意下划线)。如果安装了_hashlib,则似乎不会安装_sha这个遗留接口。出于好奇,你为什么想要导入它呢? - albertov
我很好奇XD。但现在我知道它是如何工作的了!感谢您的帮助!:P - FernandoEscher
albertov,Fernando:_hashlib和_sha是互斥的。我指出了在setup.py中实际发生的机制。尽管只有在没有适当的openssl时才会构建_hashlib。我担心这不是完全正确的答案。 - Senthil Kumaran
实际上,Senthil的答案更完整。我错误地把Fernando帖子中“他们如何导入它?”部分误读为“我如何导入它”,因此我的回答想指出“你不能,因为你的安装程序通过_hashlib模块提供它”。您的答案更具信息性,因此我点赞了。谢谢 :) - albertov
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接