예제 #1
0
 /// <summary>
 /// BlowFish解密bytes
 /// </summary>
 /// <param name="decodeStr"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 public static byte[] BlowFishDecryptBytes(byte[] bytes, string key)
 {
     byte[] keys = ASCIIEncoding.ASCII.GetBytes(key);
     BlowFishCS.BlowFish blowFish = new BlowFishCS.BlowFish(keys);
     byte[] result = blowFish.Decrypt_ECB(bytes);
     return(result);
 }
예제 #2
0
        // -----------------------------------------------------------------------------------
        /// <summary>
        /// Loads the images for a given round
        /// </summary>
        public RoundImages LoadRound(int round)
        {
            if (round >= header.availableRounds)
            {
                throw new Exception(string.Concat("Tried to load round: ", round + 1, " but only ", header.availableRounds, " rounds are available"));
            }

            BinaryReader br = new BinaryReader(System.IO.File.Open(source, FileMode.Open));

            BlowFishCS.BlowFish blowfish = new BlowFishCS.BlowFish(IllogicGate.Data.EncryptedFile.RestoreKey(ShuffledKey));

            // read and decrypt the round image and shadow
            br.BaseStream.Seek(header.roundBase[round].offset, SeekOrigin.Begin);
            byte[] rawBase = br.ReadBytes(header.roundBase[round].length);
            rawBase = blowfish.Decrypt_ECB(rawBase);
            rawBase = LZMAtools.DecompressLZMAByteArrayToByteArray(rawBase);

            br.BaseStream.Seek(header.roundShadow[round].offset, SeekOrigin.Begin);
            byte[] rawShadow = br.ReadBytes(header.roundShadow[round].length);
            rawShadow = blowfish.Decrypt_ECB(rawShadow);
            rawShadow = LZMAtools.DecompressLZMAByteArrayToByteArray(rawShadow);

            br.Close();

            return(new RoundImages(rawBase, rawShadow, header.isPortrait[round]));
        }
예제 #3
0
        public static int meta_find_encrypted(byte[] binContent, string NeedData, int pos, byte[] DecKey, int version) //Для поиска в зашифрованных данных (обычно для поиска текстур)
        {
            int bufsz         = 128;                                                                                   //Размер буфера по умолчанию
            int result        = 0;
            int Max_scan_size = 2048;                                                                                  //Проверка только определённого участка

            bool IsFinding = true;

            BlowFishCS.BlowFish decBuf = new BlowFishCS.BlowFish(DecKey, version);


            if (pos > binContent.Length - 4)
            {
                pos = 4;                              //Начинать поиск после заголовка файла
            }
            while (IsFinding)
            {
                byte[] buffer = new byte[bufsz];
                buffer = new byte[bufsz];
                if (buffer.Length > binContent.Length - pos)
                {
                    bufsz  = binContent.Length - pos;
                    buffer = new byte[bufsz];
                }

                Array.Copy(binContent, pos, buffer, 0, bufsz);
                pos++;
                Max_scan_size--;

                byte[] checkBuffer = decBuf.Crypt_ECB(buffer, version, true);

                int bfPos = 0;     //Позиция в blowfish
                while (Methods.ConvertHexToString(checkBuffer, bfPos, NeedData.Length, MainMenu.settings.ASCII_N, 1) != NeedData)
                {
                    bfPos++;
                    if (Methods.ConvertHexToString(checkBuffer, bfPos, NeedData.Length, MainMenu.settings.ASCII_N, 1) == NeedData)
                    {
                        result    = bfPos + pos - 1;
                        IsFinding = false;
                    }
                    if ((bfPos + NeedData.Length + 1) > checkBuffer.Length)
                    {
                        break;
                    }
                }



                if ((pos >= binContent.Length) || (Max_scan_size < 0))
                {
                    result    = -1;
                    IsFinding = false;
                }
            }

            return(result);
        }
예제 #4
0
        // -----------------------------------------------------------------------------------
        /// <summary>
        /// Writes bytes to an encrypted file
        /// </summary>
        /// <param name="path">Path of the file</param>
        /// <param name="data">Binary data to save</param>
        /// <param name="shuffledKey">Optional encryption key (shuffled with Util.ShuffleKey)</param>
        public static void WriteBytes(string path, byte[] data, string shuffledKey = DefaultShuffledKey)
        {
            BlowFishCS.BlowFish blowfish = new BlowFishCS.BlowFish(RestoreKey(shuffledKey));
            data = blowfish.Encrypt_ECB(data);

            FileStream stream = new FileStream(path, FileMode.Create);

            stream.Write(data, 0, data.Length);
            stream.Close();
        }
예제 #5
0
        // --- Class Declaration ------------------------------------------------------------------------
        // -----------------------------------------------------------------------------------
        /// <summary>
        /// Reads bytes from an encrypted file
        /// </summary>
        /// <param name="path">Path of the file</param>
        /// <param name="shuffledKey">Optional encryption key (shuffled with Util.ShuffleKey)</param>
        /// <returns>A byte array with the decrypted data</returns>
        public static byte[] ReadBytes(string path, string shuffledKey = DefaultShuffledKey)
        {
            FileStream stream = new FileStream(path, FileMode.Open);

            byte [] data = new byte[stream.Length];
            stream.Read(data, 0, data.Length);
            stream.Close();

            BlowFishCS.BlowFish blowfish = new BlowFishCS.BlowFish(RestoreKey(shuffledKey));
            return(blowfish.Decrypt_ECB(data));
        }
