Sample code for 30+ languages & platforms
Xbase++ Requires Chilkat v11.0.0+

Generate an RSA Key and Get as Base64 DER

See more RSA Examples

Demonstrates how to generate a 2048-bit RSA key and return the public and private parts as unencrypted Base64 encoded DER.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oRsa
LOCAL oPrivKey
LOCAL oPubKey
LOCAL nBChoosePkcs1
LOCAL cPubKeyBase64Der
LOCAL cPrivKeyPkcs1
LOCAL cPrivKeyPkcs8

nSuccess := 0

//  This example assumes the Chilkat API to have been previously unlocked.
//  See Global Unlock Sample for sample code.

oRsa := CreateObject("Chilkat.Rsa")

//  Generate a 2048-bit key.
oPrivKey := CreateObject("Chilkat.PrivateKey")
nSuccess := oRsa:GenKey(2048, oPrivKey)
IF (nSuccess == 0)
    ? oRsa:LastErrorText
    oRsa:destroy()
    oPrivKey:destroy()
    RETURN
ENDIF

//  Get the public part of the key.
oPubKey := CreateObject("Chilkat.PublicKey")
oPrivKey:ToPublicKey(oPubKey)

//  There are two possible formats for representing the RSA public key 
//  in ASN.1 (DER).  The possible formats are PKCS1 and PKCS8.
//  We can get either by setting bChoosePkcs1 to 1 or 0.
nBChoosePkcs1 := 1
cPubKeyBase64Der := oPubKey:GetEncoded(nBChoosePkcs1, "base64")
? "Public Key Base64 DER:"
? cPubKeyBase64Der

//  Get the private key as Base64 DER:
//  We can get PKCS1 or PKCS8, but with different methods:
cPrivKeyPkcs1 := oPrivKey:GetPkcs1ENC("base64")
? "Private Key PKCS1 Base64 DER:"
? cPrivKeyPkcs1

cPrivKeyPkcs8 := oPrivKey:GetPkcs8ENC("base64")
? "Private Key PKCS8 Base64 DER:"
? cPrivKeyPkcs8

oRsa:destroy()
oPrivKey:destroy()
oPubKey:destroy()