利用AES算法加密数据

准备工作:

模块安装问题:

首先在python中安装Crypto这个包
但是在安装模块后在使用过程中他会报错
下面是解决方法:
pip3 install pycrypto
安装会报错
https://github.com/sfbahr/PyCrypto-Wheels
下载合适的版本
pip3 install wheel
进入下载文件所在的目录:
pip3 install pycrypto-2.6.1-cp35-none-win32.whl

实现逻辑

from Crypto.Cipher import AES
# 通过AES算法将要发送的数据加密,保证数据的安全性
def encrypt(message):
    key = b'dfdsdfsasdfdsdfs'
    cipher = AES.new(key, AES.MODE_CBC, key)
    ba_data = bytearray(message,encoding='utf-8')
    v1 = len(ba_data)
    v2 = v1 % 16
    if v2 == 0:
        v3 = 16
    else:
        v3 = 16 - v2
    for i in range(v3):
        ba_data.append(v3)
    final_data = ba_data
    msg = cipher.encrypt(final_data) # 要加密的字符串,必须是16个字节或16个字节的倍数
    return msg

def decrypt(msg): key
= b'dfdsdfsasdfdsdfs' cipher = AES.new(key, AES.MODE_CBC, key) result = cipher.decrypt(msg) # result = b'xe8xa6x81xe5x8axa0xe5xafx86xe5x8axa0xe5xafx86xe5x8axa0sdfsd ' data = result[0:-result[-1]] return str(data,encoding='utf-8')
原文地址:https://www.cnblogs.com/zhaijihai/p/10268985.html