예제 #6
0
        // -----------------------------------------------------------------------------------
        /// <summary>
        /// Loads and decrypts a character sheet from file
        /// </summary>
        void LoadCharacterSheet()
        {
            BinaryReader br = new BinaryReader(System.IO.File.Open(source, FileMode.Open));

            BlowFishCS.BlowFish blowfish = new BlowFishCS.BlowFish(IllogicGate.Data.EncryptedFile.RestoreKey(ShuffledKey));

            // read and decrypt the character sheet
            br.BaseStream.Seek(header.characterSheet.offset, SeekOrigin.Begin);
            byte[] rawData = br.ReadBytes(header.characterSheet.length);
            rawData = blowfish.Decrypt_ECB(rawData);
            rawData = LZMAtools.DecompressLZMAByteArrayToByteArray(rawData);
            br.Close();

            _characterSheet = new BaseSheet(rawData);
        }
예제 #7
0
        public static byte[] encryptLua(byte[] luaContent, byte[] key, bool newEngine, int version)
        {   //newEngine - игры, выпущенные с Tales From the Borderlands и переизданные на новом движке
            BlowFishCS.BlowFish DoEncLua = new BlowFishCS.BlowFish(key, version);
            byte[] header = new byte[4];

            byte[] checkHeader = new byte[4];
            Array.Copy(luaContent, 0, checkHeader, 0, 4);

            if (Encoding.ASCII.GetString(checkHeader) == "\x1bLua")
            {
                if (newEngine == true)
                {
                    header = Encoding.ASCII.GetBytes("\x1bLEn");
                    byte[] tempLua = new byte[luaContent.Length - 4];
                    Array.Copy(luaContent, 4, tempLua, 0, luaContent.Length - 4);
                    tempLua = DoEncLua.Crypt_ECB(tempLua, 7, false);
                    Array.Copy(header, 0, luaContent, 0, 4);
                    Array.Copy(tempLua, 0, luaContent, 4, tempLua.Length);
                }
                else
                {
                    luaContent = DoEncLua.Crypt_ECB(luaContent, version, false);
                }
            }
            else if ((Encoding.ASCII.GetString(checkHeader) != "\x1bLEn") && (Encoding.ASCII.GetString(checkHeader) != "\x1bLEo") &&
                     (Encoding.ASCII.GetString(checkHeader) != "\x1bLua"))
            {
                if (newEngine == true)
                {
                    header = Encoding.ASCII.GetBytes("\x1bLEo");
                    byte[] tempLua2 = new byte[luaContent.Length];
                    Array.Copy(luaContent, 0, tempLua2, 0, luaContent.Length);
                    tempLua2 = DoEncLua.Crypt_ECB(tempLua2, 7, false);

                    luaContent = new byte[tempLua2.Length + 4];
                    Array.Copy(header, 0, luaContent, 0, 4);
                    Array.Copy(tempLua2, 0, luaContent, 4, luaContent.Length - 4);
                }
                else
                {
                    luaContent = DoEncLua.Crypt_ECB(luaContent, version, false);
                }
            }

            return(luaContent);
        }
예제 #8
0
        /// <summary>
        /// 链接服务器
        /// </summary>
        /// <param name="host">服务器IP</param>
        /// <param name="port">服务器端口</param>
        public void Connect(string host, int port)
        {
            Debugger.Log("conn" + host + ":" + port);
#if blowfish
            _encryptBF = new BlowFishCS.BlowFish(Encoding.ASCII.GetBytes("#$youwillbedead#$"));
            _decryptBF = new BlowFishCS.BlowFish(Encoding.ASCII.GetBytes("#$youwillbefucked#$"));
#endif
            if (_recvQueue == null)
            {
                _recvQueue = new Queue <ProtocolItem>();//发送队列不能在这里初始化
            }
            else
            {
                _recvQueue.Clear();
            }

            if (_host != host)
            {
                _host = host;
            }

            if (_port != port)
            {
                _port = port;
            }

            try
            {
                _connThread = new Thread(new ThreadStart(ConnThread));
                StopCoroutine("CheckConnectedHandler");
                StartCoroutine("CheckConnectedHandler");
                _connThread.Start();
            }
            catch (Exception e)
            {
                Debugger.LogError("socket exception:" + e);
            }
        }
예제 #9
0
        public static byte[] decryptLua(byte[] luaContent, byte[] key, int version)
        {
            byte[] headerCheck = new byte[4];
            Array.Copy(luaContent, 0, headerCheck, 0, 4);
            BlowFishCS.BlowFish decLuaNew = new BlowFishCS.BlowFish(key, 7);
            byte[] tempLua;


            switch (Encoding.ASCII.GetString(headerCheck))
            {
            case "\x1bLEn":
                tempLua = new byte[luaContent.Length - 4];
                Array.Copy(luaContent, 4, tempLua, 0, luaContent.Length - 4);
                byte[] luaHeader = { 0x1B, 0x4C, 0x75, 0x61 };     //.Lua - начало заголовка

                tempLua = decLuaNew.Crypt_ECB(tempLua, 7, true);
                Array.Copy(luaHeader, 0, luaContent, 0, 4);
                Array.Copy(tempLua, 0, luaContent, 4, tempLua.Length);
                break;

            case "\x1bLEo":
                tempLua = new byte[luaContent.Length - 4];
                Array.Copy(luaContent, 4, tempLua, 0, luaContent.Length - 4);

                tempLua    = decLuaNew.Crypt_ECB(tempLua, 7, true);
                luaContent = new byte[tempLua.Length];
                Array.Copy(tempLua, 0, luaContent, 0, luaContent.Length);
                break;

            default:
                BlowFishCS.BlowFish decLua = new BlowFishCS.BlowFish(key, version);
                luaContent = decLua.Crypt_ECB(luaContent, version, true);
                break;
            }

            return(luaContent);
        }
