Exemplo n.º 1
0
        public static String CreateMD5String(String content)
        {
            if (md5Instance == null)
                md5Instance = System.Security.Cryptography.MD5.Create ();

            return ByteArrayToString(md5Instance.ComputeHash (Encoding.UTF8.GetBytes (content)));
        }
Exemplo n.º 2
0
 public MD5CalculatingStream(System.IO.Stream basestream)
     : base(basestream)
 {
     m_hash = (System.Security.Cryptography.MD5)System.Security.Cryptography.HashAlgorithm.Create("MD5");
     m_hash.Initialize();
     m_hashbuffer = new byte[m_hash.InputBlockSize];
 }
Exemplo n.º 3
0
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (m_hash != null)
            {
                m_hash.Clear();
                m_hash = null;

                m_hashbuffer = null;
                m_hashbufferLength = 0;
            }
        }
Exemplo n.º 4
0
 static string SignVenusRequest(string postData, string secret)
 {
     System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
     byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(string.Format("{0}{1}", postData, secret)));
     return(Convert.ToBase64String(bytes, 0, bytes.Length));
 }
Exemplo n.º 5
0
 public Day05(string inputString)
 {
     Init(inputString);
     md5 = System.Security.Cryptography.MD5.Create();
 }
Exemplo n.º 6
0
        /// <summary>
        /// Creates an object
        /// </summary>
        /// <param name="bucket">Bucket to create object in</param>
        /// <param name="key">Key of the new object</param>
        /// <param name="size">Total size of bytes to be written, must match with data's length</param>
        /// <param name="contentType">Content type of the new object, null defaults to "application/octet-stream"</param>
        /// <param name="data">Stream of bytes to send</param>
        public void PutObject(string bucket, string key, long size, string contentType, Stream data)
        {
            if (size <= MinioClient.minimumPartSize)
            {
                var bytes = ReadFull(data, (int)size);
                if (bytes.Length != (int)size)
                {
                    throw new UnexpectedShortReadException(bucket, key, size, bytes.Length);
                }
                this.DoPutObject(bucket, key, null, 0, contentType, bytes);
            }
            else
            {
                var    partSize = CalculatePartSize(size);
                var    uploads  = this.ListAllIncompleteUploads(bucket, key);
                string uploadId = null;
                Dictionary <int, string> etags = new Dictionary <int, string>();
                if (uploads.Count() > 0)
                {
                    foreach (Upload upload in uploads)
                    {
                        if (key == upload.Key)
                        {
                            uploadId = upload.UploadId;
                            var parts = this.ListParts(bucket, key, uploadId);
                            foreach (Part part in parts)
                            {
                                etags[part.PartNumber] = part.ETag;
                            }
                            break;
                        }
                    }
                }
                if (uploadId == null)
                {
                    uploadId = this.NewMultipartUpload(bucket, key, contentType);
                }
                int  partNumber   = 0;
                long totalWritten = 0;
                while (totalWritten < size)
                {
                    partNumber++;
                    byte[] dataToCopy = ReadFull(data, (int)partSize);
                    if (dataToCopy == null)
                    {
                        break;
                    }
                    if (dataToCopy.Length < partSize)
                    {
                        var expectedSize = size - totalWritten;
                        if (expectedSize != dataToCopy.Length)
                        {
                            throw new UnexpectedShortReadException(bucket, key, expectedSize, dataToCopy.Length);
                        }
                    }
                    System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
                    byte[] hash = md5.ComputeHash(dataToCopy);
                    string etag = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();
                    if (!etags.ContainsKey(partNumber) || !etags[partNumber].Equals(etag))
                    {
                        etag = DoPutObject(bucket, key, uploadId, partNumber, contentType, dataToCopy);
                    }
                    etags[partNumber] = etag;
                    totalWritten     += dataToCopy.Length;
                }

                foreach (int curPartNumber in etags.Keys)
                {
                    if (curPartNumber > partNumber)
                    {
                        etags.Remove(curPartNumber);
                    }
                }

                this.CompleteMultipartUpload(bucket, key, uploadId, etags);
            }
        }
Exemplo n.º 7
0
 public string ComputeDataHash(ref byte[] data)
 {
     using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
         return(BitConverter.ToString(md5.ComputeHash(data)));
 }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            bool clean = args.Length > 0 && args[0].Equals("/clean", StringComparison.OrdinalIgnoreCase);

            if (clean)
            {
                Console.WriteLine("Performing clean build of music data.");
            }
            var dacs    = IniSerializer.Deserialize <Dictionary <string, DACInfo> >("sound/DAC/DAC.ini");
            var samples = new List <KeyValuePair <string, int> >();

            foreach (var item in dacs.Select(a => a.Value.File).Distinct())
            {
                samples.Add(new KeyValuePair <string, int>(item, (int)new FileInfo(Path.Combine("sound/DAC", item)).Length));
            }
            List <int> dacbanksizes = new List <int>()
            {
                0
            };
            List <List <string> > dacbanks = new List <List <string> > {
                new List <string>()
            };

            foreach (var item in samples.OrderByDescending(a => a.Value))
            {
                bool found = false;
                for (int bank = 0; bank < dacbanksizes.Count; bank++)
                {
                    if (dacbanksizes[bank] + item.Value <= 0x8000)
                    {
                        dacbanks[bank].Add(item.Key);
                        dacbanksizes[bank] += item.Value;
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    dacbanks.Add(new List <string>()
                    {
                        item.Key
                    });
                    dacbanksizes.Add(item.Value);
                }
            }
            var samplenums = new Dictionary <string, string>();

            using (StreamWriter sw = new StreamWriter("dacbanks.gen.asm", false, Encoding.ASCII))
            {
                for (int b = 0; b < dacbanks.Count; b++)
                {
                    sw.WriteLine("SndDAC{0}_Start:\tstartBank", b + 1);
                    sw.WriteLine();
                    foreach (string item in dacbanks[b])
                    {
                        string label = Path.GetFileNameWithoutExtension(item).Replace(' ', '_').Replace('-', '_');
                        samplenums.Add(item, label);
                        sw.WriteLine("SndDAC_{0}:\tBINCLUDE \"sound/DAC/{1}\"", label, item);
                        sw.WriteLine("SndDAC_{0}_End:", label);
                        sw.WriteLine();
                    }
                    sw.WriteLine("\tfinishBank");
                    sw.WriteLine();
                }
            }
            List <string> dacids = new List <string>(dacs.Count);

            using (StreamWriter sw = new StreamWriter("dacinfo.gen.asm", false, Encoding.ASCII))
            {
                sw.WriteLine("zDACMasterPlaylist:");
                sw.WriteLine();
                foreach (var item in dacs)
                {
                    byte flags = 0;
                    if (item.Value.Format == DACFormat.PCM)
                    {
                        flags |= 1;
                    }
                    if (item.Value.Priority)
                    {
                        flags |= 2;
                    }

                    sw.WriteLine("\tDACSample\tSndDAC_{0},{1},{2} ; {3}", samplenums[item.Value.File], item.Value.Rate, flags, item.Key);
                    dacids.Add(item.Key);
                }
            }
            using (StreamWriter sw = new StreamWriter("dacids.gen.asm", false, Encoding.ASCII))
            {
                string last = "$81";
                for (int i = 0; i < dacids.Count; i++)
                {
                    if (i % 7 == 0)
                    {
                        sw.Write("\tenum {0}={1}", dacids[i], last);
                    }
                    else
                    {
                        sw.Write(",{0}", dacids[i]);
                    }
                    if (i % 7 == 6)
                    {
                        sw.WriteLine();
                        last = dacids[i] + "+1";
                    }
                }
            }
            var  songs    = IniSerializer.Deserialize <Dictionary <string, MusicInfo> >("sound/music/music.ini");
            bool writeini = false;

            System.Security.Cryptography.MD5 md5hasher = System.Security.Cryptography.MD5.Create();
            foreach (var item in songs)
            {
                switch (Path.GetExtension(item.Value.File).ToLowerInvariant())
                {
                case ".asm":
                case ".68k":
                    string md5 = GetFileHash(md5hasher, Path.Combine("sound/music", item.Value.File), true);
                    if (clean || item.Value.MD5 != md5 || item.Value.Size <= 0 || (item.Value.OutputFile != null && !File.Exists(Path.Combine("sound/music", item.Value.OutputFile))))
                    {
                        Console.WriteLine("Building song \"{0}\"...", item.Value.Title);
                        using (StreamWriter sw = new StreamWriter("tmp.asm", false, Encoding.ASCII))
                        {
                            sw.WriteLine("\tCPU 68000");
                            sw.WriteLine("\tpadding off");
                            sw.WriteLine("kehmusic = 1");
                            sw.WriteLine("allOptimizations = 1");
                            sw.WriteLine("\tinclude \"s2.macros.asm\"");
                            sw.WriteLine("\tinclude \"sound/_smps2asm_inc.asm\"");
                            sw.WriteLine("\tinclude \"sound/music/{0}\"", item.Value.File);
                        }
                        ProcessStartInfo si = new ProcessStartInfo("win32/as/asw", "-E -xx -A -r 2 -q -U tmp.asm")
                        {
                            CreateNoWindow = true
                        };
                        si.EnvironmentVariables.Add("AS_MSGPATH", "win32/as");
                        si.EnvironmentVariables.Add("USEANSI", "n");
                        si.UseShellExecute = false;
                        using (Process proc = Process.Start(si))
                            proc.WaitForExit();
                        File.Delete("tmp.asm");
                        if (File.Exists("tmp.log"))
                        {
                            Console.Write(File.ReadAllText("tmp.log"));
                            File.Delete("tmp.log");
                        }
                        if (!File.Exists("tmp.p"))
                        {
                            continue;
                        }
                        si = new ProcessStartInfo("win32/s2p2bin", "tmp.p tmp.bin")
                        {
                            CreateNoWindow  = true,
                            UseShellExecute = false
                        };
                        using (Process proc = Process.Start(si))
                            proc.WaitForExit();
                        File.Delete("tmp.p");
                        if (!File.Exists("tmp.bin"))
                        {
                            continue;
                        }
                        item.Value.Size = (short)new FileInfo("tmp.bin").Length;
                        item.Value.MD5  = md5;
                        if (item.Value.Size <= 0xA40)
                        {
                            item.Value.OutputFile = Path.GetFileNameWithoutExtension(item.Value.File) + "_cmp.bin";
                            byte[] compressed_buffer = SonicRetro.KensSharp.Saxman.Compress("tmp.bin", true);
                            if (item.Value.Size <= compressed_buffer.Length)
                            {
                                item.Value.OutputFile = null;
                            }
                            else
                            {
                                File.WriteAllBytes(Path.Combine("sound/music", item.Value.OutputFile), compressed_buffer);
                                item.Value.Size = (short)compressed_buffer.Length;
                            }
                        }
                        else
                        {
                            item.Value.OutputFile = null;
                        }
                        File.Delete("tmp.bin");
                        writeini = true;
                    }
                    break;

                case ".bin":
                    short size = (short)new FileInfo(Path.Combine("sound/music", item.Value.File)).Length;
                    //string md5 = GetFileHash(md5hasher, Path.Combine("sound/music", item.Value.File), false);
                    if (item.Value.Size != size)
                    {
                        item.Value.Size = size;
                        writeini        = true;
                    }
                    break;
                }
            }
            if (writeini)
            {
                IniSerializer.Serialize(songs, "sound/music/music.ini");
            }
            List <int> banksizes = new List <int>()
            {
                0
            };
            List <List <KeyValuePair <string, MusicInfo> > > banks = new List <List <KeyValuePair <string, MusicInfo> > >()
            {
                new List <KeyValuePair <string, MusicInfo> >()
            };

            foreach (var item in songs.OrderByDescending(a => a.Value.Size))
            {
                bool found = false;
                for (int i = 0; i < banks.Count; i++)
                {
                    if (banksizes[i] + item.Value.Size <= 0x8000)
                    {
                        banks[i].Add(item);
                        banksizes[i] += item.Value.Size;
                        found         = true;
                        break;
                    }
                }
                if (!found)
                {
                    banks.Add(new List <KeyValuePair <string, MusicInfo> >()
                    {
                        item
                    });
                    banksizes.Add(item.Value.Size);
                }
            }
            using (StreamWriter sw = new StreamWriter("musicbanks.gen.asm", false, Encoding.ASCII))
            {
                for (int i = 0; i < banks.Count; i++)
                {
                    sw.WriteLine("; ------------------------------------------------------------------------------");
                    sw.WriteLine("; Music bank {0}", i + 1);
                    sw.WriteLine("; ------------------------------------------------------------------------------");
                    sw.WriteLine("SndMus{0}_Start:	startBank", i + 1);
                    sw.WriteLine();
                    foreach (var item in banks[i])
                    {
                        switch (Path.GetExtension(item.Value.OutputFile ?? item.Value.File).ToLowerInvariant())
                        {
                        case ".asm":
                        case ".68k":
                            sw.WriteLine("Mus_{0}:\tinclude \"sound/music/{1}\" ; ${2:X} bytes", item.Key, item.Value.File, item.Value.Size);
                            break;

                        case ".bin":
                            sw.WriteLine("Mus_{0}:\tBINCLUDE \"sound/music/{1}\" ; ${2:X} bytes", item.Key, item.Value.OutputFile ?? item.Value.File, item.Value.Size);
                            break;
                        }
                    }
                    sw.WriteLine();
                    sw.WriteLine("\tfinishBank");
                    sw.WriteLine();
                }
            }
            using (StreamWriter sw = new StreamWriter("musicinfo.gen.asm", false, Encoding.ASCII))
            {
                sw.WriteLine("zMasterPlaylist:");
                foreach (var item in songs)
                {
                    sw.Write("\tzmakePlaylistEntry\tMus_{0},", item.Key);
                    switch (Path.GetExtension(item.Value.OutputFile ?? item.Value.File).ToLowerInvariant())
                    {
                    case ".asm":
                    case ".68k":
                        sw.Write("musprop_uncompressed");
                        break;

                    case ".bin":
                        sw.Write("0");
                        break;
                    }
                    if (item.Value.PALMode)
                    {
                        sw.Write("|musprop_palmode");
                    }
                    if (item.Value.ExtraLifeJingle)
                    {
                        sw.Write("|musprop_1up");
                    }
                    if (item.Value.NoSpeedUp)
                    {
                        sw.Write("|musprop_nospeedup");
                    }
                    sw.WriteLine();
                }
            }
            using (StreamWriter sw = new StreamWriter("musicids.gen.asm", false, Encoding.ASCII))
            {
                List <string> musids = new List <string>(songs.Keys)
                {
                    "_End"
                };
                sw.WriteLine("MusID__First = 1");
                string last = "_First";
                for (int i = 0; i < musids.Count; i++)
                {
                    if (i % 7 == 0)
                    {
                        sw.Write("\tenum MusID_{0}=MusID_{1}", musids[i], last);
                    }
                    else
                    {
                        sw.Write(",MusID_{0}", musids[i]);
                    }
                    if (i % 7 == 6)
                    {
                        sw.WriteLine();
                        last = musids[i] + "+1";
                    }
                }
            }
            using (StreamWriter sw = new StreamWriter("musicnames.gen.asm", false, Encoding.ASCII))
            {
                sw.WriteLine("SongNames:\toffsetTable");
                sw.WriteLine("\toffsetTableEntry.w\tMusNam_Null");
                foreach (var item in songs)
                {
                    sw.WriteLine("\toffsetTableEntry.w\tMusNam_{0}", item.Key);
                }
                sw.WriteLine();
                sw.WriteLine("MusNam_Null:\tdc.b 0,' '");
                foreach (var item in songs)
                {
                    sw.WriteLine("MusNam_{0}:\tsongtext\t\"{1}\"", item.Key, item.Value.Title.ToUpperInvariant());
                }
                sw.WriteLine("\teven");
            }
        }
