from transforms.base import *


class CryptDeriveKey(Transform):
    """
    Microsoft CryptDeriveKey simulation
    """
    category = "crypto (key)"
    name = "CryptDeriveKey"
    icon = "wxART_DECRYPT"

    def run(self, data:bytes, hash:("md5", "sha1", "sha256")="sha256", key_len_in_bits:int=256):
        import hashlib
        if hash == "sha1":
            h = hashlib.sha1
        elif hash == "md5":
            h = hashlib.md5
        else:
             return hashlib.sha256(data).digest()
        b1 = bytearray(b'\x36' * 64)
        b2 = bytearray(b'\x5c' * 64)
        for i, v in enumerate(h(data).digest()):
            b1[i] ^= v
            b2[i] ^= v
        hash1 = h(b1).digest()
        hash2 = h(b2).digest()
        return bytes(hash1 + hash2)[:key_len_in_bits // 8]


