__author__ = 'deadblue'

import base64
import secrets

from py115._internal.crypto import _rsa, _xor


_rsa_n = bytes([
    0x86, 0x86, 0x98, 0x0c, 0x0f, 0x5a, 0x24, 0xc4, 
    0xb9, 0xd4, 0x30, 0x20, 0xcd, 0x2c, 0x22, 0x70, 
    0x3f, 0xf3, 0xf4, 0x50, 0x75, 0x65, 0x29, 0x05, 
    0x8b, 0x1c, 0xf8, 0x8f, 0x09, 0xb8, 0x60, 0x21, 
    0x36, 0x47, 0x71, 0x98, 0xa6, 0xe2, 0x68, 0x31, 
    0x49, 0x65, 0x9b, 0xd1, 0x22, 0xc3, 0x35, 0x92, 
    0xfd, 0xb5, 0xad, 0x47, 0x94, 0x4a, 0xd1, 0xea, 
    0x4d, 0x36, 0xc6, 0xb1, 0x72, 0xaa, 0xd6, 0x33, 
    0x8c, 0x3b, 0xb6, 0xac, 0x62, 0x27, 0x50, 0x2d, 
    0x01, 0x09, 0x93, 0xac, 0x96, 0x7d, 0x1a, 0xef, 
    0x00, 0xf0, 0xc8, 0xe0, 0x38, 0xde, 0x2e, 0x4d, 
    0x3b, 0xc2, 0xec, 0x36, 0x8a, 0xf2, 0xe9, 0xf1, 
    0x0a, 0x6f, 0x1e, 0xda, 0x4f, 0x72, 0x62, 0xf1, 
    0x36, 0x42, 0x0c, 0x07, 0xc3, 0x31, 0xb8, 0x71, 
    0xbf, 0x13, 0x9f, 0x74, 0xf3, 0x01, 0x0e, 0x3c, 
    0x4f, 0xe5, 0x7d, 0xf3, 0xaf, 0xb7, 0x16, 0x83, 
])

_rsa_e = 0x10001

_cipher = _rsa.Cipher(_rsa_n, _rsa_e)


def generate_key() -> bytes:
    return secrets.token_bytes(16)


def encode(key: bytes, input: str) -> str:
    input_data = bytearray(input.encode())
    _xor.transform(
        key=_xor.derive_key(key, 4),
        data=input_data
    )
    input_data.reverse()
    _xor.transform(
        key=_xor.client_key,
        data=input_data
    )
    # Prepend key
    input_data = key + input_data
    return base64.b64encode(
        _cipher.encrypt(input_data)
    ).decode()


def decode(key: bytes, input: str) -> str:
    input_data = bytearray( base64.b64decode(input) )
    plaintext = _cipher.decrypt(input_data)

    server_key, plaintext = plaintext[:16], plaintext[16:]
    _xor.transform(
        key=_xor.derive_key(server_key, 12),
        data=plaintext
    )
    plaintext.reverse()
    _xor.transform(
        key=_xor.derive_key(key, 4),
        data=plaintext
    )
    return plaintext.decode()
