Sample code for 30+ languages & platforms
PureBasic

Convert a PFX to a Java KeyStore

See more PFX/P12 Examples

Demonstrates Pfx.ToJksObj, which populates a JavaKeyStore with a JKS representation of the PFX, then writes it to a file.

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. One private-key entry is created for each private key, with certificate chains built from the PFX certificates. The password protects the generated Java KeyStore.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkJavaKeyStore.pb"
IncludeFile "CkPfx.pb"

Procedure ChilkatExample()

    success.i = 0

    pfx.i = CkPfx::ckCreate()
    If pfx.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ;  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.
    password.s = "myPfxPassword"
    success = CkPfx::ckLoadPfxFile(pfx,"qa_data/identity.pfx",password)
    If success = 0
        Debug CkPfx::ckLastErrorText(pfx)
        CkPfx::ckDispose(pfx)
        ProcedureReturn
    EndIf

    ;  Populate a Java KeyStore (JKS) representation of this PFX.  One private-key entry is created for
    ;  each private key, and the PFX certificates are used to build the certificate chains.  The 1st
    ;  argument is the alias for the first private-key entry, and the 2nd protects the generated JKS.
    ;  The JKS password should come from a secure source rather than being hard-coded.
    jksPassword.s = "myJksPassword"
    jks.i = CkJavaKeyStore::ckCreate()
    If jks.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkPfx::ckToJksObj(pfx,"myalias",jksPassword,jks)
    If success = 0
        Debug CkPfx::ckLastErrorText(pfx)
        CkPfx::ckDispose(pfx)
        CkJavaKeyStore::ckDispose(jks)
        ProcedureReturn
    EndIf

    ;  The Java KeyStore object can then be written to a .jks file.
    success = CkJavaKeyStore::ckToFile(jks,jksPassword,"qa_output/identity.jks")
    If success = 0
        Debug CkJavaKeyStore::ckLastErrorText(jks)
        CkPfx::ckDispose(pfx)
        CkJavaKeyStore::ckDispose(jks)
        ProcedureReturn
    EndIf

    Debug "Wrote a Java KeyStore with " + Str(CkJavaKeyStore::ckNumPrivateKeys(jks)) + " private key(s)."


    CkPfx::ckDispose(pfx)
    CkJavaKeyStore::ckDispose(jks)


    ProcedureReturn
EndProcedure