2017-04-18 64 views
1

我在使用Python 3上的pycryptodome進行AES-CTR加密時遇到了困難。數據可能是〜1000字節,但是當它變得足夠長時,它會中斷。我不明白這個錯誤應該是什麼意思或如何解決它。pycryptodome:OverflowError:計數器已經繞過CTR模式

from os import urandom 
from Crypto.Cipher import AES 

cipher = AES.new(urandom(16), AES.MODE_CTR, nonce=urandom(15)) 
cipher.encrypt(urandom(10000)) 

--------------------------------------------------------------------------- 
OverflowError        Traceback (most recent call last) 
<ipython-input-116-a48990362615> in <module>() 
     3 
     4 cipher = AES.new(urandom(16), AES.MODE_CTR, nonce=urandom(15)) 
----> 5 cipher.encrypt(urandom(10000)) 
     6 

/usr/local/lib/python3.5/dist-packages/Crypto/Cipher/_mode_ctr.py in encrypt(self, plaintext) 
    188   if result: 
    189    if result == 0x60002: 
--> 190     raise OverflowError("The counter has wrapped around in" 
    191          " CTR mode") 
    192    raise ValueError("Error %X while encrypting in CTR mode" % result) 

OverflowError: The counter has wrapped around in CTR mode 

回答

1

我想通了。 Nonce的塊大小隻有1個字節,所以計數器模式只能產生256個塊,這將允許加密4096個字節。如果隨機數少於幾個字節,則問題消失。

+1

[該構造函數的文檔](https://legrandin.github.io/pycryptodome/Doc/3.4/Crypto.Cipher.AES-module.html)推薦在CTR模式下使用8個字節作爲隨機數。但是,對我來說,溢出行爲似乎很愚蠢:只需傳遞一個16字節的隨機IV,而不是將其分割爲單獨的「nonce」和「initial_value」部分。但是這個庫不允許CTR模式下的'iv'參數。 – Wyzard

+0

它總是有意義的,它檢測到同一計數器被多次使用的情況,這被認爲是安全漏洞。 – ArekBulski

+1

不完全。它將計數器空間分成更小的塊,並防止從一個塊溢出到另一塊,從而防止每次使用不同的塊(隨機數)時發生衝突。但它不會阻止或檢測到隨機數的重用,並且如果您隨機選擇隨機數,碰撞的機會會增加,因爲只有一些計數器的位(隨機數部分)是隨機的,其餘( 'initial_value'部分)爲零。用16個隨機字節初始化整個計數器會更好。 – Wyzard