我正在尝试在python2中实现加密/解密功能。
这是加密方案:
 但是,我在pycrypto库的AES CTR函数中遇到'method-wrapper' object is not iterable错误

这是堆栈跟踪:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-1c44f21fcf83> in <module>()
     45         l = random.randint(16,48)
     46         m = random_bytes(l)
---> 47         assert specialDecryption(k, specialEncryption(k, m)) == m

<ipython-input-5-1c44f21fcf83> in specialEncryption(k, m)
      7     # compute PRF
      8     r = random_bytes(KEYLENGTH/8)
----> 9     prf = lengthQuadruplingPRF(k, r)
     10
     11     # xor

<ipython-input-4-59fb6141461b> in lengthQuadruplingPRF(k, r)
     34     assert len(k) == KEYLENGTH/8
     35     assert len(r) <= KEYLENGTH/8
---> 36     obj = AES.new(k, AES.MODE_CTR, counter=make_counter())
     37     output = obj.encrypt(r*4)
     38     return output

/usr/local/lib/python2.7/site-packages/Crypto/Cipher/AES.pyc in new(key, mode, *args, **kwargs)
    204
    205     kwargs["add_aes_modes"] = True
--> 206     return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
    207
    208

/usr/local/lib/python2.7/site-packages/Crypto/Cipher/__init__.pyc in _create_cipher(factory, key, mode, *args, **kwargs)
     77             raise TypeError("IV is not meaningful for the ECB mode")
     78
---> 79     return modes[mode](factory, **kwargs)

/usr/local/lib/python2.7/site-packages/Crypto/Cipher/_mode_ctr.pyc in _create_ctr_cipher(factory, **kwargs)
    323     # 'counter' used to be a callable object, but now it is
    324     # just a dictionary for backward compatibility.
--> 325     _counter = dict(counter)
    326     try:
    327         counter_len = _counter.pop("counter_len")

TypeError: 'method-wrapper' object is not iterable


这是代码:

if __name__ == '__main__':
    k = os.urandom(KEYLENGTH/8)  # generate key
    l = random.randint(16,48)
    m = os.urandom(l)
    c = specialEncryption(k, m) ## FIRST IN THE FAILURE STACK

def specialEncryption(k, m):
   ... other code

    # compute PRF
    r = os.urandom(KEYLENGTH/8)
    prf = lengthQuadruplingPRF(k, r) ## SECOND IN THE FAIL STACK

    ... other code

def make_counter():
    import struct
    def gen():
        i = 0;
        while True:
            yield struct.pack('>QQ', 0, i)
            i += 1
    return gen().next

def lengthQuadruplingPRF(k, r):
    # Input: 16 byte key, 16 byte value
    # Output: 64 byte pseudorandom bytes
    obj = AES.new(k, AES.MODE_CTR, counter=make_counter()) ## FAILS HERE
    output = obj.encrypt(r*4)
    return output

最佳答案

您的counter应该是可迭代的,能够初始化dict,而不是绑定方法。

我怀疑将您的make_counter函数更改为:

return gen()


从:

return gen().next


足以修复它。

09-05 01:13