Python中AES pkcs5加解密

2020-05-08  本文已影响0人  DjangoUnchained
介绍
pkcs5介绍
依赖包
pycryptodome
加密填充实现
from Crypto.Cipher import AES

def padding_pkcs5(value):
    BS = AES.block_size
    return str.encode(value + (BS - len(value) % BS) * chr(BS - len(value) % BS), encoding='utf-8')

加密实现
from Crypto.Cipher import AES
import hashlib
# keys是32位
def aes_ecb_encrypt(response, keys):
    response = padding_pkcs5(response)
    # mode根据实际需要填写
    cipher = AES.new(bytes.fromhex(get_sha1prng_key(keys)), mode=AES.MODE_ECB)
    encrypt_cipher = cipher.encrypt(response)
    return ''.join(['%02x' % i for i in encrypt_cipher]).upper()

def get_sha1prng_key(key):
    '''这一部分根据自己需要生成key
    same as java AES crypto key generator SHA1PRNG
    Arguments:
        key {[string]} -- [key]

    Returns:
        [string] -- [hexstring]
    '''
    signature = hashlib.sha1(key.encode()).digest()
    signature = hashlib.sha1(signature).digest()
    return ''.join(['%02x' % i for i in signature]).upper()[:32]
解密实现
def aes_ecb_decrypt(keys, value):
    keys = bytes.fromhex(get_sha1prng_key(keys))
    cryptor = AES.new(keys, AES.MODE_ECB)

    result = bytes()
    for i in range(int(len(value) / 2)):
        high = int(value[i * 2:i * 2 + 1], 16)
        low = int(value[i * 2 + 1:i * 2 + 2], 16)
        result += bytes([high * 16 + low])

    ciphertext = str(cryptor.decrypt(result), encoding='utf-8')
    ciphertext = ciphertext[0:-ord(ciphertext[-1])]
    return ciphertext
上一篇 下一篇

猜你喜欢

热点阅读