Sample code for 30+ languages & platforms
DataFlex

Encrypt a JWE with a Recipient Public Key

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.SetPublicKey, which sets the public key used to encrypt for a recipient. The example uses RSA-OAEP-256 key management with AES-256-GCM content encryption.

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. In public-key JWE, the content-encryption key is wrapped for the recipient using their public key, so only the holder of the matching private key can decrypt.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoJwe
    Variant vHeader
    Handle hoHeader
    Variant vPubKey
    Handle hoPubKey
    String sJweCompact
    String sTemp1
    Boolean bTemp1

    Move False To iSuccess

    Get Create (RefClass(cComChilkatJwe)) To hoJwe
    If (Not(IsComObjectCreated(hoJwe))) Begin
        Send CreateComObject of hoJwe
    End

    //  Protected header: RSA-OAEP-256 key management with AES-256-GCM content encryption.
    Get Create (RefClass(cComChilkatJsonObject)) To hoHeader
    If (Not(IsComObjectCreated(hoHeader))) Begin
        Send CreateComObject of hoHeader
    End
    Get ComUpdateString Of hoHeader "alg" "RSA-OAEP-256" To iSuccess
    Get ComUpdateString Of hoHeader "enc" "A256GCM" To iSuccess
    Get pvComObject of hoHeader to vHeader
    Get ComSetProtectedHeader Of hoJwe vHeader To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoJwe To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  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 public key.
    Get Create (RefClass(cComChilkatPublicKey)) To hoPubKey
    If (Not(IsComObjectCreated(hoPubKey))) Begin
        Send CreateComObject of hoPubKey
    End
    Get ComLoadFromFile Of hoPubKey "qa_data/recipient_pubkey.pem" To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoPubKey To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Set the public key used to encrypt for recipient 0.
    Get pvComObject of hoPubKey to vPubKey
    Get ComSetPublicKey Of hoJwe 0 vPubKey To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoJwe To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get ComEncrypt Of hoJwe "This is the secret content." "utf-8" To sJweCompact
    Get ComLastMethodSuccess Of hoJwe To bTemp1
    If (bTemp1 = False) Begin
        Get ComLastErrorText Of hoJwe To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Showln sJweCompact


End_Procedure