Sample code for 30+ languages & platforms
DataFlex

Enumerate Private Keys in a PFX

See more PFX/P12 Examples

Demonstrates Pfx.PrivateKeyAt, which copies the private key at a zero-based index into a PrivateKey object. The example enumerates all private keys in the PFX.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. Valid indexes are less than NumPrivateKeys. Each retrieved key is an independent copy that can be inspected or used separately.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoPfx
    String sPassword
    Integer iNumKeys
    Variant vPrivKey
    Handle hoPrivKey
    Integer i
    String sTemp1
    Integer iTemp1

    Move False To iSuccess

    Get Create (RefClass(cComChilkatPfx)) To hoPfx
    If (Not(IsComObjectCreated(hoPfx))) Begin
        Send CreateComObject of hoPfx
    End

    //  The file path is relative to the application's current working directory.  An absolute path
    //  may also be used.  Supply the path appropriate to your own environment.
    //  The PFX password should come from a secure source rather than being hard-coded.
    Move "myPfxPassword" To sPassword
    Get ComLoadPfxFile Of hoPfx "qa_data/identity.pfx" sPassword To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoPfx To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Enumerate the private keys in the PFX by zero-based index.  Valid indexes are less than
    //  NumPrivateKeys.
    Get ComNumPrivateKeys Of hoPfx To iNumKeys
    Get Create (RefClass(cComChilkatPrivateKey)) To hoPrivKey
    If (Not(IsComObjectCreated(hoPrivKey))) Begin
        Send CreateComObject of hoPrivKey
    End

    For i From 0 To (iNumKeys - 1)
        Get pvComObject of hoPrivKey to vPrivKey
        Get ComPrivateKeyAt Of hoPfx i vPrivKey To iSuccess
        If (iSuccess = False) Begin
            Get ComLastErrorText Of hoPfx To sTemp1
            Showln sTemp1
            Procedure_Return
        End

        Get ComKeyType Of hoPrivKey To sTemp1
        Get ComBitLength Of hoPrivKey To iTemp1
        Showln "Private key " i ": " sTemp1 " (" iTemp1 " bits)"
    Loop



End_Procedure