예제 #10
0
 public byte[] encryptFunction(byte[] bytes, byte[] key, int archiveVersion)
 {
     BlowFishCS.BlowFish enc = new BlowFishCS.BlowFish(key, archiveVersion);
     Methods.meta_crypt(bytes, key, archiveVersion, false);
     return(enc.Crypt_ECB(bytes, archiveVersion, false));
 }
예제 #11
0
        public static int meta_crypt(byte[] file, byte[] key, int version_archive, bool decrypt)
        {
            uint file_type = 0;
            long i, block_size = 0, block_crypt = 0, block_clean = 0, blocks;

            int meta = 1;

            if (file.Length < 4)
            {
                return((int)file_type);
            }
            byte[] check_type = new byte[4];
            Array.Copy(file, 0, check_type, 0, 4);

            file_type = BitConverter.ToUInt32(check_type, 0);

            uint p = (uint)file.Length;
            uint l = p + (uint)file.Length;

            /*
             * block_size,
             * block_crypt
             * blocks_clean
             */
            switch (file_type)
            {
            case 0x4D545245: meta = 0; break;     //ERTM

            case 0x4D42494E: meta = 0; break;     //NIBM

            case 0xFB4A1764: block_size = 0x80; block_crypt = 0x20; block_clean = 0x50; break;

            case 0xEB794091: block_size = 0x80; block_crypt = 0x20; block_clean = 0x50; break;

            case 0x64AFDEFB: block_size = 0x80; block_crypt = 0x20; block_clean = 0x50; break;

            case 0x64AFDEAA: block_size = 0x100; block_crypt = 0x8; block_clean = 0x18; break;

            case 0x4D424553: block_size = 0x40; block_crypt = 0x40; block_clean = 0x64; break;     //SEBM

            default: meta = 0; break;
            }

            if (block_size != 0)
            {
                blocks = (file.Length - 4) / block_size;
                long   poz       = 0;
                byte[] temp_file = new byte[file.Length - 4];
                Array.Copy(file, 4, temp_file, 0, temp_file.Length);


                for (i = 0; i < blocks; i++)
                {
                    byte[] block = new byte[block_size];
                    Array.Copy(temp_file, poz, block, 0, block_size);

                    if (p >= l)
                    {
                        break;
                    }
                    if (i % block_crypt == 0)
                    {
                        BlowFishCS.BlowFish enc = new BlowFishCS.BlowFish(key, version_archive);
                        //block = enc.Crypt_ECB(block, version_archive, false);
                        block = enc.Crypt_ECB(block, version_archive, decrypt);
                        Array.Copy(block, 0, temp_file, poz, block.Length);
                    }
                    else if ((i % block_clean == 0) && (i > 0))
                    {
                        Array.Copy(block, 0, temp_file, poz, block.Length);
                    }
                    else
                    {
                        XorBlock(ref block, 0xff);
                        Array.Copy(block, 0, temp_file, poz, block.Length);
                    }

                    p   += (uint)block_size;
                    poz += block_size;
                }

                Array.Copy(temp_file, 0, file, 4, temp_file.Length);
            }

            return(meta);
        }
예제 #12
0
파일: NPAPI.cs 프로젝트: qwer2003tw/NTUTWin
        public static async Task LoginNPortal(string id, string password)
        {
            string captchaText;

            do
            {
                var captchaImage = await GetCaptchaImage();

                captchaText = await GetCaptchaText(captchaImage);
            } while (string.IsNullOrEmpty(captchaText) || captchaText.Length != 4);

            var BlowFish = new BlowFishCS.BlowFish(Encoding.UTF8.GetBytes(password));
            var md5Code  = BlowFish.Encrypt_ECB(id);

            var response = await Request("https://nportal.ntut.edu.tw/login.do", "POST", new Dictionary <string, object>()
            {
                { "muid", id },
                { "mpassword", password },
                { "authcode", captchaText },
                { "md5Code", md5Code }
            }, new Dictionary <string, object>()
            {
                { "User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36" },
                { "Referer", "https://nportal.ntut.edu.tw/index.do?thetime=" + TimeStamp }
            });

            string responseString = await ConvertStreamToString(await response.Content.ReadAsStreamAsync());

            response.Dispose();

            if (responseString.Contains("登入失敗"))
            {
                if (responseString.Contains("密碼錯誤"))
                {
                    throw new NPException("帳號密碼錯誤", ErrorType.WrongIdPassword);
                }
                else if (responseString.Contains("驗證碼"))
                {
                    await LoginNPortal(id, password); //Retry
                }
                else if (responseString.Contains("帳號已被鎖住"))
                {
                    throw new NPException("嘗試錯誤太多次,帳號已被鎖定10分鐘", ErrorType.AccountLocked);
                }
            }
            else if (!responseString.Contains("\"myPortal.do?thetime="))
            {
                throw new NPException("遇到不明的錯誤", ErrorType.Unknown);
            }

            //The folling 2 request will make the server allowing us to login sub-systems
            response = await Request("https://nportal.ntut.edu.tw/myPortalHeader.do");

            //responseString = await ConvertStreamToString(await response.Content.ReadAsStreamAsync());
            response.Dispose();
            response = await Request("https://nportal.ntut.edu.tw/aptreeBox.do");

            //responseString = await ConvertStreamToString(await response.Content.ReadAsStreamAsync());
            response.Dispose();

            //Login aps
            await LoginSubSystem("https://nportal.ntut.edu.tw/ssoIndex.do?apUrl=https://aps.ntut.edu.tw/course/tw/courseSID.jsp&apOu=aa_0010-&sso=true&datetime1=" + TimeStamp);

            //Login aps-stu
            await LoginSubSystem("https://nportal.ntut.edu.tw/ssoIndex.do?apUrl=https://aps-stu.ntut.edu.tw/StuQuery/LoginSID.jsp&apOu=aa_003&sso=big5&datetime1=" + TimeStamp);
        }
