Archived Forum Post

Index of archived forum posts


How to load rsa keys from pem file and encrypt/decrypt string

Dec 14 '16 at 20:21

Hello, I am unsure how to correctly load a pem file I generate and saved to disk. I want to load the public key, encode a string and load the private key from another pem file to decrypt the string. I did try with LoadPem as no Password is given, but can not get it to work.

I am currently generating and writing the pem files as follows (works very well):


$rsa = new CkRsa();

$success = $rsa->UnlockComponent("using my key");
if ($success != true) {
    print 'RSA unlock failed' . "\n";
$success = $rsa->GenerateKey(2048);
if ($success != true) {
    print $rsa->lastErrorText() . "\n";

$publicKeyXml = $rsa->exportPublicKey();
print "public: ".$publicKeyXml . "\n";

$privateKeyXml = $rsa->exportPrivateKey();
print "private: ".$privateKeyXml . "\n";

//  Save the private key in PEM format:
$privKey = new CkPrivateKey();
$success = $privKey->LoadXml($privateKeyXml);
$success = $privKey->SaveRsaPemFile('privateKey.pem');

//  Save in PEM format
$pubKey = new CkPublicKey();
$success = $pubKey->LoadXml($publicKeyXml);
$success = $pubKey->SaveOpenSslPemFile('publicKey.pem');



Can you post the contents of the LastErrorText property after the LoadPem call fails?


Generating a new RSA key makes no sense here. If you already have a private key, then you already have both the private and public key.

Most people don't realize that a public key is just a sub-set of the private key.
For example, an RSA private key is composed of the following parts: Modulus, Exponent, P, DP, DQ, InverseQ, and D. For example, a private key in XML format:


A public key is just a sub-set of the private key. It contains just the Modulus and Exponent. Therefore, if you already have the private key, by definition you have the matching public key. To get the public key object from the private key object, just call privateKey.GetPublicKey.


I only need to find a way to load my previously stored private key (inside my privateKey.pem file) into my rsa object. I saw the function getRsaPem() which is deprecated and will be removed.

Anyway it does not load the correct string as written into the pem file itself.

With my public key I was able to use the function getPem() and the Output of the string is exactly what is written inside the publicKey.pem.

Isn't there such a function for the Private key as well?