Unicode C
Unicode C
RSA Signature/Verify with .key and .cer
See more RSA Examples
Demonstrates how to use a .key file (private key) and digital certificate (.cer, public key) to create and verify an RSA signature.Chilkat Unicode C Downloads
#include <C_CkPrivateKeyW.h>
#include <C_CkRsaW.h>
#include <C_CkCertW.h>
#include <C_CkPublicKeyW.h>
void ChilkatSample(void)
{
BOOL success;
HCkPrivateKeyW privKey;
HCkRsaW rsa;
const wchar_t *strData;
const wchar_t *hexSig;
HCkCertW cert;
HCkPublicKeyW pubKey;
HCkRsaW rsa2;
success = FALSE;
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
privKey = CkPrivateKeyW_Create();
// Load the private key from an RSA .key file:
success = CkPrivateKeyW_LoadPemFile(privKey,L"privateKey.key");
if (success == FALSE) {
wprintf(L"%s\n",CkPrivateKeyW_lastErrorText(privKey));
CkPrivateKeyW_Dispose(privKey);
return;
}
rsa = CkRsaW_Create();
// Import the private key into the RSA component:
success = CkRsaW_UsePrivateKey(rsa,privKey);
if (success == FALSE) {
wprintf(L"%s\n",CkRsaW_lastErrorText(rsa));
CkPrivateKeyW_Dispose(privKey);
CkRsaW_Dispose(rsa);
return;
}
// Create the signature as a hex string:
CkRsaW_putEncodingMode(rsa,L"hex");
strData = L"This is the string to be signed.";
// Sign the string using the sha256 hash algorithm.
// Other valid choices are "md2", "sha1", "sha384",
// "sha512", and "md5".
hexSig = CkRsaW_signStringENC(rsa,strData,L"sha256");
wprintf(L"%s\n",hexSig);
// Load a digital certificate from a .cer file:
cert = CkCertW_Create();
success = CkCertW_LoadFromFile(cert,L"myCert.cer");
if (success == FALSE) {
wprintf(L"%s\n",CkCertW_lastErrorText(cert));
CkPrivateKeyW_Dispose(privKey);
CkRsaW_Dispose(rsa);
CkCertW_Dispose(cert);
return;
}
pubKey = CkPublicKeyW_Create();
CkCertW_GetPublicKey(cert,pubKey);
// Now verify using a new instance of the RSA object:
rsa2 = CkRsaW_Create();
// Import the public key into the RSA object:
success = CkRsaW_UsePublicKey(rsa2,pubKey);
if (success == FALSE) {
wprintf(L"%s\n",CkRsaW_lastErrorText(rsa2));
CkPrivateKeyW_Dispose(privKey);
CkRsaW_Dispose(rsa);
CkCertW_Dispose(cert);
CkPublicKeyW_Dispose(pubKey);
CkRsaW_Dispose(rsa2);
return;
}
// The signature is a hex string, so make sure the EncodingMode is correct:
CkRsaW_putEncodingMode(rsa2,L"hex");
// Verify the signature:
success = CkRsaW_VerifyStringENC(rsa2,strData,L"sha256",hexSig);
if (success == FALSE) {
wprintf(L"%s\n",CkRsaW_lastErrorText(rsa2));
CkPrivateKeyW_Dispose(privKey);
CkRsaW_Dispose(rsa);
CkCertW_Dispose(cert);
CkPublicKeyW_Dispose(pubKey);
CkRsaW_Dispose(rsa2);
return;
}
wprintf(L"Success.\n");
CkPrivateKeyW_Dispose(privKey);
CkRsaW_Dispose(rsa);
CkCertW_Dispose(cert);
CkPublicKeyW_Dispose(pubKey);
CkRsaW_Dispose(rsa2);
}