Sample code for 30+ languages & platforms
C

Load PEM Public/Private Key into RSA Object

See more RSA Examples

Demonstrates how to load a PEM key into the Chilkat RSA object.

Chilkat C Downloads

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

void ChilkatSample(void)
    {
    BOOL success;
    HCkRsa rsa;
    const char *publicKeyPem;
    HCkPublicKey pubkey;
    const char *privateKeyPem;
    HCkPrivateKey privkey;

    success = FALSE;

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

    rsa = CkRsa_Create();

    // First demonstrate importing a PEM public key:
    publicKeyPem = "PEM public-key data goes here";
    pubkey = CkPublicKey_Create();

    success = CkPublicKey_LoadFromString(pubkey,publicKeyPem);
    if (success == FALSE) {
        printf("%s\n",CkPublicKey_lastErrorText(pubkey));
        CkRsa_Dispose(rsa);
        CkPublicKey_Dispose(pubkey);
        return;
    }

    success = CkRsa_UsePublicKey(rsa,pubkey);
    if (success == FALSE) {
        printf("%s\n",CkRsa_lastErrorText(rsa));
        CkRsa_Dispose(rsa);
        CkPublicKey_Dispose(pubkey);
        return;
    }

    // Demonstrate importing a PEM private key:
    privateKeyPem = "PEM private-key data goes here";
    privkey = CkPrivateKey_Create();

    // If the private key PEM is protected with a password, then 
    // call LoadEncryptedPem.  Otherwise call LoadPem.
    success = CkPrivateKey_LoadPem(privkey,privateKeyPem);
    if (success == FALSE) {
        printf("%s\n",CkPrivateKey_lastErrorText(privkey));
        CkRsa_Dispose(rsa);
        CkPublicKey_Dispose(pubkey);
        CkPrivateKey_Dispose(privkey);
        return;
    }

    success = CkRsa_UsePrivateKey(rsa,privkey);
    if (success == FALSE) {
        printf("%s\n",CkRsa_lastErrorText(rsa));
        CkRsa_Dispose(rsa);
        CkPublicKey_Dispose(pubkey);
        CkPrivateKey_Dispose(privkey);
        return;
    }

    printf("OK!\n");


    CkRsa_Dispose(rsa);
    CkPublicKey_Dispose(pubkey);
    CkPrivateKey_Dispose(privkey);

    }