最近在搞一個藍牙鎖,通信協議說是使用的標准AES-ECB加密、解密,無奈我測試的時候,加密后的數據和通信協議文檔給的數據不一致,懷疑文檔寫的aes-ecb傳參是否swap了or非標准AES-ECB?所以想到了用Python驗證一下,這里可以使用pyaes模塊。
考慮到pip工具安裝其他Python模塊比較方便,首先安裝pip,然后就可以用pip安裝其他Python模塊了,這里簡單介紹一下如何安裝pip工具(關於Python和pip在Windows環境下的詳細安裝方法,可以參考如下網頁:http://www.tuicool.com/articles/eiM3Er3):
1、登錄網站:https://pip.pypa.io/en/stable/installing/;
2、下載get-pip.py文件;
3、win運行cmd,切換目錄cd /D d:\ (回車),輸入Python get-pip.py(回車),安裝pip工具;
4、安裝完成后還需將pip路徑添加到系統環境變量中,如果Python安裝在C:\Python36,則將C:\Python36\Scripts添加到PATH中。
下面安裝pyaes就簡單多了,在cmd中輸入pip install pyaes (回車)安裝pyaes模塊(git地址:https://github.com/ricmoo/pyaes),因為我們已經安裝過了該模塊,所以這里顯示已經安裝過pyaes,提示如下:
下面就是AES-ECB的測試代碼,測試數據摘自AES數據手冊:
1 # -*- coding: utf-8 -*- 2 import os, pyaes, binascii 3 4 ''' 5 Key 2b7e151628aed2a6abf7158809cf4f3c 6 Plaintext 6bc1bee22e409f96e93d7e117393172a 7 Ciphertext 3ad77bb40d7a3660a89ecaf32466ef97 8 ''' 9 10 key_128 = b'\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c' 11 plaintext = b'\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a' 12 13 14 print('key_128: %s' %binascii.hexlify(key_128)) 15 print('plaintext: %s' %binascii.hexlify(plaintext)) 16 17 aes = pyaes.AESModeOfOperationECB(key_128) 18 ciphertext = aes.encrypt(plaintext) 19 20 # 3ad77bb40d7a3660a89ecaf32466ef97 21 print('ciphertext: %s' %binascii.hexlify(ciphertext)) #print(repr(ciphertext)) 22 23 # Since there is no state stored in this mode of operation, it 24 # is not necessary to create a new aes object for decryption. 25 #aes = pyaes.AESModeOfOperationECB(key) 26 decrypted = aes.decrypt(ciphertext) 27 28 print('decrypted: %s' %binascii.hexlify(decrypted)) #print(repr(decrypted)) 29 30 # True 31 print( decrypted == plaintext)
運行結果如下: