必须以X实例作为第一个参数调用Unbound方法(改为获取str实例)

2024-10-06 10:22:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在玩pyelliptic,但是我不能使用文件中定义的方法raw_get_ecdh_key工程量清单。你知道吗

下面是我的示例代码:

>>> import pyelliptic
>>> pubkey1="0453eb8248f42b00d057bc1adc724c4c841ec75851d6cd86f56f9bae5223219c7d3c7aff832d2383dfec167327ef38e9bf066690a8f94c055b336a607cebc2dddf".decode('hex')
>>> pubkey2="04678b95e902b04817ba258ecd3dbb2150d83850848a3b8523c11d51b6a9f89b93ea82db74ba82ba44fadb050b35eae8b96f3738e88c7c117227303a528c8df985".decode('hex')
>>> pyelliptic.ECC.raw_get_ecdh_key(pubkey1, pubkey2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method raw_get_ecdh_key() must be called with ECC instance as first argument (got str instance instead)

我在这里搜索并发现了许多关于这个问题的问题。我了解到我需要调用ECC()而不是ECC,但它没有更好的效果:

>>> pyelliptic.ECC().raw_get_ecdh_key(pubkey1, pubkey2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/pyelliptic/ecc.py", line 324, in raw_get_ecdh_key
    OpenSSL.EC_KEY_free(own_key)
UnboundLocalError: local variable 'own_key' referenced before assignment

我不知道怎么了。我检查了,变量own_key应该被引用。你知道吗


Tags: keyingetrawlinefiledecodehex
1条回答
网友
1楼 · 发布于 2024-10-06 10:22:42

这是Pyellic中一个非常明显的错误—如果您查看代码,就会发现定义own_key的部分(工程量清单第301行)被包裹在巨大的try/finally块中。如果在第301行之前引发(而不是管理)异常(这显然是发生在您身上的情况),那么执行流将跳转到finally块,该块将尝试引用此时尚未定义的own_key。你知道吗

可以通过克隆git repo并编辑raw_get_ecdh_key函数的代码so1来修复。相关的局部变量在函数的开头定义在try块之前(将它们设置为None)和2。在finally块中,在尝试使用这些变量释放资源之前,将针对None测试这些变量,即(未测试):

def raw_get_ecdh_key(self, pubkey_x, pubkey_y):
    other_key = None
    other_pub_key_x = None
    other_pub_key_y = None
    other_pub_key = None
    own_key = None
    own_priv_key = None

    try:
        # (snip code)
    finally:
        if other_key is not None:
            OpenSSL.EC_KEY_free(other_key)
        if other_pub_key_x is not None:
            OpenSSL.BN_free(other_pub_key_x)
        if other_pub_key_y is not None:
            OpenSSL.BN_free(other_pub_key_y)
        if other_pub_key is not None:
            OpenSSL.EC_POINT_free(other_pub_key)
        if own_key is not None:
            OpenSSL.EC_KEY_free(own_key)
        if own_priv_key is not None:
            OpenSSL.BN_free(own_priv_key)

然后运行unittests(最终为本例添加一些测试)并向作者提交pull请求。你知道吗

请注意,您已经应用了这个(未经测试的)修复,您应该有另一个错误—一开始是在finally块中发送给您的错误—但至少您应该有更多关于调用失败原因的信息。你知道吗

相关问题 更多 >