Exemple #1
0
        internal void HandleS01EncryptionRequest(S01EncryptionRequest s01EncryptionRequest)
        {
            waitingForEncryption = true;
            Console.WriteLine("Server is in online mode!");
            RSACryptoServiceProvider rsaProvider = CryptoHandler.DecodeRSAPublicKey(s01EncryptionRequest.serverKey);

            byte[] secretKey = CryptoHandler.GenerateAESPrivateKey();

            Console.WriteLine("Keys generated");
            if (s01EncryptionRequest.serverId != "-")
            {
                Console.WriteLine("Logging in to Mojang");
                if (!Yggdrasil.SessionCheck(manager.loginParams.UUID, manager.loginParams.SessionId, CryptoHandler.getServerHash(s01EncryptionRequest.serverId, s01EncryptionRequest.serverKey, secretKey)))
                {
                    Console.WriteLine("Mojang authentication failed");
                    return;
                }
                else
                {
                    Console.WriteLine("Mojang authentication succesful");
                }
            }

            manager.SendPacket(new C01EncryptionResponse(rsaProvider.Encrypt(secretKey, false), rsaProvider.Encrypt(s01EncryptionRequest.token, false)));

            manager.aesStream = CryptoHandler.getAesStream(manager.tcpClient.GetStream(), secretKey);
            manager.encrypted = true;
        }
Exemple #2
0
        private bool StartEncrypt()
        {
            CryptoHandler crypto = new CryptoHandler();

            List <byte> encryptionRequest = new List <byte>();
            string      serverID          = "";

            if (protocol.protocolVersion < MCVersion.MC172Version)
            {
                serverID = "lilium-pre";
            }
            encryptionRequest.AddRange(getString(serverID));
            encryptionRequest.AddRange(getArray(crypto.getPublic()));
            byte[] token = new byte[4];
            var    rng   = new System.Security.Cryptography.RNGCryptoServiceProvider(); rng.GetBytes(token);

            encryptionRequest.AddRange(getArray(token));
            SendPacket(0x01, encryptionRequest);

            List <byte> encryptResponse = new List <byte>(readDataRAW(readNextVarIntRAW()));

            if (readNextVarInt(encryptResponse) == 0x01)
            {
                List <byte> dec = new List <byte>();
                dec.AddRange(crypto.Decrypt(readNextByteArray(encryptResponse)));
                dec.RemoveRange(0, dec.Count - 16);
                byte[] key_dec   = dec.ToArray();
                byte[] token_dec = token;

                EncStream      = CryptoHandler.getAesStream(Client.GetStream(), key_dec);
                this.encrypted = true;
                return(true);
            }
            return(false);
        }
        public void Vetor(User user)
        {
            CryptoHandler Crypto = new CryptoHandler();
            AuthHandler   Auth   = new AuthHandler();

            user.IV   = Auth.HmacKey;
            user.Hmac = Crypto.Key;
            Random getKey = new Random();
            string vetor = "", hmac = "";

            for (int i = 0; i < 8; i++)
            {
                vetor = vetor + RandomStrings[getKey.Next(RandomStrings.Length)];
                hmac  = hmac + RandomStrings[getKey.Next(RandomStrings.Length)];
            }
            using (PacketManager Write = new PacketManager())
            {
                Write.OP(1);
                Write.Header();
                Write.Hex("D7 25");
                Write.Str(vetor);
                Write.Str(hmac);
                Write.Hex("00 00 00 01 00 00 00 00 00 00 00 00");
                user.Send(Write.ack);
            }
            user.IV   = Encoding.GetEncoding(949).GetBytes(vetor);
            user.Hmac = Encoding.GetEncoding(949).GetBytes(hmac);
        }
Exemple #4
0
        public byte[] DecryptHeader()
        {
            try
            {
                if (FirmwareRaw != null)
                {
                    if (FirmwareRaw.Length > 512)
                    {
                        var iv  = FirmwareIV();
                        var key = KeyHandler.Aes256;

                        var fileName  = @"header.rawBytes";
                        var rawHeader = FirmwareSigned.ByteSelect(640, 543);

                        var dec = CryptoHandler.AesDecrypt(rawHeader, key, iv);
                        File.WriteAllBytes(fileName, dec);
                    }
                }
            }
            catch (Exception ex)
            {
                UiMessages.Error(ex.ToString());
            }

            //default
            return(null);
        }
        static void Main(string[] args)
        {
            _crypto = new CryptoHandler(CryptoHandler.PASSWORD);

            Console.Write(DesypherFile());
            Console.ReadLine();
        }
Exemple #6
0
        public void Send(byte[] data)
        {
            CryptoHandler Crypto = new CryptoHandler();
            AuthHandler   Auth   = new AuthHandler();

            Crypto.Key   = this.Hmac;
            Auth.HmacKey = this.IV;
            Random getRndm = new Random();

            this.prefix = (short)getRndm.Next(9999);
            this.count  = getRndm.Next(9999);
            Int16 sizePackage = Convert.ToInt16(data.Length - 12);

            byte[] size = new byte[2];
            size = BitConverter.GetBytes(sizePackage);
            Array.Reverse(size);
            Array.Copy(size, 0, data, 4, size.Length);
            byte[] opcode = new byte[2];
            Array.Copy(data, 0, opcode, 0, opcode.Length);
            Array.Resize(ref data, data.Length - 5);
            OutPacket GetPacket = new OutPacket(data, Crypto, Auth, prefix, count);

            this.socket.Send(GetPacket.PacketData, 0, GetPacket.PacketData.Length, 0);
            //log.Hex("Enviando, PacketID {" + Convert.ToInt32(BitConverter.ToString(opcode).Replace("-", "")) + "} Size {"+BitConverter.ToString(size)+"} Payload : ",data);
        }
