Sample code for 30+ languages & platforms
Rust Requires Chilkat v11.0.0+

JWE Using General JWE JSON Serialization

See more JSON Web Encryption (JWE) Examples

This example duplicates the example A.4 in RFC 7516 for JSON Web Encryption (JWE).

This example demonstrates the capability for encrypting the same plaintext to multiple recipients. Two recipients are present in this example.

Chilkat Rust Downloads

Rust

// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

// Note: This example requires Chilkat v9.5.0.66 or greater.

let plaintext = "Live long and prosper.".to_string();

let jwe = chilkat::Jwe::new();

// First build the JWE Protected Header: {"enc":"A128CBC-HS256"}
let jwe_prot_hdr = chilkat::JsonObject::new();
let _ = jwe_prot_hdr.append_string("enc", "A128CBC-HS256");
let _ = jwe.set_protected_header(&jwe_prot_hdr);

// The first recipient uses the RSAES-PKCS1-v1_5 algorithm to encrypt
// the CEK.  The second uses AES Key Wrap to encrypt the CEK.  Key ID
// values are supplied for both keys.  The two JWE Per-Recipient
// Unprotected Header values used to represent these algorithms and key
// IDs are:
// 
//      {"alg":"RSA1_5","kid":"2011-04-29"}
// 
// and
// 
//      {"alg":"A128KW","kid":"7"}

let jwe_recipient_hdr1 = chilkat::JsonObject::new();
let _ = jwe_recipient_hdr1.append_string("alg", "RSA1_5");
let _ = jwe_recipient_hdr1.append_string("kid", "2011-04-29");
let mut recipient_index = 0;
let _ = jwe.set_recipient_header(recipient_index, &jwe_recipient_hdr1);

let jwe_recipient_hdr2 = chilkat::JsonObject::new();
let _ = jwe_recipient_hdr2.append_string("alg", "A128KW");
let _ = jwe_recipient_hdr2.append_string("kid", "7");
recipient_index = 1;
let _ = jwe.set_recipient_header(recipient_index, &jwe_recipient_hdr2);

// Set the Shared Unprotected Header:  {"jku":"https://server.example.com/keys.jwks"}
let jwe_unprot_hdr = chilkat::JsonObject::new();
let _ = jwe_unprot_hdr.append_string("jku", "https://server.example.com/keys.jwks");
let _ = jwe.set_unprotected_header(&jwe_unprot_hdr);

// Note: The intent of specifying a "kid" (an acronym for "Key ID") is that
// the software would somehow download the keys.jwks from https://server.example.com/keys.jwks,
// and would select the key (whatever format it may be, such as RSA, or an AES key wrap key, etc.),
// and then automatically use it. 

// This example keeps the "kid" and "jku" in their respective headers, but does not actually fetch
// the keys from some URL.  We'll just provide the keys directly..

