buildServerHelloFromClientHello function

ServerHelloResult buildServerHelloFromClientHello({
  1. required ClientHello ch,
  2. required KeyPair serverKeyPair,
})

Implementation

ServerHelloResult buildServerHelloFromClientHello({
  required ClientHello ch,
  required KeyPair serverKeyPair,
}) {
  // ------------------------------------------
  // 1. Select cipher suite (TLS_AES_128_GCM_SHA256)
  // ------------------------------------------
  const supportedCipherSuites = [
    0x1301, // TLS_AES_128_GCM_SHA256
  ];

  final cipherSuite = supportedCipherSuites.firstWhere(
    (cs) => ch.cipherSuites.contains(cs),
    orElse: () => throw StateError("No supported cipher suite"),
  );

  // ------------------------------------------
  // 2. Select key share (X25519)
  // ------------------------------------------
  final keyShare = ch.keyShares!.firstWhere(
    (ks) => ks.group == 0x001d,
    orElse: () => throw StateError("No X25519 key share"),
  );

  // ------------------------------------------
  // 3. Build ServerHello
  // ------------------------------------------
  final serverRandom = Uint8List(32);
  for (int i = 0; i < 32; i++) {
    serverRandom[i] = DateTime.now().microsecondsSinceEpoch >> (i % 8);
  }

  final serverHelloBytes = buildServerHello(
    serverRandom: serverRandom,
    publicKey: serverKeyPair.publicKeyBytes,
    sessionId: Uint8List(0),
    cipherSuite: cipherSuite,
    group: keyShare.group,
  );

  return ServerHelloResult(
    bytes: serverHelloBytes,
    selectedKeyShare: keyShare,
    cipherSuite: cipherSuite,
  );
}