Exemple #7
0
        /// <summary>
        /// Start network encryption. Automatically called by Login() if the server requests encryption.
        /// </summary>
        /// <returns>True if encryption was successful</returns>
        private bool StartEncryption(string uuid, string sessionID, byte[] token, string serverIDhash, byte[] serverKey)
        {
            System.Security.Cryptography.RSACryptoServiceProvider RSAService = CryptoHandler.DecodeRSAPublicKey(serverKey);
            byte[] secretKey = CryptoHandler.GenerateAESPrivateKey();

            if (Settings.DebugMessages)
            {
                ConsoleIO.WriteLineFormatted("§8Crypto keys & hash generated.");
            }

            if (serverIDhash != "-")
            {
                Console.WriteLine("Checking Session...");
                if (!ProtocolHandler.SessionCheck(uuid, sessionID, CryptoHandler.getServerHash(serverIDhash, serverKey, secretKey)))
                {
                    handler.OnConnectionLost(ChatBot.DisconnectReason.LoginRejected, "Failed to check session.");
                    return(false);
                }
            }

            //Encrypt the data
            byte[] key_enc   = dataTypes.GetArray(RSAService.Encrypt(secretKey, false));
            byte[] token_enc = dataTypes.GetArray(RSAService.Encrypt(token, false));

            //Encryption Response packet
            SendPacket(0x01, dataTypes.ConcatBytes(key_enc, token_enc));

            //Start client-side encryption
            socketWrapper.SwitchToEncrypted(secretKey);

            //Process the next packet
            int         packetID   = -1;
            List <byte> packetData = new List <byte>();

            while (true)
            {
                ReadNextPacket(ref packetID, packetData);
                if (packetID == 0x00) //Login rejected
                {
                    handler.OnConnectionLost(ChatBot.DisconnectReason.LoginRejected, ChatParser.ParseText(dataTypes.ReadNextString(packetData)));
                    return(false);
                }
                else if (packetID == 0x02) //Login successful
                {
                    login_phase = false;

                    if (!pForge.CompleteForgeHandshake())
                    {
                        return(false);
                    }

                    StartUpdating();
                    return(true);
                }
                else
                {
                    HandlePacket(packetID, packetData);
                }
            }
        }
        private void GenKeypairButton_Click()
        {
            KeyPair pair = CryptoHandler.GenKeyPair();

            pubKeyInput.Text  = Convert.ToBase64String(pair.PublicKey);
            privKeyInput.Text = Convert.ToBase64String(pair.PrivateKey);
        }
Exemple #9
0
        public static byte[] CreateRequest()
        {
            WriteToNode writeToNode = new WriteToNode();

            string[] valueList   = writeToNode.ReturnValues();
            bool[]   checkedList = writeToNode.ReturnChecked();

            NodeConfigRequest request = new NodeConfigRequest
            {
                NetworkID               = Convert.ToInt32(valueList[0]),
                HasNetworkID            = checkedList[0],
                NetworkChannel          = Convert.ToInt32(valueList[1]),
                HasNetworkChannel       = checkedList[1],
                NodeConfiguration       = SensorView._config,
                HasNodeConfiguration    = checkedList[2],
                OperatingMode           = GetOperatingMode(Convert.ToInt32(valueList[3])),
                HasOperatingMode        = checkedList[3],
                EncryptionKey           = ByteString.CopyFrom(hexToByte(valueList[4])),
                HasEncryptionKey        = checkedList[4],
                AuthenticationKey       = ByteString.CopyFrom(hexToByte(valueList[5])),
                HasAuthenticationKey    = checkedList[5],
                UplinkRate              = Convert.ToInt32(valueList[6]),
                HasUplinkRate           = checkedList[6],
                NodeRole                = GetNodeRole(Convert.ToInt32(valueList[7])),
                HasNodeRole             = checkedList[7],
                AssetTrackingEnabled    = Convert.ToInt32(valueList[8]) == 0,
                HasAssetTrackingEnabled = checkedList[8],
                FeatureLock             = Convert.ToInt32(valueList[9]) == 0,
                HasFeatureLock          = checkedList[9],
                Delay = 1
            };

            byte[] bytes = request.ToByteArray();
            byte[] paddedBytes;

            // Pad if the result is not % 16
            if ((bytes.Length % 16) != 0)
            {
                paddedBytes = new byte[bytes.Length + (16 - (bytes.Length % 16))];
                Array.Copy(bytes, 0, paddedBytes, 0, bytes.Length);
                for (int i = bytes.Length; i < paddedBytes.Length; i++)
                {
                    paddedBytes[i] = 0;
                }
            }
            else
            {
                paddedBytes = new byte[bytes.Length];
                Array.Copy(bytes, 0, paddedBytes, 0, bytes.Length);
            }

            CryptoHandler cryptoHandler = new CryptoHandler();

            byte[] Key            = hexToByte("2b7e151628aed2a6abf7158809cf4f3c"); //Convert the hex string to a byte array
            byte[] IV             = hexToByte("000102030405060708090a0b0c0d0e0f"); //Convert the hex string to a byte array
            byte[] encryptedBytes = cryptoHandler.Encrypt(paddedBytes, Key, IV);

            return(encryptedBytes);
        }
