1、 安装教程
安装步骤教程 https://github.com/sfbahr/PyCrypto-Wheels pip3 install wheel pip install pycryptodome pycrypto,pycrytodome和crypto是一个东西,crypto在python上面的名字是pycrypto它是一个第三方库,但是已经停止更新三年了,所以不建议安装这个库; 进入目录: pip3 install pycrypto-2.6.1-cp35-none-win32.whl 安装出错,试了很多次才成功安装‘ pip2 install pycryptodome pip3 install pycryptodome
2、加密
from Crypto.Cipher import AES from binascii import b2a_hex,a2b_hex # ######################### 加密 ######################### def encrpyt(message): key = b'dfdsdfsasdfdsdfs' # 必须16个字节 cipher = AES.new(key, AES.MODE_CBC, key) ba_data = bytearray(message, encoding='utf-8') v1 = len(ba_data) print('字符串长度:',v1) v2 = v1 % 16 if v2 == 0: v3 = 16 else: v3 = 16 - v2 print('需要增加的字节数,保证是16字节的倍数:',v3) for i in range(v3): ba_data.append(v3) # final_data = ba_data.decode('utf-8') final_data = ba_data.decode('utf-8') msg = cipher.encrypt(ba_data) return msg
3、 解密
# ######################### 解密 ######################### from Crypto.Cipher import AES from binascii import b2a_hex,a2b_hex def decrypt(msg): from Crypto.Cipher import AES key = b'dfdsdfsasdfdsdfs' cipher = AES.new(key, AES.MODE_CBC, key) result = cipher.decrypt(msg) data = result[0:-result[-1]] return str(data, encoding='utf-8')
4、 测试执行代码
data = "房间爱哭了房间啊" v1 = encrpyt(data) print('v1',v1) v2 = decrypt(v1) print('v2@@@',v2)
5、 结果
C:Python3python.exe D:/字符串加密解密AES.py 字符串长度: 24 需要增加的字节数,保证是16字节的倍数: 8 加密后的字符串: b'xacxfbx0bxa6xd9.rxd0xfcxc5x8beHx82x94xe4xab7xe2tqx96dx1axadxc6xccx8exe8x08x81xa8' 解密后的字符串: 房间爱哭了房间啊 Process finished with exit code 0