# -*- coding: utf-8 -*-
# Copyright (c) 2023 CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com
from typing import NamedTuple

from OpenSSL import crypto

KEY_BYTES = 2048
CIPHER = 'aes256'
PASSPHRASE_LENGTH = 32


class KeyPair(NamedTuple):
    private_key: crypto.PKey

    @property
    def public_key(self) -> str:
        raw_public_key = crypto.dump_publickey(crypto.FILETYPE_PEM, self.private_key)
        return ''.join(x for x in raw_public_key.decode().split('\n') if x and not x.startswith('-----'))

    @property
    def private_key_pem(self) -> str:
        return crypto.dump_privatekey(crypto.FILETYPE_PEM, self.private_key).decode('utf-8')

    @property
    def private_key_bytes(self) -> bytes:
        return crypto.dump_privatekey(crypto.FILETYPE_ASN1, self.private_key)


def generate() -> KeyPair:
    private_key = crypto.PKey()
    private_key.generate_key(crypto.TYPE_RSA, KEY_BYTES)
    return KeyPair(private_key=private_key)


def loads(private_key: str) -> KeyPair:
    pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, private_key.encode('utf-8'))
    return KeyPair(private_key=pkey)