// Recipient 0 uses this RSA key:
let sb_jwk = chilkat::StringBuilder::new();
let _ = sb_jwk.append("{\"kty\":\"RSA\",");
let _ = sb_jwk.append("\"n\":\"sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1Wl");
let _ = sb_jwk.append("UzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDpre");
let _ = sb_jwk.append("cbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_");
let _ = sb_jwk.append("7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBI");
let _ = sb_jwk.append("Y2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU");
let _ = sb_jwk.append("7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw\",");
let _ = sb_jwk.append("\"e\":\"AQAB\",");
let _ = sb_jwk.append("\"d\":\"VFCWOqXr8nvZNyaaJLXdnNPXZKRaWCjkU5Q2egQQpTBMwhprMzWzpR8Sxq");
let _ = sb_jwk.append("1OPThh_J6MUD8Z35wky9b8eEO0pwNS8xlh1lOFRRBoNqDIKVOku0aZb-ry");
let _ = sb_jwk.append("nq8cxjDTLZQ6Fz7jSjR1Klop-YKaUHc9GsEofQqYruPhzSA-QgajZGPbE_");
let _ = sb_jwk.append("0ZaVDJHfyd7UUBUKunFMScbflYAAOYJqVIVwaYR5zWEEceUjNnTNo_CVSj");
let _ = sb_jwk.append("-VvXLO5VZfCUAVLgW4dpf1SrtZjSt34YLsRarSb127reG_DUwg9Ch-Kyvj");
let _ = sb_jwk.append("T1SkHgUWRVGcyly7uvVGRSDwsXypdrNinPA4jlhoNdizK2zF2CWQ\",");
let _ = sb_jwk.append("\"p\":\"9gY2w6I6S6L0juEKsbeDAwpd9WMfgqFoeA9vEyEUuk4kLwBKcoe1x4HG68");
let _ = sb_jwk.append("ik918hdDSE9vDQSccA3xXHOAFOPJ8R9EeIAbTi1VwBYnbTp87X-xcPWlEP");
let _ = sb_jwk.append("krdoUKW60tgs1aNd_Nnc9LEVVPMS390zbFxt8TN_biaBgelNgbC95sM\",");
let _ = sb_jwk.append("\"q\":\"uKlCKvKv_ZJMVcdIs5vVSU_6cPtYI1ljWytExV_skstvRSNi9r66jdd9-y");
let _ = sb_jwk.append("BhVfuG4shsp2j7rGnIio901RBeHo6TPKWVVykPu1iYhQXw1jIABfw-MVsN");
let _ = sb_jwk.append("-3bQ76WLdt2SDxsHs7q7zPyUyHXmps7ycZ5c72wGkUwNOjYelmkiNS0\",");
let _ = sb_jwk.append("\"dp\":\"w0kZbV63cVRvVX6yk3C8cMxo2qCM4Y8nsq1lmMSYhG4EcL6FWbX5h9yuv");
let _ = sb_jwk.append("ngs4iLEFk6eALoUS4vIWEwcL4txw9LsWH_zKI-hwoReoP77cOdSL4AVcra");
let _ = sb_jwk.append("Hawlkpyd2TWjE5evgbhWtOxnZee3cXJBkAi64Ik6jZxbvk-RR3pEhnCs\",");
let _ = sb_jwk.append("\"dq\":\"o_8V14SezckO6CNLKs_btPdFiO9_kC1DsuUTd2LAfIIVeMZ7jn1Gus_Ff");
let _ = sb_jwk.append("7B7IVx3p5KuBGOVF8L-qifLb6nQnLysgHDh132NDioZkhH7mI7hPG-PYE_");
let _ = sb_jwk.append("odApKdnqECHWw0J-F0JWnUd6D2B_1TvF9mXA2Qx-iGYn8OVV1Bsmp6qU\",");
let _ = sb_jwk.append("\"qi\":\"eNho5yRBEBxhGBtQRww9QirZsB66TrfFReG_CcteI1aCneT0ELGhYlRlC");
let _ = sb_jwk.append("tUkTRclIfuEPmNsNDPbLoLqqCVznFbvdB7x-Tl-m0l_eFTj2KiqwGqE9PZ");
let _ = sb_jwk.append("B9nNTwMVvH3VRRSLWACvPnSiwP8N5Usy-WRXS-V7TbpxIhvepTfE0NNo\"");
let _ = sb_jwk.append("}");

// Load this JWK into a Chilkat private key object.
let rsa_priv_key = chilkat::PrivateKey::new();
if rsa_priv_key.load_jwk(&sb_jwk.get_as_string().unwrap_or_default()).is_err() {
    println!("{}", rsa_priv_key.last_error_text());
    return;
}

// Get the public key for encryption.  (The RSA private key is used for decryption.)
let rsa_pub_key = chilkat::PublicKey::new();
let _ = rsa_priv_key.to_public_key(&rsa_pub_key);
recipient_index = 0;
let _ = jwe.set_public_key(recipient_index, &rsa_pub_key);

// Recipient 1 uses AES Key Wrap
let aes_wrapping_key = "GawgguFyGrWKav7AX4VKUg".to_string();
recipient_index = 1;
let _ = jwe.set_wrapping_key(recipient_index, &aes_wrapping_key, "base64url");

