0

I am trying to get a signature string locally from the file PKCS#8 file which is in .p8 format. When I open it I can see a string between the statement

 -----BEGIN PRIVATE KEY-----
// strings line 64 characters
// strings line 64 characters
// strings line 64 characters
// strings line 8 characters
-----END PRIVATE KEY-----

I want to convert this file and sign in ecdsa to get the signature.

How can I achieve this in c language using openssl

Jafar Mohammed
  • 103
  • 1
  • 12

1 Answers1

1

Read the key data from your PKCS#8 file using PEM_read_PrivateKey() (or PEM_read_bio_PrivateKey(). This will give you the key as an EVP_PKEY object. Documentation for those functions is here:

https://www.openssl.org/docs/man1.1.1/man3/PEM_read_PrivateKey.html

Typically when signing you normally want to digest the data to be signed first using some digest function (e.g. SHA256) followed by the signature operation (ECDSA in this case). Assuming that's what you want to do you should use the EVP_DigestSign* family of functions. Documentation for those functions is here:

https://www.openssl.org/docs/man1.1.1/man3/EVP_DigestSign.html

The code might look something like this (untested):

EVP_PKEY *pkey = PEM_read_PrivateKey(myfile, NULL, NULL, NULL);
EVP_MD_CTX *mdctx = EVP_MD_CTX_new();
size_t siglen = 0;
unsigned char *sig;

if (mdctx == NULL || pkey == NULL)
    goto err;

if (!EVP_DigestSignInit(mdctx, NULL, EVP_sha256(), NULL, pkey))
    goto err;

 if(!EVP_DigestSignUpdate(mdctx, tobesigned, tobesignedlen))
    goto err;

 /* Find out the signature length */
 if(!EVP_DigestSignFinal(mdctx, NULL, &siglen))
    goto err;

 /* Allocate memory for the signature length */
 sig = OPENSSL_malloc(siglen);
 if (sig == NULL)
     goto err;

 /* Now get the signature */
 if(!EVP_DigestSignFinal(mdctx, sig, &siglen))
     goto err;

 EVP_MD_CTX_free(mdctx);
 EVP_PKEY_free(pkey);
/* Free "sig" when you've finished with it */
Matt Caswell
  • 8,167
  • 25
  • 28