Exemplo n.º 9
0
        public static ProcessModuleWow64Safe[] ModulesWow64Safe(this Process p)
        {
            if (ModuleCache.Count > 100)
            {
                ModuleCache.Clear();
            }

            const int LIST_MODULES_ALL = 3;
            const int MAX_PATH         = 260;

            var hModules = new IntPtr[1024];

            uint cb = (uint)IntPtr.Size * (uint)hModules.Length;
            uint cbNeeded;

            if (!WinAPI.EnumProcessModulesEx(p.Handle, hModules, cb, out cbNeeded, LIST_MODULES_ALL))
            {
                throw new Win32Exception();
            }
            uint numMods = cbNeeded / (uint)IntPtr.Size;

            // Create MD5 hash of loaded module pointers, if modules have changed we do the full scan
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] hashData = new byte[hModules.Count() * sizeof(Int64)];
            for (int i = 0; i < numMods; i++)
            {
                byte[] addrBytes = BitConverter.GetBytes(hModules[i].ToInt64());
                addrBytes.CopyTo(hashData, i * sizeof(Int64));
            }

            byte[] hashResult = md5.ComputeHash(hashData);
            string hashString = BitConverter.ToString(hashResult).Replace("-", string.Empty).ToLower();

            if (ModuleCache.ContainsKey(hashString))
            {
                return(ModuleCache[hashString]);
            }

            // everything below is fairly expensive, which is why we cache!
            var  ret             = new List <ProcessModuleWow64Safe>();
            var  sb              = new StringBuilder(MAX_PATH);
            bool moduleLoadError = false;

            for (int i = 0; i < numMods; i++)
            {
                try
                {
                    sb.Clear();
                    if (WinAPI.GetModuleFileNameEx(p.Handle, hModules[i], sb, (uint)sb.Capacity) == 0)
                    {
                        throw new Win32Exception();
                    }
                    string fileName = sb.ToString();

                    sb.Clear();
                    if (WinAPI.GetModuleBaseName(p.Handle, hModules[i], sb, (uint)sb.Capacity) == 0)
                    {
                        throw new Win32Exception();
                    }
                    string baseName = sb.ToString();

                    var moduleInfo = new WinAPI.MODULEINFO();
                    if (!WinAPI.GetModuleInformation(p.Handle, hModules[i], out moduleInfo, (uint)Marshal.SizeOf(moduleInfo)))
                    {
                        throw new Win32Exception();
                    }

                    ret.Add(new ProcessModuleWow64Safe()
                    {
                        FileName          = fileName,
                        BaseAddress       = moduleInfo.lpBaseOfDll,
                        ModuleMemorySize  = (int)moduleInfo.SizeOfImage,
                        EntryPointAddress = moduleInfo.EntryPoint,
                        ModuleName        = baseName
                    });
                }
                catch (Win32Exception win32Ex)
                {
                    // This exception doesnt need to be propagated up since it is a common occurence for
                    // handles to be invalidated inbetween calls to module functions. If we miss a module
                    // then we'll get it on the next invocation.
                    Log.Error(win32Ex);
                    moduleLoadError = true;
                    break;
                }
            }

            if (!moduleLoadError)
            {
                ModuleCache.Add(hashString, ret.ToArray());
            }

            return(ret.ToArray());
        }
Exemplo n.º 10
0
 public void WeakCryptographicHashSample()
 {
     System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
 }
