encryptAccessLog method

Future<AccessLogDto> encryptAccessLog(
  1. String myId,
  2. Set<String> delegations,
  3. DecryptedAccessLogDto accessLogDto
)

Implementation

Future<AccessLogDto> encryptAccessLog(String myId, Set<String> delegations, DecryptedAccessLogDto accessLogDto) async {
  final Uuid uuid = Uuid();

  Future<DecryptedAccessLogDto> getDecryptedAccessLogWithKeys(DecryptedAccessLogDto accessLog) async {
    if (accessLog.encryptionKeys.entries.any((element) => element.value.isNotEmpty)) {
      return accessLog;
    } else {
      final String secret = uuid.v4(options: {'rng': UuidUtil.cryptoRNG});
      final Set<String> newDelegations = [...delegations, myId].toSet();
      final List<Future<MapEntry<String, String>>> futureDelegationKeys = newDelegations.map((e) async {
        String key = (await this.crypto.encryptAESKeyForHcp(myId, e, accessLogDto.id, secret)).item1;
        return MapEntry(e, key);
      }).toList();
      final Map<String, String> delegationsKeys = await Map<String, String>.fromEntries(await Future.wait(futureDelegationKeys));
      final Map<String, Set<DelegationDto>> encryptionKeys = Map<String, Set<DelegationDto>>.fromEntries(
          delegationsKeys.entries.map((e) => MapEntry(e.key, [DelegationDto(owner: myId, delegatedTo: e.key, key: e.value, tags: [])].toSet())));
      accessLog.encryptionKeys = encryptionKeys;
      return accessLog;
    }
  }

  ;

  final DecryptedAccessLogDto decryptedAccessLogDto = await getDecryptedAccessLogWithKeys(accessLogDto);
  final Set<String> keys = await this.crypto.decryptEncryptionKeys(myId, decryptedAccessLogDto.encryptionKeys);
  final String stringKey = await Stream<String>.fromIterable(keys).first;
  final Uint8List byteArrayKey = Uint8List.fromList(stringKey.codeUnits);

  final Tuple2<AccessLogDto, Uint8List?> sanitizedAccessLogAndMarshalledData = await this.marshaller(decryptedAccessLogDto);
  AccessLogDto sanitizedAccessLog = sanitizedAccessLogAndMarshalledData.item1;
  final Uint8List? marshalledData = sanitizedAccessLogAndMarshalledData.item2;

  sanitizedAccessLog.encryptedSelf = marshalledData != null ? base64Encode(marshalledData.encryptAES(byteArrayKey)) : null;
  return sanitizedAccessLog;
}