I run my code on 2 devices, one server one client, I want to secure the transfer, the transfer is going on in a local network (someone else can listen).
That's why I created self-signed certificate and a key to initialize my server.
var ctx = SecurityContext()
..useCertificateChainBytes(utf8.encode(Secure.cer))
..usePrivateKeyBytes(utf8.encode(Secure.key));
socketServer = await SecureServerSocket.bind(hostAddress, Global.unusedPort, ctx,shared: true);
and on Client:
var ctx = SecurityContext()
..useCertificateChainBytes(utf8.encode(Secure.cer))
..usePrivateKeyBytes(utf8.encode(Secure.key));
connectedSocket = await SecureSocket.connect(device.ipAddress, device.port!,context: ctx);
Secure.key and Secure.cer are static Strings which have the certificate and the key.
When I try to send messages between I always get:
flutter: ----------------------------------------------------
flutter: HandshakeException: Connection terminated during handshake
I don't what to do next, how can I secure the transfer between? I don't want to encrypt the messages because I am sending file bytes between.
I solved the problem by adding Richard's answer to the code.
On client side I only need to add defaultContext and return true for every badCertificateCallback. In my case I did not return true directly. I compared the self-signed certificate which created by me and both devices have that certificate inside.
I think that this approach will be better for me to secure against man in the middle attacks as long as the app is not reverse engineered and certificate is not stolen.