Exemplo n.º 1
0
        public static async Task <InitializationResult <AuthenticatedStream> > RegisterWithServerAsync(
            Stream serverStream,
            byte[] presharedKey,
            Guid ownGuid,
            Guid serverGuid,
            IAuthenticatedConnectionFactory authenticatedConnectionFactory,
            X509Certificate2 clientCertificate,
            X509Certificate serverCertificate,
            ICryptographicService otp,
            CancellationToken token)
        {
            InitializationResult <AuthenticatedStream> From(CommunicationResult res) => From <AuthenticatedStream>(res);

            if (!otp.CanEncrypt)
            {
                throw new ArgumentException("otp needs to be able to encrypt");
            }
            token = token.AddTimeout(DefaultTimeout);

            await serverStream.WriteSafelyAsync(presharedKey, token);

            var serverGuidResult = await serverStream.ReceiveGuidSafelyAsync(token);

            if (!serverGuidResult.Successful)
            {
                return(From(serverGuidResult));
            }
            if (!serverGuidResult.Result.Equals(serverGuid))
            {
                return(new InitializationResult <AuthenticatedStream>
                {
                    Successful = false,
                    Error = new InitializationError
                    {
                        ErrorType = InitializationErrorType.Identification,
                        Message = $"Expected server to be '{serverGuid}', but instead found '{serverGuidResult.Result}'",
                    },
                });
            }
            await serverStream.WriteSafelyAsync(
                ownGuid,
                (int)InitiationMode.Otp,
                token);

            var exportCertificate    = clientCertificate.Export(X509ContentType.Cert);
            var encryptedCertificate = otp.Encrypt(exportCertificate);
            await serverStream.WriteSafelyAsync(
                (int)CommunicationData.PublicKey,
                encryptedCertificate.Length,
                encryptedCertificate,
                token);

            return(await EstablishEncryptedCommunication(false, serverGuid, authenticatedConnectionFactory,
                                                         serverStream, token));
        }
Exemplo n.º 2
0
 protected Action DataIsEncrypted(params byte[] plaintext)
 {
     return(() => CipherText = CryptographicService.Encrypt(plaintext));
 }