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

RSA Encrypt Randomly Generated AES Key

See more RSA Examples

Demonstrates how to RSA encrypt a randomly generated AES key.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oPrng
LOCAL oBdAesKey
LOCAL oCert
LOCAL oPubKey
LOCAL oRsa
LOCAL cEncryptedAesKey

nSuccess := 0

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

//  First generate a 256-bit AES key (32 bytes).
oPrng := CreateObject("Chilkat.Prng")
oBdAesKey := CreateObject("Chilkat.BinData")
nSuccess := oPrng:GenRandomBd(32, oBdAesKey)

//  Use a public key from a certificate for RSA encryption.
oCert := CreateObject("Chilkat.Cert")

nSuccess := oCert:LoadFromFile("qa_data/pem/mf_public_rsa.pem")
IF (nSuccess == 0)
    ? oCert:LastErrorText
    oPrng:destroy()
    oBdAesKey:destroy()
    oCert:destroy()
    RETURN
ENDIF

oPubKey := CreateObject("Chilkat.PublicKey")
oCert:GetPublicKey(oPubKey)

oRsa := CreateObject("Chilkat.Rsa")
nSuccess := oRsa:UsePublicKey(oPubKey)
IF (nSuccess == 0)
    ? oRsa:LastErrorText
    oPrng:destroy()
    oBdAesKey:destroy()
    oCert:destroy()
    oPubKey:destroy()
    oRsa:destroy()
    RETURN
ENDIF

//  RSA encrypt our 32-byte AES key.
//  The contents of bdAesKey are replaced with result of the RSA encryption.
nSuccess := oRsa:EncryptBd(oBdAesKey, 0)
IF (nSuccess == 0)
    ? oRsa:LastErrorText
    oPrng:destroy()
    oBdAesKey:destroy()
    oCert:destroy()
    oPubKey:destroy()
    oRsa:destroy()
    RETURN
ENDIF

//  Return the result as a base64 string
cEncryptedAesKey := oBdAesKey:GetEncoded("base64")

? "encrypted AES key = " + cEncryptedAesKey

oPrng:destroy()
oBdAesKey:destroy()
oCert:destroy()
oPubKey:destroy()
oRsa:destroy()