import os
import sys
import base64
import hmac
import hashlib
sys.path.append('/home/pi/workspace/fukuzono_work/IoTHubDeviceTwin/DeviceTwin_Test')
import DPSconfig
group_symmetric_key = DPSconfig.group_symmetric_key

def derive_device_key(device_id):
    """
    The unique device ID and the group master key should be encoded into "utf-8"
    After this the encoded group master key must be used to compute an HMAC-SHA256 of the encoded registration ID.
    Finally the result must be converted into Base64 format.
    The device key is the "utf-8" decoding of the above result.
    """
    message = device_id.encode("utf-8")
    signing_key = base64.b64decode(group_symmetric_key.encode("utf-8"))
    signed_hmac = hmac.HMAC(signing_key, message, hashlib.sha256)
    device_key_encoded = base64.b64encode(signed_hmac.digest())
    return device_key_encoded.decode("utf-8")