예제 #13
0
        public static string FindingDecrytKey(byte[] bytes, string TypeFile, ref byte[] KeyEnc, ref int version) //Ищем ключ расшифровки для файлов langdb, dlog и d3dtx
        {
            string result = null;

            byte[] decKey = null;

            byte[] CheckVersion = new byte[4];
            Array.Copy(bytes, 4, CheckVersion, 0, 4);

            if ((BitConverter.ToInt32(CheckVersion, 0) < 0) || (BitConverter.ToInt32(CheckVersion, 0) > 6))
            {
                if (KeyEnc != null)
                {
                    try
                    {
                        byte[] tmpFile = new byte[bytes.Length];
                        Array.Copy(bytes, 0, tmpFile, 0, bytes.Length);
                        Methods.meta_crypt(tmpFile, KeyEnc, version, true);
                        byte[] CheckVer = new byte[4];
                        Array.Copy(tmpFile, 4, CheckVer, 0, 4);

                        if ((BitConverter.ToInt32(CheckVer, 0) > 0) && (BitConverter.ToInt32(CheckVer, 0) < 6))
                        {
                            Array.Copy(tmpFile, 0, bytes, 0, bytes.Length);

                            if (TypeFile == "texture" || TypeFile == "font")
                            {
                                int TexturePosition = -1;
                                if (TypeFile == "texture")
                                {
                                    TexturePosition = FindStartOfStringSomething(bytes, 4, ".d3dtx") + 6;
                                }
                                else
                                {
                                    TexturePosition = FindStartOfStringSomething(bytes, 4, ".tga") + 4;
                                }

                                if (FindStartOfStringSomething(bytes, TexturePosition, "DDS ") == -1)
                                {
                                    int    DDSPos     = meta_find_encrypted(bytes, "DDS ", TexturePosition, KeyEnc, version);
                                    byte[] tempHeader = new byte[2048];
                                    if (tempHeader.Length > bytes.Length - DDSPos)
                                    {
                                        tempHeader = new byte[bytes.Length - DDSPos];
                                    }

                                    Array.Copy(bytes, DDSPos, tempHeader, 0, tempHeader.Length);
                                    BlowFishCS.BlowFish decHeader = new BlowFishCS.BlowFish(KeyEnc, version);
                                    tempHeader = decHeader.Crypt_ECB(tempHeader, version, true);
                                    Array.Copy(tempHeader, 0, bytes, DDSPos, tempHeader.Length);
                                }
                            }

                            result = "File successfully decrypted.";
                            return(result);
                        }
                    }
                    catch
                    {
                        KeyEnc = null; //I don't know why I did this...
                    }
                }

                for (int a = 0; a < MainMenu.gamelist.Count; a++)
                {
                    byte[] CheckVerOld = CheckVersion;           //Old encryption method (for versions 2-6)
                    byte[] tempFileOld = new byte[bytes.Length]; //A temporary file for old encryption method
                    byte[] CheckVerNew = CheckVersion;           //Newer encryption method (for versions 7-9)
                    byte[] tempFileNew = new byte[bytes.Length]; //A temporary file for newer encryption method

                    decKey = MainMenu.gamelist[a].key;

                    Array.Copy(bytes, 0, tempFileOld, 0, bytes.Length);
                    Array.Copy(bytes, 0, tempFileNew, 0, bytes.Length);

                    if (((BitConverter.ToInt32(CheckVerOld, 0) < 0) || BitConverter.ToInt32(CheckVerOld, 0) > 6) ||
                        (BitConverter.ToInt32(CheckVerNew, 0) < 0) || (BitConverter.ToInt32(CheckVerNew, 0) > 6))
                    {
                        Methods.meta_crypt(tempFileOld, decKey, 2, true);
                        CheckVerOld = new byte[4];
                        Array.Copy(tempFileOld, 4, CheckVerOld, 0, 4);
                        Methods.meta_crypt(tempFileNew, decKey, 7, true);
                        CheckVerNew = new byte[4];
                        Array.Copy(tempFileNew, 4, CheckVerNew, 0, 4);
                    }

                    if ((BitConverter.ToInt32(CheckVerOld, 0) > 0) && (BitConverter.ToInt32(CheckVerOld, 0) < 6))
                    {
                        Array.Copy(tempFileOld, 0, bytes, 0, bytes.Length);

                        if (TypeFile == "texture" || TypeFile == "font")
                        {
                            int TexturePosition = -1;
                            if (FindStartOfStringSomething(bytes, 4, "DDS ") == -1)// > bytes.Length - 100)
                            {
                                if (TypeFile == "texture")
                                {
                                    TexturePosition = FindStartOfStringSomething(bytes, 4, ".d3dtx") + 6;
                                }
                                else
                                {
                                    TexturePosition = FindStartOfStringSomething(bytes, 4, ".tga") + 4;
                                }


                                int    DDSPos     = meta_find_encrypted(bytes, "DDS ", TexturePosition, decKey, 2);
                                byte[] tempHeader = new byte[2048];
                                if (tempHeader.Length > bytes.Length - DDSPos)
                                {
                                    tempHeader = new byte[bytes.Length - DDSPos];
                                }

                                Array.Copy(bytes, DDSPos, tempHeader, 0, tempHeader.Length);
                                BlowFishCS.BlowFish decHeader = new BlowFishCS.BlowFish(decKey, 2);
                                tempHeader = decHeader.Crypt_ECB(tempHeader, 2, true);
                                Array.Copy(tempHeader, 0, bytes, DDSPos, tempHeader.Length);
                            }
                        }

                        result  = "Decryption key: " + MainMenu.gamelist[a].gamename + ". Blowfish type: old (versions 2-6)";
                        KeyEnc  = MainMenu.gamelist[a].key;
                        version = 2;
                        break;
                    }
                    else if ((BitConverter.ToInt32(CheckVerNew, 0) > 0) && (BitConverter.ToInt32(CheckVerNew, 0) < 6))
                    {
                        Array.Copy(tempFileNew, 0, bytes, 0, bytes.Length);

                        if (TypeFile == "texture" || TypeFile == "font")
                        {
                            int TexturePosition = -1;

                            if (TypeFile == "texture")
                            {
                                TexturePosition = FindStartOfStringSomething(bytes, 4, ".d3dtx") + 6;
                            }
                            else
                            {
                                TexturePosition = FindStartOfStringSomething(bytes, 4, ".tga") + 4;
                            }

                            if (FindStartOfStringSomething(bytes, TexturePosition, "DDS ") == -1)//> bytes.Length - 100)
                            {
                                int    DDSPos     = meta_find_encrypted(bytes, "DDS ", TexturePosition, decKey, 7);
                                byte[] tempHeader = new byte[2048];
                                if (tempHeader.Length > bytes.Length - DDSPos)
                                {
                                    tempHeader = new byte[bytes.Length - DDSPos];
                                }

                                Array.Copy(bytes, DDSPos, tempHeader, 0, tempHeader.Length);
                                BlowFishCS.BlowFish decHeader = new BlowFishCS.BlowFish(decKey, 7);
                                tempHeader = decHeader.Crypt_ECB(tempHeader, 7, true);
                                Array.Copy(tempHeader, 0, bytes, DDSPos, tempHeader.Length);
                            }
                        }

                        result  = "Decryption key: " + MainMenu.gamelist[a].gamename + ". Blowfish type: new (versions 7-9)";
                        KeyEnc  = MainMenu.gamelist[a].key;
                        version = 7;
                        break;
                    }
                }
            }
            else //Check dds header only file
            {
                if ((TypeFile == "texture" || TypeFile == "font") && KeyEnc != null)
                {
                    try
                    {
                        int DDSstart = -1;
                        if (TypeFile == "texture")
                        {
                            DDSstart = FindStartOfStringSomething(bytes, 4, ".d3dtx") + 6;
                        }
                        else
                        {
                            DDSstart = FindStartOfStringSomething(bytes, 4, ".tga") + 4;
                        }

                        int DDSPos = meta_find_encrypted(bytes, "DDS ", DDSstart, KeyEnc, version);

                        if ((DDSPos != -1) && (DDSPos < (bytes.Length - 100)))
                        {
                            byte[] tempHeader = new byte[2048];
                            if (tempHeader.Length > bytes.Length - DDSPos)
                            {
                                tempHeader = new byte[bytes.Length - DDSPos];
                            }

                            Array.Copy(bytes, DDSPos, tempHeader, 0, tempHeader.Length);
                            BlowFishCS.BlowFish decHeader = new BlowFishCS.BlowFish(KeyEnc, version);
                            tempHeader = decHeader.Crypt_ECB(tempHeader, version, true);
                            Array.Copy(tempHeader, 0, bytes, DDSPos, tempHeader.Length);
                            DDSstart = DDSPos;

                            result = "File successfully decrypted.";
                            return(result);
                        }
                    }
                    catch
                    {
                        KeyEnc = null;
                    }
                }
                try
                {
                    if (TypeFile == "texture" || TypeFile == "font")
                    {
                        int DDSstart = -1;
                        if (TypeFile == "texture")
                        {
                            DDSstart = FindStartOfStringSomething(bytes, 4, ".d3dtx") + 6;
                        }
                        else
                        {
                            DDSstart = FindStartOfStringSomething(bytes, 4, ".tga") + 4;
                        }

                        for (int i = 0; i < MainMenu.gamelist.Count; i++)
                        {
                            int DDSPos = meta_find_encrypted(bytes, "DDS ", DDSstart, MainMenu.gamelist[i].key, 2);

                            if ((DDSPos != -1) && (DDSPos < (bytes.Length - 100)))
                            {
                                byte[] tempHeader = new byte[2048];
                                if (tempHeader.Length > bytes.Length - DDSPos)
                                {
                                    tempHeader = new byte[bytes.Length - DDSPos];
                                }

                                Array.Copy(bytes, DDSPos, tempHeader, 0, tempHeader.Length);
                                BlowFishCS.BlowFish decHeader = new BlowFishCS.BlowFish(MainMenu.gamelist[i].key, 2);
                                tempHeader = decHeader.Crypt_ECB(tempHeader, 2, true);
                                Array.Copy(tempHeader, 0, bytes, DDSPos, tempHeader.Length);
                                DDSstart = DDSPos;

                                result = "Decryption key: " + MainMenu.gamelist[i].gamename + ". Blowfish type: old (versions 2-6)";
                                KeyEnc = MainMenu.gamelist[i].key;

                                break;
                            }
                        }

                        if (DDSstart == -1)
                        {
                            for (int i = 0; i < MainMenu.gamelist.Count; i++)
                            {
                                int DDSPos = meta_find_encrypted(bytes, "DDS ", DDSstart, MainMenu.gamelist[i].key, 7);

                                if ((DDSPos != -1) && (DDSPos < (bytes.Length - 100)))
                                {
                                    byte[] tempHeader = new byte[2048];
                                    if (tempHeader.Length > bytes.Length - DDSPos)
                                    {
                                        tempHeader = new byte[bytes.Length - DDSPos];
                                    }

                                    Array.Copy(bytes, DDSPos, tempHeader, 0, tempHeader.Length);
                                    BlowFishCS.BlowFish decHeader = new BlowFishCS.BlowFish(MainMenu.gamelist[i].key, 7);
                                    tempHeader = decHeader.Crypt_ECB(tempHeader, 7, true);
                                    Array.Copy(tempHeader, 0, bytes, DDSPos, tempHeader.Length);
                                    DDSstart = DDSPos;

                                    result = "Decryption key: " + MainMenu.gamelist[i].gamename + ". Blowfish type: new (versions 7-9)";
                                    KeyEnc = MainMenu.gamelist[i].key;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    result = "Error " + ex.Message;
                }
            }

            return(result);
        }
예제 #14
0
 /// <summary>
 /// Cifra con BlowFish
 /// </summary>
 /// <param name="Text"></param>
 /// <param name="Key"></param>
 /// <returns></returns>
 private string EncryptString(string Text, string Key)
 {
     BlowFishCS.BlowFish crypt = new BlowFishCS.BlowFish(Key);
     return(crypt.Encrypt_CBC(Text));
 }
예제 #15
0
 /// <summary>
 /// 构建加密属性,并指定相应的加密KEY
 /// </summary>
 /// <param name="key">加密KEY</param>
 public StringCrypto(string key)
 {
     mBlowfish = new BlowFishCS.BlowFish(key);
 }
예제 #16
0
 /// <summary>
 /// 构建加密属性
 /// </summary>
 public StringCrypto()
 {
     mBlowfish = new BlowFishCS.BlowFish(BlowfishKey);
 }
예제 #17
0
        // -----------------------------------------------------------------------------------
#if UNITY_EDITOR
        /// <summary>
        /// Creates a file with the character sheet and each round image
        /// Only available in editor mode
        /// encrypting them separately
        /// </summary>
        /// <param name="filename">File to save to</param>
        /// <param name="guid"> Unique id to identify the character </param>
        /// <param name="tags"> comma separated tags, like IB </param>
        /// <param name="charSheetFile"> PNG file with the character sheet </param>
        /// <param name="roundFiles"> PNG files for each round (base, shadow) </param>
        /// <param name="updateFile"> File to update. If null, a new one is created </param>
        public static void CreateFile(string filename, string guid, string characterName, string artist, string tags, string charSheetFile, List <string[]> roundFiles, File updateFile = null)
        {
            string tempFile = Application.temporaryCachePath + "/temp_charfile.chr";

            // count the number of available rounds
            int availableRounds = updateFile != null ? updateFile.availableRounds : 0;

            for (int i = availableRounds; i < Config.Rounds; i++)
            {
                // can only add extra rounds in this version
                // not remove or leave empty gaps. So, only increase count
                // if a new one is added, otherwise keep previous count
                if (roundFiles[i] != null)
                {
                    availableRounds++;
                }
            }

            // ----- Validation check -----
            // the update file is null, so all other png files must exist and be set
            string errors = "";

            if (updateFile == null)
            {
                if (string.IsNullOrEmpty(charSheetFile))
                {
                    errors += "You must set the character sheet file\n";
                }
                if (availableRounds == 0)
                {
                    errors += "Set at least one round file!\n";
                }

                // make sure we don't leave empty holes
                for (int i = 0; i < availableRounds; i++)
                {
                    if (string.IsNullOrEmpty(roundFiles[i][0]))
                    {
                        errors += string.Format("You must set the base image file for round {0}\n", i + 1);
                    }
                    if (string.IsNullOrEmpty(roundFiles[i][1]))
                    {
                        errors += string.Format("You must set the shadow image file for round {0}\n", i + 1);
                    }
                }
            }

            // no need to continue at this point
            if (!string.IsNullOrEmpty(errors))
            {
                throw new Exception(errors);
            }

            // ----- File creation -----
            BinaryWriter bw = new BinaryWriter(System.IO.File.Open(tempFile, FileMode.Create));

            BlowFishCS.BlowFish blowfish = new BlowFishCS.BlowFish(IllogicGate.Data.EncryptedFile.RestoreKey(ShuffledKey));


            // save an empty header to make space for it
            Header header = new Header(Version1, guid);

            header.availableRounds = availableRounds;
            header.tags            = tags;
            header.artist          = artist;
            header.characterName   = characterName;
            // if we're updating, keep creation date
            if (updateFile != null)
            {
                header.createdDate = updateFile.header.createdDate;
            }
            header.Save(bw);

            byte[] data;

            // encrypt and save the character sheet file
            if (string.IsNullOrEmpty(charSheetFile))
            {
                data = updateFile.baseSheet.source.GetRawTextureData();
            }
            else
            {
                data = GetRawTextureData(charSheetFile);
            }
            data = LZMAtools.CompressByteArrayToLZMAByteArray(data);
            data = blowfish.Encrypt_ECB(data);
            header.characterSheet = new Entry((int)bw.BaseStream.Position, data.Length);
            bw.Write(data);

            // encrypt and save round images
            int         img_w, img_h;
            Orientation orientation;

            for (int i = 0; i < header.availableRounds; i++)
            {
                // load original images if available
                RoundImages original = null;
                if (updateFile != null && i < updateFile.availableRounds)
                {
                    original = updateFile.LoadRound(i);
                }

                // just copy the image from the previously loaded character file
                if (roundFiles[i] == null)
                {
                    data  = original.baseImage.GetRawTextureData();
                    img_w = original.baseImage.width;
                    img_h = original.baseImage.height;
                }
                // load from file
                else
                {
                    data = GetRawTextureData(roundFiles[i][0], out img_w, out img_h);
                }

                orientation = CheckOrientation(img_w, img_h);
                if (orientation == Orientation.Invalid)
                {
                    throw new Exception("Invalid image size for base image " + (i + 1));
                }

                data = LZMAtools.CompressByteArrayToLZMAByteArray(data);
                data = blowfish.Encrypt_ECB(data);
                header.roundBase[i] = new Entry((int)bw.BaseStream.Position, data.Length);
                bw.Write(data);


                // just copy the image from the previously loaded character file
                if (roundFiles[i] == null)
                {
                    data  = original.shadowImage.GetRawTextureData();
                    img_w = original.shadowImage.width;
                    img_h = original.shadowImage.height;
                }
                // load from file
                else
                {
                    data = GetRawTextureData(roundFiles[i][1], out img_w, out img_h, true);
                }

                orientation = CheckOrientation(img_w, img_h);
                if (orientation == Orientation.Invalid)
                {
                    throw new Exception("Invalid image size for shadow image " + (i + 1));
                }


                data = LZMAtools.CompressByteArrayToLZMAByteArray(data);
                data = blowfish.Encrypt_ECB(data);
                header.roundShadow[i] = new Entry((int)bw.BaseStream.Position, data.Length);
                bw.Write(data);

                header.isPortrait[i] = orientation == Orientation.Portrait;
            }

            // rewind and overwrite header
            bw.Seek(0, SeekOrigin.Begin);
            header.Save(bw);

            bw.Close();

            // replace files
            if (System.IO.File.Exists(filename))
            {
                System.IO.File.Delete(filename);
            }
            System.IO.File.Move(tempFile, filename);
        }
예제 #18
0
        public static string FindingDecrytKey(byte[] bytes, string TypeFile) //Ищем ключ расшифровки для файлов langdb, dlog и d3dtx
        {
            string result = null;

            byte[] decKey;

            byte[] CheckVersion = new byte[4];
            Array.Copy(bytes, 4, CheckVersion, 0, 4);

            if ((BitConverter.ToInt32(CheckVersion, 0) < 0) || (BitConverter.ToInt32(CheckVersion, 0) > 6))
            {
                for (int a = 0; a < MainMenu.gamelist.Count; a++)
                {
                    byte[] CheckVerOld = CheckVersion;           //Старый метод шифрования (Версии 2-6)
                    byte[] tempFileOld = new byte[bytes.Length]; //Временный файл для расшифровки (старый метод шифрования)
                    byte[] CheckVerNew = CheckVersion;           //Поновее метод шифрования (Версии 7-9)
                    byte[] tempFileNew = new byte[bytes.Length];

                    decKey = MainMenu.gamelist[a].key;

                    Array.Copy(bytes, 0, tempFileOld, 0, bytes.Length);
                    Array.Copy(bytes, 0, tempFileNew, 0, bytes.Length);

                    if (((BitConverter.ToInt32(CheckVerOld, 0) < 0) || BitConverter.ToInt32(CheckVerOld, 0) > 6) ||
                        (BitConverter.ToInt32(CheckVerNew, 0) < 0) || (BitConverter.ToInt32(CheckVerNew, 0) > 6))
                    {
                        Methods.meta_crypt(tempFileOld, decKey, 2, true);
                        CheckVerOld = new byte[4];
                        Array.Copy(tempFileOld, 4, CheckVerOld, 0, 4);
                        Methods.meta_crypt(tempFileNew, decKey, 7, true);
                        CheckVerNew = new byte[4];
                        Array.Copy(tempFileNew, 4, CheckVerNew, 0, 4);
                    }

                    if ((BitConverter.ToInt32(CheckVerOld, 0) > 0) && (BitConverter.ToInt32(CheckVerOld, 0) < 6))
                    {
                        Array.Copy(tempFileOld, 0, bytes, 0, bytes.Length);

                        if (TypeFile == "texture" || TypeFile == "font")
                        {
                            int TexturePosition = -1;
                            if (FindStartOfStringSomething(bytes, 4, "DDS ") > bytes.Length - 100)
                            {
                                if (TypeFile == "texture")
                                {
                                    TexturePosition = FindStartOfStringSomething(bytes, 4, ".d3dtx") + 6;
                                }
                                else
                                {
                                    TexturePosition = FindStartOfStringSomething(bytes, 4, ".tga") + 4;
                                }


                                int    DDSPos     = meta_find_encrypted(bytes, "DDS ", TexturePosition, decKey, 2);
                                byte[] tempHeader = new byte[2048];
                                if (tempHeader.Length > bytes.Length - DDSPos)
                                {
                                    tempHeader = new byte[bytes.Length - DDSPos];
                                }

                                Array.Copy(bytes, DDSPos, tempHeader, 0, tempHeader.Length);
                                BlowFishCS.BlowFish decHeader = new BlowFishCS.BlowFish(decKey, 2);
                                tempHeader = decHeader.Crypt_ECB(tempHeader, 2, true);
                                Array.Copy(tempHeader, 0, bytes, DDSPos, tempHeader.Length);
                            }
                        }

                        result = "Decryption key: " + MainMenu.gamelist[a].gamename + ". Blowfish type: old (versions 2-6)";
                        break;
                    }
                    else if ((BitConverter.ToInt32(CheckVerNew, 0) > 0) && (BitConverter.ToInt32(CheckVerNew, 0) < 6))
                    {
                        Array.Copy(tempFileNew, 0, bytes, 0, bytes.Length);

                        if (TypeFile == "texture" || TypeFile == "font")
                        {
                            int TexturePosition = -1;
                            if (FindStartOfStringSomething(bytes, 4, "DDS ") > bytes.Length - 100)
                            {
                                if (TypeFile == "texture")
                                {
                                    TexturePosition = FindStartOfStringSomething(bytes, 4, ".d3dtx") + 6;
                                }
                                else
                                {
                                    TexturePosition = FindStartOfStringSomething(bytes, 4, ".tga") + 4;
                                }

                                int    DDSPos     = meta_find_encrypted(bytes, "DDS ", TexturePosition, decKey, 7);
                                byte[] tempHeader = new byte[2048];
                                if (tempHeader.Length > bytes.Length - DDSPos)
                                {
                                    tempHeader = new byte[bytes.Length - DDSPos];
                                }

                                Array.Copy(bytes, DDSPos, tempHeader, 0, tempHeader.Length);
                                BlowFishCS.BlowFish decHeader = new BlowFishCS.BlowFish(decKey, 7);
                                tempHeader = decHeader.Crypt_ECB(tempHeader, 7, true);
                                Array.Copy(tempHeader, 0, bytes, DDSPos, tempHeader.Length);
                            }
                        }

                        result = "Decryption key: " + MainMenu.gamelist[a].gamename + ". Blowfish type: new (versions 7-9)";
                        break;
                    }
                }
            }
            else //Проверка файлов, в которых зашифрован только заголовок DDS-текстуры
            {
                try
                {
                    if (TypeFile == "texture" || TypeFile == "font")
                    {
                        int DDSstart = -1;
                        //Пока что придумал сделать авторасшифровку для одиночных текстур. Да и вроде шрифты были зашифрованы с 1 текстурой.
                        if (TypeFile == "texture")
                        {
                            DDSstart = FindStartOfStringSomething(bytes, 4, ".d3dtx") + 6;
                        }
                        else
                        {
                            DDSstart = FindStartOfStringSomething(bytes, 4, ".tga") + 4;
                        }

                        for (int i = 0; i < MainMenu.gamelist.Count; i++)
                        {
                            int DDSPos = meta_find_encrypted(bytes, "DDS ", DDSstart, MainMenu.gamelist[i].key, 2);

                            if ((DDSPos != -1) && (DDSPos < (bytes.Length - 100)))
                            {
                                byte[] tempHeader = new byte[2048];
                                if (tempHeader.Length > bytes.Length - DDSPos)
                                {
                                    tempHeader = new byte[bytes.Length - DDSPos];
                                }

                                Array.Copy(bytes, DDSPos, tempHeader, 0, tempHeader.Length);
                                BlowFishCS.BlowFish decHeader = new BlowFishCS.BlowFish(MainMenu.gamelist[i].key, 2);
                                tempHeader = decHeader.Crypt_ECB(tempHeader, 2, true);
                                Array.Copy(tempHeader, 0, bytes, DDSPos, tempHeader.Length);
                                DDSstart = DDSPos;

                                result = "Decryption key: " + MainMenu.gamelist[i].gamename + ". Blowfish type: old (versions 2-6)";
                            }
                        }

                        if (DDSstart == -1)
                        {
                            for (int i = 0; i < MainMenu.gamelist.Count; i++)
                            {
                                int DDSPos = meta_find_encrypted(bytes, "DDS ", DDSstart, MainMenu.gamelist[i].key, 7);

                                if ((DDSPos != -1) && (DDSPos < (bytes.Length - 100)))
                                {
                                    byte[] tempHeader = new byte[2048];
                                    if (tempHeader.Length > bytes.Length - DDSPos)
                                    {
                                        tempHeader = new byte[bytes.Length - DDSPos];
                                    }

                                    Array.Copy(bytes, DDSPos, tempHeader, 0, tempHeader.Length);
                                    BlowFishCS.BlowFish decHeader = new BlowFishCS.BlowFish(MainMenu.gamelist[i].key, 7);
                                    tempHeader = decHeader.Crypt_ECB(tempHeader, 7, true);
                                    Array.Copy(tempHeader, 0, bytes, DDSPos, tempHeader.Length);
                                    DDSstart = DDSPos;

                                    result = "Decryption key: " + MainMenu.gamelist[i].gamename + ". Blowfish type: new (versions 7-9)";
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    result = "Error " + ex.Message;
                }
            }

            return(result);
        }
예제 #19
0
        public string CalculatePasswordHash(string password)
        {
            BlowFishCS.BlowFish b = new BlowFishCS.BlowFish(salt);

            return(b.Encrypt_ECB(password));
        }
예제 #20
0
 /// <summary>
 /// 构建加密属性,并指定相应的加密KEY
 /// </summary>
 /// <param name="key">加密KEY</param>
 public StringCrypto(string key)
 {
     mBlowfish = new BlowFishCS.BlowFish(key);
 }
예제 #21
0
 /// <summary>
 /// 构建加密属性
 /// </summary>
 public StringCrypto()
 {
     mBlowfish = new BlowFishCS.BlowFish(BlowfishKey);
 }