Sample code for 30+ languages & platforms
DataFlex

RSA Encrypt Randomly Generated AES Key

See more RSA Examples

Demonstrates how to RSA encrypt a randomly generated AES key.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoPrng
    Variant vBdAesKey
    Handle hoBdAesKey
    Handle hoCert
    Variant vPubKey
    Handle hoPubKey
    Handle hoRsa
    String sEncryptedAesKey
    String sTemp1

    Move False To iSuccess

    // 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).
    Get Create (RefClass(cComChilkatPrng)) To hoPrng
    If (Not(IsComObjectCreated(hoPrng))) Begin
        Send CreateComObject of hoPrng
    End
    Get Create (RefClass(cComChilkatBinData)) To hoBdAesKey
    If (Not(IsComObjectCreated(hoBdAesKey))) Begin
        Send CreateComObject of hoBdAesKey
    End
    Get pvComObject of hoBdAesKey to vBdAesKey
    Get ComGenRandomBd Of hoPrng 32 vBdAesKey To iSuccess

    // Use a public key from a certificate for RSA encryption.
    Get Create (RefClass(cComChilkatCert)) To hoCert
    If (Not(IsComObjectCreated(hoCert))) Begin
        Send CreateComObject of hoCert
    End

    Get ComLoadFromFile Of hoCert "qa_data/pem/mf_public_rsa.pem" To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoCert To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatPublicKey)) To hoPubKey
    If (Not(IsComObjectCreated(hoPubKey))) Begin
        Send CreateComObject of hoPubKey
    End
    Get pvComObject of hoPubKey to vPubKey
    Get ComGetPublicKey Of hoCert vPubKey To iSuccess

    Get Create (RefClass(cComChilkatRsa)) To hoRsa
    If (Not(IsComObjectCreated(hoRsa))) Begin
        Send CreateComObject of hoRsa
    End
    Get pvComObject of hoPubKey to vPubKey
    Get ComUsePublicKey Of hoRsa vPubKey To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoRsa To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    // RSA encrypt our 32-byte AES key.
    // The contents of bdAesKey are replaced with result of the RSA encryption.
    Get pvComObject of hoBdAesKey to vBdAesKey
    Get ComEncryptBd Of hoRsa vBdAesKey False To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoRsa To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    // Return the result as a base64 string
    Get ComGetEncoded Of hoBdAesKey "base64" To sEncryptedAesKey

    Showln "encrypted AES key = " sEncryptedAesKey


End_Procedure