from security import ( security_calc_hash, security_decrypt_to, security_encrypt_to, security_get_api_encryption_key, security_get_hw_hash, security_get_resource_encryption_key, ) from credentials import Credentials from security_provider import SecurityProvider class TpmSecurityProvider(SecurityProvider): def __init__(self): try: from tpm2_pytss import FAPI from tpm2_pytss import TSS2_Exception except (ImportError, NotImplementedError) as e: raise RuntimeError("tpm2-pytss FAPI is not available") from e self._TSS2_Exception = TSS2_Exception self._fapi = FAPI() try: self._fapi.provision(is_provisioned_ok=True) except TSS2_Exception: pass self._fapi.get_random(1) @property def kind(self) -> str: return "tpm" def encrypt_to(self, input_bytes: bytes, key: str) -> bytes: return security_encrypt_to(input_bytes, key) def decrypt_to(self, ciphertext_with_iv_bytes: bytes, key: str) -> bytes: return security_decrypt_to(ciphertext_with_iv_bytes, key) def get_hw_hash(self, hardware: str) -> str: return security_get_hw_hash(hardware) def get_api_encryption_key( self, creds_email: str, creds_password: str, hardware_hash: str ) -> str: creds = Credentials(creds_email, creds_password) return security_get_api_encryption_key(creds, hardware_hash) def get_resource_encryption_key(self) -> str: return security_get_resource_encryption_key() def calc_hash(self, key: str) -> str: return security_calc_hash(key) def seal(self, object_path: str, data: bytes) -> None: self._fapi.create_seal(object_path, data=data, exists_ok=True) def unseal(self, object_path: str) -> bytes: return self._fapi.unseal(object_path)