Exemplo n.º 11
0
        /// <summary>
        /// Creates an object
        /// </summary>
        /// <param name="bucketName">Bucket to create object in</param>
        /// <param name="objectName">Key of the new object</param>
        /// <param name="size">Total size of bytes to be written, must match with data's length</param>
        /// <param name="contentType">Content type of the new object, null defaults to "application/octet-stream"</param>
        /// <param name="data">Stream of bytes to send</param>
        public void PutObject(string bucketName, string objectName, Stream data, long size, string contentType)
        {
            if (size >= MinioClient.maximumStreamObjectSize)
            {
                throw new ArgumentException("Input size is bigger than stipulated maximum of 50GB.");
            }

            if (size <= MinioClient.minimumPartSize)
            {
                var bytes = ReadFull(data, (int)size);
                if (bytes.Length != (int)size)
                {
                    throw new UnexpectedShortReadException("Data read " + bytes.Length + " is shorter than the size " + size + " of input buffer.");
                }
                this.PutObject(bucketName, objectName, null, 0, bytes, contentType);
                return;
            }
            var    partSize = MinioClient.minimumPartSize;
            var    uploads  = this.ListIncompleteUploads(bucketName, objectName);
            string uploadId = null;
            Dictionary <int, string> etags = new Dictionary <int, string>();

            if (uploads.Count() > 0)
            {
                foreach (Upload upload in uploads)
                {
                    if (objectName == upload.Key)
                    {
                        uploadId = upload.UploadId;
                        var parts = this.ListParts(bucketName, objectName, uploadId);
                        foreach (Part part in parts)
                        {
                            etags[part.PartNumber] = part.ETag;
                        }
                        break;
                    }
                }
            }
            if (uploadId == null)
            {
                uploadId = this.NewMultipartUpload(bucketName, objectName, contentType);
            }
            int  partNumber   = 0;
            long totalWritten = 0;

            while (totalWritten < size)
            {
                partNumber++;
                byte[] dataToCopy = ReadFull(data, (int)partSize);
                if (dataToCopy == null)
                {
                    break;
                }
                if (dataToCopy.Length < partSize)
                {
                    var expectedSize = size - totalWritten;
                    if (expectedSize != dataToCopy.Length)
                    {
                        throw new UnexpectedShortReadException("Unexpected short read. Read only " + dataToCopy.Length + " out of " + expectedSize + "bytes");
                    }
                }
                System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
                byte[] hash = md5.ComputeHash(dataToCopy);
                string etag = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();
                if (!etags.ContainsKey(partNumber) || !etags[partNumber].Equals(etag))
                {
                    etag = this.PutObject(bucketName, objectName, uploadId, partNumber, dataToCopy, contentType);
                }
                etags[partNumber] = etag;
                totalWritten     += dataToCopy.Length;
            }

            foreach (int curPartNumber in etags.Keys)
            {
                if (curPartNumber > partNumber)
                {
                    etags.Remove(curPartNumber);
                }
            }
            this.CompleteMultipartUpload(bucketName, objectName, uploadId, etags);
        }
Exemplo n.º 12
0
 /// <summary>
 /// Usage:
 /// var md5 = System.Security.Cryptography.MD5.Create();
 /// var md5string = Md5.CalculateMd5(input, md5);
 /// </summary>
 /// <param name="input"></param>
 /// <param name="md5"></param>
 /// <returns></returns>
 public static string CalculateMd5(string input, System.Security.Cryptography.MD5 md5)
 {
     byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
     byte[] hash       = md5.ComputeHash(inputBytes);
     return(ByteArrayToHexViaLookup32(hash));
 }
Exemplo n.º 13
0
 public Timeline(string Path)
 {
     _timelinePath = Path;
     md5Gen        = System.Security.Cryptography.MD5.Create();
 }
Exemplo n.º 14
0
        public async Task CheckNewVersionAsync(bool manual = false)
        {
            string availableVersionResponse = await mainLink.HttpClientController.DownloadFileToStringAsync("https://deltaconnected.com/arcdps/x64/d3d9.dll.md5sum");

            string availableVersion = availableVersionResponse.Split(' ')[0];

            if ((availableVersion != "") && (File.Exists($@"{GW2Location}\bin64\d3d9.dll")))
            {
                using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
                {
                    try
                    {
                        if (File.Exists($@"{GW2Location}\bin64\d3d9.dll"))
                        {
                            byte[] hash = null;
                            using (FileStream stream = File.OpenRead($@"{GW2Location}\bin64\d3d9.dll"))
                            {
                                hash = md5.ComputeHash(stream);
                            }
                            if (!BitConverter.ToString(hash).Replace("-", "").ToLower().Equals(availableVersion))
                            {
                                buttonCheckNow.Enabled   = false;
                                groupBoxUpdating.Enabled = true;
                                if (manual)
                                {
                                    DialogResult result = MessageBox.Show("New arcdps version available.\nDo you want to download the new version?", "arcdps version checker", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                                    if (result.Equals(DialogResult.Yes))
                                    {
                                        await UpdateArcAsync();
                                    }
                                }
                                else
                                {
                                    if (Properties.Settings.Default.ArcAutoUpdate)
                                    {
                                        await UpdateArcAsync();
                                    }
                                    else
                                    {
                                        mainLink.ShowBalloon("arcdps version checking", "New version of arcdps available.\nGo to arcdps version checking settings to use the auto-update.", 8500);
                                    }
                                }
                            }
                            else
                            {
                                if (manual)
                                {
                                    MessageBox.Show("arcdps is up to date.", "arcdps version checker", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                            }
                        }
                        else
                        {
                            buttonCheckNow.Enabled   = false;
                            groupBoxUpdating.Enabled = true;
                            if (manual)
                            {
                                DialogResult result = MessageBox.Show("New arcdps version available.\nDo you want to download the new version?", "arcdps version checker", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                                if (result.Equals(DialogResult.Yes))
                                {
                                    await UpdateArcAsync();
                                }
                            }
                            else
                            {
                                mainLink.ShowBalloon("arcdps version checking", "New version of arcdps available.\nGo to arcdps version checking settings to use the auto-update.", 8500);
                            }
                        }
                    }
                    catch
                    {
                        if (manual)
                        {
                            MessageBox.Show("There has been an error trying to check if arcdps is up to date.", "arcdps version checker", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            else
            {
                buttonCheckNow.Enabled   = false;
                groupBoxUpdating.Enabled = true;
                if (manual)
                {
                    DialogResult result = MessageBox.Show("New arcdps version available\nDo you want to download the new version?", "arcdps version checker", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                    if (result.Equals(DialogResult.Yes))
                    {
                        await UpdateArcAsync();
                    }
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Will attempt to load object properties.
        /// </summary>
        /// <exception cref="Exception"></exception>
        private void LoadObjectProperties()
        {
            byte   itemIdOffset = 100;
            string localDatFile = "ObjectProperties" + this.TibiaVersion + ".dat";
            string datPath      = this.TibiaProcess.MainModule.FileName;

            datPath = datPath.Substring(0, datPath.LastIndexOf(Path.DirectorySeparatorChar) + 1) + "Tibia.dat";

            if (!File.Exists(datPath))
            {
                throw new Exception("Could not load object properties since Tibia.dat could not be found in the client's directory." +
                                    "\nWithout object properties, modules like cavebot will not function properly.");
            }

            using (BinaryReader readerDatFile = new BinaryReader(File.OpenRead(datPath)))
            {
                bool queryServer = false, queryClient = false;
                System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
                byte[] datHash = md5.ComputeHash(readerDatFile.BaseStream);
                readerDatFile.BaseStream.Position = 4; // first 4 bytes is file signature

                if (File.Exists(localDatFile))
                {
                    using (BinaryReader readerLocalFile = new BinaryReader(File.OpenRead(localDatFile)))
                    {
                        if (datHash.DataEquals(readerLocalFile.ReadBytes(datHash.Length)))
                        {
                            ushort count = readerLocalFile.ReadUInt16();
                            this.ObjectProperties = new Objects.ObjectProperties[count];
                            for (ushort i = 0; i < count; i++)
                            {
                                try
                                {
                                    Objects.ObjectProperties objProperty = new Objects.ObjectProperties((ushort)(i + itemIdOffset));
                                    objProperty.Flags        = readerLocalFile.ReadUInt32();
                                    this.ObjectProperties[i] = objProperty;
                                    if (this.ObjectPropertyRead != null)
                                    {
                                        this.ObjectPropertyRead(i, count);
                                    }
                                }
                                catch
                                {
                                    queryServer = true;
                                    break;
                                }
                            }
                            if (!queryClient && !queryServer)
                            {
                                if (this.ObjectPropertiesFinishedReading != null)
                                {
                                    this.ObjectPropertiesFinishedReading(count);
                                }
                                return;
                            }
                        }
                        else
                        {
                            queryServer = true;
                        }
                    }
                }
                else
                {
                    queryServer = true;
                }

                if (queryServer)
                {
                    try
                    {
                        TcpClient      tc = new TcpClient(this.ObjectPropertiesServerIP, this.ObjectPropertiesServerPort);
                        Objects.Packet p  = new Objects.Packet();
                        p.AddBytes(datHash);
                        p.AddLength();
                        p.Send(tc);

                        p = Objects.Packet.GetNextPacket(tc.GetStream());
                        if (p.Length == 0)
                        {
                            queryClient = true;
                        }
                        else
                        {
                            p.GetUInt16();
                            byte[] hash  = p.GetBytes(datHash.Length);
                            ushort count = p.GetUInt16();
                            byte[] data  = p.GetBytes(count * 4);
                            tc.Close();
                            this.ObjectProperties = new Objects.ObjectProperties[count];
                            for (ushort i = 0; i < count; i++)
                            {
                                var objProps = new Objects.ObjectProperties((ushort)(itemIdOffset + i));
                                objProps.Flags           = BitConverter.ToUInt32(data, i * 4);
                                this.ObjectProperties[i] = objProps;
                                if (this.ObjectPropertyRead != null)
                                {
                                    this.ObjectPropertyRead(i, count);
                                }
                            }
                            if (this.ObjectPropertiesFinishedReading != null)
                            {
                                this.ObjectPropertiesFinishedReading(count);
                            }
                            this.SaveObjectProperties(datHash);
                            return;
                        }
                    }
                    catch
                    {
                        queryClient = true;
                    }
                }

                if (queryClient)
                {
                    try
                    {
                        ushort itemCount = (ushort)(readerDatFile.ReadUInt16() - itemIdOffset);
                        this.ObjectProperties = new Objects.ObjectProperties[itemCount];
                        for (int i = 0; i < itemCount; i++)
                        {
                            Objects.ObjectProperties objProperties = new ObjectProperties((ushort)(i + itemIdOffset));
                            switch (this.TibiaVersion)
                            {
                            case 772:
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.HasAutomapColor))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.HasAutomapColor);
                                }
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.HasHelpLens))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.HasHelpLens);
                                }
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.IsBlocking))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.IsBlocking);
                                }
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.IsContainer))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.IsContainer);
                                }
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.IsFloorChange))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.IsFloorChange);
                                }
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.IsFluidContainer))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.IsFluidContainer);
                                }
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.IsGround))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.IsGround);
                                }
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.IsHangable))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.IsHangable);
                                }
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.IsImmobile))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.IsImmobile);
                                }
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.IsAlwaysTopUse))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.IsAlwaysTopUse);
                                }
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.IsMissileBlocking))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.IsMissileBlocking);
                                }
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.IsPathBlocking))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.IsPathBlocking);
                                }
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.IsPickupable))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.IsPickupable);
                                }
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.IsSplash))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.IsSplash);
                                }
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.IsStackable))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.IsStackable);
                                }
                                //if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.IsTopOrder1)) objProperties.AddFlag(Enums.ObjectPropertiesFlags.IsTopOrder1);
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.IsTopOrder2))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.IsTopUseIfOnly);
                                }
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.IsTopOrder3))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.IsWalkThrough);
                                }
                                if (this.Packets.GetObjectProperty((ushort)(i + itemIdOffset), (byte)Enums.ObjectProperties772.IsUsable))
                                {
                                    objProperties.AddFlag(Enums.ObjectPropertiesFlags.IsUsable);
                                }
                                break;
                            }
                            this.ObjectProperties[i] = objProperties;
                            if (this.ObjectPropertyRead != null)
                            {
                                this.ObjectPropertyRead(i + 1, itemCount);
                            }
                        }
                        if (this.ObjectPropertiesFinishedReading != null)
                        {
                            this.ObjectPropertiesFinishedReading(itemCount);
                        }
                        this.SaveObjectProperties(datHash);
                    }
                    catch (Exception ex)
                    {
                        if (this.ObjectPropertiesFailed != null)
                        {
                            this.ObjectPropertiesFailed(ex);
                        }
                    }
                }
            }
        }
