import Crypto, base64
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Cipher import DES


# rsa解密密文方法
def get_max_length(rsa_key, encrypt=True):
    """加密内容过长时 需要分段加密 换算每一段的长度.
        :param rsa_key: 钥匙.
        :param encrypt: 是否是加密.
    """
    blocksize = Crypto.Util.number.size(rsa_key.n) / 8
    reserve_size = 11  # 预留位为11
    if not encrypt:  # 解密时不需要考虑预留位
        reserve_size = 0
    maxlength = blocksize - reserve_size
    return maxlength
# ------------------------解密密文------------------------
def decryption(text_encrypted_base64: str, private_key: bytes):
    # 字符串指定编码（转为bytes）
    text_encrypted_base64 = text_encrypted_base64.encode('utf-8')
    # base64解码
    text_encrypted = base64.b64decode(text_encrypted_base64)
    # 构建私钥对象
    private_key = RSA.importKey(private_key)
    max_length = int(get_max_length(private_key, False))
    cipher_private = PKCS1_v1_5.new(private_key)
    length = len(text_encrypted)
    if length < max_length:
        return b''.join(cipher_private.decrypt(text_encrypted, b'xyz'))
        # 需要分段
    offset = 0
    res = []
    while length - offset > 0:
        if length - offset > max_length:
            res.append(cipher_private.decrypt(text_encrypted[offset:offset + max_length], b'xyz'))
        else:
            res.append(cipher_private.decrypt(text_encrypted[offset:], b'xyz'))
        offset += max_length
    text_decrypted = b''
    for i in res:
        text_decrypted += i
    # print(text_decrypted.decode())
    return text_decrypted.decode()
