AES加密

安装模块

  • 直接安装(适用linux,mac)

    pip3 install pycrypto

  • 下载后安装(直接安装Windows可能会失败)

    https://github.com/sfbahr/PyCrypto-Wheels
    pip3 install wheel
    进入目录:
    pip3 install pycrypto-2.6.1-cp35-none-win32.whl

加密

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):
    from Crypto.Cipher import AES
    key = b'dfdsdfsasdfdsdfs'
    cipher = AES.new(key, AES.MODE_CBC, key)
    result = cipher.decrypt(msg) #result是二进制码
    data = result[0:-result[-1]]
    return str(data,encoding='utf-8')
原文地址:https://www.cnblogs.com/liangchengyang/p/10435071.html