Unicode C
Unicode C
Generate RSA Key and Sign a String
See more RSA Examples
Demonstrates how to generate a new RSA public/private key pair and use it to generate a signature for a string. The (binary) digital signature is returned as a hexidecimalized string.Chilkat Unicode C Downloads
#include <C_CkRsaW.h>
#include <C_CkPrivateKeyW.h>
#include <C_CkPublicKeyW.h>
void ChilkatSample(void)
{
BOOL success;
HCkRsaW rsa;
HCkPrivateKeyW privKey;
const wchar_t *strData;
const wchar_t *hexSig;
HCkPublicKeyW pubKey;
success = FALSE;
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
rsa = CkRsaW_Create();
// Generate a 2048-bit RSA key.
privKey = CkPrivateKeyW_Create();
success = CkRsaW_GenKey(rsa,2048,privKey);
CkRsaW_UsePrivateKey(rsa,privKey);
// Return the signature in hex.
CkRsaW_putEncodingMode(rsa,L"hex");
strData = L"This is the string to be signed.";
// Sign the SHA256 hash of the string.
hexSig = CkRsaW_signStringENC(rsa,strData,L"sha256");
wprintf(L"%s\n",hexSig);
// Now verify the signature:
pubKey = CkPublicKeyW_Create();
CkPrivateKeyW_ToPublicKey(privKey,pubKey);
CkRsaW_UsePublicKey(rsa,pubKey);
success = CkRsaW_VerifyStringENC(rsa,strData,L"sha256",hexSig);
if (success == TRUE) {
wprintf(L"Signature verified!\n");
}
else {
wprintf(L"%s\n",CkRsaW_lastErrorText(rsa));
}
// Try it with an invalid signature:
success = CkRsaW_VerifyStringENC(rsa,strData,L"sha256",L"not a valid sig");
if (success == TRUE) {
wprintf(L"Signature verified!\n");
}
else {
wprintf(L"Signature validation failed!\n");
}
// Try it with invalid data:
success = CkRsaW_VerifyStringENC(rsa,L"Not the original data",L"sha256",hexSig);
if (success == TRUE) {
wprintf(L"Signature verified!\n");
}
else {
wprintf(L"Signature validation failed!\n");
}
CkRsaW_Dispose(rsa);
CkPrivateKeyW_Dispose(privKey);
CkPublicKeyW_Dispose(pubKey);
}