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 <CkRsaW.h>
#include <CkPrivateKeyW.h>
#include <CkPublicKeyW.h>
void ChilkatSample(void)
{
bool success = false;
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
CkRsaW rsa;
// Generate a 2048-bit RSA key.
CkPrivateKeyW privKey;
success = rsa.GenKey(2048,privKey);
rsa.UsePrivateKey(privKey);
// Return the signature in hex.
rsa.put_EncodingMode(L"hex");
const wchar_t *strData = L"This is the string to be signed.";
// Sign the SHA256 hash of the string.
const wchar_t *hexSig = rsa.signStringENC(strData,L"sha256");
wprintf(L"%s\n",hexSig);
// Now verify the signature:
CkPublicKeyW pubKey;
privKey.ToPublicKey(pubKey);
rsa.UsePublicKey(pubKey);
success = rsa.VerifyStringENC(strData,L"sha256",hexSig);
if (success == true) {
wprintf(L"Signature verified!\n");
}
else {
wprintf(L"%s\n",rsa.lastErrorText());
}
// Try it with an invalid signature:
success = rsa.VerifyStringENC(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 = rsa.VerifyStringENC(L"Not the original data",L"sha256",hexSig);
if (success == true) {
wprintf(L"Signature verified!\n");
}
else {
wprintf(L"Signature validation failed!\n");
}
}