getKeyFor method

Future<ChaCha20Key> getKeyFor(
  1. LocalityUser localityUser, {
  2. SharedKeyRepository? sharedKeyRepository,
})

Retrieves or generates a shared key for secure communication with another user.

  • localityUser: The target LocalityUser for whom the shared key is generated.
  • sharedKeyRepository: An optional repository to cache and retrieve shared keys.

If a sharedKeyRepository is provided, the method first checks for an existing shared key using the localityUser's public key. If no key exists, a new shared key is computed, stored in the repository, and returned. If no repository is provided, the shared key is computed directly.

Returns: A Future resolving to the computed ChaCha20Key.

Implementation

Future<ChaCha20Key> getKeyFor(
  LocalityUser localityUser, {
  SharedKeyRepository? sharedKeyRepository,
}) async {
  if (sharedKeyRepository != null) {
    // Attempt to retrieve an existing shared key from the repository.
    String? existingKey = await sharedKeyRepository
        .getKey(localityUser.publicKey, password: privateKey);

    if (existingKey == null) {
      // Compute a new shared secret if no key exists in the repository.
      BigInt sharedKey =
          KeyPair.computeSharedSecret(privateKey, localityUser.publicKey);
      sharedKeyRepository.upsertKey(
          localityUser.id, sharedKey.toRadixString(16),
          password: privateKey);
      return ChaCha20Key.fromBigInt(sharedKey);
    } else {
      // Use the existing shared key if found in the repository.
      return ChaCha20Key.fromBigInt(BigInt.parse(existingKey, radix: 16));
    }
  }

  // Compute the shared secret directly if no repository is provided.
  return ChaCha20Key.fromBigInt(
      KeyPair.computeSharedSecret(privateKey, localityUser.publicKey));
}