使用pyaes测试AES-ECB 加密解密示例

  最近在搞一个蓝牙锁,通信协议说是使用的标准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:Python36Scripts添加到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'x2bx7ex15x16x28xaexd2xa6xabxf7x15x88x09xcfx4fx3c'
11 plaintext = b'x6bxc1xbexe2x2ex40x9fx96xe9x3dx7ex11x73x93x17x2a'
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)

  运行结果如下:

原文地址:https://www.cnblogs.com/twxbtx/p/7436757.html