Sample code for 30+ languages & platforms
DataFlex

Get the Public Key from a Private Key

See more Private Key Examples

Demonstrates the Chilkat PrivateKey.ToPublicKey method, which extracts the public portion of the loaded private key into an independent PublicKey object. The only argument is the PublicKey that receives the copy.

Note: The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background: A key pair's public half is derived from the private half, and this is how you obtain it — the public key you distribute for others to verify signatures or encrypt to you, while the private key stays secret. The resulting PublicKey is an independent copy, so exporting or sharing it never risks exposing the private material. From there, export it as PEM, JWK, or XML as needed.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoPrivKey
    Variant vPubKey
    Handle hoPubKey
    Boolean iPreferPkcs1
    String sPubPem
    String sTemp1
    Boolean bTemp1

    Move False To iSuccess

    //  Load a private key to export.
    Get Create (RefClass(cComChilkatPrivateKey)) To hoPrivKey
    If (Not(IsComObjectCreated(hoPrivKey))) Begin
        Send CreateComObject of hoPrivKey
    End
    Get ComLoadPemFile Of hoPrivKey "qa_data/private.pem" To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoPrivKey To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Extract the public portion of the private key into an independent PublicKey object.  The
    //  PublicKey is a separate copy, unaffected by later changes to the PrivateKey.
    Get Create (RefClass(cComChilkatPublicKey)) To hoPubKey
    If (Not(IsComObjectCreated(hoPubKey))) Begin
        Send CreateComObject of hoPubKey
    End
    Get pvComObject of hoPubKey to vPubKey
    Get ComToPublicKey Of hoPrivKey vPubKey To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoPrivKey To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  The PublicKey can now be exported or shared -- for example as PEM.  The argument prefers the
    //  traditional PKCS #1 PEM when a traditional representation exists.
    Move True To iPreferPkcs1
    Get ComGetPem Of hoPubKey iPreferPkcs1 To sPubPem
    Get ComLastMethodSuccess Of hoPubKey To bTemp1
    If (bTemp1 = False) Begin
        Get ComLastErrorText Of hoPubKey To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Showln sPubPem


End_Procedure