Class Jwe
- All Implemented Interfaces:
AutoCloseable
Create and decrypt JSON Web Encryption payloads in compact or JSON form.
Chilkat.Jwe is the Chilkat class for creating and decrypting
JSON Web Encryption objects. It supports text and binary payloads, compact
serialization, flattened JSON serialization, general JSON serialization,
protected and unprotected headers, Additional Authenticated Data, single or
multiple recipients, and several key-management approaches including RSA,
AES key wrapping, direct symmetric encryption, AES-GCM key wrapping, and
PBES2 password-based key wrapping.
Encrypt text or binary data
Protect string or binary payloads using JWE content-encryption algorithms and the key-management method required by the recipient.
Decrypt JWE messages
Load a compact, flattened, or general JWE object and decrypt the payload using the appropriate private key, symmetric key, or password.
Compact and JSON formats
Produce or consume compact serialization for single-recipient workflows, or JSON serialization when richer header or multi-recipient structure is needed.
Single or multiple recipients
Create JWE data for one recipient or use general JSON serialization when the same encrypted payload must be decryptable by multiple recipients.
Headers and AAD
Configure protected headers, unprotected headers, recipient-specific headers, and Additional Authenticated Data for protocol-specific JWE requirements.
Flexible key management
Use RSA key management, AES key wrapping, direct symmetric keys, AES-GCM key wrapping, or PBES2 password-based key wrapping.
Common pattern:
Choose the JWE serialization format, set the protected header values such as
alg and enc, add the recipient key information,
provide the plaintext payload, and encrypt. To decrypt, load the JWE, provide
the matching key or password, and retrieve the plaintext as text, bytes, or a
Chilkat binary buffer.
For an extended overview, see Jwe Class Overview.
</section>
Instances hold a native Chilkat object: close them with ChilkatObject.close() (try-with-resources) when
done; an unclosed instance is freed when it becomes unreachable.
- See Also:
- Online reference
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionDecrypts recipientindexfrom the currently loaded JWE and returns the plaintext decoded using charsetcharset.voidDecrypts recipientindexand appends the authenticated plaintext bytes tobd.voiddecryptSb(int index, String charset, StringBuilder contentSb)Decrypts recipientindex, authenticates the JWE, decodes the plaintext bytes using charsetcharset, and appends the resulting text tocontentSb.Encryptscontentand returns the resulting compact, flattened JSON, or general JSON JWE.voidencryptBd(BinData contentBd, StringBuilder jweSb)Encrypts the exact bytes incontentBdand appends the resulting JWE text tojweSb.voidencryptSb(StringBuilder contentSb, String charset, StringBuilder jweSb)Encodes the text incontentSbusing charsetcharset, encrypts it, and appends the resulting JWE text tojweSb.intfindRecipient(String paramName, String paramValue, boolean caseSensitive)Searches only the per-recipient unprotected headers for a member namedparamNamewhose string value equalsparamValue.voidgetHeader(JsonObject json)Copies the entire currently loaded JWE structure intojsonas a JSON object.intReturns the number of recipients in the loaded JWE or in the JWE currently being configured.booleanControls whether encryption prefers JWE Compact Serialization.booleanControls which JWE JSON Serialization is produced for a single recipient.voidgetProtectedHeader(JsonObject json)Copies the decoded shared JWE Protected Header intojson.Provides a comma-separated list of specialized compatibility options that are not exposed as ordinary properties.voidLoadsjweas JWE Compact Serialization, Flattened JWE JSON Serialization, or General JWE JSON Serialization.voidloadJweSb(StringBuilder sb)Loads the complete JWE text insb.voidSets external Additional Authenticated Data (AAD) for a JWE being encrypted.voidSets external Additional Authenticated Data (AAD) to the exact bytes inaad.voidsetPassword(int index, String password)Sets the PBES2 password for recipientindex.voidsetPreferCompact(boolean value)Sets thePreferCompactproperty; seegetPreferCompact().voidsetPreferFlattened(boolean value)Sets thePreferFlattenedproperty; seegetPreferFlattened().voidsetPrivateKey(int index, PrivateKey privKey)Sets the private key used to decrypt recipientindex.voidsetProtectedHeader(JsonObject json)Sets the shared JWE Protected Header fromjson.voidsetPublicKey(int index, PublicKey pubKey)Sets the public key used to encrypt for recipientindex.voidsetRecipientHeader(int index, JsonObject json)Sets the per-recipient unprotected header for zero-based recipient indexindex.voidsetUncommonOptions(String value)Sets theUncommonOptionsproperty; seegetUncommonOptions().voidsetUnprotectedHeader(JsonObject json)Sets the shared JWE Unprotected Header fromjson.voidsetWrappingKey(int index, String encodedKey, String encoding)Sets the symmetric key for recipientindex.Methods inherited from class com.chilkatsoft.chilkat2.ChilkatObject
close, getDebugLogFilePath, getLastErrorHtml, getLastErrorText, getLastErrorXml, getLastMethodSuccess, getVerboseLogging, getVersion, isClosed, setDebugLogFilePath, setLastMethodSuccess, setVerboseLogging, toString
-
Constructor Details
-
Jwe
public Jwe()Creates a newJweobject.
-
-
Method Details
-
getNumRecipients
public int getNumRecipients()Returns the number of recipients in the loaded JWE or in the JWE currently being configured. Recipient indexes are zero-based and must be in the range0through1000.Object state How the count is determined
After
LoadJweorLoadJweSbReturns1for compact or flattened serialization, or the number of elements in the general JSONrecipientsarray.Before encryption Returns one more than the highest index having a public key, wrapping key, or password, with a minimum value of
1. Private keys and recipient headers do not increase the create-mode count.Indexes may be configured in any order, but encryption processes every recipient from index
0throughNumRecipients - 1. For example, setting only a public key at index2implies three recipients; encryption then fails for indexes0and1because they are not fully configured. In practice, configure a contiguous range beginning at0.No recipient removal method: Re-setting an indexed key, password, or header replaces only that value. There is no method to remove an individual configured recipient, so use a fresh
Jweobject for an unrelated recipient set.- Returns:
- the value of the
NumRecipientsproperty (read-only)
-
getPreferCompact
public boolean getPreferCompact()Controls whether encryption prefers JWE Compact Serialization. The default istrue.Configuration Serialization selected
More than one recipient General JWE JSON Serialization, regardless of this property.
One recipient,
PreferCompact=true, and no shared unprotected header Compact Serialization.One recipient and
PreferCompact=falseA JSON serialization;PreferFlattenedchooses flattened or general form.One recipient with a shared unprotected header, even an empty one A JSON serialization because compact form cannot carry the
unprotectedmember.A per-recipient header by itself does not prevent compact output. If compact form is selected, that header is not included. Set this property to
falsewhen a single-recipient per-recipient header must be emitted.AAD and compact form: Setting AAD does not itself force JSON output. If compact serialization is selected, the configured AAD is ignored and Chilkat logs a warning. Set
PreferCompacttofalsewhen AAD must be carried and authenticated.- Returns:
- the value of the
PreferCompactproperty
-
setPreferCompact
public void setPreferCompact(boolean value)Sets thePreferCompactproperty; seegetPreferCompact().- Parameters:
value- the new value
-
getPreferFlattened
public boolean getPreferFlattened()Controls which JWE JSON Serialization is produced for a single recipient. The default istrue. It has no effect when compact form is selected or when multiple recipients require general JSON.Condition Result
One recipient, JSON required, and this property is
trueFlattened JWE JSON Serialization.One recipient, JSON required, and this property is
falseGeneral JWE JSON Serialization containing a one-elementrecipientsarray.More than one recipient General JWE JSON Serialization.
To force general JSON for a single recipient, set both
PreferCompactandPreferFlattenedtofalse.Empty header objects: A shared protected header is emitted only when it contains members. A shared unprotected header is emitted whenever it has been set, even when empty. A configured per-recipient header is also emitted in JSON form even when empty.
- Returns:
- the value of the
PreferFlattenedproperty
-
setPreferFlattened
public void setPreferFlattened(boolean value)Sets thePreferFlattenedproperty; seegetPreferFlattened().- Parameters:
value- the new value
-
getUncommonOptions
Provides a comma-separated list of specialized compatibility options that are not exposed as ordinary properties. The default is the empty string, which is appropriate for normal JWE creation and decryption.Option Effect
jwe-no-inflate-limitStarting in v11.7.0. Removes the limit on the decompressed size of a JWE that useszip:DEF. By default, decryption fails if the plaintext would decompress to more than 64 MB, which protects against decompression bombs.Use only for trusted senders: A small compressed JWE can expand to an enormous plaintext. Set
jwe-no-inflate-limitonly when every JWE you decrypt comes from a trusted source and legitimately decompresses to more than 64 MB.- Returns:
- the value of the
UncommonOptionsproperty
-
setUncommonOptions
Sets theUncommonOptionsproperty; seegetUncommonOptions().- Parameters:
value- the new value (notnull)
-
decrypt
Decrypts recipientindexfrom the currently loaded JWE and returns the plaintext decoded using charsetcharset. The valid recipient index range is0throughNumRecipients - 1.- Call
LoadJweorLoadJweSb. - Inspect headers and select an acceptable recipient and algorithm under application policy.
- Set the required private key, wrapping key, or password at the same index.
- Call this method.
Loaded AAD is used automatically. Authentication is completed before plaintext is returned. For
zip:DEF, decompression occurs only after successful authentication, and no partial decompressed output is returned. Starting in v11.7.0, decryption fails if the plaintext would decompress to more than 64 MB, unlessUncommonOptionscontainsjwe-no-inflate-limit.Charset errors: Charset conversion errors cause
Decryptto fail.- Parameters:
index- theindexargumentcharset- thecharsetargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
- Call
-
decryptBd
Decrypts recipientindexand appends the authenticated plaintext bytes tobd. No character-set conversion is performed. Loaded AAD is used automatically, andzip:DEFis decompressed only after authentication succeeds.Atomic destination behavior: On success, plaintext bytes are appended and existing bytes are preserved. On failure,
bdis left unchanged; no partial or unauthenticated plaintext is delivered.- Parameters:
index- theindexargumentbd- thebdargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
decryptSb
Decrypts recipientindex, authenticates the JWE, decodes the plaintext bytes using charsetcharset, and appends the resulting text tocontentSb. Loaded AAD is used automatically, andzip:DEFis decompressed only after authentication succeeds.Atomic destination behavior: On success, plaintext is appended and existing text is preserved. On failure,
contentSbis left unchanged; no unauthenticated or partially decoded plaintext is delivered.Charset handling: Invalid byte sequences forcharsetcause failure. UseDecryptBdfor raw binary plaintext.- Parameters:
index- theindexargumentcharset- thecharsetargument (notnull)contentSb- thecontentSbargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
encrypt
Encryptscontentand returns the resulting compact, flattened JSON, or general JSON JWE.contentis converted to bytes using charsetcharset. If the text cannot be represented in that charset, the method fails.Before calling this method, configure the protected header and each recipient's required public key, wrapping key, or password. The selected
algandencvalues determine the required key type and length; final compatibility checks occur during this call. Chilkat generates the content-encryption IV automatically: 12 bytes for AES-GCM content encryption and 16 bytes for AES-CBC-HMAC content encryption.Serialization is selected by
NumRecipients,PreferCompact,PreferFlattened, and whether a shared unprotected header is present. A single per-recipient header is omitted if compact serialization is selected. Configured AAD is also ignored in compact form and causes a warning.Generated state persists: Encryption replaces any previously loaded JWE and can add
epk, AES-GCM wrappingiv/tag, and other generated parameters to the stored headers. Use a fresh object or reset headers for independent operations, especially to prevent AES-GCM wrapping-IV reuse.Compression and extensions:zip:DEFcompresses before encryption. Unknownzipvalues are ignored. The class does not enforcecrit; applications must apply any critical-extension policy themselves.- Parameters:
content- thecontentargument (notnull)charset- thecharsetargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
encryptBd
Encrypts the exact bytes incontentBdand appends the resulting JWE text tojweSb. No character-set conversion is performed, making this the appropriate method for arbitrary binary content.The same recipient configuration, serialization-selection, AAD, compression, and generated-header rules described for
Encryptapply.Failure behavior: Check the
true/falsereturn before usingjweSb. A failure does not append a partial JWE.- Parameters:
contentBd- thecontentBdargument (notnull)jweSb- thejweSbargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
encryptSb
Encodes the text incontentSbusing charsetcharset, encrypts it, and appends the resulting JWE text tojweSb. Existing text injweSbis preserved. If the input contains characters that cannot be represented incharset, the call fails.The same recipient configuration, serialization-selection, AAD, compression, and generated-header rules described for
Encryptapply.Failure behavior: Check the
true/falsereturn before usingjweSb. A failure does not append a partial JWE.- Parameters:
contentSb- thecontentSbargument (notnull)charset- thecharsetargument (notnull)jweSb- thejweSbargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
findRecipient
Searches only the per-recipient unprotected headers for a member namedparamNamewhose string value equalsparamValue.caseSensitivecontrols whether both the member-name and value comparisons are case-sensitive.Returns the zero-based index of the first matching recipient, or
-1when no match is found. A value of-1is also returned when the object cannot be searched; treat it simply as “no matching recipient found.” The protected and shared unprotected headers are not searched.A common use is to load a JWE, find a recipient by
kid, set the corresponding key or password at the returned index, and decrypt using that same index.Routing only: Per-recipient headers are unprotected and attacker-controlled. Validate acceptable key identifiers and algorithms under application policy, and trust the result only after authenticated decryption succeeds.
- Parameters:
paramName- theparamNameargument (notnull)paramValue- theparamValueargument (notnull)caseSensitive- thecaseSensitiveargument- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
getHeader
Copies the entire currently loaded JWE structure intojsonas a JSON object. This is the full JWE representation, not a decoded or merged JOSE header.The object can contain
protectedin its original base64url-encoded form,unprotected,header,recipients,encrypted_key,iv,ciphertext,tag,aad, and any retained unknown top-level members. A JWE originally loaded from compact form is also exposed in this JSON-object representation.On success,
jsonis overwritten. The method requires a loaded JWE; on failure,jsonis left unchanged. UseGetProtectedHeaderto obtain the decoded protected-header JSON.No effective-header merge: This method does not decode
protectedand does not combine protected, shared unprotected, and per-recipient members. Applications must inspect the relevant objects explicitly.- Parameters:
json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getProtectedHeader
Copies the decoded shared JWE Protected Header intojson. Only the protected header is returned; it is not merged with the shared unprotected header or any per-recipient header.The method succeeds after a protected header was configured with
SetProtectedHeader, or after a JWE containing a protected header was loaded. On successjsonis overwritten; on failure it is left unchanged.Use this method to inspect
alg,enc,zip,crit, and other protected parameters before choosing a key or applying application policy.Authentication timing: The header can be decoded before a key is supplied, but its integrity is established only when authenticated decryption succeeds. The
Jweclass does not enforcecrit; applications requiring critical-extension processing must do so themselves.- Parameters:
json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
loadJwe
Loadsjweas JWE Compact Serialization, Flattened JWE JSON Serialization, or General JWE JSON Serialization. Loading parses structure and headers but does not decrypt, authenticate, or apply application algorithm policy.Input rule Behavior
Leading or trailing whitespace Trimmed before format detection.
First non-whitespace character is
{{Parsed as flattened or general JSON.Other input Treated as compact serialization and required to contain exactly five dot-separated segments.
Empty compact
encrypted_keysegment Accepted, as required bydirand directECDH-ES.Protected header Base64url-decoded and parsed as UTF-8 JSON during loading. Invalid protected-header encoding or JSON causes failure.
General JSON with top-level flattened recipient members The
recipientsarray takes precedence; top-levelheaderandencrypted_keyare ignored.Unknown top-level members Retained and visible through
GetHeader, but otherwise ignored.Most semantic checks are deferred until decryption, including presence and support of
alg/enc, key compatibility, PBES2 parameter validity, and decoding or length checks foriv,tag,ciphertext, andencrypted_key.State replacement: Every load attempt discards the previous loaded JWE and clears configured protected, shared unprotected, recipient-header, and AAD state. A failed load does not restore the prior message. Public keys, private keys, wrapping keys, and passwords are not cleared. The normal decrypt sequence is therefore: load first, then set the selected recipient key, then decrypt. Parsing details: Padding, alternate Base64 alphabets, line breaks, and duplicate JSON member names follow Chilkat's underlying JSON and base64url decoders when each value is used. Malformed values generally fail during decryption if they were not needed during initial loading. No authentication yet: Headers and
kidvalues are attacker-controlled until authenticated decryption succeeds. Apply an algorithm and key-selection allowlist before decrypting untrusted input.- Parameters:
jwe- thejweargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
loadJweSb
Loads the complete JWE text insb. It accepts compact, flattened JSON, or general JSON serialization and otherwise follows all parsing, state-replacement, deferred-validation, and security behavior documented forLoadJwe.The source
StringBuilderis read during the call and does not need to remain alive afterward.- Parameters:
sb- thesbargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setAad
Sets external Additional Authenticated Data (AAD) for a JWE being encrypted.aadis encoded using charsetcharset, and the resulting bytes replace any previously configured AAD. Chilkat copies the bytes. Passing an empty string clears AAD. If encoding or another validation step fails, the previous AAD remains unchanged.In JSON serialization, AAD is base64url-encoded into the top-level
aadmember and included in the authentication calculation. It is visible but cannot be modified without causing authentication failure.Compact serialization: AAD does not force JSON serialization. If compact form is selected, Chilkat ignores the configured AAD and logs a warning. Set
PreferCompacttofalsewhen AAD must be emitted.Decryption: After loading a JSON JWE, Chilkat automatically uses its serializedaadvalue. Do not call this method merely to repeat AAD before decryption.Exact bytes: Character encoding is part of the AAD definition. UseSetAadBdwhen the protocol defines exact binary AAD.- Parameters:
aad- theaadargument (notnull)charset- thecharsetargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setAadBd
Sets external Additional Authenticated Data (AAD) to the exact bytes inaad. Chilkat copies the bytes, replacing previous AAD. Passing emptyBinDataclears AAD and causes noaadmember to be emitted. If the setter fails, the previous AAD remains unchanged.In JSON serialization, the bytes are base64url-encoded into the top-level
aadmember and authenticated without being encrypted.Compact serialization: AAD does not force JSON output. If compact form is selected, the configured AAD is ignored and a warning is logged. Set
PreferCompacttofalsewhen AAD is required.Decryption: A loaded JSON JWE supplies its own AAD automatically; do not set it again before decrypting.- Parameters:
aad- theaadargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setPassword
Sets the PBES2 password for recipientindex. The valid index range is0through1000. Chilkat convertspasswordto UTF-8, copies it, and replaces only the password at that index.Use this method with
PBES2-HS256+A128KW,PBES2-HS384+A192KW, orPBES2-HS512+A256KW. The applicable header must also contain:Header member Requirement
p2sBase64url-encoded salt. Chilkat does not generate it, impose a minimum length, or detect reuse. Generate a fresh random salt of at least 8 bytes for each encryption.p2cA JSON integer or quoted numeric string from1through999000. Chilkat does not generate it.The parameters may be in the protected header or the recipient header. A recipient-header value takes precedence over a shared value. Missing or invalid values are detected during encryption or decryption, not by this setter or by
LoadJwe. If this setter fails, the previously stored password remains unchanged.Cost policy: The built-in maximum is 999,000 iterations. Applications accepting untrusted JWEs should still apply their own acceptable
p2crange before decryption. Recipient indexing: Passwords contribute to create-modeNumRecipients. Configure a contiguous recipient range beginning at index0.- Parameters:
index- theindexargumentpassword- thepasswordargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setPrivateKey
Sets the private key used to decrypt recipientindex. The valid index range is0through1000. Chilkat copiesprivKeyand releases any previously stored private key at that index; the source object may be discarded after this call.Key type Applicable
algvaluesRSA private key
RSA1_5,RSA-OAEP,RSA-OAEP-256,RSA-OAEP-384, andRSA-OAEP-512.EC private key
ECDH-ESand theECDH-ES+A128KW,+A192KW, and+A256KWvariants.Call
LoadJwefirst, then set the private key for the selected recipient index, and finally call a decryption method with the same index. Loading does not clear previously stored keys, so explicitly overwrite keys when reusing the object for unrelated messages.Validation timing: A
truereturn means the key was copied and stored. RSA-versus-EC type, curve, key size, and compatibility with the loadedalgare validated during decryption, not by this setter. If the setter fails, the previously stored key remains unchanged. RSA-OAEP-256 compatibility: During decryption, Chilkat includes a fallback for tokens produced by older Chilkat versions that labeled the algorithmRSA-OAEP-256while using SHA-1 for the mask-generation function. Recipient count: Private keys are decryption state and do not increase create-modeNumRecipients.- Parameters:
index- theindexargumentprivKey- theprivKeyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setProtectedHeader
Sets the shared JWE Protected Header fromjson. Chilkat copies the sourceJsonObject, replacing the previously configured protected header only if the call succeeds. The caller does not need to keepjsonalive or call this method again after modifying the original object.The protected header is serialized as UTF-8 and base64url-encoded. It is visible, but its encoded form is included in the authenticated data, so any modification causes authenticated decryption to fail.
JWE pattern Recommended placement
Single-recipient compact JWE Place
algandenchere.Single-recipient JSON JWE Normally place
algandenchere.Multiple recipients using different key-management algorithms Place the shared
enchere and each recipient-specificalgin its per-recipient header.Multiple recipients using one common
algThe commonalgmay be placed here.- For PBES2,
p2sandp2cmay be placed here or in the applicable recipient header. - For ECDH-ES encryption, a protected header must be configured. Chilkat generates a fresh
ephemeral EC key and writes its public JWK to
epk. Optionalapuandapvvalues must be supplied here as base64url strings. - For single-recipient compact AES-GCM key wrapping, Chilkat writes the wrapping
ivandtaghere. In JSON serialization they are written to the recipient header instead. zip:DEFenables DEFLATE compression. Otherzipvalues are ignored.
Object reuse: Encryption can add generated members such as ECDH
epkor AES-GCM key-wrapiv/tagto the stored headers. These values remain for later calls. Reusing an existing AES-GCM wrapping IV with the same key is unsafe; use a freshJweobject or reset the headers for each independent encryption. Critical extensions: TheJweclass does not enforcecrit. Applications that accept critical JOSE extensions must inspect this header and reject unsupported entries before trusting the decrypted content.- Parameters:
json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
- For PBES2,
-
setPublicKey
Sets the public key used to encrypt for recipientindex. The valid index range is0through1000. Chilkat copiespubKeyand replaces only the public key at that index; the source object need not remain alive.Key type Applicable
algvaluesRSA public key
RSA1_5,RSA-OAEP,RSA-OAEP-256,RSA-OAEP-384, andRSA-OAEP-512.EC public key
ECDH-ESand theECDH-ES+A128KW,+A192KW, and+A256KWvariants.For ECDH-ES, Chilkat generates a fresh ephemeral key pair for each encryption on the same curve as the recipient key and writes the generated public key to protected-header
epk. If anepkobject was preconfigured, only itscrvvalue is used as a curve-name hint; Chilkat replaces itskty,x, andyvalues.NIST P-256, P-384, P-521, and supported Brainpool EC keys can be used. X25519 is not supported by this JWE ECDH-ES implementation. ECDH-ES, including its
+A*KWvariants, should be used with a single recipient.Validation timing: A
trueresult means the key was copied. Key type, size, curve, andalgcompatibility are checked whenEncrypt,EncryptSb, orEncryptBdruns. If the setter fails, the previously stored key remains unchanged. Algorithm names:RSA-OAEP-384andRSA-OAEP-512are Chilkat extensions beyond the base JOSE algorithm set; confirm peer interoperability before selecting them. Recipient indexing: Public keys contribute to create-modeNumRecipients. Configure a contiguous range beginning at index0; skipped lower indexes cause encryption to attempt incomplete recipients and fail.- Parameters:
index- theindexargumentpubKey- thepubKeyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setRecipientHeader
Sets the per-recipient unprotected header for zero-based recipient indexindex. The valid index range is0through1000. Chilkat copiesjson, and calling this method again at the same index replaces only that recipient header.In flattened JSON this becomes the top-level
headermember. In general JSON it becomes theheadermember of the corresponding element in therecipientsarray. An empty object is retained and emitted as"header":{}; it does not remove the recipient, and no recipient-removal method exists.Typical members include
kid, recipient-specificalg, PBES2p2s/p2c, or AES-GCM key-wrapiv/tag. Use the same index with the appropriate key or password setter.Compact serialization: A per-recipient header alone does not force JSON output. If compact serialization is selected for a single recipient, this header is omitted. Set
PreferCompacttofalsewhen it must be serialized.Recipient counting: Before encryption,NumRecipientsis determined by configured public keys, wrapping keys, and passwords. A recipient header by itself does not increase that count.Not authenticated: Per-recipient headers are unprotected. Treat values such askidas routing hints and accept them only under application policy and after authenticated decryption succeeds.- Parameters:
index- theindexargumentjson- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setUnprotectedHeader
Sets the shared JWE Unprotected Header fromjson. Chilkat copies the sourceJsonObject; a successful call replaces the previous shared unprotected header, while a failed call preserves it.The header applies to every recipient and can be represented only by JWE JSON Serialization. Setting it forces JSON output even when
jsonis empty, in which case the output contains"unprotected":{}.Not authenticated: This header is neither encrypted nor integrity-protected. Do not place algorithm-policy, identity, authorization, or trusted key-location decisions here unless the application independently validates them.Loading a JWE:
LoadJweandLoadJweSbdiscard this configured header and replace all header state with the loaded message.- Parameters:
json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setWrappingKey
Sets the symmetric key for recipientindex.encodedKeycontains the key bytes encoded according toencoding, such ashexorbase64. The valid index range is0through1000.Chilkat decodes and copies the key. A decoding failure returns
falseand leaves the previous key at that index unchanged. Algorithm-specific key length is validated during encryption or decryption.Algorithm family Required key length
A128KWorA128GCMKW16 bytesA192KWorA192GCMKW24 bytesA256KWorA256GCMKW32 bytesdirwithA128GCM16 bytesdirwithA192GCM24 bytesdirwithA256GCM32 bytesdirwithA128CBC-HS25632 bytesdirwithA192CBC-HS38448 bytesdirwithA256CBC-HS51264 bytesFor
dir, set the direct content-encryption key at index0. Direct encryption uses one shared key and is intended for a single recipient.AES-GCM key wrapping: For
A128GCMKW,A192GCMKW, andA256GCMKW, Chilkat normally generates the required 12-byte wrapping IV and computes the 16-byte tag. A pre-setivis used as-is and must decode to exactly 12 bytes. A pre-settagis replaced by the computed tag. Compact output stores these values in the protected header; JSON output stores them in the recipient header. During decryption, the IV may be read from the recipient or a shared header; the tag is read from the recipient header, with the shared protected header also consulted for recipient index0. Both values are required. Never reuse a wrapping IV: Generated AES-GCM wrapping parameters remain in the stored headers after encryption. Reusing the object can therefore reuse an existing IV. Use a fresh object or reset the headers before each independent AES-GCM key-wrap encryption. Recipient indexing: Wrapping keys contribute to create-modeNumRecipients. Configure every index from0through the highest index used.- Parameters:
index- theindexargumentencodedKey- theencodedKeyargument (notnull)encoding- theencodingargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-