import requests
import base64
import subprocess
import json
from dh_tests import DiffieHellmanConsoleManager

SMC_LICENSE_KEY = "6087bee1-85b6-416e-8dce-cf5609ecc77f"
NDR_LICENSE_KEY = "7eea457f-5069-452d-b623-122bfe22b75e"
NDR_IP_ADDRESS = "192.168.56.10"
REGISTER_DEVICE_API_URL = f"https://{NDR_IP_ADDRESS}:8000/api/v1/auth/session/add-trusted-device"

# Forming base64 wsmc code
smc_base64_license_key = base64.b64encode(SMC_LICENSE_KEY.encode('utf-8')).decode('utf-8')

# Forming base64 ndr code
ndr_base64_license_key = base64.b64encode(NDR_LICENSE_KEY.encode('utf-8')).decode('utf-8')

# Declaring DH manager

dh_manager = DiffieHellmanConsoleManager()


# Генерируем параметры Diffie-Hellman
# dhparam_command = ['openssl', 'dhparam', '-out', 'dhp.pem', '2048']
# subprocess.run(dhparam_command, check=True)

dh_manager.dh_params = dh_manager.generate_dh_params()

# Генерируем закрытый ключ DH
# genpkey_command = ['openssl', 'genpkey', '-paramfile', 'dhp.pem', '-out', 'dhkeyA.pem']
# subprocess.run(genpkey_command, check=True)

dh_manager.host_private_key = dh_manager.generate_host_private_key(dh_params=dh_manager.dh_params)

# Извлекаем открытый ключ DH из закрытого ключа
# pkey_command = ['openssl', 'pkey', '-in', 'dhkeyA.pem', '-pubout', '-out', 'dhpubA.pem']
# subprocess.run(pkey_command, check=True)

dh_manager.host_public_key = dh_manager.generate_host_public_key(dh_manager.host_private_key)

# Получаем ключ из файла
# f = open("dhpubA.pem", "r")
global_key_A = dh_manager.host_public_key
smc_global_key = base64.b64encode(global_key_A.encode('utf-8')).decode('utf-8')

print("-"*60)
print(smc_base64_license_key)
print("-"*60)
print(ndr_base64_license_key)
print("-"*60)
print(smc_global_key)

# Делаем запрос на регистрацию устройства
request_data = {
    "lic_key_ndr": ndr_base64_license_key,
    "lic_key_smc": smc_base64_license_key,
    "public_key": smc_global_key
}

response = requests.post(REGISTER_DEVICE_API_URL, json=request_data, verify=False)

print("Status code:", response.status_code)
print("Headers:", response.headers)
response_body = json.loads(response.text)
print("Response body:", response_body['data']['public_key'])

dh_manager.remote_public_key = dh_manager.decode_remote_public_key(response_body['data']['public_key'])

print('-'*10 + "Add trusted device result" + '-'*10)
print(dh_manager.dh_params)
print(dh_manager.host_public_key)
print(dh_manager.host_private_key)
print(dh_manager.remote_public_key)
print('-'*30)

dh_manager.shared_key = dh_manager.generate_shared_key(
    dh_manager.host_private_key,
    dh_manager.remote_public_key
)
