C
C
RSA Signature with Certificate's Private Key from PFX
See more RSA Examples
Demonstrates how to use a certificate's private key from a PFX file to create an RSA signature.Chilkat C Downloads
#include <C_CkCertStore.h>
#include <C_CkJsonObject.h>
#include <C_CkCert.h>
#include <C_CkPrivateKey.h>
#include <C_CkRsa.h>
void ChilkatSample(void)
{
BOOL success;
HCkCertStore certStore;
HCkJsonObject jsonCN;
HCkCert cert;
HCkPrivateKey privKey;
HCkRsa rsa;
const char *strData;
const char *hexSig;
success = FALSE;
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Create an instance of a certificate store object, load a PFX file,
// locate the certificate we need, and use it for signing.
// (a PFX file may contain more than one certificate.)
certStore = CkCertStore_Create();
// The 1st argument is the filename, the 2nd arg is the
// PFX file's password:
success = CkCertStore_LoadPfxFile(certStore,"chilkat.pfx","test");
if (success == FALSE) {
printf("%s\n",CkCertStore_lastErrorText(certStore));
CkCertStore_Dispose(certStore);
return;
}
// Find the certificate by the subject common name:
jsonCN = CkJsonObject_Create();
CkJsonObject_UpdateString(jsonCN,"CN","cert common name");
cert = CkCert_Create();
success = CkCertStore_FindCert(certStore,jsonCN,cert);
if (success == FALSE) {
printf("%s\n",CkCertStore_lastErrorText(certStore));
CkCertStore_Dispose(certStore);
CkJsonObject_Dispose(jsonCN);
CkCert_Dispose(cert);
return;
}
privKey = CkPrivateKey_Create();
success = CkCert_GetPrivateKey(cert,privKey);
if (success == FALSE) {
printf("%s\n",CkCert_lastErrorText(cert));
CkCertStore_Dispose(certStore);
CkJsonObject_Dispose(jsonCN);
CkCert_Dispose(cert);
CkPrivateKey_Dispose(privKey);
return;
}
rsa = CkRsa_Create();
success = CkRsa_UsePrivateKey(rsa,privKey);
if (success == FALSE) {
printf("%s\n",CkRsa_lastErrorText(rsa));
CkCertStore_Dispose(certStore);
CkJsonObject_Dispose(jsonCN);
CkCert_Dispose(cert);
CkPrivateKey_Dispose(privKey);
CkRsa_Dispose(rsa);
return;
}
// Encode the signature as a hex string
CkRsa_putEncodingMode(rsa,"hex");
strData = "This is the string to be signed.";
// Sign the string using the sha-1 hash algorithm.
// Other valid choices are "sha-256", "md2" and "md5".
hexSig = CkRsa_signStringENC(rsa,strData,"sha-1");
printf("%s\n",hexSig);
printf("Success!\n");
CkCertStore_Dispose(certStore);
CkJsonObject_Dispose(jsonCN);
CkCert_Dispose(cert);
CkPrivateKey_Dispose(privKey);
CkRsa_Dispose(rsa);
}