Sample code for 30+ languages & platforms
C

Generate an RSA Key and Get as Base64 DER

See more RSA Examples

Demonstrates how to generate a 2048-bit RSA key and return the public and private parts as unencrypted Base64 encoded DER.

Chilkat C Downloads

C
#include <C_CkRsa.h>
#include <C_CkPrivateKey.h>
#include <C_CkPublicKey.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkRsa rsa;
    HCkPrivateKey privKey;
    HCkPublicKey pubKey;
    BOOL bChoosePkcs1;
    const char *pubKeyBase64Der;
    const char *privKeyPkcs1;
    const char *privKeyPkcs8;

    success = FALSE;

    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    rsa = CkRsa_Create();

    // Generate a 2048-bit key.
    privKey = CkPrivateKey_Create();
    success = CkRsa_GenKey(rsa,2048,privKey);
    if (success == FALSE) {
        printf("%s\n",CkRsa_lastErrorText(rsa));
        CkRsa_Dispose(rsa);
        CkPrivateKey_Dispose(privKey);
        return;
    }

    // Get the public part of the key.
    pubKey = CkPublicKey_Create();
    CkPrivateKey_ToPublicKey(privKey,pubKey);

    // There are two possible formats for representing the RSA public key 
    // in ASN.1 (DER).  The possible formats are PKCS1 and PKCS8.
    // We can get either by setting bChoosePkcs1 to TRUE or FALSE.
    bChoosePkcs1 = TRUE;
    pubKeyBase64Der = CkPublicKey_getEncoded(pubKey,bChoosePkcs1,"base64");
    printf("Public Key Base64 DER:\n");
    printf("%s\n",pubKeyBase64Der);

    // Get the private key as Base64 DER:
    // We can get PKCS1 or PKCS8, but with different methods:
    privKeyPkcs1 = CkPrivateKey_getPkcs1ENC(privKey,"base64");
    printf("Private Key PKCS1 Base64 DER:\n");
    printf("%s\n",privKeyPkcs1);

    privKeyPkcs8 = CkPrivateKey_getPkcs8ENC(privKey,"base64");
    printf("Private Key PKCS8 Base64 DER:\n");
    printf("%s\n",privKeyPkcs8);


    CkRsa_Dispose(rsa);
    CkPrivateKey_Dispose(privKey);
    CkPublicKey_Dispose(pubKey);

    }