PureBasic
PureBasic
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 PureBasic Downloads
IncludeFile "CkJwe.pb"
IncludeFile "CkJsonObject.pb"
IncludeFile "CkPublicKey.pb"
Procedure ChilkatExample()
success.i = 0
jwe.i = CkJwe::ckCreate()
If jwe.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
; Protected header: RSA-OAEP-256 key management with AES-256-GCM content encryption.
header.i = CkJsonObject::ckCreate()
If header.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkJsonObject::ckUpdateString(header,"alg","RSA-OAEP-256")
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 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.
pubKey.i = CkPublicKey::ckCreate()
If pubKey.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
success = CkPublicKey::ckLoadFromFile(pubKey,"qa_data/recipient_pubkey.pem")
If success = 0
Debug CkPublicKey::ckLastErrorText(pubKey)
CkJwe::ckDispose(jwe)
CkJsonObject::ckDispose(header)
CkPublicKey::ckDispose(pubKey)
ProcedureReturn
EndIf
; Set the public key used to encrypt for recipient 0.
success = CkJwe::ckSetPublicKey(jwe,0,pubKey)
If success = 0
Debug CkJwe::ckLastErrorText(jwe)
CkJwe::ckDispose(jwe)
CkJsonObject::ckDispose(header)
CkPublicKey::ckDispose(pubKey)
ProcedureReturn
EndIf
jweCompact.s = CkJwe::ckEncrypt(jwe,"This is the secret content.","utf-8")
If CkJwe::ckLastMethodSuccess(jwe) = 0
Debug CkJwe::ckLastErrorText(jwe)
CkJwe::ckDispose(jwe)
CkJsonObject::ckDispose(header)
CkPublicKey::ckDispose(pubKey)
ProcedureReturn
EndIf
Debug jweCompact
CkJwe::ckDispose(jwe)
CkJsonObject::ckDispose(header)
CkPublicKey::ckDispose(pubKey)
ProcedureReturn
EndProcedure