前言:接口中上次的手机号码和密码是传入的加密的,模拟自动化的时候也需要先对数据进行加密

  • 1.各种语言实现 
网上已经各种语言实现好的AES加密,可以点击查看:http://outofmemory.cn/code-snippet/35524/AES-with-javascript-java-csharp-python-or-php

  • 2.python实现时踩的坑 
(1)iv的使用,必须使用; 
(2)iv的正确使用,格式:’\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0’; 
(3)最后要解析成base64.b64encode; 
(4)根据需求进行设置加密模式与密钥长度。

代码操作

# coding=utf-8

import hashlib
from Crypto.Cipher import AES
import base64


class AesCrypter(object):
    def __init__(self):
        self.key = b'********'
        self.iv = b'\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0'

    def encrypt(self, data):
        data1 = self.pkcs7padding(data)
        data = bytes(data1, encoding="utf8")  # 传进来的参数先变成字节
        h_key = hashlib.sha256(self.key).digest()
        cipher = AES.new(h_key, AES.MODE_CBC, self.iv)
        encrypted = cipher.encrypt(data)
        return base64.b64encode(encrypted)

    def decrypt(self, data):
        data = base64.b64decode(data)
        h_key = hashlib.sha256(self.key).digest()
        cipher = AES.new(h_key, AES.MODE_CBC, self.iv)
        decrypted = cipher.decrypt(data)
        decrypted = self.pkcs7unpadding(decrypted)
        return decrypted

    def pkcs7padding(self, data):
        # AES.block_size 16位
        bs = AES.block_size
        padding = bs - len(data) % bs  # 16-11%16
        padding_text = chr(padding) * padding  # chr()返回当前正是对应的ascii码
        return data + padding_text

    def pkcs7unpadding(self, data):
        lengt = len(data)
        unpadding = data[lengt - 1]
        return data[0:lengt - unpadding]

    def sha(self, text):
        # key进行256哈希
        sha256 = hashlib.sha256()
        sha256.update(text.encode('utf-8'))
        res = sha256.hexdigest()
        return res


if __name__ == '__main__':
    aes = AesCrypter()
    encrypted = aes.encrypt('39999912332')  # 加密
    print(encrypted)
    plain = aes.decrypt(encrypted)  # 解密
    print(plain)

运行后的结果