1. python版本接入样例

def aes_256_encrypt(plain_str, app_key):
    raw = pad(plain_str)
    iv = gen_iv(app_key)
    cipher = AES.new(app_key, AES.MODE_CBC, iv)
    r = base64.b64encode(cipher.encrypt(raw)).decode()
    return base64.b64encode(r.encode()).decode()


def aes_256_decrypt(msg, app_key):
    enc = base64.b64decode(msg).decode()
    enc = base64.b64decode(enc)
    iv = gen_iv(app_key)
    cipher = AES.new(app_key, AES.MODE_CBC, iv)
    return unpad(cipher.decrypt(enc).decode("utf-8"))


def gen_iv(app_key):
    m = hashlib.md5()
    m.update(app_key.encode("utf-8"))
    return m.hexdigest()[:16]


def pad(text):
    """填充方式,加密内容必须为16字节的倍数,若不足则使用self.iv进行填充"""
    text_length = len(text)
    amount_to_pad = AES.block_size - (text_length % AES.block_size)
    if amount_to_pad == 0:
        amount_to_pad = AES.block_size
    pad = chr(amount_to_pad)
    return text + pad * amount_to_pad


def unpad(text):
    pad = ord(text[-1])
    return text[:-pad]


## 使用时 直接调用aes_256_encrypt 加密;aes_256_decrypt对应解密
@Copyright © cosmos 2019 all right reserved,powered by Gitbook修订时间: 2019-12-16 16:51:27

results matching ""

    No results matching ""