Sample code for 30+ languages & platforms
PureBasic

Encrypt Binary Content to a JWE

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.EncryptBd, which encrypts binary content held in a BinData and writes the resulting JWE into a StringBuilder.

Background. JWE (JSON Web Encryption) protects content with a content-encryption algorithm (the header enc value) while the content-encryption key is managed by the key-management algorithm (the header alg value). This example uses AES key wrapping with a symmetric wrapping key.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkBinData.pb"
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkJwe.pb"
IncludeFile "CkJsonObject.pb"

Procedure ChilkatExample()

    success.i = 0

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

    ;  Set the JWE protected header, specifying the key-management algorithm (alg) and the content-
    ;  encryption algorithm (enc).
    header.i = CkJsonObject::ckCreate()
    If header.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkJsonObject::ckUpdateString(header,"alg","A256KW")
    CkJsonObject::ckUpdateString(header,"enc","A256GCM")
    success = CkJwe::ckSetProtectedHeader(jwe,header)
    If success = 0
        Debug CkJwe::ckLastErrorText(jwe)
        CkJwe::ckDispose(jwe)
        CkJsonObject::ckDispose(header)
        ProcedureReturn
    EndIf

    ;  The 256-bit key-wrapping key (base64) for recipient index 0.  In production, obtain the key
    ;  from a secure source rather than hard-coding it.
    base64Key.s = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU="
    success = CkJwe::ckSetWrappingKey(jwe,0,base64Key,"base64")
    If success = 0
        Debug CkJwe::ckLastErrorText(jwe)
        CkJwe::ckDispose(jwe)
        CkJsonObject::ckDispose(header)
        ProcedureReturn
    EndIf

    ;  Encrypt binary content held in a BinData, writing the resulting JWE into a StringBuilder.
    bdContent.i = CkBinData::ckCreate()
    If bdContent.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkBinData::ckAppendString(bdContent,"Binary content to encrypt.","utf-8")

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

    success = CkJwe::ckEncryptBd(jwe,bdContent,sbJwe)
    If success = 0
        Debug CkJwe::ckLastErrorText(jwe)
        CkJwe::ckDispose(jwe)
        CkJsonObject::ckDispose(header)
        CkBinData::ckDispose(bdContent)
        CkStringBuilder::ckDispose(sbJwe)
        ProcedureReturn
    EndIf

    Debug CkStringBuilder::ckGetAsString(sbJwe)


    CkJwe::ckDispose(jwe)
    CkJsonObject::ckDispose(header)
    CkBinData::ckDispose(bdContent)
    CkStringBuilder::ckDispose(sbJwe)


    ProcedureReturn
EndProcedure