Exemplo n.º 16
0
		static FSDirectory()
		{
			{
				try
				{
					System.String name = SupportClass.AppSettings.Get("Lucene.Net.FSDirectory.class", typeof(FSDirectory).FullName);
					IMPL = System.Type.GetType(name);
				}
				catch (System.Security.SecurityException)
				{
					try
					{
						IMPL = System.Type.GetType(typeof(FSDirectory).FullName);
					}
					catch (System.Exception e)
					{
						throw new System.SystemException("cannot load default FSDirectory class: " + e.ToString());
					}
				}
                catch (System.Exception e)
                {
                    throw new System.SystemException("cannot load FSDirectory class: " + e.ToString());
                }
            }
			{
				try
				{
					DIGESTER = System.Security.Cryptography.MD5.Create();
				}
				catch (System.Exception e)
				{
					throw new System.SystemException(e.ToString());
				}
			}
		}
Exemplo n.º 17
0
 static HashHelper()
 {
     _md5    = System.Security.Cryptography.MD5.Create();
     _sha1   = new System.Security.Cryptography.SHA1Managed();
     _sha256 = new System.Security.Cryptography.SHA256Managed();
 }
Exemplo n.º 18
0
		static FSDirectory()
		{
			DISABLE_LOCKS = System.Configuration.ConfigurationSettings.AppSettings.Get("disableLuceneLocks") != null;
			{
				try
				{
					DIGESTER = System.Security.Cryptography.MD5.Create();
				}
				catch (System.Exception e)
				{
					throw new System.SystemException(e.ToString());
				}
			}
		}
Exemplo n.º 19
0
        private void BtnLogin_Click(object sender, EventArgs e)
        {
            string hostname = TxtHost.Text.ToLower().Trim();
            string username = TxtUser.Text.ToLower().Trim();
            string password = TxtPass.Text.ToLower().Trim();

            // Try to set the hostname
            if (!Network.GameComms.SetHost(hostname))
            {
                MessageBox.Show(this, "Please check hostname");
            }

            bool is_new_user = (Button)sender == BtnNew;

            if (username.Length > 0 && password.Length > 0)
            {
                output_username = username;
                output_password = password;

                MsgLogin msg = new MsgLogin();
                msg.Action       = (is_new_user) ? MsgLogin.ActionType.NewUser : MsgLogin.ActionType.LoginUser;
                msg.Username     = username;
                msg.PasswordHash = password;

                using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
                {
                    // Convert the password to bytes
                    byte[] pw_bytes   = Encoding.ASCII.GetBytes(output_password);
                    byte[] hash_bytes = md5.ComputeHash(pw_bytes);

                    // Convert the bytes to a hex string
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < hash_bytes.Length; i++)
                    {
                        sb.Append(hash_bytes[i].ToString("x2"));
                    }
                    msg.PasswordHash = sb.ToString();
                }

                try
                {
                    Network.GameComms.ResetSocket();
                }
                catch (System.Net.Sockets.SocketException)
                {
                    MessageBox.Show(this, "Unable to connect to server");
                    return;
                }

                if (chkUseSecure.Checked)
                {
                    if (!Network.GameComms.SetupSSL())
                    {
                        MessageBox.Show(this, "Unable to setup SSL connection");
                        return;
                    }
                }

                Network.GameComms.SendMessage(msg);

                MsgServerResponse msg_response = null;

                for (int i = 0; i < 10; ++i)
                {
                    MsgBase msg_b = Network.GameComms.ReceiveMessage();

                    if (msg_b == null)
                    {
                        Thread.Sleep(100);
                    }
                    else
                    {
                        if (msg_b is MsgServerResponse)
                        {
                            msg_response = (MsgServerResponse)msg_b;
                        }

                        break;
                    }
                }

                if (msg_response != null && msg_response.ResponseCode == ResponseCodes.OK)
                {
                    Network.GameComms.SetPlayer(msg_response.User);
                    DialogResult = DialogResult.OK;
                    Close();
                }
                else
                {
                    MessageBox.Show(this, "Login Failed");
                }
            }
        }
Exemplo n.º 20
0
 public CMd5Hash()
 {
     Md5Hash   = new   System.Text.StringBuilder();
     Comparer  = System.StringComparer.OrdinalIgnoreCase;
     Md5Hasher = System.Security.Cryptography.MD5.Create();
 }
Exemplo n.º 21
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            if (!Input.Email.EndsWith("@mvla.net"))
            {
                ModelState.AddModelError(string.Empty, "Not a valid MVLA email address!");
                return(Page());
            }

            returnUrl ??= Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                StringBuilder sb = new StringBuilder();
                using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
                {
                    byte[] inputBytes = Encoding.ASCII.GetBytes(Input.Email.Trim().ToLower());
                    byte[] hashBytes  = md5.ComputeHash(inputBytes);

                    for (int i = 0; i < hashBytes.Length; i++)
                    {
                        sb.Append(hashBytes[i].ToString("X2"));
                    }
                }

                var user = new ContraUser {
                    Name = Input.Name,

                    Articles       = new List <Article>(),
                    ArticlesLiked  = new List <Article>(),
                    ArticlesViewed = new List <Article>(),
                    CommentsLiked  = new List <Comment>(),

                    ProfilePictureURL = "https://gravatar.com/avatar/" + sb.ToString() + "?d=identicon",
                    UserName          = Input.Email,
                    Email             = Input.Email,
                    DateJoined        = DateTime.Now
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code },
                        protocol: Request.Scheme);

                    await _emailSender.SendConfirmEmailAsync(Input.Email, Input.Name, callbackUrl);

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemplo n.º 22
0
 public MD5()
 {
     this._algorithm = System.Security.Cryptography.MD5.Create();
 }
Exemplo n.º 23
0
        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            this.contextMenuStripTreeNode.Items.Clear();
            if (e.Button == MouseButtons.Right && e.Node != null)
            {
                var selectedNode = e.Node;
                treeView1.SelectedNode = selectedNode;
                if (selectedNode.Parent != null) //file node selected
                {
                    ToolStripMenuItem menu1 = new ToolStripMenuItem();
                    menu1.Text   = "open path";
                    menu1.Click += new System.EventHandler((sender1, e1) =>
                    {
                        Process p             = new Process();
                        p.StartInfo.FileName  = "explorer.exe";
                        p.StartInfo.Arguments = @"/e,/select," + selectedNode.Text;
                        p.Start();
                    });

                    ToolStripMenuItem menu2 = new ToolStripMenuItem();
                    menu2.Text   = "open file";
                    menu2.Click += new System.EventHandler((sender1, e1) =>
                    {
                        Process p             = new Process();
                        p.StartInfo.FileName  = "explorer.exe";
                        p.StartInfo.Arguments = selectedNode.Text;
                        p.Start();
                    });

                    ToolStripMenuItem menu3 = new ToolStripMenuItem();
                    menu3.Text   = "delete";
                    menu3.Click += new System.EventHandler((sender1, e1) =>
                    {
                        if (MessageBox.Show("are you sure to delete this file?", "warning", MessageBoxButtons.OKCancel) == DialogResult.OK)
                        {
                            FileInfo file = new FileInfo(selectedNode.Text);
                            file.Delete();
                            selectedNode.Parent.Nodes.Remove(selectedNode);
                        }
                    });
                    this.contextMenuStripTreeNode.Items.Clear();
                    this.contextMenuStripTreeNode.Items.AddRange(new ToolStripItem[] { menu1, menu2, menu3 });
                    this.contextMenuStripTreeNode.Show(MousePosition.X, MousePosition.Y);
                }
                else //fileGroup node selected
                {
                    ToolStripMenuItem menu1 = new ToolStripMenuItem();
                    menu1.Text   = "compute hash";
                    menu1.Click += new System.EventHandler((sender1, e1) =>
                    {
                        List <string> md5list = new List <string>();

                        foreach (TreeNode fileNode in selectedNode.Nodes)
                        {
                            System.Security.Cryptography.MD5 calcer = System.Security.Cryptography.MD5.Create();
                            FileStream fs = new FileStream(fileNode.Text, FileMode.Open);
                            var hash      = calcer.ComputeHash(fs);
                            calcer.Clear();
                            fs.Close();
                            StringBuilder stringBuilder = new StringBuilder();
                            for (int i = 0; i < hash.Length; i++)
                            {
                                stringBuilder.Append(hash[i].ToString("x2"));
                            }
                            md5list.Add(stringBuilder.ToString());
                        }
                        string str = "";
                        foreach (var item in md5list)
                        {
                            str += item + "\r\n";
                        }
                        MessageBox.Show(str);
                    });
                    ToolStripMenuItem menu2 = new ToolStripMenuItem();
                    menu2.Text   = "compare content";
                    menu2.Click += new System.EventHandler((sender1, e1) =>
                    {
                        bool issame = CompareFile(selectedNode.Nodes[0].Text, selectedNode.Nodes[1].Text);
                        MessageBox.Show(issame ? "内容完全一致" : "内容不一致");
                    });

                    this.contextMenuStripTreeNode.Items.Clear();
                    this.contextMenuStripTreeNode.Items.AddRange(new ToolStripItem[] { menu1, menu2 });
                    this.contextMenuStripTreeNode.Show(MousePosition.X, MousePosition.Y);
                }
            }
        }
