Sample code for 30+ languages & platforms
Dart

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 Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // 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"
  // 	}

  final json = CkJsonObject();
  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');

  final pubkey = CkPublicKey();

  try {
    pubkey.loadFromString(json.emit());
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    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.
  final jwt = CkJwt();

  final jweProtHdr = CkJsonObject();
  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');

  final jwe = CkJwe();
  jwe.setProtectedHeader(jweProtHdr);
  jwe.setPublicKey(0, pubkey);

  final plainText = 'This is the text to be encrypted.';
  final String strJwe;
  try {
    strJwe = jwe.encrypt(plainText, 'utf-8');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  print(strJwe);

  print('Success.');
}