private static void DecryptArchiveSave(KIFHDR hdr, List <KIFENTRY> entries, uint tocSeed, uint fileKey,
                                               Blowfish blowfish, int keyIndex, Stream inStream, Stream outStream, KifintProgressArgs progress,
                                               KifintProgressCallback callback)
        {
            BinaryReader reader = new BinaryReader(inStream);
            BinaryWriter writer = new BinaryWriter(outStream);

            const int ProgressThreshold = 1;

            progress.EntryName  = null;
            progress.EntryIndex = 0;
            progress.EntryCount = entries.Count;

            // Decrypt the KIFINT entries using the file key
            for (uint i = 0; i < hdr.EntryCount; i++, progress.EntryIndex++)
            {
                if (unchecked ((int)i) == keyIndex)
                {
                    continue;
                }

                KIFENTRY entry = entries[unchecked ((int)i)];

                // Give the entry the correct name
                UnobfuscateFileName(entry.FileNameRaw, unchecked (tocSeed + i));
                // Apply the extra offset to be decrypted
                entry.Offset += i;
                // Decrypt the entry's length and offset
                blowfish.Decrypt(ref entry.Info);

                progress.EntryName = entry.FileName;
                if (i % ProgressThreshold == 0 || i + 1 == hdr.EntryCount)
                {
                    callback?.Invoke(progress);
                }

                // Goto the entry's decrypted offset, read the buffer, then decrypt it
                inStream.Position = entry.Offset;
                byte[] buffer = reader.ReadBytes(entry.Length);
                blowfish.Decrypt(buffer, entry.Length & ~7);

                // Move to the entry's offset in the output stream and write the buffer
                outStream.Position = entry.Offset;
                writer.Write(buffer);

                // Make sure to reassign the entry to the list, because
                // it's not an array and does not return struct references.
                entries[unchecked ((int)i)] = entry;
            }

            entries.RemoveAt(keyIndex);
            hdr.EntryCount--;

            outStream.Position = 0;
            writer.WriteUnmanaged(hdr);
            writer.WriteUnmanagedArray(entries);
        }
        private static string[] IdentifyFileTypes(Stream stream, string kifintPath, string vcode2)
        {
            BinaryReader reader = new BinaryReader(stream);
            KIFHDR       hdr    = reader.ReadUnmanaged <KIFHDR>();

            if (hdr.Signature != "KIF")             // It's really a KIF INT file
            {
                throw new UnexpectedFileTypeException(kifintPath, "KIF");
            }

            KIFENTRY[] entries = reader.ReadUnmanagedArray <KIFENTRY>(hdr.EntryCount);

            uint tocSeed = GenTocSeed(vcode2);
            uint fileKey = 0;
            bool decrypt = false;

            // Obtain the decryption file key if one exists
            for (int i = 0; i < hdr.EntryCount; i++)
            {
                if (entries[i].FileName == "__key__.dat")
                {
                    fileKey = MersenneTwister.GenRand(entries[i].Length);
                    decrypt = true;
                    break;
                }
            }

            HashSet <string> extensions = new HashSet <string>();

            // Decrypt the KIFINT entries using the file key
            if (decrypt)
            {
                for (uint i = 0; i < hdr.EntryCount; i++)
                {
                    if (entries[i].FileName == "__key__.dat")
                    {
                        continue;
                    }
                    // Give the entry the correct name
                    UnobfuscateFileName(entries[i].FileNameRaw, tocSeed + i);
                }
            }
            for (uint i = 0; i < hdr.EntryCount; i++)
            {
                string entryFileName = entries[i].FileName;
                if (entryFileName == "__key__.dat")
                {
                    continue;
                }
                extensions.Add(Path.GetExtension(entryFileName));
            }

            return(extensions.ToArray());
        }
        /// <summary>
        ///  Decrypts the KIFINT archives using the known archive type, install directory, and name of executable with
        ///  the V_CODE2 used to decrypt.
        /// </summary>
        /// <param name="type">The type of archive to look for and decrypt.</param>
        /// <param name="stream">The stream to the open KIFINT archive.</param>
        /// <param name="installDir">The installation directory for both the archives and executable.</param>
        /// <param name="exePath">The path to the executable to extract the V_CODE2 key from.</param>
        /// <returns>The <see cref="KifintLookup"/> merged with all loaded archives.</returns>
        ///
        /// <exception cref="ArgumentNullException">
        ///  <paramref name="stream"/>, <paramref name="kifintPath"/>, or <paramref name="exePath"/> is null.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        ///  The <paramref name="stream"/> is closed.
        /// </exception>
        private static Kifint Decrypt(KifintType type, Stream stream, string kifintPath, string vcode2,
                                      KifintProgressArgs progress, KifintProgressCallback callback)
        {
            if (kifintPath == null)
            {
                throw new ArgumentNullException(nameof(kifintPath));
            }
            if (vcode2 == null)
            {
                throw new ArgumentNullException(nameof(vcode2));
            }

            BinaryReader reader = new BinaryReader(stream);
            KIFHDR       hdr    = reader.ReadUnmanaged <KIFHDR>();

            if (hdr.Signature != "KIF")             // It's really a KIF INT file
            {
                throw new UnexpectedFileTypeException(kifintPath, "KIF");
            }

            KIFENTRY[] entries = reader.ReadUnmanagedArray <KIFENTRY>(hdr.EntryCount);

            progress.EntryIndex = 0;
            progress.EntryCount = entries.Length;

            uint tocSeed = GenTocSeed(vcode2);
            uint fileKey = 0;
            bool decrypt = false;

            // Obtain the decryption file key if one exists
            for (int i = 0; i < hdr.EntryCount; i++)
            {
                if (entries[i].FileName == "__key__.dat")
                {
                    fileKey = MersenneTwister.GenRand(entries[i].Length);
                    decrypt = true;
                    break;
                }
            }

            const int ProgressThreshold = 500;

            // Decrypt the KIFINT entries using the file key
            if (decrypt)
            {
                for (uint i = 0; i < hdr.EntryCount; i++)
                {
                    if (entries[i].FileName == "__key__.dat")
                    {
                        continue;
                    }

                    progress.EntryIndex++;
                    if (i % ProgressThreshold == 0)
                    {
                        callback?.Invoke(progress);
                    }

                    // Give the entry the correct name
                    UnobfuscateFileName(entries[i].FileNameRaw, tocSeed + i);
                    // Give apply the extra offset to be decrypted
                    entries[i].Offset += i;
                    // Decrypt the entry's length and offset
                    DecryptEntry(ref entries[i].Info, fileKey);
                }
            }

            return(new Kifint(kifintPath, entries, decrypt, fileKey, type));
        }
        /// <summary>
        ///  Decrypts the KIFINT archives using the known archive type, install directory, and name of executable with
        ///  the V_CODE2 used to decrypt.
        /// </summary>
        /// <param name="type">The type of archive to look for and decrypt.</param>
        /// <param name="stream">The stream to the open KIFINT archive.</param>
        /// <param name="installDir">The installation directory for both the archives and executable.</param>
        /// <param name="exePath">The path to the executable to extract the V_CODE2 key from.</param>
        /// <returns>The <see cref="KifintLookup"/> merged with all loaded archives.</returns>
        ///
        /// <exception cref="ArgumentNullException">
        ///  <paramref name="stream"/>, <paramref name="kifintPath"/>, or <paramref name="exePath"/> is null.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        ///  The <paramref name="stream"/> is closed.
        /// </exception>
        private static KifintArchive LoadLookup(KifintType type, Stream stream, string kifintPath, string vcode2,
                                                KifintProgressArgs progress, KifintProgressCallback callback)
        {
            if (kifintPath == null)
            {
                throw new ArgumentNullException(nameof(kifintPath));
            }
            if (vcode2 == null)
            {
                throw new ArgumentNullException(nameof(vcode2));
            }

            BinaryReader reader = new BinaryReader(stream);
            KIFHDR       hdr    = reader.ReadUnmanaged <KIFHDR>();

            UnexpectedFileTypeException.ThrowIfInvalid(hdr.Signature, KIFHDR.ExpectedSignature);

            KIFENTRY[] entries = reader.ReadUnmanagedArray <KIFENTRY>(hdr.EntryCount);

            progress.EntryName  = null;
            progress.EntryIndex = 0;
            progress.EntryCount = entries.Length;

            // Table of contents seed
            uint     tocSeed      = GenerateTocSeed(vcode2);
            uint     fileKey      = 0;
            int      fileKeyIndex = -1;
            Blowfish blowfish     = null;

            // Obtain the decryption file key if one exists
            for (int i = 0; i < hdr.EntryCount; i++)
            {
                if (entries[i].FileName == KeyFileName)
                {
                    fileKey      = MersenneTwister.GenRand(entries[i].Length);
                    blowfish     = CatDebug.NewBlowfish(fileKey);
                    fileKeyIndex = i;
                    break;
                }
            }

            const int ProgressThreshold = 500;

            // Decrypt the KIFINT entries using the file key
            if (fileKeyIndex != -1)
            {
                for (uint i = 0; i < hdr.EntryCount; i++, progress.EntryIndex++)
                {
                    if (unchecked ((int)i) == fileKeyIndex)
                    {
                        continue;
                    }

                    // Give the entry the correct name
                    UnobfuscateFileName(entries[i].FileNameRaw, unchecked (tocSeed + i));
                    // Apply the extra offset before decryption
                    entries[i].Offset += i;
                    // Decrypt the entry's offset and length
                    blowfish.Decrypt(ref entries[i].Info);

                    progress.EntryName = entries[i].FileName;
                    if (i % ProgressThreshold == 0 || i + 1 == hdr.EntryCount)
                    {
                        callback?.Invoke(progress);
                    }
                }
            }

            return(new KifintArchive(kifintPath, entries, fileKeyIndex != -1, fileKey, type, blowfish));
        }
        private static bool DecryptArchive(Stream inStream, string kifintPath, string kifintBackup, string vcode2, bool isBackup,
                                           KifintProgressArgs progress, KifintProgressCallback callback)
        {
            if (kifintPath == null)
            {
                throw new ArgumentNullException(nameof(kifintPath));
            }
            if (vcode2 == null)
            {
                throw new ArgumentNullException(nameof(vcode2));
            }

            /*const string BackupName = "intbackup";
             * string dir = Path.GetDirectoryName(kifintPath);
             * string name = Path.GetFileName(kifintPath);
             * string kifintBackup = Path.Combine(dir, BackupName, name);
             * bool isBackup = Path.GetFileName(dir).ToLower() == BackupName;
             * if (isBackup) {
             *      dir = Path.GetDirectoryName(dir);
             *      kifintPath = Path.Combine(dir, name);
             * }
             * else {
             *
             * }*/
            Directory.CreateDirectory(Path.GetDirectoryName(kifintBackup));

            BinaryReader reader = new BinaryReader(inStream);
            KIFHDR       hdr    = reader.ReadUnmanaged <KIFHDR>();

            try {
                UnexpectedFileTypeException.ThrowIfInvalid(hdr.Signature, KIFHDR.ExpectedSignature);
            } catch (UnexpectedFileTypeException) {
                if (!isBackup && File.Exists(kifintBackup))
                {
                    inStream.Close();
                    // We must have stopped while decrypting an archive. Let's restart from the already-made backup
                    using (inStream = File.OpenRead(kifintBackup))
                        DecryptArchive(inStream, kifintPath, kifintBackup, vcode2, true, progress, callback);
                    return(true);
                }
                throw;
            }

            List <KIFENTRY> entries = new List <KIFENTRY>(hdr.EntryCount);

            entries.AddRange(reader.ReadUnmanagedArray <KIFENTRY>(hdr.EntryCount));

            // Table of contents seed
            uint     tocSeed  = GenerateTocSeed(vcode2);
            uint     fileKey  = 0;
            bool     decrypt  = false;
            Blowfish blowfish = null;
            int      keyIndex = -1;

            // Obtain the decryption file key if one exists
            for (int i = 0; i < hdr.EntryCount; i++)
            {
                if (entries[i].FileName == KeyFileName)
                {
                    fileKey  = MersenneTwister.GenRand(entries[i].Length);
                    decrypt  = true;
                    blowfish = CatDebug.NewBlowfish(fileKey);
                    keyIndex = i;
                    break;
                }
            }

            // This archive is already decrypted, return and let the calling method know
            if (!decrypt)
            {
                return(false);
            }

            if (isBackup)
            {
                using (Stream outStream = File.Create(kifintPath))
                    DecryptArchiveSave(hdr, entries, tocSeed, fileKey, blowfish, keyIndex, inStream, outStream,
                                       progress, callback);
            }
            else
            {
                if (File.Exists(kifintBackup))
                {
                    File.Delete(kifintBackup);
                }
                inStream.Close();
                File.Move(kifintPath, kifintBackup);
                using (inStream = File.OpenRead(kifintBackup))
                    using (Stream outStream = File.Create(kifintPath))
                        DecryptArchiveSave(hdr, entries, tocSeed, fileKey, blowfish, keyIndex, inStream, outStream,
                                           progress, callback);
            }

            return(true);
        }
