2017-08-18 61 views
2

這個小Python程序應該加密平原使用一個128位的密鑰pycrypto不再現NIST測試向量的AES(CFB模式)

from Crypto.Cipher import AES 

#   1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 
key = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 
iv = b'\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 
plain = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 

aes = AES.new(key, AES.MODE_CFB, iv) 
cipher = aes.encrypt(plain) 

print(' '.join('{:2x}'.format(b) for b in cipher)) 
在CFB模式下使用AES 密碼

我把這個鍵,IV和來自NIST test vectors之一的簡單密碼組合(CFB128VarTxt128.rsp)。對於這個特殊的組合,我期待的密碼:

3a d7 8e 72 6c 1e c0 2b 7e bf e9 2b 23 d9 ec 34 

但pycrypto計算

3a 81 e1 d4 b8 24 75 61 46 31 63 4b 5c 79 d6 bc 

的第一個字節是正確的,而其他不匹配。我也嘗試了不同的測試向量,但結果保持不變。除第一個字節外,所有字節都不匹配。

我很肯定,NIST測試向量是有效的,因爲我之前在使用AES和Crypto ++時使用它們,我也很確定,pycrypto的實現是正確的,因爲它的輸出與在線工具如this page 。顯然,這是我,誰正在使用的工具不正確的方式...

有沒有人有線索,如何重現與pycrypto NIST測試向量?

這是NIST例如

# CAVS 11.1 
# Config info for aes_values 
# AESVS VarTxt test data for CFB128 
# State : Encrypt and Decrypt 
# Key Length : 128 
# Generated on Fri Apr 22 15:11:53 2011 
... 
COUNT = 0 
KEY = 00000000000000000000000000000000 
IV = 80000000000000000000000000000000 
PLAINTEXT = 00000000000000000000000000000000 
CIPHERTEXT = 3ad78e726c1ec02b7ebfe92b23d9ec34 
+0

我得到了與PyCrypto 2.6.0相同的結果... – ForceBru

回答

3

你缺少一個關鍵字參數,segment_size,在您的通話AES.new(...)。這是反饋大小,默認爲8.如果您的代碼行更改爲

aes = AES.new(key, AES.MODE_CFB, iv, segment_size=128) 

您將得到正確的結果。

如在該文檔中指出:

segment_size(整數) - (僅MODE_CFB)的 明文和密文在分段的比特數.The它必須是8 如果爲0的倍數。或未指定,則將假定爲8.

您的結果與NIST文檔中可能標記爲「CFB8」的內容相對應。

+0

啊,這很有道理! –

+0

thx爲RTFM。現在一切都按預期工作。非常感謝 – avitase

0

使用AES.MODE_CFB時,我也得到了同樣的結果如你,但我得到你希望當我用AES.MODE_CBC,而不是結果。

from Crypto.Cipher import AES 

def show(b): 
    print(*['{:02x}'.format(u) for u in b]) 

key = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 
iv = b'\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 
plain = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 

crypto = AES.new(key, AES.MODE_CBC, iv) 
cipher = crypto.encrypt(plain) 
show(cipher) 

# We need a fresh AES object to decrypt 
crypto = AES.new(key, AES.MODE_CBC, iv) 
decoded = crypto.decrypt(cipher) 
show(decoded) 

輸出

3a d7 8e 72 6c 1e c0 2b 7e bf e9 2b 23 d9 ec 34 
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00