tpm2-software / tpm2-tss-engine

OpenSSL Engine for TPM2 devices
https://tpm2-software.github.io
BSD 3-Clause "New" or "Revised" License
149 stars 99 forks source link

Usage of openssl API with tpm2tss engine as a Clibary #166

Closed Muthukumar-S1979 closed 4 years ago

Muthukumar-S1979 commented 4 years ago

Hi, I would like to invoke the below openssl API configured with tpm2tss engine (wrapper) and generate CSR .

openssl req -new -engine tpm2tss -keyform engine -out server.csr –key test_key **test_key - is the key generated using tpm2tss-rsa-genkey API.

Instead of using it in to command prompt , i need to call it as API inside by 'C' application . Am not getting how to do it. I tried reading the examples inside 'tpm2-software/tpm2-tss-engine' but i couldnt get any info that am looking for.

Looking forward for your valuable response.

williamcroberts commented 4 years ago

To Call it in a C API, you need to load the engine, sample code from here:

#include <openssl/engine.h>
#include <stdio.h>
#include <string.h>

int main(int argc, const char* argv[] ) {
    OpenSSL_add_all_algorithms();

    ERR_load_crypto_strings();

    ENGINE_load_dynamic();
    ENGINE *oezgan_engine = ENGINE_by_id("oezgan");

    if( oezgan_engine == NULL )
    {
        printf("Could not Load Oezgan Engine!\n");
        exit(1);
    }
    printf("Oezgan Engine successfully loaded\n");

    int init_res = ENGINE_init(oezgan_engine);
    printf("Engine name: %s init result : %d \n",ENGINE_get_name(oezgan_engine), init_res);
    return 0;
}

Their are other ways to load an engine, you should look at the man page

Once you have an engine, you need to tell OSSL what you want to use it for, via something like:

ENGINE_set_default(e, ENGINE_METHOD_ALL & ~ENGINE_METHOD_RAND);

Again, their are other methods for doing this as pointed out in the man page previously. At this point you have the engine you want and told openssl to use it. Now you need to use it:

At this point you want to enable OpenSSL application req like behavior. It's quite a complicated program, theirs a ton of state building and then calls to X509_REQ_sign_ctx():

int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
                     STACK_OF(OPENSSL_STRING) *sigopts)
{
    int rv;
    EVP_MD_CTX *mctx = EVP_MD_CTX_new();
    rv = do_sign_init(mctx, pkey, md, sigopts);
    if (rv > 0)
        rv = X509_REQ_sign_ctx(x, mctx);
    EVP_MD_CTX_free(mctx);
    return rv > 0 ? 1 : 0;
}

So you'll need to build up all that state and invoke that API. See man page

These types of questions are better asked on our mailing list, and likely the OpenSSL mailing list. Their could be better ways to do this that others may know.