public Byte[] SignHmac(Byte[] dataToSign)
{
TpmHandle hmacKeyHandle = new TpmHandle(AIOTH_PERSISTED_KEY_HANDLE + logicalDeviceId);
int dataIndex = 0;
Byte[] iterationBuffer;
Byte[] hmac = { };
if (dataToSign.Length <= 1024)
{
try
{
// Open the TPM
Tpm2Device tpmDevice = new TbsDevice();
tpmDevice.Connect();
var tpm = new Tpm2(tpmDevice);
// Calculate the HMAC in one shot
hmac = tpm.Hmac(hmacKeyHandle, dataToSign, TpmAlgId.Sha256);
// Dispose of the TPM
tpm.Dispose();
}
catch
{
return hmac;
}
}
else
{
try
{
// Open the TPM
Tpm2Device tpmDevice = new TbsDevice();
tpmDevice.Connect();
var tpm = new Tpm2(tpmDevice);
// Start the HMAC sequence
Byte[] hmacAuth = new byte[0];
TpmHandle hmacHandle = tpm.HmacStart(hmacKeyHandle, hmacAuth, TpmAlgId.Sha256);
while (dataToSign.Length > dataIndex + 1024)
{
// Repeat to update the hmac until we only hace <=1024 bytes left
iterationBuffer = new Byte[1024];
Array.Copy(dataToSign, dataIndex, iterationBuffer, 0, 1024);
tpm.SequenceUpdate(hmacHandle, iterationBuffer);
dataIndex += 1024;
}
// Finalize the hmac with the remainder of the data
iterationBuffer = new Byte[dataToSign.Length - dataIndex];
Array.Copy(dataToSign, dataIndex, iterationBuffer, 0, dataToSign.Length - dataIndex);
TkHashcheck nullChk;
hmac = tpm.SequenceComplete(hmacHandle, iterationBuffer, TpmHandle.RhNull, out nullChk);
// Dispose of the TPM
tpm.Dispose();
}
catch
{
return hmac;
}
}
return hmac;
}