Generating a new KeyPair for the Token

From OpenCA Labs WiKi

After creating an empty PKI_TOKEN, it is possible to generate a new keypair that will be stored within the PKI_TOKEN and used for every signing operations.

The function to use is PKI_TOKEN_new_keypair() as shown in the following example:

#include <libpki/pki.h>

int main () {
   PKI_TOKEN *tk = NULL;

   /* Initialize the library */
   PKI_init_all();

   /* Generates an Empty PKI_TOKEN */
   tk = PKI_TOKEN_new_null();
   if( tk == NULL ) {
      printf("ERROR, can not generate a new PKI_TOKEN!\n");
      return(1);
   }

   /* Now we have our PKI_TOKEN, let's generate a new KeyPair */
   rv = PKI_TOKEN_new_keypair( tk, 2048, "myLabel" );
   if( rv == PKI_ERR ) {
      printf("ERROR, can not generate the KeyPair!\n");
      return(1);
   }

   printf("All Done.\n");

   return ( 0 );
}

This small code generates a keypair by using the RSA algorithm and a keysize of 2048 bits. The default value for the PKI_TOKEN is: PKI_ALGOR_DEFAULT (equiv to PKI_ALGOR_RSA_SHA256 or PKI_ALGOR_RSA_SHA1 as fallback for hardware tokens).

In order to use a different algorithm, you have to change the PKI_TOKEN's algorithm by using the PKI_TOKEN_set_algor(). This function accepts only one parameter, and the possible values are:

  • For RSA Algorithm:
    • PKI_ALGOR_RSA_SHA1 (soon to be dismissed)
    • PKI_ALGOR_RSA_SHA224
    • PKI_ALGOR_RSA_SHA256
    • PKI_ALGOR_RSA_SHA384
    • PKI_ALGOR_RSA_SHA512
    • PKI_ALGOR_RSA_MD2 (deprecated)
    • PKI_ALGOR_RSA_MD5 (deprecated)
    • PKI_ALGOR_RSA_MD4 (deprecated)
  • For DSA Algorithm:
    • PKI_ALGOR_DSA_SHA1 (soon to be dismissed)
    • PKI_ALGOR_DSA_SHA224
    • PKI_ALGOR_DSA_SHA256
    • PKI_ALGOR_DSA_SHA384
    • PKI_ALGOR_DSA_SHA512
    • PKI_ALGOR_DSA_MD2 (deprecated)
    • PKI_ALGOR_DSA_MD5 (deprecated)
    • PKI_ALGOR_DSA_MD4 (deprecated)
  • For ECDSA Algorithm;
    • PKI_ALGOR_ECDSA_SHA1 (soon to be dismissed)
    • PKI_ALGOR_ECDSA_SHA224
    • PKI_ALGOR_ECDSA_SHA256
    • PKI_ALGOR_ECDSA_SHA384
    • PKI_ALGOR_ECDSA_SHA512
    • PKI_ALGOR_ECDSA_MD2 (deprecated)
    • PKI_ALGOR_ECDSA_MD5 (deprecated)
    • PKI_ALGOR_ECDSA_MD4 (deprecated)

The following example shows how to generate an ECDSA keypair:

#include <libpki/pki.h>

int main () {
   PKI_TOKEN *tk = NULL;

   /* Initialize the library */
   PKI_init_all();

   /* Generates an Empty PKI_TOKEN */
   if((tk = PKI_TOKEN_new_null()) == NULL ) {
      return(1);
   }

   /* Sets the requested algorithm */
   if((rv = PKI_TOKEN_set_algorithm( PKI_ALGOR_ECDSA_SHA224 )) == PKI_ERR) {
      printf("ERROR, can not select the ECDSA_SHA224 algorithm!\n");
      return(1);
   }

   /* Now we have our PKI_TOKEN, let's generate a new KeyPair */
   if((rv = PKI_TOKEN_new_keypair( tk, 224, "myLabel" )) == PKI_ERR ) {
      printf("ERROR, can not generate the KeyPair!\n");
      return(1);
   }

   printf("All Done.\n");

   return ( 0 );
}