Exemple #10
0
 /// <summary>
 /// Switch network reading/writing to an encrypted stream
 /// </summary>
 /// <param name="secretKey">AES secret key</param>
 public void SwitchToEncrypted(byte[] secretKey)
 {
     if (encrypted)
     {
         throw new InvalidOperationException("Stream is already encrypted!?");
     }
     this.s         = CryptoHandler.getAesStream(c.GetStream(), secretKey);
     this.encrypted = true;
 }
        private bool StartEncryption(string uuid, string username, string sessionID, byte[] token, string serverIDhash, byte[] serverKey)
        {
            System.Security.Cryptography.RSACryptoServiceProvider RSAService = CryptoHandler.DecodeRSAPublicKey(serverKey);
            byte[] secretKey = CryptoHandler.GenerateAESPrivateKey();

            if (Settings.DebugMessages)
            {
                ConsoleIO.WriteLineFormatted("§8Crypto keys & hash generated.");
            }

            if (serverIDhash != "-")
            {
                Console.WriteLine("Checking Session...");
                if (!ProtocolHandler.SessionCheck(uuid, sessionID, CryptoHandler.getServerHash(serverIDhash, serverKey, secretKey)))
                {
                    handler.OnConnectionLost(ChatBot.DisconnectReason.LoginRejected, "Failed to check session.");
                    return(false);
                }
            }

            //Encrypt the data
            byte[] key_enc   = RSAService.Encrypt(secretKey, false);
            byte[] token_enc = RSAService.Encrypt(token, false);
            byte[] keylen    = BitConverter.GetBytes((short)key_enc.Length);
            byte[] tokenlen  = BitConverter.GetBytes((short)token_enc.Length);

            Array.Reverse(keylen);
            Array.Reverse(tokenlen);

            //Building the packet
            byte[] data = new byte[5 + (short)key_enc.Length + (short)token_enc.Length];
            data[0] = 0xFC;
            keylen.CopyTo(data, 1);
            key_enc.CopyTo(data, 3);
            tokenlen.CopyTo(data, 3 + (short)key_enc.Length);
            token_enc.CopyTo(data, 5 + (short)key_enc.Length);

            //Send it back
            Send(data);

            //Getting the next packet
            byte[] pid = new byte[1];
            Receive(pid, 0, 1, SocketFlags.None);
            if (pid[0] == 0xFC)
            {
                readData(4);
                s         = CryptoHandler.getAesStream(c.GetStream(), secretKey);
                encrypted = true;
                return(true);
            }
            else
            {
                ConsoleIO.WriteLineFormatted("§8Invalid response to StartEncryption packet");
                return(false);
            }
        }
        private void ApplySettingsButton_Click()
        {
            byte[] pubKey         = null;
            byte[] privKey        = null;
            bool   privKeyChanged = privKeyInput.Text != PrivKeyHiddenBlurb;

            try
            {
                if (pubKeyInput.Text.Trim() != "")
                {
                    pubKey = Convert.FromBase64String(pubKeyInput.Text);
                    if (!CryptoHandler.IsKeyValid(pubKey))
                    {
                        ShowToast("Invalid Public Key");
                        return;
                    }
                }
            }
            catch (FormatException)
            {
                ShowToast("Invalid Public Key Format");
                return;
            }

            try
            {
                if (privKeyChanged && privKeyInput.Text.Trim() != "")
                {
                    privKey = Convert.FromBase64String(privKeyInput.Text);
                    if (!CryptoHandler.IsKeyValid(privKey))
                    {
                        ShowToast("Invalid Private Key");
                        return;
                    }
                }
            }
            catch (FormatException)
            {
                ShowToast("Invalid Private Key Format");
                return;
            }

            AppSettings.Global.TargetUrl = targetUrlSettingInput.Text;
            AppSettings.Global.Positions = posAvailInput.Text;
            AppSettings.Global.DeviceId  = deviceIdInput.Text;
            AppSettings.Global.GroupId   = groupIdInput.Text;
            AppSettings.Global.KioskMode = kioskModeSwitch.Checked;
            AppSettings.Global.PubKey    = pubKey;

            if (privKeyChanged)
            {
                AppSettings.Global.PrivKey = privKey;
            }

            ShowToast("Settings Saved");
        }
Exemple #13
0
        public ActionResult UpdateAssembly(string objectAsString)
        {
            var postData = (Dictionary <string, object>) new JavaScriptSerializer().Deserialize <Dictionary <string, object> >(objectAsString);

            var crypto = new CryptoHandler();

            var result = crypto.DecryptJsonDataString(postData["data"].ToString(), postData["key"].ToString());

            return(UpdateAssemblyParsed(result));
        }
Exemple #14
0
 private void btnSaveEncrypted_Click(object sender, EventArgs e)
 {
     dlgSave.FileName = Path.GetFileNameWithoutExtension(_qualifiedFilename) + "-modified";
     if (dlgSave.ShowDialog() != DialogResult.OK)
     {
         return;
     }
     WriteVaultData();
     File.WriteAllText(dlgSave.FileName, CryptoHandler.EncryptSave(vaultData.VaultData.ToString(Formatting.None)));
 }
Exemple #15
0
        private void btnLoadSave_Click(object sender, EventArgs e)
        {
            // Pick the file
            dlgLoadSave.ShowDialog();
            if (dlgLoadSave.SafeFileName == null || dlgLoadSave.SafeFileName.Equals(""))
            {
                return;
            }
            _qualifiedFilename = dlgLoadSave.FileName;


            // Determine whether or not it is encrypted (done automatically by decryption method)
            // Decrypt if neccessary
            var inputFile   = File.ReadAllText(dlgLoadSave.FileName);
            var workingData = CryptoHandler.GetDecryptedSave(inputFile);

            // Determine if the file is a valid fallout shelter save
            try
            {
                if (!SaveValidator.IsValidSave(workingData))
                {
                    MessageBox.Show(@"Unknown error when loading " + dlgLoadSave.SafeFileName +
                                    @". The file is most likely corrupt or invalid.");
                    return;
                }
            }
            catch (Exception)
            {
                MessageBox.Show(@"Unknown error when loading " + dlgLoadSave.SafeFileName +
                                @". The file is most likely corrupt or invalid.");
                return;
            }

            // Load the save into a new VaultData object
            vaultData = new VaultDataInterface(workingData);

            // Parse VaultData object into form controls
            PopulateVaultData();

            // Enable form controls
            dgridDwellers.Enabled     = true;
            numCaps.Enabled           = true;
            numLunchBox.Enabled       = true;
            numHandyBox.Enabled       = true;
            numStimpak.Enabled        = true;
            numRadaway.Enabled        = true;
            numudEnergy.Enabled       = true;
            numudFood.Enabled         = true;
            numudWater.Enabled        = true;
            numudPetCarriers.Enabled  = true;
            numudNukaQuantums.Enabled = true;
            numudStarterPacks.Enabled = true;
            btnSaveEncrypted.Enabled  = true;
            btnSaveJson.Enabled       = true;
        }
