PKCS12 files
From OpenCA::Wiki
[edit]
Load a P12 as a new Token
This example shows how to load a PKCS#12 file into a PKI_TOKEN.
#include <libpki/pki.h>
int main (int argc, char *argv[]) {
PKI_X509_PKCS12 *p12 = NULL;
PKI_CRED cred;
PKI_TOKEN *tk = NULL;
PKI_X509_CERT_STACK *x_sk = NULL;
PKI_X509_CERT *x = NULL;
char * url_s = NULL;
char * pwd = "mySecurePasswordHere!";
if( argc < 2 ) {
printf("USAGE: p12 <filename>\n\n");
exit(1);
}
url_s = argv[1];
// Init The Library
PKI_init_all();
if(( PKI_log_init (PKI_LOG_TYPE_STDOUT, PKI_LOG_INFO, NULL,
PKI_LOG_FLAGS_ENABLE_DEBUG, NULL )) == PKI_ERR ) {
exit(1);
}
cred.password = pwd;
// Loads a Token from a PKCS#12 file
if((tk = PKI_TOKEN_new_p12( url_s, NULL, &cred)) == NULL){
printf("ERROR::Can not load PKI_TOKEN!\n");
exit(1);
}
// Now you can use the tk (PKI_TOKEN) as usual, for example
// Save the CA certificate to stderr ("fd://2")
PKI_X509_CERT_put( tk->cacert, PKI_DATA_FORMAT_PEM, "fd://2",
NULL, NULL, NULL );
return (0);
}
[edit]
Create a new PKCS#12
This example shows how to create a new PKCS#12 file
#include <libpki/pki.h>
int main (int argc, char *argv[]) {
PKI_X509_PKCS12 *p12 = NULL;
PKI_X509_PKCS12_DATA *data = NULL;
PKI_CRED *cred = NULL;
PKI_TOKEN *tk = NULL;
int rv = 0;
PKI_init_all();
if(( PKI_log_init (PKI_LOG_TYPE_STDERR, PKI_LOG_INFO, NULL,
PKI_LOG_FLAGS_ENABLE_DEBUG, NULL )) == PKI_ERR ) {
exit(1);
}
// Create a new PKI_CRED object
if((cred = PKI_CRED_new( NULL, "mySecurePasswordHere!")) == NULL ) {
printf("ERROR::Can not initialize CREDS!\n");
return(1);
}
// We now need to create a PKCS12_DATA object where to store our data
if((data = PKI_X509_PKCS12_DATA_new()) == NULL ) {
printf("ERROR::Memory\n");
exit(1);
}
// Let's add a keypair
rv = PKI_X509_PKCS12_DATA_add_keypair ( data, tk->keypair, cred );
if( rv == PKI_ERR ) {
printf("Can not add keypair!\n");
exit(2);
}
// Now, add user certs
rv = PKI_X509_PKCS12_DATA_add_certs ( data, tk->cert, tk->cacert,
tk->trustedCerts, cred );
// Let's add the other certificates we want to include
rv = PKI_X509_PKCS12_DATA_add_other_certs ( data, tk->otherCerts, cred );
// Let's now create the new encoded PKCS12
if((p12 = PKI_X509_PKCS12_new ( data, cred )) == NULL ) {
printf("ERROR::Can not create a new P12!\n");
exit(3);
}
// Let's save the generated PKCS12 in a file ("out/test-new.p12")
PKI_X509_PKCS12_put( p12, PKI_DATA_FORMAT_ASN1,
"out/test-new.p12", NULL, cred, NULL );
exit(0);
}

