#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <tss/tss_error.h>
#include <tss/platform.h>
#include <tss/tss_defines.h>
#include <tss/tss_typedef.h>
#include <tss/tss_structs.h>
#include <tss/tspi.h>
#include <trousers/trousers.h>
#define Debug(message, tResult) printf("%s : %s\n", message, (char *)Trspi_Error_String(result))
int main()
{
printf("#########程序开始运行:###########\n");
TSS_HCONTEXT hContext;
TSS_RESULT result;
TSS_HTPM hTPM;
TSS_HPCRS hPcrs;
int i;
TSS_HKEY hSRK = 0;
TSS_HPOLICY hSRKPolicy = 0;
TSS_UUID SRK_UUID = TSS_UUID_SRK;
BYTE wks[20];
BYTE valueToExtend[250];
int count = 0;
FILE * sfp;
char *fp = "/home/shm/tpm-test/test-tpm1/usr.img";
char *buf;
TSS_HHASH hHash;
BYTE *digest, *data;
UINT32 digestLen;
if((sfp=fopen(fp,"rb"))==NULL)
{
printf("!Source file cannot be opened\n");
return 0;
}
long int length;
fseek(sfp,0,SEEK_END);
length = ftell(sfp);
fseek(sfp,0,SEEK_SET);
printf("\n*the file's length = %ld \n",length);
buf = (char *)malloc(length);
fread(buf,length,1,sfp);
printf("*the file's contests :\n %s\n",buf);
result = Tspi_Context_Create(&hContext);
Debug(" 1-Create Context",result);
result = Tspi_Context_Connect(hContext,NULL);
Debug(" 2-Context Connect", result);
result = Tspi_Context_GetTpmObject(hContext, &hTPM);
Debug("Get TPM Handle", result);
result = Tspi_Context_LoadKeyByUUID(hContext, TSS_PS_TYPE_SYSTEM, SRK_UUID, &hSRK);
Debug("Get the SRK handle", result);
result = Tspi_GetPolicyObject(hSRK, TSS_POLICY_USAGE, &hSRKPolicy);
Debug("Get the SRK policy", result);
result = Tspi_Policy_SetSecret(hSRKPolicy, TSS_SECRET_MODE_SHA1, 20, wks);
data = buf;
Tspi_Context_CreateObject(hContext, TSS_OBJECT_TYPE_HASH, TSS_HASH_SHA1, &hHash);
Tspi_Hash_UpdateHashValue(hHash, strlen(data), data);
Tspi_Hash_GetHashValue(hHash, &digestLen, &digest);
printf("----源数据的二进制形式: \n");
for (i = 0; i < strlen(data); i++)
printf("%02x", *(data + i));
printf("\n*the file's length = %ld \n",length);
printf("\n----被散列后的hash值: \n");
for (i = 0; i < digestLen; i++)
printf("%02x", *(digest + i));
printf("\n*the hashValue's length = %d \n",digestLen);
BYTE *rgbPcrValue;
UINT32 ulPcrLen;
UINT32 pcrToExtend = 10;
result = Tspi_TPM_PcrRead(hTPM, pcrToExtend, &ulPcrLen, &rgbPcrValue);
printf("PCR %02d ", pcrToExtend);
for (i = 0; i < 20; i++)
printf("%02x", *(rgbPcrValue + i));
printf("\n");
result = Tspi_TPM_PcrExtend(hTPM, pcrToExtend,20,digest, NULL, &ulPcrLen, &rgbPcrValue);
Debug("*********Extend the PCR**********", result);
result = Tspi_TPM_PcrRead(hTPM, pcrToExtend, &ulPcrLen, &rgbPcrValue);
printf("PCR %02d ", pcrToExtend);
for (i = 0; i < 20; i++)
printf("%02x", *(rgbPcrValue + i));
printf("\n");
fclose(sfp);
Tspi_Context_FreeMemory(hContext, NULL);
Tspi_Context_Close(hContext);
printf("\n######释放资源成功,程序结束。#########\n");
return 0;
}