python - _sha 在 python hashlib 中导入

标签 python hashlib

嗯,今天我在查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 提供,并且只有当您的 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]

关于python - _sha 在 python hashlib 中导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4590242/

相关文章:

python - 使用 hashlib 散列种子 numpy.random.RandomState

python - 如何从电子邮件中获取 csv 附件并保存

python - 如何使用 python ElementTree 获取 XML 中的同级标签值

python - 获取目录中文件的信息并在表格中打印

python - 为什么Python的Hashlib不是强类型的?

python (django) hashlib vs Nodejs 加密

python - Unix md5 与 python 的 hashlib.md5 不同吗?

python - 使用 Python 对字符串中的元素进行排序

Python从元组列表中生成字典列表

python - 如何通过 Python 计算 Linux 上具有特定标题的窗口的数量?