encryptContact method

Future<ContactDto> encryptContact(
  1. String myId,
  2. Set<String> delegations,
  3. DecryptedContactDto contact
)

Implementation

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

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

  Tuple2<ContactDto, Uint8List?> t = await this.marshaller(contact);

  ContactDto sanitizedContact = t.item1;
  final Uint8List? marshalledData = t.item2;

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

  return sanitizedContact;
}