Exemple #16
0
        /// <summary>
        /// Start network encryption. Automatically called by Login() if the server requests encryption.
        /// </summary>
        /// <returns>True if encryption was successful</returns>

        private bool StartEncryption(string uuid, string sessionID, byte[] token, string serverIDhash, byte[] serverKey)
        {
            System.Security.Cryptography.RSACryptoServiceProvider RSAService = CryptoHandler.DecodeRSAPublicKey(serverKey);
            byte[] secretKey = CryptoHandler.GenerateAESPrivateKey();

            ConsoleIO.WriteLineFormatted("§8Crypto keys & hash generated.");

            if (serverIDhash != "-")
            {
                Console.WriteLine("Checking Session...");
                if (!ProtocolHandler.SessionCheck(uuid, sessionID, CryptoHandler.getServerHash(serverIDhash, serverKey, secretKey)))
                {
                    handler.OnConnectionLost(ChatBot.DisconnectReason.LoginRejected, "Failed to check session.");
                    return(false);
                }
            }

            //Encrypt the data
            byte[] key_enc   = RSAService.Encrypt(secretKey, false);
            byte[] token_enc = RSAService.Encrypt(token, false);
            byte[] key_len   = getVarInt(key_enc.Length);
            byte[] token_len = getVarInt(token_enc.Length);

            //Encryption Response packet
            SendPacket(0x01, concatBytes(key_len, key_enc, token_len, token_enc));

            //Start client-side encryption
            s         = CryptoHandler.getAesStream(c.GetStream(), secretKey, this);
            encrypted = true;

            //Process the next packet
            int packetID = -1;

            byte[] packetData = new byte[] { };
            while (true)
            {
                readNextPacket(ref packetID, ref packetData);
                if (packetID == 0x00) //Login rejected
                {
                    handler.OnConnectionLost(ChatBot.DisconnectReason.LoginRejected, ChatParser.ParseText(readNextString(ref packetData)));
                    return(false);
                }
                else if (packetID == 0x02) //Login successful
                {
                    login_phase = false;
                    StartUpdating();
                    return(true);
                }
                else
                {
                    handlePacket(packetID, packetData);
                }
            }
        }
        /// <summary>
        /// Start network encryption. Automatically called by Login() if the server requests encryption.
        /// </summary>
        /// <returns>True if encryption was successful</returns>

        private bool StartEncryption(string uuid, string sessionID, byte[] token, string serverIDhash, byte[] serverKey)
        {
            System.Security.Cryptography.RSACryptoServiceProvider RSAService = CryptoHandler.DecodeRSAPublicKey(serverKey);
            byte[] secretKey = CryptoHandler.GenerateAESPrivateKey();

            ConsoleIO.WriteLineFormatted("§8Crypto keys & hash generated.");

            if (serverIDhash != "-")
            {
                Console.WriteLine("Checking Session...");
                if (!ProtocolHandler.SessionCheck(uuid, sessionID, CryptoHandler.getServerHash(serverIDhash, serverKey, secretKey)))
                {
                    handler.OnConnectionLost(ChatBot.DisconnectReason.LoginRejected, "Failed to check session.");
                    return(false);
                }
            }

            //Encrypt the data
            byte[] key_enc   = RSAService.Encrypt(secretKey, false);
            byte[] token_enc = RSAService.Encrypt(token, false);
            byte[] key_len   = BitConverter.GetBytes((short)key_enc.Length); Array.Reverse(key_len);
            byte[] token_len = BitConverter.GetBytes((short)token_enc.Length); Array.Reverse(token_len);

            //Encryption Response packet
            byte[] packet_id                  = getVarInt(0x01);
            byte[] encryption_response        = concatBytes(packet_id, key_len, key_enc, token_len, token_enc);
            byte[] encryption_response_tosend = concatBytes(getVarInt(encryption_response.Length), encryption_response);
            Send(encryption_response_tosend);

            //Start client-side encryption
            s         = CryptoHandler.getAesStream(c.GetStream(), secretKey, this);
            encrypted = true;

            //Read and skip the next packet
            int  received_packet_size = readNextVarInt();
            int  received_packet_id   = readNextVarInt();
            bool encryption_success   = (received_packet_id == 0x02);

            if (received_packet_id == 0)
            {
                handler.OnConnectionLost(ChatBot.DisconnectReason.LoginRejected, ChatParser.ParseText(readNextString()));
            }
            else
            {
                readData(received_packet_size - getVarInt(received_packet_id).Length);
            }
            if (encryption_success)
            {
                StartUpdating();
            }
            return(encryption_success);
        }
        public bool SwitchToEncrypted(string serverID, byte[] Serverkey, byte[] token)
        {
            if (ServerData.OnlineMode)
            {
                var    crypto    = CryptoHandler.DecodeRSAPublicKey(Serverkey);
                byte[] secretKey = CryptoHandler.GenerateAESPrivateKey();
                byte[] key_enc   = crypto.Encrypt(secretKey, false);
                byte[] token_enc = crypto.Encrypt(token, false);
                //Console.WriteLine(key_enc.Length + " " + token_enc.Length);

                SendPacket(0x01, concatBytes(getArray(key_enc), getArray(token_enc)));

                this.s    = CryptoHandler.getAesStream(c.GetStream(), secretKey);
                encrypted = true;

                int         packetID   = -1;
                List <byte> packetData = new List <byte>();
                while (true)
                {
                    readNextPacket(ref packetID, packetData);
                    if (packetID == 0x00)
                    {
                        handler.OnConnectionLost(Conn.DisconnectReason.LoginRejected, readNextString(packetData));
                        return(false);
                    }
                    else if (packetID == 0x02)//Logined
                    {
                        Debug.Log("Login Success");
                        login_phase = false;
                        handler.OnLogin(packetData);
                        StartUpdating();
                        return(true);
                    }
                    else
                    {
                        if (packetID == 0x03 && login_phase)
                        {
                            if (protocolversion >= MCVersion.MC18Version)
                            {
                                compression_treshold = readNextVarInt(packetData);
                            }
                        }
                        handler.receivePacket(packetID, packetData);
                    }
                }
            }
            else
            {
                handler.OnConnectionLost(Conn.DisconnectReason.LoginRejected, ServerData.MsgEncryptReject);
            }
            return(false);
        }
        public static T LoadObject <T>(string filename)
        {
            string saveFolder = Directory.GetCurrentDirectory();
            string savePath   = Path.Combine(saveFolder, filename);

            if (!File.Exists(savePath))
            {
                File.Create(savePath);
            }

            string rawData = CryptoHandler.DecryptContent(File.ReadAllBytes(savePath));

            return(JsonConvert.DeserializeObject <T>(rawData));
        }