// OK.. everything has been specified.
// Now encrypt.  Chilkat will use the general JSON serialization because it is only
// possible serializationto use given there are multiple recipients. 
let Ok(str_jwe) = jwe.encrypt(&plaintext, "utf-8") else {
    println!("{}", jwe.last_error_text());
    return;
};

// The strJwe is in the most compact form possible (a single line).
// Let's load it into a JSON object and examine in a non-compact pretty-printed format:
let json_temp = chilkat::JsonObject::new();
let _ = json_temp.load(&str_jwe);
json_temp.set_emit_compact(false);
println!("{}", json_temp.emit().unwrap_or_default());

// The JWE looks like this:
// (Note: Because of random values used in the encryption process, your encrypted results will be different.)

// 	{ 
// 	  "protected": "eyJlbmMiOiJBMTI4Q0JDLUhTMjU2In0",
// 	  "unprotected": { 
// 	    "jku": "https://server.example.com/keys.jwks"
// 	  },
// 	  "recipients": [
// 	    { 
// 	      "header": { 
// 	        "alg": "RSA1_5",
// 	        "kid": "2011-04-29"
// 	      },
// 	      "encrypted_key": "WlUggejR-vStJVNKgjG2mQrVv74aga1FFutT8E-n-yJEOTsOVnGjhj1NW_Snd9DqHAhFrc7NEvKCFplKWGnusBZxxjm1JpdUa0MIpkGmncJHQQdfm21vcbEUbDmfqVY79SnEis3tih1D3qmyp_Bxti4byDAHJIOJv_cj0Sx8oHZzgGtOLjtHsydyo1MtBIqI0w86i_uhUuraihZ3ngj67YZ6uqpR6lulkPIVohfF3oJ0D3Ay_XOCHWlHYkTg6VZsa0FDrPtfB2pG3TxTBPwI4IMj5uF_D3zrg51dCYKU1Gah71ujLaXRE5q9XF7oOknxiWQuWc7Ox8JP03lSx-DiVA"
// 	    },
// 	    { 
// 	      "header": { 
// 	        "alg": "A128KW",
// 	        "kid": "7"
// 	      },
// 	      "encrypted_key": "8diBP2aUUB_Jl5WxCuMJLN6HsppE3rhSjcecee0fBcwB31zbPAVejQ"
// 	    } 
// 	  ],
// 	  "iv": "JqahFKx5Z8SFT_LnkfOq0Q",
// 	  "ciphertext": "YcSdjlszsaY1ADcs4Vw85H_WoAqnkDIJaJsTkmCj05s",
// 	  "tag": "G3KF2CZ-DMhm0cqUbhJKMA"
// 	} 

// To decrypt, we don't need both recipient keys.  We can decrypt with one key or the other.
// The FindRecipient method can be used to find a particular recipient index.

// First, load the JWE..
let jwe2 = chilkat::Jwe::new();
if jwe2.load_jwe(&str_jwe).is_err() {
    println!("{}", jwe2.last_error_text());
    return;
}

// Let's say we have the AES key wrap key, and we know the "kid" equals "7".
let case_sensitive = false;
recipient_index = jwe2.find_recipient("kid", "7", case_sensitive);
if recipient_index < 0 {
    println!("Unable to find recipient with kid=7");
    return;
}

// Set the AES wrap key for the recipient index.
let _ = jwe2.set_wrapping_key(recipient_index, &aes_wrapping_key, "base64url");

// Decrypt
let Ok(mut original_plaintext) = jwe2.decrypt(recipient_index, "utf-8") else {
    println!("{}", jwe2.last_error_text());
    return;
};

println!("original text decrypted with AES key wrap key: ");
println!("{}", original_plaintext);

// Now, let's do the same with the RSA private key:
recipient_index = jwe2.find_recipient("kid", "2011-04-29", case_sensitive);
if recipient_index < 0 {
    println!("Unable to find recipient with kid=2011-04-29");
    return;
}

// Set the RSA private key for the recipient index.
let _ = jwe2.set_private_key(recipient_index, &rsa_priv_key);

