Ejemplo n.º 1
0
        /// <summary>
        /// Writes the Key and IV from the specified <see cref="EncryptionProvider"/>
        /// <para/>
        /// to a new <see cref="Packet"/> using the specified <see cref="RSAHelper"/> to encrypt the values
        /// <para/>
        /// this method is the counterpart to <see cref="HandshakeHelper.GetDecryptor(RSAHelper, Packet)"/>
        /// </summary>
        /// <param name="rsa">The <see cref="RSAHelper"/> to use for encrypting the Key and IV</param>
        /// <param name="encryptor">The actual Encryptor to take the Key and IV from</param>
        /// <returns></returns>
        public static Packet WriteEncryptor(RSAHelper rsa, EncryptionProvider encryptor)
        {
            Packet       pkt = new Packet();
            MemoryStream outputDataStream = new MemoryStream();
            StreamWriter outputWriter     = new StreamWriter(outputDataStream);

            outputWriter.WriteLine(rsa.EncryptToBase64String(encryptor.IV));
            outputWriter.WriteLine(rsa.EncryptToBase64String(encryptor.Key));
            outputWriter.Flush();

            pkt.TypeID            = (int)PacketType.Handshake;
            pkt.ChannelID         = CryptoCommon.GetPrngInt(); // Adding an element of randomness to our sent data
            pkt.DestinationUserID = CryptoCommon.GetPrngInt(); // Adding an element of randomness to our sent data
            pkt.Data = outputDataStream.GetBuffer();
            return(pkt);
        }
Ejemplo n.º 2
0
        private bool NegotiateSessionKeys(Stream netStream, out EncryptionProvider decryptor, out EncryptionProvider encryptor, RSAHelper pubRSA, RSAHelper privRSA)
        {
            StreamReader reader = new StreamReader(netStream);
            StreamWriter writer = new StreamWriter(netStream);

            encryptor = new EncryptionProvider();
            try
            {
                Packet packet           = WriteEncryptor(pubRSA, encryptor);
                byte[] serializedPacket = ToySerializer.Serialize(packet);
                string sendData         = pubRSA.EncryptToBase64String(serializedPacket);
                writer.WriteLine(sendData); // Writing the packet as a Base64 encoded string to the network stream in the current instance
                writer.Flush();

                string read = reader.ReadLine(); // Getting response
                packet    = ToySerializer.Deserialize <Packet>(privRSA.DecryptBase64String(read));
                decryptor = GetDecryptor(privRSA, packet);
            }
            catch { decryptor = null; return(false); }
            return(true);
        }