The example 'C' program keytest.c demonstrates how to load a private SSL key to perform actions such as digital signing of certificates or other data, using the OpenSSL library functions.
/* ------------------------------------------------------------------------ *
* file: keytest.c *
* purpose: tests loading of a private key for certificate signing *
* author: 02/23/2004 Frank4DD *
* ------------------------------------------------------------------------ */
#include <stdio.h>
#include <string.h>
#include <openssl/x509v3.h>
#include <openssl/objects.h>
#include <openssl/pem.h>
#include <openssl/evp.h>
int main() {
EVP_PKEY *ca_pkey;
FILE *fp;
char pass[] = "testpass";
/* ---------------------------------------------------------- *
* This function call is essential to make many PEM and other *
* openssl functions work. It is not well documented. *
------------------------------------------------------------ */
OpenSSL_add_all_algorithms();
ca_pkey = EVP_PKEY_new();
fp = fopen ("cakey.pem", "r");
PEM_read_PrivateKey( fp, &ca_pkey, NULL, pass);
fclose(fp);
PEM_write_PrivateKey(stdout,ca_pkey,NULL,NULL,0,0,NULL);
exit(0);
}
Compile the test program with:
> gcc -lssl -lcrypto keytest.c -o keytest
The program expects a keyfile called ca_key.pem in the same directory it is run. If the key loading is successful, i.e. the passphrase is correct, the following output is produced for an unencrypted key (of course not a "real" one :-) ) With an incorrect passphrase, the key wont be loaded and the pointer is NULL.
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDiE2O5d2Mz8VgaLBjBEqbQnvltO/4u8HSRk60OE6ISRReF4+TA
Ldf+u+ZpJJDYVrusFrU9MNedv9/P6USqj6h42wt1LPVloCtkPiWZgoa5/2F5fXIt
fdaZrUW8fNhAnrVjva+egDg7LNB39cYza2K+0ahYnBIKlHFS4Glv2Xu23QIDAQAB
AoGARYsx6+uN2KylLWfjNYFHT2WX1MJfrpDJSv7ifTIM6RHX6pfwBi4UA4hJmI5n
ACWuFYHmvqwHp78eWhanyM/oQrEEhiD6HqrNxZMBXWs1mQ7M4t9+HWY2aOF1f4pz
A+3YK+HzuIU0Qm3ulTL/s8bkGNv1PFL8s+MbQQNm9n4RqAECQQD5WFhEDk3wu8Ba
cr8UFa1YxNCRHcXudWtaKfoVpxt9jU0vxMWU5H/l2IGU2yrcuBVTe3q988rSJs1n
MQKlzCp5AkEA6BwQPj3eH9Y9Er8908mUUMv6cTF/es+EKuaD03OajbOLqFXJkVyT
BVSR9jBnjy0adQ59DVfdBL13RLM4uA1WhQJBAICrWSkNZKT0jgderUHVCdYEAkjQ
X2J1T0eA39+qkyIP96PN29PAsktOlVfWXWD20XJ6BtXc523Yvigg/2fFWqkCQDrt
FPqXrBctDqg5wPqJjIvOnTArfs+w6z7w8rq1+KDM2kHMNbYfqHuL8tprg38H1lWt
bfX7PnM7npHkZhvj1vkCQGsJq8cm8t2SOHCUmuJWGBJDDAhuBC/87QlSQtM/w+x5
aYhmkHLdlxPGr1nBobOBtSLM1uEQ3iA7sKZ+XNcAOeE=
-----END RSA PRIVATE KEY-----