Java
Chilkat2 Java
JWE using ECDH-ES, BP-256, A256GCM
See more JSON Web Encryption (JWE) Examples
Create a JWE with the following header:
{
"alg": "ECDH-ES",
"enc": "A256GCM",
"exp": 1621957030,
"cty": "NJWT",
"epk": {
"kty": "EC",
"x": "QLpJ_LpFx-6yJhsb4OvHwU1khLnviiOwYOvmf5clK7w"
"y": "AJh7pJ3zZKDJkm8rbeG69GBooTosXJgSsvNFH0i3Vxnu"
"crv": "BP-256"
}
}
Note: This example requires Chilkat v9.5.0.87 or greater.
Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Jwe;
import com.chilkatsoft.chilkat2.Jwt;
import com.chilkatsoft.chilkat2.PublicKey;
public class ChilkatExample {
public static void main(String[] args) {
// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Load our brainpool BP-256 public key.
// {
// "use": "enc",
// "kid": "puk_idp_enc",
// "kty": "EC",
// "crv": "BP-256",
// "x": "QLpJ_LpFx-6yJhsb4OvHwU1khLnviiOwYOvmf5clK7w",
// "y": "AJh7pJ3zZKDJkm8rbeG69GBooTosXJgSsvNFH0i3Vxnu"
// }
JsonObject json = new JsonObject();
json.updateString("use", "enc");
json.updateString("kid", "puk_idp_enc");
json.updateString("kty", "EC");
json.updateString("crv", "BP-256");
json.updateString("x", "QLpJ_LpFx-6yJhsb4OvHwU1khLnviiOwYOvmf5clK7w");
json.updateString("y", "AJh7pJ3zZKDJkm8rbeG69GBooTosXJgSsvNFH0i3Vxnu");
PublicKey pubkey = new PublicKey();
try {
pubkey.loadFromString(json.emit());
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Build our protected header:
// {
// "alg": "ECDH-ES",
// "enc": "A256GCM",
// "exp": 1621957030,
// "cty": "NJWT",
// "epk": {
// "kty": "EC",
// "x": "QLpJ_LpFx-6yJhsb4OvHwU1khLnviiOwYOvmf5clK7w"
// "y": "AJh7pJ3zZKDJkm8rbeG69GBooTosXJgSsvNFH0i3Vxnu"
// "crv": "BP-256"
// }
// }
// Use jwt only for getting the current date/time + 3600 seconds.
Jwt jwt = new Jwt();
JsonObject jweProtHdr = new JsonObject();
jweProtHdr.updateString("alg", "ECDH-ES");
jweProtHdr.updateString("enc", "A256GCM");
jweProtHdr.updateInt("exp", jwt.genNumericDate(3600));
jweProtHdr.updateString("cty", "NJWT");
jweProtHdr.updateString("epk.kty", "EC");
jweProtHdr.updateString("epk.x", "QLpJ_LpFx-6yJhsb4OvHwU1khLnviiOwYOvmf5clK7w");
jweProtHdr.updateString("epk.y", "AJh7pJ3zZKDJkm8rbeG69GBooTosXJgSsvNFH0i3Vxnu");
jweProtHdr.updateString("epk.crv", "BP-256");
Jwe jwe = new Jwe();
jwe.setProtectedHeader(jweProtHdr);
jwe.setPublicKey(0, pubkey);
String plainText = "This is the text to be encrypted.";
String strJwe;
try {
strJwe = jwe.encrypt(plainText, "utf-8");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println(strJwe);
System.out.println("Success.");
}
}