【问题标题】:_sha import in python hashlib_sha 在 python hashlib 中导入
【发布时间】:2011-01-04 02:44:26
【问题描述】:

嗯,今天我在检查python中的hashlib模块,但后来我发现了一些我仍然无法弄清楚的东西。

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

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

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

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

【问题讨论】:

    标签: python hashlib


    【解决方案1】:

    实际上,_sha 模块由 shamodule.c 提供,_md5 由 md5module.c 和 md5.c 提供,并且只有在默认情况下不使用 OpenSSL 编译 Python 时才会构建它们。

    您可以在 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]
    

    【讨论】:

      【解决方案2】:

      似乎您的 python 安装在 _haslib 而不是 _sha (两个 C 模块)中编译了 sha。来自 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 之外导入该模块形式?
      • 是的,导入_hashlib(注意下划线)。 _sha 似乎是一个遗留接口,如果_hashlib 是,则不会安装。出于好奇,您为什么要导入它?
      • 我很好奇 XD。但现在我明白了它是如何工作的!谢谢您的帮助! :P
      • albertov, Fernando: _hashlib 和 _sha 是专有的。我指出了 setup.py 中实际发生的机制。虽然,_hashlib 只有在您没有正确的 openssl 时才会构建。恐怕,如果这不是一个完全正确的答案。
      • 其实Senthil的回答比较完整。我误读了“他们如何导入它?” Fernando 的帖子的一部分是“我如何导入它”,所以我的回答想指出“你不能,因为你的安装是通过 _hashlib 模块提供的”。您的回答提供了更多信息,因此我赞成。谢谢:)
      猜你喜欢
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      • 2017-12-10
      • 2013-12-22
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      相关资源
      最近更新 更多