Sample code for 30+ languages & platforms
DataFlex

Iterate Keys and Certs in PEM

See more PEM Examples

Demonstrates how to access each of the private keys and certs contained within a PEM.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoPem
    String sPassword
    String sPemContent
    Integer iNumPrivateKeys
    Integer i
    Variant vPrivKey
    Handle hoPrivKey
    Variant vCert
    Handle hoCert
    Integer iNumCerts
    String sTemp1
    Integer iTemp1

    Move False To iSuccess

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

    Get Create (RefClass(cComChilkatPem)) To hoPem
    If (Not(IsComObjectCreated(hoPem))) Begin
        Send CreateComObject of hoPem
    End

    // Load the PEM from a file.
    // If the PEM is encrypted, provide a password.  Otherwise pass an empty string for the password.
    Move "myPassword" To sPassword
    Get ComLoadPemFile Of hoPem "../myPemFiles/myPem.pem" sPassword To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoPem To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    // Note: If the app already has the PEM pre-loaded in a string variable, then load it 
    // by calling LoadPem instead.  
    Move "... the PEM contents ..." To sPemContent
    Get ComLoadPem Of hoPem sPemContent sPassword To iSuccess
    // Check for success as before..

    // Iterate over the private keys.
    Get ComNumPrivateKeys Of hoPem To iNumPrivateKeys
    Move 0 To i

    Get Create (RefClass(cComChilkatPrivateKey)) To hoPrivKey
    If (Not(IsComObjectCreated(hoPrivKey))) Begin
        Send CreateComObject of hoPrivKey
    End
    While (i < iNumPrivateKeys)
        Get pvComObject of hoPrivKey to vPrivKey
        Get ComPrivateKeyAt Of hoPem i vPrivKey To iSuccess
        Get ComBitLength Of hoPrivKey To iTemp1
        Showln "Private Key " i " is " iTemp1 " in length"
        Move (i + 1) To i
    Loop

    // Iterate over the certificates.
    Get Create (RefClass(cComChilkatCert)) To hoCert
    If (Not(IsComObjectCreated(hoCert))) Begin
        Send CreateComObject of hoCert
    End
    Get ComNumCerts Of hoPem To iNumCerts
    Move 0 To i
    While (i < iNumCerts)
        Get pvComObject of hoCert to vCert
        Get ComCertAt Of hoPem i vCert To iSuccess
        Get ComSubjectDN Of hoCert To sTemp1
        Showln "Certificate " i " : " sTemp1
        Move (i + 1) To i
    Loop



End_Procedure