Exemplo n.º 24
0
 private static String MD5Checksum(String data)
 {
     System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
     return(BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(data))).Replace("-", "").ToLower());
 }
Exemplo n.º 25
0
        private void MineThroughText(string FilePath, string Cluster)
        {
            StreamReader            Reader       = new StreamReader(FilePath);
            uint                    LineCounters = 0;
            List <DistributionList> DistList     = new List <DistributionList>();

            if ("" == txtLinesToSample.Text.Trim())
            {
                txtLinesToSample.Text = "100";
            }

            while (!Reader.EndOfStream && LineCounters < Convert.ToInt32(txtLinesToSample.Text))
            {
                string   pattern     = "";
                string   LinePattern = "";
                string   strText     = "";
                string[] tokens;

                // read line
                strText = Reader.ReadLine();
                LineCounters++;
                rtbOpenFile.Text = rtbOpenFile.Text + "\n" + strText;

                // string to token
                tokens = strText.Split(new Char[] { ' ', ',', '\t' });

                // Find pattern in each token
                foreach (string token in tokens)
                {
                    if (token != "")
                    {
                        string tempPattern = ConvertRegEx(token);

                        if (pattern != "Text")
                        {
                            pattern     = tempPattern;
                            LinePattern = LinePattern + " " + pattern;
                        }
                        else if (tempPattern != "Text")
                        {
                            pattern     = tempPattern;
                            LinePattern = LinePattern + " " + pattern;
                        }
                    }
                }

                rtbRegEx.Text = rtbRegEx.Text + "\n" + LinePattern;
                DistributionList Line = DistList.Find(
                    delegate(DistributionList DL)
                {
                    return(DL.Line == LinePattern);
                }
                    );

                if (Line != null)
                {
                    Line.Frequency++;
                }
                else
                {
                    DistributionList Item = new DistributionList();
                    Item.Line      = LinePattern;
                    Item.Frequency = 1;
                    DistList.Add(Item);
                }
            }
            Reader.Close();

            rtbPattern.Text = rtbFrequency.Text = "";
            //DistList.Sort();
            foreach (DistributionList T in DistList)
            {
                rtbPattern.Text   = rtbPattern.Text + "\n" + T.Line;// +"::" + T.Frequency;
                rtbFrequency.Text = rtbFrequency.Text + "\n" + T.Line + "::" + T.Frequency;
            }

            string hash;
            string fhash;

            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
            {
                hash = BitConverter.ToString(
                    md5.ComputeHash(Encoding.UTF8.GetBytes(rtbFrequency.Text))
                    ).Replace("-", String.Empty);
            }

            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
            {
                fhash = BitConverter.ToString(
                    md5.ComputeHash(Encoding.UTF8.GetBytes(rtbPattern.Text))
                    ).Replace("-", String.Empty);
            }

            //Check DB
            SqlCeConnection Conn = new SqlCeConnection(@"Data Source=C:\Users\achinbha\SkyDrive\Code-Project\Str2RegEx\Str2RegEx\Sampler.sdf");

            Conn.Open();
            SqlCeCommand    Command    = new SqlCeCommand("Select * from SampleDB WHERE Hash='" + hash + "'", Conn);
            SqlCeDataReader DataReader = Command.ExecuteReader();

            //If pattern exist in DB, update its frequency
            // Else insert to DB
            if (DataReader.Read())
            {
                lblCluster.Text   = "Cluster: " + DataReader.GetString(0);
                lblHash.Text      = "Hash: " + DataReader.GetString(1);
                lblFrequency.Text = "Frequency: " + DataReader[2].ToString();

                SqlCeDataAdapter Adapter = new SqlCeDataAdapter(Command);
                Adapter.UpdateCommand = new SqlCeCommand("UPDATE SampleDB SET Frequency=" + (Convert.ToInt32(DataReader[2].ToString()) + 1) + "WHERE Hash = '" + hash + "'", Conn);
                Adapter.UpdateCommand.ExecuteNonQuery();
            }
            else
            {
                lblCluster.Text = "Cluster: " + Cluster;
                lblHash.Text    = "Hash: " + hash;

                //
                // TODO:
                // Check with user for Cluster name if not provided
                //
                SqlCeDataAdapter Adapter = new SqlCeDataAdapter(Command);
                Adapter.UpdateCommand = new SqlCeCommand("Insert into SampleDB (Cluster, Hash, Frequency, Stack) Values ('" + Cluster + "', '" + hash + "', 0, '')", Conn);
                lblFrequency.Text     = "Frequency: " + Adapter.UpdateCommand.ExecuteNonQuery();
            }
            dataGridView1.Refresh();
            DataReader.Close();
            Conn.Close();

            bool flag = false;

            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                if (dataGridView1.Rows[i].Cells[1].Value.ToString() == hash)
                {
                    dataGridView1.ClearSelection();
                    flag = true;
                    int Frequency = Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value.ToString());
                    Frequency = Frequency + 1;
                    dataGridView1.Rows[i].Cells[2].Value = Frequency;
                    dataGridView1.Rows[i].Selected       = true;
                    break;
                }
            }

            if (flag == false)
            {
                //dataGridView1.Rows.Add(hash, 0, Cluster,"");
            }
        }
