Как подписать сообщение с TPM2? - PullRequest
0 голосов
/ 08 марта 2019

С MethodA():

Сначала я создал шаблон, затем ключ подписи.Затем сохранил контекст с помощью ContextSave(); И маршаллировал его в файл.

Из MethodB():

Я демонтировал файл, и сделал ContextLoad(); Здесь это не удается с проверкой целостности.Что я сделал не так?

Я создал ключ подписи так:

var keyTemplate = new TpmPublic(TpmAlgId.Sha1,          // Name algorithm
     ObjectAttr.UserWithAuth | ObjectAttr.Sign |        // Signing key
     ObjectAttr.FixedParent | ObjectAttr.FixedTPM |     // Non-migratable 
     ObjectAttr.SensitiveDataOrigin,
     null,                                              // No policy
     new RsaParms(new SymDefObject(),
                  new SchemeRsassa(TpmAlgId.Sha1), 2048, 0),
     new Tpm2bPublicKeyRsa());


TpmHandle keyHandle = tpm[ownerAuth].CreatePrimary(
     TpmRh.Owner,                            // In the owner-hierarchy
     new SensitiveCreate(keyAuth, null),     // With this auth-value
     keyTemplate,                            // Describes key
     null,                                   // Extra data for creation ticket
     new PcrSelection[0],                    // Non-PCR-bound
     out keyPublic,                          // PubKey and attributes
     out creationData, out creationHash, out creationTicket);    // Not used here

РЕДАКТИРОВАТЬ 1:

MethodA ();

        public static void MethodA()
    {
        try
        {
            Tpm2Device tpmDevice = new TcpTpmDevice(tpm_host, tpm_port);
            //Tpm2Device tpmDevice = new TbsDevice();
            tpmDevice.Connect();
            var tpm = new Tpm2(tpmDevice);
            if (tpmDevice is TcpTpmDevice)
            {
                tpmDevice.PowerCycle();
                tpm.Startup(Su.Clear);
            }


            // 
            // The TPM needs a template that describes the parameters of the key
            // or other object to be created.  The template below instructs the TPM 
            // to create a new 2048-bit non-migratable signing key.
            // 
            var keyTemplate = new TpmPublic(TpmAlgId.Sha1,                                  // Name algorithm
                                        ObjectAttr.UserWithAuth | ObjectAttr.Sign |     // Signing key
                                        ObjectAttr.FixedParent | ObjectAttr.FixedTPM | // Non-migratable 
                                        ObjectAttr.SensitiveDataOrigin,
                                        null,                                    // No policy
                                        new RsaParms(new SymDefObject(),
                                                     new SchemeRsassa(TpmAlgId.Sha1), 2048, 0),
                                        new Tpm2bPublicKeyRsa());



            //
            // AuthValue encapsulates an authorization value: essentially a byte-array.
            // OwnerAuth is the owner authorization value of the TPM-under-test.  We
            // assume that it (and other) auths are set to the default (null) value.
            // If running on a real TPM, which has been provisioned by Windows, this
            // value will be different. An administrator can retrieve the owner
            // authorization value from the registry.
            //
            //var ownerAuth = new AuthValue();

            // 
            // Authorization for the key we are about to create.
            // 
            var keyAuth = new byte[] { 1, 2, 3 };

            TpmPublic keyPublic;
            CreationData creationData;
            TkCreation creationTicket;
            byte[] creationHash;

            // 
            // Ask the TPM to create a new primary RSA signing key.
            // 
            TpmHandle keyHandle = tpm[ownerAuth].CreatePrimary(
                TpmRh.Owner,                            // In the owner-hierarchy
                new SensitiveCreate(keyAuth, null),     // With this auth-value
                keyTemplate,                            // Describes key
                null,                                   // Extra data for creation ticket
                new PcrSelection[0],                    // Non-PCR-bound
                out keyPublic,                          // PubKey and attributes
                out creationData, out creationHash, out creationTicket);    // Not used here



            // 
            // Print out text-versions of the public key just created
            // 
            //Console.WriteLine("New public key\n" + keyPublic.ToString());



            Context ctx = tpm.ContextSave(keyHandle);
            File.WriteAllBytes("key.bin", Marshaller.GetTpmRepresentation(ctx));






            // Clean up.
            tpm.FlushContext(keyHandle);
            tpm.Dispose();


        }
        catch (Exception e)
        {
            Console.WriteLine("Exception occurred: {0}", e.Message);
        }


    }

MethodB ():

public static void MethodB()
    {
       try
        {
            Tpm2Device tpmDevice = new TcpTpmDevice(tpm_host, tpm_port);
            //Tpm2Device tpmDevice = new TbsDevice();
            tpmDevice.Connect();
            var tpm = new Tpm2(tpmDevice);
            if (tpmDevice is TcpTpmDevice)
            {
                tpmDevice.PowerCycle();
                tpm.Startup(Su.Clear);
            }




            Context ctx2 = Marshaller.FromTpmRepresentation<Context>(File.ReadAllBytes("key.bin"));
            TpmHandle keyHandle = tpm.ContextLoad(ctx2); //integrity check fail

1 Ответ

0 голосов
/ 14 марта 2019

Этот код присутствует как в MethodA(), так и в MethodB():

if (tpmDevice is TcpTpmDevice)
{
    tpmDevice.PowerCycle();
    tpm.Startup(Su.Clear);
}

Это распространенный шаблон в примерах TSS MSR.Он проверяет, является ли TPM, с которым вы говорите, имитируемым устройством, и, если это так, выполняет на нем команду «Очистить», проверяя, что вы начинаете с чистого листа.Делать это в MethodA() хорошо, но, делая это и в MethodB(), вы в основном отменяете то, что делали в MethodA(): только что созданный вами ключ удаляется, и проверка целостности из-за этого не проходит.

...