// Decrypt
original_plaintext = jwe2.decrypt(recipient_index, "utf-8").unwrap_or_default();
if !jwe2.last_method_success() {
    println!("{}", jwe2.last_error_text());
    return;
}

println!("original text decrypted with RSA private key: ");
println!("{}", original_plaintext);

// ---------------------------------------------------------------------------------
// It should also be possible to decrypt the JWE as shown in RFC 7516, Appendix A.4.7
// because it was produced using the same keys.

let sb_jwe = chilkat::StringBuilder::new();
let _ = sb_jwe.append("{");
let _ = sb_jwe.append("\"protected\":");
let _ = sb_jwe.append("\"eyJlbmMiOiJBMTI4Q0JDLUhTMjU2In0\",");
let _ = sb_jwe.append("\"unprotected\":");
let _ = sb_jwe.append("{\"jku\":\"https://server.example.com/keys.jwks\"},");
let _ = sb_jwe.append("\"recipients\":[");
let _ = sb_jwe.append("{\"header\":");
let _ = sb_jwe.append("{\"alg\":\"RSA1_5\",\"kid\":\"2011-04-29\"},");
let _ = sb_jwe.append("\"encrypted_key\":");
let _ = sb_jwe.append("\"UGhIOguC7IuEvf_NPVaXsGMoLOmwvc1GyqlIKOK1nN94nHPoltGRhWhw7Zx0-");
let _ = sb_jwe.append("kFm1NJn8LE9XShH59_i8J0PH5ZZyNfGy2xGdULU7sHNF6Gp2vPLgNZ__deLKx");
let _ = sb_jwe.append("GHZ7PcHALUzoOegEI-8E66jX2E4zyJKx-YxzZIItRzC5hlRirb6Y5Cl_p-ko3");
let _ = sb_jwe.append("YvkkysZIFNPccxRU7qve1WYPxqbb2Yw8kZqa2rMWI5ng8OtvzlV7elprCbuPh");
let _ = sb_jwe.append("cCdZ6XDP0_F8rkXds2vE4X-ncOIM8hAYHHi29NX0mcKiRaD0-D-ljQTP-cFPg");
let _ = sb_jwe.append("wCp6X-nZZd9OHBv-B3oWh2TbqmScqXMR4gp_A\"},");
let _ = sb_jwe.append("{\"header\":");
let _ = sb_jwe.append("{\"alg\":\"A128KW\",\"kid\":\"7\"},");
let _ = sb_jwe.append("\"encrypted_key\":");
let _ = sb_jwe.append("\"6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ\"}],");
let _ = sb_jwe.append("\"iv\":");
let _ = sb_jwe.append("\"AxY8DCtDaGlsbGljb3RoZQ\",");
let _ = sb_jwe.append("\"ciphertext\":");
let _ = sb_jwe.append("\"KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY\",");
let _ = sb_jwe.append("\"tag\":");
let _ = sb_jwe.append("\"Mz-VPPyU4RlcuYv1IwIvzw\"");
let _ = sb_jwe.append("}");

if jwe2.load_jwe_sb(&sb_jwe).is_err() {
    println!("{}", jwe2.last_error_text());
    return;
}

// We can decrypt with either key.  Let's use the AES key wrap key...
recipient_index = jwe2.find_recipient("kid", "7", case_sensitive);
if recipient_index < 0 {
    println!("Unable to find recipient with kid=7");
    return;
}

// Set the AES wrap key for the recipient index.
let _ = jwe2.set_wrapping_key(recipient_index, &aes_wrapping_key, "base64url");

// Decrypt
original_plaintext = jwe2.decrypt(recipient_index, "utf-8").unwrap_or_default();
if !jwe2.last_method_success() {
    println!("{}", jwe2.last_error_text());
    return;
}

println!("original text decrypted from published JWE, with AES key wrap key: ");
println!("{}", original_plaintext);

// The output:

// original text decrypted with AES key wrap key: 
// Live long and prosper.
// original text decrypted with RSA private key: 
// Live long and prosper.
// original text decrypted from published JWE, with AES key wrap key: 
// Live long and prosper.