![]() |
Chilkat HOME Android™ AutoIt C C# C++ Chilkat2-Python CkPython Classic ASP DataFlex Delphi DLL Go Java Node.js Objective-C PHP Extension Perl PowerBuilder PowerShell PureBasic Ruby SQL Server Swift Tcl Unicode C Unicode C++ VB.NET VBScript Visual Basic 6.0 Visual FoxPro Xojo Plugin
(C++) RSA Sign with PKCS8 Encrypted KeyDemonstrates how to load a private key from an encrypted PKCS8 file and create an RSA digital signature (and then verify it). Note: This example requires Chilkat v11.0.0 or greater.
#include <CkPrivateKey.h> #include <CkRsa.h> #include <CkCert.h> #include <CkPublicKey.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. CkPrivateKey privKey; // Load the private key from an RSA PEM file: success = privKey.LoadAnyFormatFile("raul_privateKey.key","a0123456789"); if (success == false) { std::cout << privKey.lastErrorText() << "\r\n"; return; } CkRsa rsa; // Import the private key into the RSA component: success = rsa.UsePrivateKey(privKey); if (success == false) { std::cout << rsa.lastErrorText() << "\r\n"; return; } // This example will sign a string, and receive the signature // in a hex-encoded string. Therefore, set the encoding mode // to "hex": rsa.put_EncodingMode("hex"); const char *strData = "This is the string to be signed."; // Sign the string using the sha256 hash algorithm. // Other valid choices are sha1, sha384, sha512 and others. const char *hexSig = rsa.signStringENC(strData,"sha256"); if (rsa.get_LastMethodSuccess() == false) { std::cout << rsa.lastErrorText() << "\r\n"; return; } std::cout << hexSig << "\r\n"; // Now verify with the public key. // This example shows how to use the public key from // a digital certificate (.cer file) CkCert cert; success = cert.LoadFromFile("raul_publicKey.cer"); if (success == false) { std::cout << cert.lastErrorText() << "\r\n"; return; } CkPublicKey pubKey; cert.GetPublicKey(pubKey); CkRsa rsa2; success = rsa2.UsePublicKey(pubKey); if (success == false) { std::cout << rsa2.lastErrorText() << "\r\n"; return; } // Verify the signature against the original data: rsa2.put_EncodingMode("hex"); success = rsa2.VerifyStringENC(strData,"sha256",hexSig); if (success == false) { std::cout << rsa2.lastErrorText() << "\r\n"; return; } std::cout << "Signature verified!" << "\r\n"; // Verify with incorrect data: success = rsa2.VerifyStringENC("something else","sha256",hexSig); if (success != true) { std::cout << "Signature not verified! (which was expected in this case)" << "\r\n"; } else { std::cout << "Hmmm... that's not right..." << "\r\n"; } } |
© 2000-2025 Chilkat Software, Inc. All Rights Reserved.