Sample code for 30+ languages & platforms
PureBasic

Export a Public Key as DER into a BinData

Demonstrates the Chilkat PublicKey.GetDerBd method, which writes the public key as binary DER into a BinData. The first argument selects the representation (as for GetPem) and the second is the BinData that receives the bytes (its contents are replaced).

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: The in-memory binary export: the raw DER lands in a BinData ready to hash, transmit, or hand to another API without a temporary file. It is the BinData counterpart to the text exporters, and the first argument picks the same PKCS #1 versus SubjectPublicKeyInfo structure.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkPublicKey.pb"
IncludeFile "CkBinData.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  Load a public key to export.  LoadFromFile inspects the content, so it accepts DER, PEM, XML,
    ;  JWK, and other supported representations.
    pubKey.i = CkPublicKey::ckCreate()
    If pubKey.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkPublicKey::ckLoadFromFile(pubKey,"qa_data/public.pem")
    If success = 0
        Debug CkPublicKey::ckLastErrorText(pubKey)
        CkPublicKey::ckDispose(pubKey)
        ProcedureReturn
    EndIf

    ;  Write the public key as binary DER into a BinData.  The 1st argument selects the representation
    ;  (as for GetPem) and the 2nd is the BinData that receives the bytes (its contents are replaced).
    preferPkcs1.i = 0
    bd.i = CkBinData::ckCreate()
    If bd.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkPublicKey::ckGetDerBd(pubKey,preferPkcs1,bd)
    If success = 0
        Debug CkPublicKey::ckLastErrorText(pubKey)
        CkPublicKey::ckDispose(pubKey)
        CkBinData::ckDispose(bd)
        ProcedureReturn
    EndIf

    Debug "Exported " + Str(CkBinData::ckNumBytes(bd)) + " DER bytes."


    CkPublicKey::ckDispose(pubKey)
    CkBinData::ckDispose(bd)


    ProcedureReturn
EndProcedure