Exemple #20
0
        /// <summary>
        /// Initializes a new instance of OutPacket from the given payload data, crypto handler, auth handler, prefix and count.
        /// </summary>
        /// <param name="payload">The ready payload data.</param>
        /// <param name="crypto">The crypto handler to be used.</param>
        /// <param name="auth">The auth handler to be used.</param>
        /// <param name="prefix">The packet's prefix.</param>
        /// <param name="count">The packet's count.</param>
        public OutPacket(byte[] payload, CryptoHandler crypto, AuthHandler auth, short prefix, int count)
        {
            byte[] packetPrefix  = LittleEndian.GetBytes(prefix);
            byte[] packetCount   = LittleEndian.GetBytes(count);
            byte[] iv            = Generate.IV();
            byte[] encryptedData = crypto.EncryptPacket(payload, iv);

            byte[] size = LittleEndian.GetBytes(Convert.ToInt16(16 + encryptedData.Length + 10));

            byte[] authData = Sequence.Concat(packetPrefix, packetCount, iv, encryptedData);
            byte[] hmac     = auth.GetHmac(authData);

            PacketData = Sequence.Concat(size, authData, hmac);
        }
Exemple #21
0
        private static void LoadConfig(string filename, IDictionary <string, Type> algorithms, IDictionary <string, string> oid)
        {
            if (!File.Exists(filename))
            {
                return;
            }

            try {
                using (TextReader reader = new StreamReader(filename)) {
                    CryptoHandler  handler = new CryptoHandler(algorithms, oid);
                    SmallXmlParser parser  = new SmallXmlParser();
                    parser.Parse(reader, handler);
                }
            }
            catch {
            }
        }
        public static async Task <bool> SaveObject <T>(string filename, T classObject)
        {
            try
            {
                string saveFolder = Directory.GetCurrentDirectory();
                string savePath   = Path.Combine(saveFolder, filename);

                string rawData = await Task.Run(() => JsonConvert.SerializeObject(classObject));

                await Task.Run(() => File.WriteAllBytes(savePath, CryptoHandler.EncryptContent(rawData)));

                return(true);
            }
            catch
            {
                return(false);
            }
        }
        public void Send(byte[] data)
        {
            CryptoHandler Crypto = new CryptoHandler();
            AuthHandler   Auth   = new AuthHandler();

            Crypto.Key   = this.Hmac;
            Auth.HmacKey = this.IV;
            Random getRndm = new Random();

            this.prefix = (short)getRndm.Next(9999);
            this.count  = getRndm.Next(9999);
            Int16 sizePackage = Convert.ToInt16(data.Length - 12);

            byte[] size = new byte[2];
            size = BitConverter.GetBytes(sizePackage);
            Array.Reverse(size);
            Array.Copy(size, 0, data, 4, size.Length);
            byte[] opcode = new byte[2];
            Array.Copy(data, 0, opcode, 0, opcode.Length);
            Array.Resize(ref data, data.Length - 5);
            OutPacket GetPacket = new OutPacket(data, Crypto, Auth, prefix, count);

            this.socket.Send(GetPacket.PacketData, 0, GetPacket.PacketData.Length, 0);
        }
    /// <summary>
    /// Gets the next packet from the server
    /// </summary>
    /// <returns></returns>
    public PacketData ReadNextPacket()
    {
        int packetId;

        byte[] payload;

        lock (_streamReadLock)
        {
            int         length = VarInt.ReadNext(ReadBytes);
            List <byte> buffer = new List <byte>();

            // check if data is compressed
            if (_compressionThreshold >= 0)
            {
                int dataLength = VarInt.ReadNext(ReadBytes);
                length -= VarInt.GetBytes(dataLength).Length;                   // remove size of data length from rest of packet length
                if (dataLength != 0)
                {
                    byte[] compressedBuffer = ReadBytes(length);
                    buffer.AddRange(ZlibStream.UncompressBuffer(compressedBuffer));
                }
                else
                {
                    buffer.AddRange(ReadBytes(length));
                }
            }
            else
            {
                buffer.AddRange(ReadBytes(length));
            }

            packetId = VarInt.ReadNext(buffer);
            payload  = buffer.ToArray();
        }

        // handles some stuff during login phase
        if (State == ProtocolState.LOGIN)
        {
            // handle compression packet
            if (packetId == (int)ClientboundIDs.LogIn_SetCompression)
            {
                _compressionThreshold = VarInt.ReadNext(new List <byte>(payload));
                return(ReadNextPacket());
            }

            // handle protocol encryption packet
            if (packetId == (int)ClientboundIDs.LogIn_EncryptionRequest)
            {
                var encRequestPkt = new EncryptionRequestPacket()
                {
                    Payload = payload
                };

                var aesSecret = CryptoHandler.GenerateSharedSecret();
                var authHash  = CryptoHandler.SHAHash(Encoding.ASCII.GetBytes(encRequestPkt.ServerID).Concat(aesSecret, encRequestPkt.PublicKey));

                Debug.Log($"Sending hash to Mojang servers: {authHash}");

                // check session with mojang
                if (!MojangAPI.JoinServer(authHash))
                {
                    throw new UnityException("Invalid session. (Try restarting game or relogging into Minecraft account)");
                }

                // use pub key to encrypt shared secret
                using (var rsaProvider = CryptoHandler.DecodeRSAPublicKey(encRequestPkt.PublicKey))
                {
                    byte[] encSecret = rsaProvider.Encrypt(aesSecret, false);
                    byte[] encToken  = rsaProvider.Encrypt(encRequestPkt.VerifyToken, false);

                    // respond to server with private key
                    var responsePkt = new EncryptionResponsePacket()
                    {
                        SharedSecret = encSecret,
                        VerifyToken  = encToken
                    };
                    WritePacket(responsePkt);


                    // enable aes encryption
                    _aesStream = new AesStream(Client.GetStream(), aesSecret);
                    _encrypted = true;

                    // read the next packet
                    return(ReadNextPacket());
                }
            }
        }

        return(new PacketData
        {
            ID = packetId,
            Payload = payload
        });
    }
