dtls2 0.13.4 copy "dtls2: ^0.13.4" to clipboard
dtls2: ^0.13.4 copied to clipboard

A DTLS library for Dart, implemented via FFI bindings to OpenSSL.

example/example.dart

// Copyright (c) 2022 Jan Romann
// Copyright (c) 2021 Famedly GmbH
// SPDX-License-Identifier: MIT

import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:dtls2/dtls2.dart';

const _identity = "Client_identity";

const _preSharedKey = "secretPSK";

final _serverKeyStore = {_identity: _preSharedKey};

const _ciphers = "PSK-AES128-CCM8";

Iterable<int>? _serverPskCallback(List<int> identity) {
  final identityString = utf8.decode(identity);

  final psk = _serverKeyStore[identityString];

  if (psk == null) {
    return null;
  }

  return utf8.encode(psk);
}

final context = DtlsClientContext(
  verify: true,
  withTrustedRoots: true,
  ciphers: _ciphers,
  pskCredentialsCallback: (identityHint) {
    print(identityHint);
    return PskCredentials(
      identity: utf8.encode(_identity),
      preSharedKey: utf8.encode(_preSharedKey),
    );
  },
);

void main() async {
  const bindAddress = "::";
  final peerAddress = InternetAddress("::1");
  final peerPort = 5684;

  final dtlsServer = await DtlsServer.bind(
      bindAddress,
      peerPort,
      DtlsServerContext(
        pskKeyStoreCallback: _serverPskCallback,
        ciphers: _ciphers,
        identityHint: "This is the identity hint!",
      ));

  dtlsServer.listen(
    (connection) {
      connection.listen(
        (event) async {
          print(utf8.decode(event.data));
          connection.send(utf8.encode('Bye World'));
          await connection.close();
        },
        onDone: () async {
          await dtlsServer.close();
          print("Server connection closed.");
        },
      );
    },
    onDone: () => print("Server closed."),
  );

  final dtlsClient = await DtlsClient.bind(bindAddress, 0);

  final DtlsConnection connection;
  try {
    connection = await dtlsClient.connect(
      peerAddress,
      peerPort,
      context,
      timeout: Duration(seconds: 5),
    );
  } on TimeoutException {
    await dtlsClient.close();
    rethrow;
  }

  connection
    ..listen(
      (datagram) async {
        print(utf8.decode(datagram.data));
        await connection.close();
        print('Client connection closed.');
      },
      onDone: () async {
        await dtlsClient.close();
        print('Client closed.');
      },
    )
    ..send(utf8.encode('Hello World'));
}
5
likes
0
pub points
35%
popularity

Publisher

unverified uploader

A DTLS library for Dart, implemented via FFI bindings to OpenSSL.

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

collection, ffi

More

Packages that depend on dtls2