encryptJWE function
Encrypts the provided data
using the specified key
and optional epk
.
Returns the compact serialization of the encrypted JWE.
Implementation
String encryptJWE(
String data,
Map<String, dynamic> key, {
Map<String, dynamic>? epk,
}) {
var keyJwk = JsonWebKey.fromJson(key);
var builder = JsonWebEncryptionBuilder();
builder.stringContent = data;
builder.addRecipient(keyJwk, algorithm: "dir");
builder.encryptionAlgorithm = "A256GCM";
if (epk != null) {
var epkJwk = Jwk.fromJson(epk);
builder.setProtectedHeader("epk", epkJwk.toJson());
}
var jwe = builder.build();
var split = jwe.toCompactSerialization().split(".");
if (epk != null) {
String jsonString = utf8.decode(base64Url.decode(split[0]));
var jsonObject = json.decode(jsonString);
jsonObject["alg"] = "ECDH-ES";
split[0] = base64Url.encode(utf8.encode(json.encode(jsonObject)));
if (split[0].length % 4 != 0) {
var paddingLength = 4 - (split[0].length % 4);
split[0] += "=" * paddingLength;
}
}
return split.join(".");
}