Exemple #25
0
 /// <summary>
 /// Initializes a new instance of InPacket from the given packet buffer and crypto handler.
 /// </summary>
 /// <param name="packetData">The packet buffer the way it was received.</param>
 /// <param name="cryptoHandler">The current crypto handler.</param>
 public InPacket(byte[] packetData, CryptoHandler cryptoHandler)
 {
     _packetData    = packetData;
     _cryptoHandler = cryptoHandler;
 }
 public static CryptoHandler GetInstance()
 {
     if (instance == null) { instance = new CryptoHandler(); }
     return instance;
 }
Exemple #27
0
	private static void LoadConfig (string filename, IDictionary<string,Type> algorithms, IDictionary<string,string> oid)
	{
		if (!File.Exists (filename))
			return;

		try {
			using (TextReader reader = new StreamReader (filename)) {
				CryptoHandler handler = new CryptoHandler (algorithms, oid);
				SmallXmlParser parser = new SmallXmlParser ();
				parser.Parse (reader, handler);
			}
		}
		catch {
		}
	}
Exemple #28
0
        public static void DisplayValues(byte[] input)                  // Get values from node config and display them
        {
            byte[] Key = hexToByte("2b7e151628aed2a6abf7158809cf4f3c"); //Convert the hex string to a byte array
            byte[] IV  = hexToByte("000102030405060708090a0b0c0d0e0f"); //Convert the hex string to a byte array

            CryptoHandler cryptoHandler = new CryptoHandler();

            byte[] data = cryptoHandler.Decrypt(input, Key, IV);

            int lastIndex = Array.FindLastIndex(data, b => b != 0);

            Array.Resize(ref data, lastIndex + 1);

            RLConfigPayload payload = RLConfigPayload.Parser.ParseFrom(data);

            string NodeID         = "Node ID (SN): " + payload.NodeID.ToString();
            string NetworkID      = "Network ID: " + payload.NetworkID.ToString();
            string NetworkChannel = "Network Channel: " + payload.NetworkChannel.ToString();
            string AppAreaID      = "Application Area ID: " + payload.ApplicationAreaID.ToString("X");
            string HardVer        = "Hardware Version: " + payload.HardwareVersion.ToString();
            string Softver        = "Software Version: " + payload.SoftwareVersion.Major.ToString() + "." + payload.SoftwareVersion.Devel.ToString() + "." + payload.SoftwareVersion.Maint.ToString() + "." + payload.SoftwareVersion.Minor.ToString();
            string MeshVer        = "Wirepas Version: " + payload.WirepasVersion.Major.ToString() + "." + payload.WirepasVersion.Devel.ToString() + "." + payload.WirepasVersion.Maint.ToString() + "." + payload.WirepasVersion.Minor.ToString();
            string NodeConfig     = payload.NodeConfiguration.ToString();

            string OperatingMode = "Operating Mode: ";

            switch (payload.OperatingMode)
            {
            case NodeOperatingMode.Run:
                OperatingMode = "Operating Mode: Run";
                break;

            case NodeOperatingMode.Inventory:
                OperatingMode = "Operating Mode: Inventory";
                break;
            }
            string HeadNodeRSSI = "Normalized Head Node RSSI: " + (Convert.ToDouble((payload.HeadNodeRSSI) / 254.0f) * 100.0f).ToString() + "%";
            string BatVoltage   = "Battery Voltage: " + (Convert.ToDouble(payload.BatteryVoltage) / 1000.0f).ToString() + " V";
            string GateConnect  = "Gateway Connected: " + (payload.GatewayConnected ? "Yes" : "No").ToString();
            string UplinkRate   = "Uplink Rate: " + payload.UplinkRate.ToString() + " Seconds";

            string DeviceRole = "Device Role: ";

            switch (payload.NodeRole)
            {
            case NodeRole.HeadnodeAnchor:
                DeviceRole = "Device Role: Router";
                break;

            case NodeRole.SubnodeTracked:
                DeviceRole = "Device Role: Leaf";
                break;
            }

            string AssetTrack = "Asset Tracking: " + (payload.AssetTrackingEnabled ? "Enabled" : "Disabled").ToString();

            string[] valueList = new string[] { NodeID, NetworkID, NetworkChannel, AppAreaID, HardVer, Softver, MeshVer, NodeConfig, OperatingMode, HeadNodeRSSI, BatVoltage, GateConnect, UplinkRate, DeviceRole, AssetTrack };

            ReadFromNode readValues = new ReadFromNode();

            readValues.DisplayValues(valueList); //Display the values
        }
        static void Main(string[] args)
        {
            var admin = new Administrator();

            if (args.Length == 0)
            {
                Console.WriteLine("Welcome to the School application \n");
                Console.WriteLine("Would you like to apply or check your application status? a to apply, c to check");
                Console.Write("> ");
                string response = Console.ReadLine();
                if (response == "c")
                {
                    Console.WriteLine("Enter your e-mail that you applied with.");
                    Console.Write("> ");
                    response = Console.ReadLine();
                    Client.CheckApplicantStatus(response);
                }
                else if (response == "a")
                {
                    Console.WriteLine("Enter your first name. (15 character length)");
                    Console.Write("> ");
                    string firstName = Console.ReadLine();
                    Console.WriteLine("Enter your last name. (20 character length)");
                    Console.Write("> ");
                    string lastName = Console.ReadLine();
                    Console.WriteLine("Enter your e-mail. (35 character length)");
                    Console.Write("> ");
                    string email = Console.ReadLine();
                    Console.WriteLine("Are you male, female, or other. (6 character length)");
                    Console.Write("> ");
                    string gender = Console.ReadLine();
                    Console.WriteLine("Enter what degree you are majoring in if you have a major, if not enter nothing. (20 character length)");
                    Console.Write("> ");
                    string major = Console.ReadLine();

                    // this is a mistake but I didnt want to do a check after EVERY INPUT
                    // it checks to make sure the strings arent empty or null
                    bool valueCheck = firstName != null && firstName != string.Empty && lastName != null &&
                                      lastName != string.Empty && email != null && email != string.Empty && gender != null;

                    // this checks the length of each string before it gets accepted and if its not it wont apply.
                    bool stringLengthCheck = firstName.Length <= 15 && lastName.Length <= 20 &&
                                             email.Length <= 35 && gender.Length <= 6 && major.Length <= 20;

                    if (valueCheck == true && stringLengthCheck == true)
                    {
                        Client.Apply(0, firstName, lastName, email, gender.ToUpper(), major);
                    }
                    else
                    {
                        Console.WriteLine("Length of input was too long, please try again..");
                    }
                }
                else
                {
                    Console.WriteLine($"{response} not valid..");
                }
            }
            else if (args.Length == 3) // this is section is for the admin and all the actions that the admin can perform
            {
                if (args[0] == "-a")
                {
                    if (admin.CheckPassword(Int32.Parse(args[1]), args[2]) == true)
                    {
                        Console.WriteLine("Logged in!");
                        bool loopCondition = true;
                        while (loopCondition)
                        {
                            Console.WriteLine("What would you like to do?");
                            Console.WriteLine("  1) Add new admin");
                            Console.WriteLine("  2) Expell student");
                            Console.WriteLine("  3) Accept student");
                            Console.WriteLine("  4) Reject applicant");
                            Console.WriteLine("  5) View all students");
                            Console.WriteLine("  6) View all applicants");
                            Console.WriteLine("  7) View all expelled students");
                            Console.WriteLine("  8) View all admins");
                            Console.WriteLine("  9) View expell reason");
                            Console.WriteLine("  10) View student by");
                            Console.WriteLine("  11) View applicant by");
                            Console.WriteLine("  12) View expelled student by");
                            Console.WriteLine("   Q) to exit");
                            Console.Write("> ");
                            string response = Console.ReadLine();
                            string name, password, reason, id;
                            bool   lengthCheck; // a boolean variable that will hold the comparison for each length for each method
                            int    numericId;
                            switch (response)
                            {
                            case "1":
                                while (true)
                                {
                                    Console.WriteLine("What is the name of the new admin? (15 character max length)");
                                    Console.Write("> ");
                                    name = Console.ReadLine();
                                    Console.WriteLine("What is the password of the new admin?");
                                    Console.Write("> ");
                                    password    = Console.ReadLine();
                                    lengthCheck = name.Length <= 15 && password.Length <= 65;
                                    if (lengthCheck == true)
                                    {
                                        var hashedPassword = CryptoHandler.SaltAndHashPassword(password);
                                        admin.NewAdmin(0, name, hashedPassword);
                                        break;
                                    }
                                    else
                                    {
                                        Console.WriteLine("Input was invalid please try again.");
                                        continue;
                                    }
                                }
                                break;

                            case "2":
                                while (true)
                                {
                                    Console.WriteLine("What is the ID of the student?");
                                    Console.Write("> ");
                                    id = Console.ReadLine();
                                    Console.WriteLine("What is the reason of expulsion?");
                                    Console.Write("> ");
                                    reason = Console.ReadLine();
                                    if (reason.Length <= 500 && int.TryParse(id, out numericId))
                                    {
                                        admin.ExpellStudent(numericId, reason);
                                        break;
                                    }
                                    else
                                    {
                                        if (reason.Length > 500)
                                        {
                                            Console.WriteLine("Reason length too long, reason length is 500 characters, please try again..");
                                        }
                                        if (int.TryParse(id, out numericId) == false)
                                        {
                                            Console.WriteLine($"Sorry, {id} is not a number.. Try again..");
                                        }
                                        continue;
                                    }
                                }
                                break;

                            case "3":
                                while (true)
                                {
                                    Console.WriteLine("What is the ID of the applicant?");
                                    Console.Write("> ");
                                    id = Console.ReadLine();
                                    if (int.TryParse(id, out numericId))
                                    {
                                        admin.AcceptApplicant(numericId);
                                        break;
                                    }
                                    else
                                    {
                                        Console.WriteLine($"Sorry, {id} is not a number.. Try again..");
                                        continue;
                                    }
                                }
                                break;

                            case "4":
                                while (true)
                                {
                                    Console.WriteLine("What is the student's ID?");
                                    Console.Write("> ");
                                    id = Console.ReadLine();
                                    // checks if the id is numeric or not and if it is it gets
                                    // parsed as an in and assigned to the numericId variable
                                    if (int.TryParse(id, out numericId))
                                    {
                                        admin.RejectApplicant(numericId);
                                        break;
                                    }
                                    else
                                    {
                                        Console.WriteLine($"Sorry, {id} is not a number.. Try again..");
                                        continue;
                                    }
                                }
                                break;

                            case "5":
                                admin.ViewStudents();
                                break;

                            case "6":
                                admin.ViewApplicants();
                                break;

                            case "7":
                                admin.ViewExpelledStudents();
                                break;

                            case "8":
                                admin.ViewAdmins();
                                break;

                            case "9":
                                Console.WriteLine("What is the student's ID?");
                                Console.Write("> ");
                                id = Console.ReadLine();
                                if (int.TryParse(id, out numericId))
                                {
                                    admin.ViewExpellReason(numericId);
                                }
                                else
                                {
                                    Console.WriteLine($"Sorry, {id} is not a number..");
                                }
                                break;

                            case "10":
                                switch (SortBy())
                                {
                                case "1":
                                    admin.ViewStudentsBy("firstname");
                                    break;

                                case "2":
                                    admin.ViewStudentsBy("lastname");
                                    break;

                                case "3":
                                    admin.ViewStudentsBy("email");
                                    break;

                                case "4":
                                    admin.ViewStudentsBy("gender");
                                    break;

                                case "5":
                                    admin.ViewStudentsBy("major");
                                    break;

                                default:
                                    Console.WriteLine("Input invalid.. please try again");
                                    break;
                                }
                                break;

                            case "11":
                                switch (SortBy())
                                {
                                case "1":
                                    admin.ViewApplicantsBy("firstname");
                                    break;

                                case "2":
                                    admin.ViewApplicantsBy("lastname");
                                    break;

                                case "3":
                                    admin.ViewApplicantsBy("email");
                                    break;

                                case "4":
                                    admin.ViewApplicantsBy("gender");
                                    break;

                                case "5":
                                    admin.ViewApplicantsBy("major");
                                    break;

                                default:
                                    Console.WriteLine("Input invalid.. please try again");
                                    break;
                                }
                                break;

                            case "12":
                                switch (SortBy())
                                {
                                case "1":
                                    admin.ViewExpelledStudentsBy("firstname");
                                    break;

                                case "2":
                                    admin.ViewExpelledStudentsBy("lastname");
                                    break;

                                case "3":
                                    admin.ViewExpelledStudentsBy("email");
                                    break;

                                case "4":
                                    admin.ViewExpelledStudentsBy("gender");
                                    break;

                                case "5":
                                    admin.ViewExpelledStudentsBy("major");
                                    break;

                                default:
                                    Console.WriteLine("Input invalid.. please try again");
                                    break;
                                }
                                break;

                            case "q":
                            case "Q":
                                loopCondition = false;     //exits program if input is "q" or "Q"
                                break;

                            default:
                                Console.WriteLine("Input invalid.. please try again");
                                break;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Password incorrect.. try again with proper credentials..");
                    }
                }
            }
            else
            {
                Console.WriteLine("Arguments invalid..");
            }
        }
Exemple #30
0
        public ClientSession(Socket socket) : base(socket)
        {
            Log.Inform("Cliente conectado.");

            IP = BitConverter.ToUInt32(IPAddress.Parse(GetIP()).GetAddressBytes(), 0);

            InitiateReceive(2, true);

            // Generate new security keys
            CryptoKey      = Generate.Key();
            _CryptoHandler = new CryptoHandler(CryptoKey);

            AuthKey      = Generate.Key();
            _AuthHandler = new AuthHandler(AuthKey);

            short TempPrefix = Generate.Prefix();

            try
            {
                PayloadWriter pWriter = new PayloadWriter();

                pWriter.WriteData(TempPrefix);
                pWriter.WriteData((int)8);
                pWriter.WriteData(_AuthHandler.HmacKey);
                pWriter.WriteData((int)8);
                pWriter.WriteData(_CryptoHandler.Key);

                byte[] plContent = { 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0, 0x00, 0x00, 0x00, 0x00, 0x00 };
                pWriter.WriteData(plContent);

                OutPacket oPacket = new OutPacket(pWriter.GetPayload(CenterOpcodes.SET_SECURITY_KEY_NOT), tempCryptoHandler,
                                                  tempAuthHandler, Prefix, ++Count);

                Send(oPacket);
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                Close();
            }

            Prefix = TempPrefix;

            try
            {
                PayloadWriter pWritter = new PayloadWriter();

                byte[] plContent = { 0x00, 0x00, 0x27, 0x10 };
                pWritter.WriteData(plContent);

                OutPacket oPacket = new OutPacket(pWritter.GetPayload(CenterOpcodes.ENU_WAIT_TIME_NOT), _CryptoHandler,
                                                  _AuthHandler, Prefix, ++Count);

                Send(oPacket);
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                Close();
            }
        }
Exemple #31
0
 /// <summary>
 /// Initializes a new instance of InPacket from the given packet buffer and crypto handler.
 /// </summary>
 /// <param name="packetBuffer">The packet buffer the way it was received.</param>
 /// <param name="crypto">The current crypto handler.</param>
 public InPacket(byte[] packetBuffer, CryptoHandler crypto)
 {
     PacketData    = packetBuffer;
     CryptoHandler = crypto;
 }