Sample code for 30+ languages & platforms
PureBasic

Decrypt a JWE with a Private Key

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.SetPrivateKey, which sets the private key used to decrypt a recipient of a loaded JWE.

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. The private key unwraps the content-encryption key that was wrapped with the corresponding public key during encryption.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkPrivateKey.pb"
IncludeFile "CkJwe.pb"

Procedure ChilkatExample()

    success.i = 0

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

    ;  Load the JWE compact serialization to be decrypted.
    jweCompact.s = "eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBMjU2R0NNIn0.<...>.<iv>.<ciphertext>.<tag>"
    success = CkJwe::ckLoadJwe(jwe,jweCompact)
    If success = 0
        Debug CkJwe::ckLastErrorText(jwe)
        CkJwe::ckDispose(jwe)
        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.
    ;  Load the recipient's private key.
    privKey.i = CkPrivateKey::ckCreate()
    If privKey.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkPrivateKey::ckLoadPemFile(privKey,"qa_data/recipient_privkey.pem")
    If success = 0
        Debug CkPrivateKey::ckLastErrorText(privKey)
        CkJwe::ckDispose(jwe)
        CkPrivateKey::ckDispose(privKey)
        ProcedureReturn
    EndIf

    ;  Set the private key used to decrypt recipient 0.
    success = CkJwe::ckSetPrivateKey(jwe,0,privKey)
    If success = 0
        Debug CkJwe::ckLastErrorText(jwe)
        CkJwe::ckDispose(jwe)
        CkPrivateKey::ckDispose(privKey)
        ProcedureReturn
    EndIf

    content.s = CkJwe::ckDecrypt(jwe,0,"utf-8")
    If CkJwe::ckLastMethodSuccess(jwe) = 0
        Debug CkJwe::ckLastErrorText(jwe)
        CkJwe::ckDispose(jwe)
        CkPrivateKey::ckDispose(privKey)
        ProcedureReturn
    EndIf

    Debug content


    CkJwe::ckDispose(jwe)
    CkPrivateKey::ckDispose(privKey)


    ProcedureReturn
EndProcedure