Exemplo n.º 26
0
 private string GetMd5(string str)
 {
     System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
     return(BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", null).ToLower());
 }
Exemplo n.º 27
0
        private string GetHDsid()
        {
            string KeyPw = string.Empty;

            try
            {
                using (System.Management.ManagementClass mc = new System.Management.ManagementClass("Win32_DiskDrive"))
                {
                    string strHardDiskID = string.Empty;
                    foreach (System.Management.ManagementObject mo in mc.GetInstances())
                    {
                        if (mo["Index"].ToString().Trim() == "0")
                        {
                            foreach (System.Management.PropertyData pd in mo.Properties)
                            {
                                bool has = false;
                                switch (pd.Name.Trim())
                                {
                                case "Caption":
                                {
                                    strHardDiskID += mo["Caption"].ToString().Trim();
                                    break;
                                }

                                case "SerialNumber":
                                {
                                    strHardDiskID += mo["SerialNumber"].ToString().Trim();
                                    has            = true;
                                    break;
                                }

                                case "Signature":
                                {
                                    strHardDiskID += mo["Signature"].ToString().Trim();
                                    break;
                                }

                                default:
                                {
                                    break;
                                }
                                }
                                if (has)
                                {
                                    break;
                                }
                            }
                            break;
                        }
                    }
                    strHardDiskID = string.IsNullOrEmpty(strHardDiskID) ? "13816350872" : strHardDiskID;
                    using (System.Security.Cryptography.MD5 md = System.Security.Cryptography.MD5.Create())
                    {
                        KeyPw = BitConverter.ToString(md.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strHardDiskID))).Replace("-", string.Empty);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return(KeyPw);
        }
Exemplo n.º 28
0
        public DataTable enterVerify(string account, string access_code, out THC_Library.Error error)
        {
            error = null;
            DataTable resultTable = null;

            byte[] pwdBytes = System.Text.Encoding.Default.GetBytes(access_code);
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            pwdBytes = md5.ComputeHash(pwdBytes);
            string strPwd = Convert.ToBase64String(pwdBytes);

            IList <SqlParameter> paraList = new System.Collections.Generic.List <SqlParameter>();
            string strSQL = "select AU001,AU003 from activity_user where AU001=@AU001";

            paraList.Add(new SqlParameter("@AU001", account));

            DataBaseControl dbCtl = new DataBaseControl();

            try
            {
                dbCtl.Open();
                IDataReader dataReader = dbCtl.GetReader(strSQL, paraList);
                if (dataReader.Read())
                {
                    string PWD = dataReader["AU003"].ToString();
                    dataReader.Close();
                    if (PWD != strPwd)
                    {
                        throw new Exception("請輸入正確的密碼");
                    }
                }
                else
                {
                    dataReader.Close();
                    throw new Exception("請輸入正確的帳號");
                }

                strSQL = "update activity_user set AU004=@AU004 where AU001=@AU001";
                paraList.Clear();
                paraList.Add(new SqlParameter("@AU004", DateTime.Now));
                paraList.Add(new SqlParameter("@AU001", account));
                dbCtl.ExecuteCommad(strSQL, paraList);

                if (account == "root.admin")
                {
                    strSQL = "select AU001,AU002,AU004 from activity_user where AU001!='root.admin'";
                    paraList.Clear();
                    resultTable = dbCtl.GetDataTable(strSQL, paraList);
                }
            }
            catch (Exception ex)
            {
                error              = new THC_Library.Error();
                error.Number       = THC_Library.THCException.SYSTEM_ERROR;
                error.ErrorMessage = ex.Message;
            }
            finally
            {
                dbCtl.Close();
            }

            return(resultTable);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Creates an object from inputstream
        /// </summary>
        /// <param name="bucketName">Bucket to create object in</param>
        /// <param name="objectName">Key of the new object</param>
        /// <param name="size">Total size of bytes to be written, must match with data's length</param>
        /// <param name="contentType">Content type of the new object, null defaults to "application/octet-stream"</param>
        /// <param name="data">Stream of bytes to send</param>
        /// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
        /// <param name="metaData">Object metadata to be stored. Defaults to null.</param>
        public async Task PutObjectAsync(string bucketName, string objectName, Stream data, long size, string contentType = null, Dictionary <string, string> metaData = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            utils.validateBucketName(bucketName);
            utils.validateObjectName(objectName);
            if (metaData == null)
            {
                metaData = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
            }
            else
            {
                metaData = new Dictionary <string, string>(metaData, StringComparer.OrdinalIgnoreCase);
            }
            if (string.IsNullOrWhiteSpace(contentType))
            {
                contentType = "application/octet-stream";
            }
            if (!metaData.ContainsKey("Content-Type"))
            {
                metaData["Content-Type"] = contentType;
            }
            if (data == null)
            {
                throw new ArgumentNullException("Invalid input stream,cannot be null");
            }

            // for sizes less than 5Mb , put a single object
            if (size < Constants.MinimumPartSize && size >= 0)
            {
                var bytes = ReadFull(data, (int)size);
                if (bytes.Length != (int)size)
                {
                    throw new UnexpectedShortReadException("Data read " + bytes.Length + " is shorter than the size " + size + " of input buffer.");
                }
                await this.PutObjectAsync(bucketName, objectName, null, 0, bytes, metaData, cancellationToken);

                return;
            }
            // For all sizes greater than 5MiB do multipart.

            dynamic multiPartInfo = utils.CalculateMultiPartSize(size);
            double  partSize      = multiPartInfo.partSize;
            double  partCount     = multiPartInfo.partCount;
            double  lastPartSize  = multiPartInfo.lastPartSize;

            Part[] totalParts = new Part[(int)partCount];
            Part   part       = null;

            Part[] existingParts = null;

            string uploadId = await this.getLatestIncompleteUploadIdAsync(bucketName, objectName, cancellationToken);

            if (uploadId == null)
            {
                uploadId = await this.NewMultipartUploadAsync(bucketName, objectName, metaData, cancellationToken);
            }
            else
            {
                existingParts = await this.ListParts(bucketName, objectName, uploadId, cancellationToken).ToArray();
            }

            double expectedReadSize = partSize;
            int    partNumber;
            bool   skipUpload = false;

            for (partNumber = 1; partNumber <= partCount; partNumber++)
            {
                byte[] dataToCopy = ReadFull(data, (int)partSize);

                if (partNumber == partCount)
                {
                    expectedReadSize = lastPartSize;
                }
                if (existingParts != null && partNumber <= existingParts.Length)
                {
                    part = existingParts[partNumber - 1];
                    if (part != null && partNumber == part.PartNumber && expectedReadSize == part.partSize())
                    {
                        System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
                        byte[] hash = md5.ComputeHash(dataToCopy);
                        string etag = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();
                        if (etag.Equals(part.ETag))
                        {
                            totalParts[partNumber - 1] = new Part()
                            {
                                PartNumber = part.PartNumber, ETag = part.ETag, size = part.partSize()
                            };
                            skipUpload = true;
                        }
                    }
                }
                else
                {
                    skipUpload = false;
                }

                if (!skipUpload)
                {
                    string etag = await this.PutObjectAsync(bucketName, objectName, uploadId, partNumber, dataToCopy, metaData, cancellationToken);

                    totalParts[partNumber - 1] = new Part()
                    {
                        PartNumber = partNumber, ETag = etag, size = (long)expectedReadSize
                    };
                }
            }
            Dictionary <int, string> etags = new Dictionary <int, string>();

            for (partNumber = 1; partNumber <= partCount; partNumber++)
            {
                etags[partNumber] = totalParts[partNumber - 1].ETag;
            }
            await this.CompleteMultipartUploadAsync(bucketName, objectName, uploadId, etags, cancellationToken);
        }
Exemplo n.º 30
0
        private static bool Load(string fileName)
        {
            using (FileStream compressedStream = new FileStream(fileName, FileMode.Open))
                using (DeflateStream deflateStream = new DeflateStream(compressedStream, CompressionMode.Decompress, true))
                    using (MemoryStream stream = new MemoryStream())
                        using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
                        {
                            int hashSize = md5.HashSize / 8;

                            try
                            {
                                deflateStream.CopyTo(stream);
                            }
                            catch
                            {
                                InvalidateCompressedStream(compressedStream);

                                return(false);
                            }

                            stream.Seek(0L, SeekOrigin.Begin);

                            byte[] currentHash = new byte[hashSize];
                            stream.Read(currentHash, 0, hashSize);

                            byte[] expectedHash = md5.ComputeHash(stream);

                            if (!CompareHash(currentHash, expectedHash))
                            {
                                InvalidateCompressedStream(compressedStream);

                                return(false);
                            }

                            stream.Seek((long)hashSize, SeekOrigin.Begin);

                            Header header = ReadHeader(stream);

                            if (header.Magic != HeaderMagic)
                            {
                                InvalidateCompressedStream(compressedStream);

                                return(false);
                            }

                            if (header.CacheFileVersion != InternalVersion)
                            {
                                InvalidateCompressedStream(compressedStream);

                                return(false);
                            }

                            if (header.FeatureInfo != GetFeatureInfo())
                            {
                                InvalidateCompressedStream(compressedStream);

                                return(false);
                            }

                            if (header.InfosLen % InfoEntry.Stride != 0)
                            {
                                InvalidateCompressedStream(compressedStream);

                                return(false);
                            }

                            byte[] infosBuf       = new byte[header.InfosLen];
                            byte[] codesBuf       = new byte[header.CodesLen];
                            byte[] relocsBuf      = new byte[header.RelocsLen];
                            byte[] unwindInfosBuf = new byte[header.UnwindInfosLen];

                            stream.Read(infosBuf, 0, header.InfosLen);
                            stream.Read(codesBuf, 0, header.CodesLen);
                            stream.Read(relocsBuf, 0, header.RelocsLen);
                            stream.Read(unwindInfosBuf, 0, header.UnwindInfosLen);

                            try
                            {
                                PtcJumpTable = (PtcJumpTable)_binaryFormatter.Deserialize(stream);
                            }
                            catch
                            {
                                PtcJumpTable = new PtcJumpTable();

                                InvalidateCompressedStream(compressedStream);

                                return(false);
                            }

                            _infosStream.Write(infosBuf, 0, header.InfosLen);
                            _codesStream.Write(codesBuf, 0, header.CodesLen);
                            _relocsStream.Write(relocsBuf, 0, header.RelocsLen);
                            _unwindInfosStream.Write(unwindInfosBuf, 0, header.UnwindInfosLen);

                            return(true);
                        }
        }
Exemplo n.º 31
0
        private string DrawSignatureImage(List <Point> Points, string path)
        {
            int    width  = 512;
            int    height = 128;
            Bitmap bmp    = new Bitmap(width, height);

            Graphics g          = Graphics.FromImage(bmp);
            Brush    whiteBrush = new SolidBrush(Color.White);
            Brush    blackBrush = new SolidBrush(Color.Black);
            Pen      p          = new Pen(blackBrush);

            bmp.SetResolution(height / 2, width / 2);
            g.TranslateTransform(0f, height);
            g.ScaleTransform(1f, -1f);
            g.FillRegion(whiteBrush,
                         new Region(new Rectangle(0, 0, width, height)));

            p.Width    = 10;
            p.StartCap = System.Drawing.Drawing2D.LineCap.Round;
            p.EndCap   = System.Drawing.Drawing2D.LineCap.Round;
            p.LineJoin = System.Drawing.Drawing2D.LineJoin.Round;

            List <Point> line = new List <Point>();

            foreach (Point point in Points)
            {
                if (point.IsEmpty)
                {
                    try {
                        g.DrawLines(p, line.ToArray());
                        line.Clear();
                    } catch (Exception) {
                        System.Console.Write("BAD LINE: ");
                        foreach (Point pt in line)
                        {
                            System.Console.Write(pt);
                            System.Console.Write(" ");
                        }
                        System.Console.WriteLine("");
                    }
                }
                else
                {
                    line.Add(point);
                }
            }

            // silly rigamarole to get a unique file name
            System.Security.Cryptography.MD5 hasher = System.Security.Cryptography.MD5.Create();
            System.Text.ASCIIEncoding        enc    = new System.Text.ASCIIEncoding();
            byte[] hash = hasher.ComputeHash(enc.GetBytes(DateTime.Now.ToString()));
            System.Text.StringBuilder sBuilder = new System.Text.StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sBuilder.Append(hash[i].ToString("x2"));
            }
            string base_fn = path + "\\" + sBuilder.ToString() + ".bmp";

            bmp.Save(base_fn, System.Drawing.Imaging.ImageFormat.Bmp);

            // pass through 1bpp conversion
            byte[] fixbpp = BitmapBPP.BitmapConverter.To1bpp(base_fn);
            System.IO.File.WriteAllBytes(base_fn, fixbpp);

            return(base_fn);
        }
Exemplo n.º 32
0
		static FSDirectory()
		{
			{
				try
				{
					System.String name = typeof(FSDirectory).FullName;
					IMPL = System.Type.GetType(name);
				}
				catch (System.Security.SecurityException)
				{
					try
					{
						IMPL = System.Type.GetType(typeof(FSDirectory).FullName);
					}
					catch (System.Exception e)
					{
						throw new System.SystemException("cannot load default FSDirectory class: " + e.ToString(), e);
					}
				}
                catch (System.Exception e)
                {
                    throw new System.SystemException("cannot load FSDirectory class: " + e.ToString(), e);
                }
            }
			{
				try
				{
					DIGESTER = System.Security.Cryptography.MD5.Create();
				}
				catch (System.Exception e)
				{
					throw new System.SystemException(e.ToString(), e);
				}
			}
		}
Exemplo n.º 33
0
        private void DownloadNow()
        {
            if (InvokeRequired)
            {
                Invoke(new Action(DownloadNow));
                return;
            }
            DialogResult A = MessageBox.Show("Download '" + FileNameX + "'?", "DOWLOAD?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (A == DialogResult.No)
            {
                CallDefaultIcon();
                return;
            }
            // OpenDialog to select local
            FolderBrowserDialog Folder = new FolderBrowserDialog();

            Folder.ShowNewFolderButton = true;
            Folder.Description         = "Select folder to save this file!";
            Folder.ShowDialog();
            if (String.IsNullOrEmpty(Folder.SelectedPath))
            {
                MessageBox.Show("No path selected!", "EMPTY!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                CallDefaultIcon();
                return;
            }
            // Finish all pre then download
            Attachments DownloadAtt = new Attachments();

            string[] TempData = DownloadAtt.Download(AttachmentId);
            if (IsEncrypted == true)
            {
                DialogResult ask = MessageBox.Show("This file is encrypted! Do you want decrypt it now?", "DECRYPT THIS FILE?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (ask == DialogResult.Yes)
                {
                    // Check key
                    EnterKey KeyIn = new EnterKey();
                    while (true)
                    {
                        Operations.Content.Message.CurrentPassword = string.Empty;
                        KeyIn.ShowDialog();
                        if (Operations.Content.Message.CurrentPassword == string.Empty)
                        {
                            MessageBox.Show("This content is WhiteSpace or Empty!",
                                            "NO CONTENT", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            continue;
                        }
                        #region For Decrypt
                        byte[] Temp;
                        switch (Operations.GlobalVarriable.KindOfCrypt)
                        {
                        case 0:
                        {
                            Temp = Operations.AES.DecryptFile(TempData[0], Operations.Content.Message.CurrentPassword);
                            break;
                        }

                        case 1:
                        {
                            Temp = Operations.DES.DecryptFile(TempData[0], Operations.Content.Message.CurrentPassword);
                            break;
                        }

                        case 2:
                        {
                            Temp = Operations.TwoFish.DecryptFile(TempData[0], Operations.Content.Message.CurrentPassword);
                            break;
                        }

                        case 3:
                        {
                            Temp = Operations.BlowFish.DecryptFile(TempData[0], Operations.Content.Message.CurrentPassword);
                            break;
                        }

                        default:
                            Temp = Operations.AES.DecryptFile(TempData[0], Operations.Content.Message.CurrentPassword);
                            break;
                        }
                        #endregion
                        if (Temp == null)
                        {
                            DialogResult C = MessageBox.Show("Wrong password! Do you want to try again?", "TRY AGAIN?", MessageBoxButtons.YesNo,
                                                             MessageBoxIcon.Question);
                            if (C == DialogResult.No)
                            {
                                DialogResult D = MessageBox.Show("Try to download without decrypt?", "TRY TO DOWNLOAD?",
                                                                 MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                                if (DialogResult.No == D)
                                {
                                    CallDefaultIcon();
                                    return;
                                }
                                else
                                {
                                    Operations.Content.Message.CurrentPassword = string.Empty;
                                    break;
                                }
                            }
                            else
                            {
                                continue;
                            }
                        }
                        else
                        {
                            try
                            {
                                string SavePath = Path.Combine(Folder.SelectedPath, FileNameX);
                                while (File.Exists(SavePath))
                                {
                                    System.Security.Cryptography.MD5 Hash = System.Security.Cryptography.MD5.Create();
                                    SavePath = Folder.SelectedPath + "\\" +
                                               Path.GetFileNameWithoutExtension(FileNameX) +
                                               "_" + BitConverter.ToString(Hash.ComputeHash(
                                                                               Encoding.UTF8.GetBytes(DateTime.Now.ToString()))).Replace("-", "") +
                                               Path.GetExtension(FileNameX);
                                }
                                File.WriteAllBytes(SavePath, Temp);
                                SuccessBox.Show("Successfully decrypted!");
                                Temp        = null;
                                TempData    = null;
                                DownloadAtt = null;
                                CallDefaultIcon();
                                return;
                            }
                            catch (Exception ee)
                            {
                                MessageBox.Show("Can not save '" + FileNameX + "', Try run this program with administration and try again!",
                                                "CAN NOT SAVE!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                CallDefaultIcon();
                                MessageBox.Show(ee.ToString());
                                return;
                            }
                        }
                    }
                }
            }
            // No encrypt
            try
            {
                string SavePath = Path.Combine(Folder.SelectedPath, FileNameX);
                while (File.Exists(SavePath))
                {
                    System.Security.Cryptography.MD5 Hash = System.Security.Cryptography.MD5.Create();
                    SavePath = Folder.SelectedPath + "\\" +
                               Path.GetFileNameWithoutExtension(FileNameX) +
                               "_" + BitConverter.ToString(Hash.ComputeHash(
                                                               Encoding.UTF8.GetBytes(DateTime.Now.ToString()))).Replace("-", "") +
                               Path.GetExtension(FileNameX);
                }
                File.WriteAllBytes(SavePath, Convert.FromBase64String(TempData[0]));
                SuccessBox.Show("Successfully saved!");
                TempData    = null;
                DownloadAtt = null;
                CallDefaultIcon();
                return;
            }
            catch (Exception ee)
            {
                MessageBox.Show("Can not save '" + FileNameX + "', Try run this program with administration and try again!",
                                "CAN NOT SAVE!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                CallDefaultIcon();
                MessageBox.Show(ee.ToString());
                return;
            }
        }
Exemplo n.º 34
0
 /// <summary>
 /// Computes the MD5 hash value for the specified byte array.
 /// </summary>
 /// <param name="bytes">The input to compute the hash code for.</param>
 /// <returns>The computed hash code as GUID.</returns>
 /// <remarks>
 /// One instance of the MD5 Crypto Service Provider
 /// can't operate properly with multiple simultaneous threads.
 /// Use lock to solve this problem.
 /// </remarks>
 public static Guid ComputeMd5Hash(byte[] bytes)
 {
     byte[] hash;
     lock (HashProviderLock)
     {
         HashProvider = HashProvider ?? new System.Security.Cryptography.MD5CryptoServiceProvider();
         hash = HashProvider.ComputeHash(bytes);
     }
     return new Guid(hash);
 }
Exemplo n.º 35
0
 public static Guid HashGuid(string uniqueString)
 {
     System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
     byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes(uniqueString));
     return(new Guid(hash));
 }
Exemplo n.º 36
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            if (!Input.Email.EndsWith("@mvla.net"))
            {
                ModelState.AddModelError(string.Empty, "Not a valid MVLA email address!");
                return(Page());
            }

            returnUrl ??= Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                StringBuilder sb = new StringBuilder();
                using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
                {
                    byte[] inputBytes = Encoding.ASCII.GetBytes(Input.Email.Trim().ToLower());
                    byte[] hashBytes  = md5.ComputeHash(inputBytes);

                    for (int i = 0; i < hashBytes.Length; i++)
                    {
                        sb.Append(hashBytes[i].ToString("X2"));
                    }
                }

                var user = new ContraUser
                {
                    Name = info.Principal.FindFirstValue(ClaimTypes.Name),

                    Articles       = new List <Article>(),
                    ArticlesLiked  = new List <Article>(),
                    ArticlesViewed = new List <Article>(),
                    CommentsLiked  = new List <Comment>(),

                    ProfilePictureURL = "https://gravatar.com/avatar/" + sb.ToString() + "?d=identicon",
                    UserName          = Input.Email,
                    Email             = Input.Email,
                    DateJoined        = DateTime.Now
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);

                        var userId = await _userManager.GetUserIdAsync(user);

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId, code },
                            protocol: Request.Scheme);

                        await _emailSender.SendConfirmEmailAsync(Input.Email, info.Principal.FindFirstValue(ClaimTypes.Name), callbackUrl);

                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                        }
                        else
                        {
                            await _signInManager.SignInAsync(user, isPersistent : false);

                            return(LocalRedirect(returnUrl));
                        }
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
Exemplo n.º 37
0
        static void Main(string[] args)
        {
            bool clean = args.Length > 0 && args[0].Equals("/clean", StringComparison.OrdinalIgnoreCase);

            if (clean)
            {
                Console.WriteLine("Performing clean build of music data.");
            }
            var dacs = IniSerializer.Deserialize <Dictionary <string, DACInfo> >("Sound/DAC/DAC.ini");

            if (dacs.Count > 96)
            {
                Console.WriteLine("Warning: You have {0} DAC samples, but SMPS can only use 96!", dacs.Count);
            }
            int dacheadsize = dacs.Count * 7;
            var samples     = new List <KeyValuePair <string, int> >();

            foreach (var item in dacs.Select(a => a.Value.File).Distinct())
            {
                samples.Add(new KeyValuePair <string, int>(item, (int)new FileInfo(Path.Combine("Sound/DAC", item)).Length));
            }
            List <int> dacbanksizes = new List <int>()
            {
                dacheadsize
            };
            List <List <string> > dacbanks = new List <List <string> > {
                new List <string>()
            };

            foreach (var item in samples.OrderByDescending(a => a.Value))
            {
                bool found = false;
                for (int bank = 0; bank < dacbanksizes.Count; bank++)
                {
                    if (dacbanksizes[bank] + item.Value <= 0x8000)
                    {
                        dacbanks[bank].Add(item.Key);
                        dacbanksizes[bank] += item.Value;
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    dacbanks.Add(new List <string>()
                    {
                        item.Key
                    });
                    dacbanksizes.Add(item.Value + dacheadsize);
                }
            }
            var samplenums = new Dictionary <string, string>();

            using (StreamWriter sw = new StreamWriter("dacsamples.gen.asm", false, Encoding.ASCII))
            {
                for (int b = 0; b < dacbanks.Count; b++)
                {
                    sw.WriteLine("DacBank{0}:\tstartBank", b + 1);
                    sw.WriteLine("\tDAC_Master_Table");
                    sw.WriteLine();
                    foreach (string item in dacbanks[b])
                    {
                        string label = Path.GetFileNameWithoutExtension(item).Replace(' ', '_').Replace('-', '_');
                        samplenums.Add(item, label);
                        sw.WriteLine("DAC_{0}_Data:\tDACBINCLUDE \"sound/DAC/{1}\"", label, item);
                    }
                    sw.WriteLine();
                    sw.WriteLine("\tfinishBank");
                    sw.WriteLine();
                }
            }
            List <string> dacids = new List <string>(dacs.Count);

            using (StreamWriter sw = new StreamWriter("dacinfo.gen.asm", false, Encoding.ASCII))
            {
                sw.WriteLine("DAC_Master_Table macro");
                sw.WriteLine("\tifndef DACPointers");
                sw.WriteLine("DACPointers label *");
                sw.WriteLine("\telseif (DACPointers&$7FFF)<>((*)&$7FFF)");
                sw.WriteLine("\t\tfatal \"Inconsistent placement of DAC_Master_Table macro on bank \\{soundBankName}\"");
                sw.WriteLine("\tendif");
                sw.WriteLine();
                foreach (var item in dacs)
                {
                    sw.WriteLine("\tDAC_Setup\t{0},DAC_{1}_Data ; {2}", item.Value.Rate, samplenums[item.Value.File], item.Key);
                    dacids.Add(item.Key);
                }
                sw.WriteLine("\tendm");
            }
            using (StreamWriter sw = new StreamWriter("dacbanks.gen.asm", false, Encoding.ASCII))
            {
                sw.WriteLine("\tdb\tzmake68kBank(DacBank1)");
                foreach (var item in dacs)
                {
                    sw.WriteLine("\tdb\tzmake68kBank(DAC_{0}_Data)", samplenums[item.Value.File]);
                }
            }
            using (StreamWriter sw = new StreamWriter("dacids.gen.asm", false, Encoding.ASCII))
            {
                string last = "$81";
                for (int i = 0; i < dacids.Count; i++)
                {
                    if (i % 7 == 0)
                    {
                        sw.Write("\tenum {0}={1}", dacids[i], last);
                    }
                    else
                    {
                        sw.Write(",{0}", dacids[i]);
                    }
                    if (i % 7 == 6)
                    {
                        sw.WriteLine();
                        last = dacids[i] + "+1";
                    }
                }
            }
            using (StreamWriter sw = new StreamWriter("tmp.asm", false, Encoding.ASCII))
            {
                sw.WriteLine("\tCPU 68000");
                sw.WriteLine("\tpadding off");
                sw.WriteLine("SonicDriverVer = 5");
                sw.WriteLine("SourceDriver set 3");
                sw.WriteLine("SourceSMPS2ASM set 0");
                sw.WriteLine("\tinclude \"sonic3k.macros.asm\"");
                sw.WriteLine("\tinclude \"Sound/_smps2asm_inc.asm\"");
                sw.WriteLine("\tinclude \"Sound/UniBank.asm\"");
            }
            ProcessStartInfo _si = new ProcessStartInfo("AS/Win32/asw", "-E -xx -A -r 2 -q -U tmp.asm")
            {
                CreateNoWindow = true
            };

            _si.EnvironmentVariables.Add("AS_MSGPATH", "AS/Win32");
            _si.EnvironmentVariables.Add("USEANSI", "n");
            _si.UseShellExecute = false;
            using (Process proc = Process.Start(_si))
                proc.WaitForExit();
            File.Delete("tmp.asm");
            if (File.Exists("tmp.log"))
            {
                Console.Write(File.ReadAllText("tmp.log"));
                File.Delete("tmp.log");
            }
            _si = new ProcessStartInfo("AS/Win32/fdp2bin", "tmp.p tmp.bin")
            {
                CreateNoWindow  = true,
                UseShellExecute = false
            };
            using (Process proc = Process.Start(_si))
                proc.WaitForExit();
            File.Delete("tmp.p");
            short uvbsize = (short)new FileInfo("tmp.bin").Length;

            File.Delete("tmp.bin");
            var  songs    = IniSerializer.Deserialize <Dictionary <string, MusicInfo> >("Sound/Music/Music.ini");
            bool writeini = false;

            System.Security.Cryptography.MD5 md5hasher = System.Security.Cryptography.MD5.Create();
            foreach (var item in songs)
            {
                switch (Path.GetExtension(item.Value.File).ToLowerInvariant())
                {
                case ".asm":
                case ".68k":
                    string md5 = GetFileHash(md5hasher, Path.Combine("sound/music", item.Value.File), true);
                    if (clean || item.Value.MD5 != md5 || item.Value.Size <= 0)
                    {
                        Console.WriteLine("Building song \"{0}\"...", item.Value.Title ?? item.Key);
                        using (StreamWriter sw = new StreamWriter("tmp.asm", false, Encoding.ASCII))
                        {
                            sw.WriteLine("\tCPU 68000");
                            sw.WriteLine("\tpadding off");
                            sw.WriteLine("SonicDriverVer = 5");
                            sw.WriteLine("z80_UniVoiceBank = 0");
                            if (item.Value.ExtData != null && item.Value.ExtData.Length > 0)
                            {
                                foreach (var dat in item.Value.ExtData)
                                {
                                    sw.WriteLine("{0} = 0", dat);
                                }
                            }
                            sw.WriteLine("\tinclude \"sonic3k.macros.asm\"");
                            sw.WriteLine("\tinclude \"Sound/_smps2asm_inc.asm\"");
                            sw.WriteLine("\tinclude \"Sound/Music/{0}\"", item.Value.File);
                        }
                        ProcessStartInfo si = new ProcessStartInfo("AS/Win32/asw", "-E -xx -A -r 2 -q -U tmp.asm")
                        {
                            CreateNoWindow = true
                        };
                        si.EnvironmentVariables.Add("AS_MSGPATH", "AS/Win32");
                        si.EnvironmentVariables.Add("USEANSI", "n");
                        si.UseShellExecute = false;
                        using (Process proc = Process.Start(si))
                            proc.WaitForExit();
                        File.Delete("tmp.asm");
                        if (File.Exists("tmp.log"))
                        {
                            Console.Write(File.ReadAllText("tmp.log"));
                            File.Delete("tmp.log");
                        }
                        if (!File.Exists("tmp.p"))
                        {
                            continue;
                        }
                        si = new ProcessStartInfo("AS/Win32/fdp2bin", "tmp.p tmp.bin")
                        {
                            CreateNoWindow  = true,
                            UseShellExecute = false
                        };
                        using (Process proc = Process.Start(si))
                            proc.WaitForExit();
                        File.Delete("tmp.p");
                        if (!File.Exists("tmp.bin"))
                        {
                            continue;
                        }
                        item.Value.Size = (short)new FileInfo("tmp.bin").Length;
                        item.Value.MD5  = md5;
                        File.Delete("tmp.bin");
                        writeini = true;
                    }
                    break;

                case ".bin":
                    short size = (short)new FileInfo(Path.Combine("sound/music", item.Value.File)).Length;
                    //string md5 = GetFileHash(md5hasher, Path.Combine("sound/music", item.Value.File), false);
                    if (item.Value.Size != size)
                    {
                        item.Value.Size = size;
                        writeini        = true;
                    }
                    break;
                }
            }
            if (writeini)
            {
                IniSerializer.Serialize(songs, "sound/music/music.ini");
            }
            Dictionary <string, string> musicfiles = new Dictionary <string, string>();
            int        musheadsize = songs.Count * 2 + uvbsize;
            List <int> banksizes   = new List <int>()
            {
                musheadsize
            };
            List <List <KeyValuePair <string, MusicInfo> > > banks = new List <List <KeyValuePair <string, MusicInfo> > >()
            {
                new List <KeyValuePair <string, MusicInfo> >()
            };

            foreach (var item in songs.OrderByDescending(a => a.Value.Size))
            {
                if (musicfiles.ContainsKey(item.Value.File))
                {
                    continue;
                }
                musicfiles.Add(item.Value.File, item.Key);
                bool found = false;
                for (int i = 0; i < banks.Count; i++)
                {
                    if (banksizes[i] + item.Value.Size <= 0x8000)
                    {
                        banks[i].Add(item);
                        banksizes[i] += item.Value.Size;
                        found         = true;
                        break;
                    }
                }
                if (!found)
                {
                    banks.Add(new List <KeyValuePair <string, MusicInfo> >()
                    {
                        item
                    });
                    banksizes.Add(item.Value.Size + musheadsize);
                }
            }
            using (StreamWriter sw = new StreamWriter("musicdata.gen.asm", false, Encoding.ASCII))
            {
                for (int i = 0; i < banks.Count; i++)
                {
                    sw.WriteLine("; ------------------------------------------------------------------------------");
                    sw.WriteLine("; Music bank {0}", i + 1);
                    sw.WriteLine("; ------------------------------------------------------------------------------");
                    sw.WriteLine("Mus_Bank{0}_Start:\tstartBank", i + 1);
                    sw.WriteLine("\tMusic_Master_Table");
                    if (i == 0)
                    {
                        sw.Write("z80_UniVoiceBank:");
                    }
                    sw.WriteLine("\tinclude \"Sound/UniBank.asm\" ; {0:X} bytes", uvbsize);
                    foreach (var item in banks[i])
                    {
                        switch (Path.GetExtension(item.Value.File).ToLowerInvariant())
                        {
                        case ".asm":
                        case ".68k":
                            sw.WriteLine("MusData_{0}:\tinclude \"Sound/Music/{1}\" ; ${2:X} bytes", item.Key, item.Value.File, item.Value.Size);
                            break;

                        case ".bin":
                            sw.WriteLine("MusData_{0}:\tBINCLUDE \"Sound/Music/{1}\" ; ${2:X} bytes", item.Key, item.Value.File, item.Value.Size);
                            break;
                        }
                    }
                    sw.WriteLine();
                    sw.WriteLine("\tfinishBank");
                    sw.WriteLine();
                }
            }
            using (StreamWriter sw = new StreamWriter("musicinfo.gen.asm", false, Encoding.ASCII))
            {
                sw.WriteLine("Music_Master_Table macro");
                sw.WriteLine("\tifndef MusicPointers");
                sw.WriteLine("MusicPointers label *");
                sw.WriteLine("\telseif (MusicPointers&$7FFF)<>((*)&$7FFF)");
                sw.WriteLine("\t\tfatal \"Inconsistent placement of Music_Master_Table macro on bank \\{soundBankName}\"");
                sw.WriteLine("\tendif");
                foreach (var item in songs)
                {
                    sw.WriteLine("\tdeclsong\tMusData_{0}", musicfiles[item.Value.File]);
                }
                sw.WriteLine("\tifndef zMusIDPtr__End");
                sw.WriteLine("zMusIDPtr__End label *");
                sw.WriteLine("\tendif");
                sw.WriteLine("\tendm");
            }
            using (StreamWriter sw = new StreamWriter("musicbanks.gen.asm", false, Encoding.ASCII))
            {
                foreach (var item in songs)
                {
                    sw.WriteLine("\tdb\tzmake68kBank(MusData_{0})", musicfiles[item.Value.File]);
                }
            }
            using (StreamWriter sw = new StreamWriter("musicids.gen.asm", false, Encoding.ASCII))
            {
                List <string> musids = new List <string>(songs.Keys);
                sw.WriteLine("\tphase $01");
                sw.WriteLine("Mus__First = *");
                for (int i = 0; i < musids.Count; i++)
                {
                    sw.WriteLine("Mus_{0}\tds.b\t1 ; ${1:X2}", musids[i], i + 1);
                }
                sw.WriteLine("Mus__End = *");
            }

            /*using (StreamWriter sw = new StreamWriter("musicnames.gen.asm", false, Encoding.ASCII))
             * {
             *      sw.WriteLine("SongNames:\toffsetTable");
             *      sw.WriteLine("\toffsetTableEntry.w\tMusNam_Null");
             *      foreach (var item in songs)
             *              sw.WriteLine("\toffsetTableEntry.w\tMusNam_{0}", item.Key);
             *      sw.WriteLine();
             *      sw.WriteLine("MusNam_Null:\tdc.b 0,' '");
             *      foreach (var item in songs)
             *              sw.WriteLine("MusNam_{0}:\tsongtext\t\"{1}\"", item.Key, item.Value.Title.ToUpperInvariant());
             *      sw.WriteLine("\teven");
             * }*/
        }