encryptHealthElement method

Future<HealthElementDto> encryptHealthElement(
  1. String myId,
  2. Set<String> delegations,
  3. DecryptedHealthElementDto healthElementDto
)

Implementation

Future<HealthElementDto> encryptHealthElement(String myId, Set<String> delegations, DecryptedHealthElementDto healthElementDto) async {
  Map<String, Set<DelegationDto>> encryptionKeys = healthElementDto.encryptionKeys;
  Uint8List? secret;
  if (encryptionKeys.entries.any((element) => element.value.isNotEmpty)) {
    secret = (await this.crypto.decryptEncryptionKeys(myId, healthElementDto.encryptionKeys)).firstOrNull?.formatAsKey().fromHexString();
  } else {
    secret = Uint8List.fromList(List<int>.generate(32, (i) => random.nextInt(256)));
    final List<Tuple2<String, String>> secretForDelegates = await Future.wait((<String>{...delegations, myId})
        .map((String d) async => Tuple2(d, (await this.crypto.encryptAESKeyForHcp(myId, d, healthElementDto.id, secret!.toHexString())).item1)));
    encryptionKeys = {
      ...encryptionKeys,
      ...Map.fromEntries(
          secretForDelegates.map((t) => MapEntry(t.item1, <DelegationDto>{DelegationDto(owner: myId, delegatedTo: t.item1, key: t.item2)})))
    };
  }

  if (secret == null) {
    throw FormatException("Cannot get encryption key fo ${healthElementDto.id} and hcp $myId");
  }

  Tuple2<HealthElementDto, Uint8List?> tuple = await this.marshaller(healthElementDto);
  final HealthElementDto sanitizedHealthElement = tuple.item1;
  final Uint8List? marshalledData = tuple.item2;

  sanitizedHealthElement.encryptionKeys = encryptionKeys;
  sanitizedHealthElement.encryptedSelf = marshalledData != null ? base64.encoder.convert(marshalledData.encryptAES(secret)) : null;

  return sanitizedHealthElement;
}