Exemplo n.º 6
0
        private static void Run(Stream stream, string intFile, string exeFile,
                                string outputDir, ExkifintCallback progress = null)
        {
            Stopwatch watch     = Stopwatch.StartNew();
            DateTime  startTime = DateTime.UtcNow;
            string    gameId    = FindVCode2(exeFile);


            BinaryReader reader = new BinaryReader(stream);
            KIFHDR       hdr    = reader.ReadStruct <KIFHDR>();

            if (hdr.Signature != "KIF")             // It's really a KIF INT file
            {
                throw new InvalidFileException(Path.GetFileName(intFile), "INT");
            }

            KIFENTRY[] entries = reader.ReadStructArray <KIFENTRY>(hdr.EntryCount);

            uint tocSeed = GenTocSeed(gameId);
            uint fileKey = 0;
            bool decrypt = false;

            /*const string fileName = "bom_s.hg3";
             * const uint offset = 1112718577;
             * const int length = 1907629000;
             * const uint fileKey2 = 1457527205;
             * KIFENTRY kifEntry = new KIFENTRY {
             *      FileNameRaw = new char[64],
             *      Offset = offset,
             *      Length = length,
             * };
             * Array.Copy(fileName.ToCharArray(), kifEntry.FileNameRaw, fileName.Length);
             * DecryptEntry(ref kifEntry, fileKey2);*/

            ExkifintArgs args = new ExkifintArgs();

            for (int i = 0; i < hdr.EntryCount; i++)
            {
                if (entries[i].FileName == "__key__.dat")
                {
                    if (!decrypt)
                    {
                        //MersenneTwister.Seed(entries[i].Length);
                        //fileKey = MersenneTwister.GenRand();
                        fileKey = MersenneTwister.GenRand(entries[i].Length);
                        decrypt = true;
                    }
                }
                else
                {
                    args.FileCount++;
                }
            }

            DateTime  lastRefresh = DateTime.MinValue;
            Stopwatch writeTime   = new Stopwatch();
            TimeSpan  refreshTime = TimeSpan.FromMilliseconds(20);

            //Stopwatch processTime = new Stopwatch();
            for (uint i = 0; i < hdr.EntryCount; i++)
            {
                if (entries[i].FileName == "__key__.dat")
                {
                    continue;
                }

                if (decrypt)
                {
                    UnobfuscateFileName(entries[i].FileNameRaw, tocSeed + i);
                    //UnobfuscateFileName(ref entries[i].FileName, tocSeed + i);

                    entries[i].Offset += i;

                    DecryptEntry(ref entries[i].Info, fileKey);

                    /*Blowfish bf = new Blowfish();
                     * bf.Set_Key((byte*) &file_key, 4);
                     * byte[] entry_buff = entries[i].bytes;
                     * bf.Decrypt(entry_buff, 8);
                     * entries[i].bytes = entry_buff;*/
                }

                args.Ellapsed = DateTime.UtcNow - startTime;
                // Round to nearest hundredth
                args.Percent  = Math.Round((double)args.FileIndex / args.FileCount * 10000) / 100;
                args.FileName = entries[i].FileName;
                TimeSpan sinceRefresh = DateTime.UtcNow - lastRefresh;
                if (sinceRefresh >= refreshTime)
                {
                    lastRefresh = DateTime.UtcNow;
                    writeTime.Start();
                    progress?.Invoke(args);
                    writeTime.Stop();
                }

                //processTime.Restart();
                stream.Position = entries[i].Offset;
                byte[] buffer = reader.ReadBytes(entries[i].Length);

                if (decrypt)
                {
                    DecryptData(buffer, entries[i].Length, fileKey);

                    /*Blowfish bf = new Blowfish();
                     * bf.Set_Key((byte*)&file_key, 4);
                     * bf.Decrypt(buff, (len / 8) * 8);*/
                }

                string path = Path.Combine(outputDir, entries[i].FileName);
                File.WriteAllBytes(path, buffer);
                args.FileIndex++;
                //processTime.Stop();
                //if (processTime.ElapsedMilliseconds >= 500)
                //	Trace.WriteLine($"Large File: {buffer.Length / 1024:###,###,###,###}KB [{processTime.ElapsedMilliseconds}ms]");
            }

            args.Ellapsed = DateTime.UtcNow - startTime;
            args.Percent  = 100.0;
            progress?.Invoke(args);
            Trace.WriteLine($"Console Write Time: {writeTime.Elapsed:mm\\:ss\\.fff}");
        }