Unicode C
Unicode C
Generate an RSA Key and Save to Encrypted PEM
See more RSA Examples
Demonstrates how to generate an RSA key and save to an encrypted PEM file.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 *password;
const wchar_t *path;
HCkPublicKeyW pubKey;
BOOL preferPkcs1;
success = FALSE;
rsa = CkRsaW_Create();
// Generate a 2048-bit key.
privKey = CkPrivateKeyW_Create();
success = CkRsaW_GenKey(rsa,2048,privKey);
if (success == FALSE) {
wprintf(L"%s\n",CkRsaW_lastErrorText(rsa));
CkRsaW_Dispose(rsa);
CkPrivateKeyW_Dispose(privKey);
return;
}
password = L"secret";
// Saving to a relative path (from the current working directory of the process).
path = L"rsaKeys/myTestRsaPrivate.pem";
// Encrypt the PEM using 256-bit AES encryption.
CkPrivateKeyW_putPkcs8EncryptAlg(privKey,L"aes256");
success = CkPrivateKeyW_SavePkcs8EncryptedPemFile(privKey,password,path);
if (success == FALSE) {
wprintf(L"%s\n",CkPrivateKeyW_lastErrorText(privKey));
CkRsaW_Dispose(rsa);
CkPrivateKeyW_Dispose(privKey);
return;
}
//
// We can also save the public key.
// There is no need to encrypt public keys.
pubKey = CkPublicKeyW_Create();
CkPrivateKeyW_ToPublicKey(privKey,pubKey);
path = L"rsaKeys/myTestRsaPublic.pem";
// Choose PKCS1 or PKCS8
// We'll choose PKCS8.
preferPkcs1 = FALSE;
success = CkPublicKeyW_SavePemFile(pubKey,preferPkcs1,path);
if (success == FALSE) {
wprintf(L"%s\n",CkPublicKeyW_lastErrorText(pubKey));
CkRsaW_Dispose(rsa);
CkPrivateKeyW_Dispose(privKey);
CkPublicKeyW_Dispose(pubKey);
return;
}
//
wprintf(L"Success.\n");
CkRsaW_Dispose(rsa);
CkPrivateKeyW_Dispose(privKey);
CkPublicKeyW_Dispose(pubKey);
}