Ejemplo n.º 1
0
 private static string Hash(string str)
 {
     System.Security.Cryptography.SHA512Managed sha512 = new System.Security.Cryptography.SHA512Managed();
     byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);
     bytes = sha512.ComputeHash(bytes);
     return BitConverter.ToString(bytes).Replace("-", "");
 }
Ejemplo n.º 2
0
 private string SHA512(string hash_string)
 {
     System.Security.Cryptography.SHA512Managed sha512 = new System.Security.Cryptography.SHA512Managed();
     Byte[] EncryptedSHA512 = sha512.ComputeHash(System.Text.Encoding.UTF8.GetBytes(hash_string));
     sha512.Clear();
     string hashed = BitConverter.ToString(EncryptedSHA512).Replace("-", "").ToLower();
     return hashed;
 }
Ejemplo n.º 3
0
 public static string CreateSHAHash(string Password)
 {
     string Salt = "ozauyvbyerytrg";
     System.Security.Cryptography.SHA512Managed HashTool = new System.Security.Cryptography.SHA512Managed();
     Byte[] PasswordAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(Password, Salt));
     Byte[] EncryptedBytes = HashTool.ComputeHash(PasswordAsByte);
     HashTool.Clear();
     return Convert.ToBase64String(EncryptedBytes);
 }
        //private helpers
        private string getHashedPassword(string rawPassword)
        {
            using (System.Security.Cryptography.SHA512Managed hashTool =
                new System.Security.Cryptography.SHA512Managed()) {

                Byte[] PasswordAsByte = System.Text.Encoding.UTF8.GetBytes(rawPassword);
                Byte[] EncryptedBytes = hashTool.ComputeHash(PasswordAsByte);
                hashTool.Clear();

                return Convert.ToBase64String(EncryptedBytes);
            }
        }
Ejemplo n.º 5
0
        internal static byte[] ToByteSha512(string text)
        {
            if (String.IsNullOrEmpty(text))
            {
                return(new byte[0]);
            }

            using (var hashingAlgorithm = new System.Security.Cryptography.SHA512Managed())
            {
                byte[] textData = System.Text.Encoding.UTF8.GetBytes(text);
                return(hashingAlgorithm.ComputeHash(textData));
            }
        }
Ejemplo n.º 6
0
        public static string Hash(string password)
        {
            var bytes = new UTF8Encoding().GetBytes(password);

            byte[] hashBytes;

            using (var algorithm = new System.Security.Cryptography.SHA512Managed())
            {
                hashBytes = algorithm.ComputeHash(bytes);
            }

            return(Convert.ToBase64String(hashBytes));
        }
Ejemplo n.º 7
0
        internal static string Hash(decimal identificationNumber)
        {
            var salt1 = "jdhjdbbgh@fcshbsg@hbjksb";
            var salt2 = "hhggbkklklkl;ujnk*jnknk)";
            var bytes = new UTF8Encoding().GetBytes(salt1 + identificationNumber + salt2);

            byte[] hashBytes;
            using (var algorithm = new System.Security.Cryptography.SHA512Managed())
            {
                hashBytes = algorithm.ComputeHash(bytes);
            }
            return(Convert.ToBase64String(hashBytes));
        }
Ejemplo n.º 8
0
        void initLAN()
        {
            url = "LAN";
            App.theCore.joinCircle(url);
            System.Security.Cryptography.SHA512Managed sha = new System.Security.Cryptography.SHA512Managed();

            circleHash = BitConverter.ToUInt64(sha.ComputeHash(Encoding.UTF8.GetBytes(url.ToLower())), 0);
            App.theCore.chatReceivedEvent += chatReceived;
            MainForm.colorChange          += colorChanged;
            ((MainForm)App.mainForm).setColors();

            App.settings.setBool("Joined LAN Circle", true);
        }
Ejemplo n.º 9
0
        void win_OnLoginClick(string username, string password)
        {
            System.Security.Cryptography.SHA512Managed sha512 = new System.Security.Cryptography.SHA512Managed();
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(password);
            string encPassword = System.Convert.ToBase64String(sha512.ComputeHash(bytes));

            EngineRequest request = new EngineRequest();
            request.Engine = _engine;
            request.Database = _db;
            request.OnComplete = new EngineBase.CompletionDelegate(OnAuthenticated);
            request.RequestingPartyType = OpenDMS.Storage.Security.RequestingPartyType.User;

            _engine.AuthenticateUser(request, username, encPassword);
        }
Ejemplo n.º 10
0
        internal static string ToStringSha512(string text)
        {
            if (String.IsNullOrEmpty(text))
            {
                return(String.Empty);
            }

            using (var hashingAlgorithm = new System.Security.Cryptography.SHA512Managed())
            {
                byte[] textData = System.Text.Encoding.UTF8.GetBytes(text);
                byte[] hash     = hashingAlgorithm.ComputeHash(textData);
                return(BitConverter.ToString(hash).Replace("-", String.Empty));
            }
        }
        public string Cifrador(string clave = "")
        {
            string contrasena = "";

            System.Security.Cryptography.SHA512Managed passwd = new System.Security.Cryptography.SHA512Managed();
            if (clave != null)
            {
                byte[] texto        = System.Text.Encoding.ASCII.GetBytes(clave);
                byte[] textocifrado = passwd.ComputeHash(texto);
                contrasena = Convert.ToBase64String(textocifrado);
            }

            return(contrasena);
        }
Ejemplo n.º 12
0
        private string HashPassword(string password)
        {
            StringBuilder stringHash = new StringBuilder();

            using (var hmac = new System.Security.Cryptography.SHA512Managed())
            {
                var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
                for (int i = 0; i < computedHash.Length; i++)
                {
                    stringHash.Append(computedHash[i].ToString("X2"));
                }
            }
            return(stringHash.ToString());;
        }
Ejemplo n.º 13
0
 protected void Page_Load(object sender, EventArgs e)
 {
     order_Id = Request.QueryString["orderID"].ToString();
     string hash_string = order_Id + apiKey + merchant_id;
     System.Security.Cryptography.SHA512Managed sha512 = new System.Security.Cryptography.SHA512Managed();
     Byte[] EncryptedSHA512 = sha512.ComputeHash(System.Text.Encoding.UTF8.GetBytes(hash_string));
     sha512.Clear();
     hashed = BitConverter.ToString(EncryptedSHA512).Replace("-", "").ToLower();
     url 	= checkstatusurl + "/" + merchant_id  + "/" + order_Id + "/" + hashed + "/" + "orderstatus.reg";
     string jsondata = new WebClient().DownloadString(url);
     RemitaResponse result = JsonConvert.DeserializeObject<RemitaResponse>(jsondata);
     message = result.message;
     rrr = result.RRR;
     statuscode = result.status;
 }
Ejemplo n.º 14
0
        void win_OnLoginClick(string username, string password)
        {
            System.Security.Cryptography.SHA512Managed sha512 = new System.Security.Cryptography.SHA512Managed();
            byte[] bytes       = System.Text.Encoding.UTF8.GetBytes(password);
            string encPassword = System.Convert.ToBase64String(sha512.ComputeHash(bytes));

            EngineRequest request = new EngineRequest();

            request.Engine              = _engine;
            request.Database            = _db;
            request.OnComplete          = new EngineBase.CompletionDelegate(OnAuthenticated);
            request.RequestingPartyType = OpenDMS.Storage.Security.RequestingPartyType.User;

            _engine.AuthenticateUser(request, username, encPassword);
        }
Ejemplo n.º 15
0
 private bool VerifyPasswordHash(string password, byte[] passwordHash)
 {
     using (var hasher = new System.Security.Cryptography.SHA512Managed())
     {
         var hash = hasher.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
         for (int i = 0; i < hash.Length; i++)
         {
             if (hash[i] != passwordHash[i])
             {
                 return(false);
             }
         }
         return(true);
     }
 }
        /// <summary>
        /// Create an SHA512 hash of a string of text.
        /// </summary>
        /// <param name="text">Text to hash</param>
        /// <param name="uppercase"></param>
        /// <returns>The SHA512 hash of the input string</returns>
        public static string ToSha512Hash(this string text, bool uppercase = true)
        {
            using (var sha512 = new System.Security.Cryptography.SHA512Managed())
            {
                var hash = sha512.ComputeHash(Encoding.UTF8.GetBytes(text));
                var sb   = new StringBuilder(hash.Length * 2);

                foreach (byte b in hash)
                {
                    sb.Append(uppercase ? b.ToString("X2") : b.ToString("x2"));
                }

                return(sb.ToString());
            }
        }
Ejemplo n.º 17
0
        public static string Hash(string wordToHash)
        {
            string key = "";

            System.Security.Cryptography.SHA512 hashtool = new System.Security.Cryptography.SHA512Managed();
            Byte[] strHash       = System.Text.Encoding.UTF8.GetBytes(string.Concat(wordToHash));
            Byte[] encryptedHash = hashtool.ComputeHash(strHash);
            hashtool.Clear();
            StringBuilder hexString = new StringBuilder();

            for (int i = 0; i < encryptedHash.Length; i++)
            {
                hexString.Append(String.Format("{0:X2}", encryptedHash[i]));
            }
            key = hexString.ToString();
            return(key);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Generate hash.
        /// </summary>
        /// <param name="text">hash string.</param>
        /// <returns>return string</returns>
        private static string GenerateHash512(string text)
        {
            byte[] message = Encoding.UTF8.GetBytes(text);

            byte[] hashValue;
            System.Security.Cryptography.SHA512Managed hashString = new System.Security.Cryptography.SHA512Managed();
            string hex = string.Empty;

            hashValue = hashString.ComputeHash(message);

            foreach (byte x in hashValue)
            {
                hex += string.Format(CultureInfo.InvariantCulture, "{0:x2}", x);
            }

            return(hex);
        }
Ejemplo n.º 19
0
        public static String ToSveaAuthorizationHeader(this String body, string merchantId, string sharedSecret, DateTime dateTime)
        {
            byte[] hash;
            string hashString = body + sharedSecret + dateTime.ToSveaString();

            using (var sha = new System.Security.Cryptography.SHA512Managed())
            {
                hash = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(hashString));
            }
            StringBuilder hashHexSb = new StringBuilder();

            foreach (var b in hash)
            {
                hashHexSb.Append(String.Format("{0:x2}", b));
            }
            return($"Svea {Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{merchantId}:{hashHexSb.ToString()}"))}");
        }
Ejemplo n.º 20
0
        private void HashFiles(System.IO.FileInfo[] files, SortedList <string, string> infoList)
        {
            string directory = null;
            var    firstFile = files.FirstOrDefault();

            if (firstFile != null)
            {
                directory = firstFile.Directory.FullName;
            }

            SortedList <string, string> previouslyHashedFiles = GetHashedFiles(directory);


            foreach (var file in files)
            {
                try
                {
                    if (file.Name != "hashes.txt")
                    {
                        string hashString = null;
                        if (previouslyHashedFiles.ContainsKey(file.Name))
                        {
                            hashString = previouslyHashedFiles[file.Name];
                        }
                        var fileHashedAlready = !string.IsNullOrEmpty(hashString);
                        if (!fileHashedAlready)
                        {
                            var sha512 = new System.Security.Cryptography.SHA512Managed();
                            var hash   = sha512.ComputeHash(file.OpenRead());
                            hashString = Convert.ToBase64String(hash);
                        }

                        infoList.Add(hashString, file.FullName);

                        UpdateHashFile(previouslyHashedFiles, infoList, file);
                    }

                    backgroundWorker1.ReportProgress(++index);
                }
                catch (Exception ex)
                {
                    // TODO: Log error
                    exception = ex;
                }
            }
        }
Ejemplo n.º 21
0
 public static string GetHashedValue(string strVal)
 {
     try
     {
         var    bytes = new UTF8Encoding().GetBytes(strVal);
         byte[] hashBytes;
         using (var algorithm = new System.Security.Cryptography.SHA512Managed())
         {
             hashBytes = algorithm.ComputeHash(bytes);
         }
         string strHashedValue = Convert.ToBase64String(hashBytes);
         return(strHashedValue);
     }
     catch (Exception ex)
     {
         return(Convert.ToString(ex.Message));
     }
 }
Ejemplo n.º 22
0
        public static byte[] SHA512EncryptToBytes(string input, Encoding encoding)
        {
            if (input == null || input.Length == 0)
            {
                return(null);
            }
            if (encoding == null)
            {
                encoding = System.Text.UTF8Encoding.UTF8;
            }

            byte[] inputBytes = encoding.GetBytes(input);
            System.Security.Cryptography.SHA512Managed sha = new System.Security.Cryptography.SHA512Managed();
            byte[] shaResults = sha.ComputeHash(inputBytes);

            sha.Clear();
            return(shaResults);
        }
Ejemplo n.º 23
0
        public static PasswordVO Create(string clear_text)
        {
            if (string.IsNullOrWhiteSpace(clear_text))
            {
                throw new ArgumentNullException("clear_text");
            }

            using (var sha512 = new System.Security.Cryptography.SHA512Managed())
            {
                var buffer = System.Text.UTF8Encoding.UTF8.GetBytes(clear_text);
                var hash   = sha512.ComputeHash(buffer);

                return(new PasswordVO()
                {
                    _password = Convert.ToBase64String(hash), Buffer = hash,
                });
            }
        }
Ejemplo n.º 24
0
        public string Hash(string password)
        {
            if (string.IsNullOrEmpty(password))
            {
                return("");
            }

#if DEBUG
            return(password);
#else
            var    bytes = new UTF8Encoding().GetBytes(password);
            byte[] hashBytes;
            using (var algorithm = new System.Security.Cryptography.SHA512Managed())
            {
                hashBytes = algorithm.ComputeHash(bytes);
            }
            return(Convert.ToBase64String(hashBytes));
#endif
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Generates hash equivalent for the plain text data
        /// </summary>
        /// <param name="inputText">Plain text input string</param>
        /// <returns></returns>
        public string ComputeHash(string inputText)
        {
            if (string.IsNullOrWhiteSpace(inputText))
            {
                throw new NullReferenceException("inputText should not be empty!");
            }

            byte[] _saltBytes;
            
            if (string.IsNullOrWhiteSpace(saltValue))
            {
                saltValue = System.Web.Security.Membership.GeneratePassword(128, 64);
            }

            _saltBytes = Encoding.UTF8.GetBytes(saltValue);

            byte[] _plainTextBytes = Encoding.UTF8.GetBytes(inputText);
            byte[] _plainTextWithSaltBytes = new byte[_plainTextBytes.Length + _saltBytes.Length];

            _plainTextBytes.CopyTo(_plainTextWithSaltBytes, 0);
            _saltBytes.CopyTo(_plainTextWithSaltBytes, _plainTextBytes.Length);

            System.Security.Cryptography.HashAlgorithm _hash;

            switch (_hashAlgorithm)
            {
                case CustomHashAlgorithm.HashAlgorithm.SHA1:
                    _hash = new System.Security.Cryptography.SHA1Managed();
                    break;
                case CustomHashAlgorithm.HashAlgorithm.SHA256:
                    _hash = new System.Security.Cryptography.SHA256Managed();
                    break;
                case CustomHashAlgorithm.HashAlgorithm.SHA384:
                    _hash = new System.Security.Cryptography.SHA384Managed();
                    break;
                default:
                    _hash = new System.Security.Cryptography.SHA512Managed();
                    break;
            }

            return Convert.ToBase64String(_hash.ComputeHash(_plainTextWithSaltBytes));
        }
Ejemplo n.º 26
0
        private string GenerateToken()
        {
            var    hashfunc = new System.Security.Cryptography.SHA512Managed();
            Random rand     = new Random((int)DateTime.Now.Ticks);

            byte[] buffer = new byte[20];
            rand.NextBytes(buffer);
            var hash = hashfunc.ComputeHash(buffer);

            StringBuilder sb = new StringBuilder();

            foreach (byte b in hash)
            {
                sb.Append(b.ToString("x2"));
            }

            //_logger.LogInformation(sb.ToString());

            return(sb.ToString());
        }
Ejemplo n.º 27
0
        public CirclePanel(string url, UI.JoinCircleForm.CircleType circleType)
        {
            InitializeComponent();
            setupUserList();

            if (url.ToLower() == "http://lan/" || circleType == JoinCircleForm.CircleType.LAN)
            {
                initLAN();
                return;
            }
            this.circleType = circleType;
            this.url        = url;

            System.Security.Cryptography.SHA512Managed sha = new System.Security.Cryptography.SHA512Managed();

            circleHash = BitConverter.ToUInt64(sha.ComputeHash(Encoding.UTF8.GetBytes(url.ToLower())), 0);
            App.theCore.joinCircle(url);
            App.theCore.chatReceivedEvent += chatReceived;
            MainForm.colorChange          += colorChanged;
            ((MainForm)App.mainForm).setColors();


            System.Threading.Thread t = new System.Threading.Thread(joinLoop);
            t.IsBackground = true;
            t.Name         = "Circle join loop";
            t.Start();

            if (circleType == JoinCircleForm.CircleType.bootstrap)
            {
                App.settings.addStringToArrayNoDup("Bootstrap Circles Open", url);
            }
            else if (circleType == JoinCircleForm.CircleType.kademlia)
            {
                App.settings.addStringToArrayNoDup("Kademlia Circles Open", url);
            }
            if (isMono)
            {
                userListView.OwnerDraw = true;
            }
        }
        public void GivenUserEntityAndPasswordInfo_MapPasswordInfoCorrectlyMapsPasswordInfoToUserEntity_WhenCalled()
        {
            //arrange
            var passwordInfo = new DTOs.PasswordInfo
            {
                salt = "salt"
            };
            var crypto = new System.Security.Cryptography.SHA512Managed();

            passwordInfo.hash = crypto.ComputeHash(System.Text.Encoding.ASCII.GetBytes("apassword"));

            var userInfo = new Entities.UserInfo
            {
                email = "anemail",
                id    = 1
            };
            var userEntity = new Entities.User
            {
                id       = 1,
                userinfo = userInfo,
                username = "******"
            };

            var sut = new Mappings.UserEntityMapper();

            //act
            userEntity = sut.MapPasswordInfo(userEntity, passwordInfo);

            //assert
            Assert.AreEqual(userEntity.username, "username");
            Assert.AreEqual(userEntity.id, 1);
            Assert.AreEqual(userEntity.pwhash, passwordInfo.hash);
            Assert.AreEqual(userEntity.salt, passwordInfo.salt);
            Assert.AreEqual(userEntity.userinfo.email, "anemail");
            Assert.AreEqual(userEntity.userinfo.id, 1);
        }
Ejemplo n.º 29
0
        public string GetSHA512Hash(string pathName)
        {
            string strResult = "";
            string strHashData = "";

            byte[] arrbytHashValue;
            System.IO.FileStream oFileStream = null;

            System.Security.Cryptography.SHA512 oSHA512Hasher = new System.Security.Cryptography.SHA512Managed();

            try
            {
                oFileStream = GetFileStream(pathName);
                arrbytHashValue = oSHA512Hasher.ComputeHash(oFileStream);
                oFileStream.Close();

                strHashData = System.BitConverter.ToString(arrbytHashValue);
                strHashData = strHashData.Replace("-", "");
                strResult = strHashData;
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, "Error!", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.MessageBoxDefaultButton.Button1);
            }

            return (strResult);
        }
Ejemplo n.º 30
0
 public static string HashPassword(string password)
 {
     var algorithm = new System.Security.Cryptography.SHA512Managed();
     var hashByte = algorithm.ComputeHash(Encoding.UTF8.GetBytes(password));
     return Convert.ToBase64String(hashByte);
 }
Ejemplo n.º 31
0
        public static int Main(string[] args)
        {
            bool interactive = true;

            if (args.Length > 0)
            {
                interactive = false;
            }

            foreach (string arg in args)
            {
                if (arg.Contains("--generatediffs"))
                {
                    gendiffs = true;
                }
            }

            newAssCS = true;

            Console.WriteLine(string.Format("[( Pluton Patcher v{0} )]", Version));
            try {
                plutonAssembly = AssemblyPatcher.FromFile("Pluton.dll");
                rustAssembly   = AssemblyPatcher.FromFile("Assembly-CSharp.dll");
            } catch (FileNotFoundException ex) {
                Console.WriteLine("You are missing " + ex.FileName + " did you move the patcher to the managed folder ?");
                if (interactive)
                {
                    Console.WriteLine("Press any key to continue...");
                }
                return((int)ExitCode.DLL_MISSING);
            } catch (Exception ex) {
                Console.WriteLine("An error occured while reading the assemblies :");
                Console.WriteLine(ex.ToString());
                if (interactive)
                {
                    Console.WriteLine("Press any key to continue...");
                }
                return((int)ExitCode.DLL_READ_ERROR);
            }

            bNPC        = rustAssembly.GetType("BaseNPC");
            bPlayer     = rustAssembly.GetType("BasePlayer");
            codeLock    = rustAssembly.GetType("CodeLock");
            hooksClass  = plutonAssembly.GetType("Pluton.Hooks");
            itemCrafter = rustAssembly.GetType("ItemCrafter");
            pLoot       = rustAssembly.GetType("PlayerLoot");

            //Check if patching is required
            TypePatcher plutonClass = rustAssembly.GetType("PlutonPatched");

            if (plutonClass == null)
            {
                try {
                    if (gendiffs)
                    {
                        string hash = string.Empty;
                        using (var sha512 = new System.Security.Cryptography.SHA512Managed())
                            hash = BitConverter.ToString(sha512.ComputeHash(File.ReadAllBytes("Assembly-CSharp.dll"))).Replace("-", "").ToLower();

                        Directory.CreateDirectory("diffs");

                        string hashpath = "diffs" + Path.DirectorySeparatorChar + "lastHash";

                        if (File.Exists(hashpath))
                        {
                            newAssCS = hash != File.ReadAllText(hashpath);
                        }

                        if (newAssCS)
                        {
                            foreach (var difffile in Directory.GetFiles("diffs"))
                            {
                                if (difffile.Contains(".htm"))
                                {
                                    string filename = Path.GetFileName(difffile);
                                    string dirname  = Path.GetDirectoryName(difffile);
                                    Directory.CreateDirectory(Path.Combine(dirname, "old"));
                                    File.Move(difffile, difffile.Replace(Path.Combine(dirname, filename), Path.Combine(dirname, "old", filename)));
                                }
                            }
                        }

                        if (gendiffs && newAssCS)
                        {
                            File.WriteAllText(hashpath, hash);
                        }
                    }
                    PatchASMCSharp();
                    Console.WriteLine("Patched Assembly-CSharp !");
                } catch (Exception ex) {
                    interactive = true;
                    Console.WriteLine("An error occured while patching Assembly-CSharp :");
                    Console.WriteLine();
                    Console.WriteLine(ex.Message.ToString());

                    //Normal handle for the others
                    Console.WriteLine();
                    Console.WriteLine(ex.StackTrace.ToString());
                    Console.WriteLine();

                    if (interactive)
                    {
                        Console.WriteLine("Press any key to continue...");
                    }
                    return((int)ExitCode.ACDLL_GENERIC_PATCH_ERR);
                }
            }
            else
            {
                Console.WriteLine("Assembly-CSharp.dll is already patched!");
                return((int)ExitCode.ACDLL_ALREADY_PATCHED);
            }

            try {
                rustAssembly.Write("Assembly-CSharp.dll");
            } catch (Exception ex) {
                Console.WriteLine("An error occured while writing the assembly :");
                Console.WriteLine("Error at: " + ex.TargetSite.Name);
                Console.WriteLine("Error msg: " + ex.Message);

                if (interactive)
                {
                    Console.WriteLine("Press any key to continue...");
                }

                return((int)ExitCode.DLL_WRITE_ERROR);
            }

            //Successfully patched the server
            Console.WriteLine("Completed !");

            if (interactive)
            {
                System.Threading.Thread.Sleep(250);
            }

            return((int)ExitCode.SUCCESS);
        }
        public override bool ValidateUser(string username, string password)
        {
            if (string.IsNullOrEmpty(username))
            {
                return false;
            }
            if (string.IsNullOrEmpty(password))
            {
                return false;
            }
            var Context = UserContext.Current;
            {
                SecurityUser securityUser = null;
                securityUser = Context.Users.FirstOrDefault(Usr => Usr.Username == username);
                if (securityUser == null)
                {
                    return false;
                }
                if (!securityUser.Enabled)
                {
                    return false;
                }
                if (securityUser.IsLockedOut)
                {
                    return false;
                }
                String HashedPassword = securityUser.EncryptedPassword;
                Boolean VerificationSucceeded = false;
                if (String.IsNullOrWhiteSpace(securityUser.OldSalt))
                {
                    VerificationSucceeded = (HashedPassword != null &&
                                                     Crypto.VerifyHashedPassword(HashedPassword, password));
                }
                else
                {
                    var SHa = new System.Security.Cryptography.SHA512Managed();
                    var TPass = Convert.ToBase64String(SHa.ComputeHash(Encoding.UTF8.GetBytes(password + ":" + securityUser.OldSalt)));
                    VerificationSucceeded = (HashedPassword != null && (HashedPassword == TPass));
                }
                if (VerificationSucceeded)
                {
                    securityUser.PasswordFailuresSinceLastSuccess = 0;
                    securityUser.LastLoginDate = DateTime.Now;
                    securityUser.LastActivityDate = DateTime.Now;
                }
                else
                {
                    int Failures = securityUser.PasswordFailuresSinceLastSuccess;
                    if (Failures < MaxInvalidPasswordAttempts)
                    {
                        securityUser.PasswordFailuresSinceLastSuccess += 1;
                        securityUser.LastPasswordFailureDate = DateTime.Now;
                    }
                    else if (Failures >= MaxInvalidPasswordAttempts)
                    {
                        securityUser.LastPasswordFailureDate = DateTime.Now;
                        securityUser.LastLockoutDate = DateTime.Now;
                        securityUser.IsLockedOut = true;
                    }
                }

                Context.SaveChanges();
                if (VerificationSucceeded)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
Ejemplo n.º 33
0
 static byte[] ComputeSHA512(byte[] data)
 {
     System.Security.Cryptography.SHA512Managed crypt = new System.Security.Cryptography.SHA512Managed();
     return(crypt.ComputeHash(data, 0, data.Length));
 }
Ejemplo n.º 34
0
        public ActionResult OrderSummury(string CategoryId, string VehicleOwnerId, string LoadOwnerId, string LoadPrice = "")
        {
            OrderSummuryModel objOrderSummury = new OrderSummuryModel();

            try
            {
                if (CategoryId != null && Convert.ToInt32(CategoryId) > 0 && VehicleOwnerId != null && Convert.ToInt32(VehicleOwnerId) > 0 && LoadOwnerId != null && Convert.ToInt32(LoadOwnerId) > 0)
                {
                    objOrderSummury = service.getOrderSummuryByCategoryId(Convert.ToInt32(CategoryId), Convert.ToInt32(VehicleOwnerId), Convert.ToInt32(LoadOwnerId));
                }
                if (objOrderSummury != null)
                {
                    objOrderSummury.PaymentSummury.merchantId     = ConfigurationManager.AppSettings["merchantId"];
                    objOrderSummury.PaymentSummury.serviceTypeId  = ConfigurationManager.AppSettings["serviceTypeId"];
                    objOrderSummury.PaymentSummury.apiKey         = ConfigurationManager.AppSettings["apiKey"];
                    objOrderSummury.PaymentSummury.responseurl    = ConfigurationManager.AppSettings["ResponseUrl"];
                    objOrderSummury.PaymentSummury.gatewayUrl     = ConfigurationManager.AppSettings["GatewayUrl"];
                    objOrderSummury.PaymentSummury.checkStatusUrl = ConfigurationManager.AppSettings["CheckSatusUrl"];

                    if (objOrderSummury.LoadOwnerDetail.LoadOwner.FirstName != null && objOrderSummury.LoadOwnerDetail.LoadOwner.FirstName != "")
                    {
                        objOrderSummury.PaymentSummury.payerName = objOrderSummury.LoadOwnerDetail.LoadOwner.FirstName;
                    }
                    else
                    {
                        objOrderSummury.PaymentSummury.payerName = "Test";
                    }

                    if (objOrderSummury.LoadOwnerDetail.LoadOwner.EmailID != null && objOrderSummury.LoadOwnerDetail.LoadOwner.EmailID != "")
                    {
                        objOrderSummury.PaymentSummury.payerEmail = objOrderSummury.LoadOwnerDetail.LoadOwner.EmailID;
                    }
                    else
                    {
                        objOrderSummury.PaymentSummury.payerName = "*****@*****.**";
                    }
                    if (objOrderSummury.LoadDetail.LoadPrice > 0)
                    {
                        objOrderSummury.PaymentSummury.amt = Convert.ToString(objOrderSummury.LoadDetail.LoadPrice);
                    }
                    else
                    {
                        objOrderSummury.PaymentSummury.amt = "1000";
                    }

                    objOrderSummury.PaymentSummury.payerPhone = "123456789";
                    objOrderSummury.PaymentSummury.orderId    = objOrderSummury.LoadDetail.LoadId.ToString();


                    long   milliseconds = DateTime.Now.Ticks;
                    string order_Id     = milliseconds.ToString();
                    string hash_string  = objOrderSummury.PaymentSummury.merchantId + objOrderSummury.PaymentSummury.serviceTypeId + objOrderSummury.LoadDetail.LoadId.ToString() + objOrderSummury.PaymentSummury.amt + objOrderSummury.PaymentSummury.responseurl + objOrderSummury.PaymentSummury.apiKey;
                    System.Security.Cryptography.SHA512Managed sha512 = new System.Security.Cryptography.SHA512Managed();
                    Byte[] EncryptedSHA512 = sha512.ComputeHash(System.Text.Encoding.UTF8.GetBytes(hash_string));
                    sha512.Clear();
                    objOrderSummury.PaymentSummury.hash = BitConverter.ToString(EncryptedSHA512).Replace("-", "").ToLower();
                }
                return(View("OrderSummury", objOrderSummury));
            }
            catch (Exception ex) {
                throw new Exception(ex.Message);
            }
        }
Ejemplo n.º 35
0
        private void EncodeText(object sender, RoutedEventArgs e)
        {
            // Caesar cipher encode
            if (Cipher.Text == "Caesar cipher" && tbKey.Text != "")
            {
                lbDecText.Content = "  Your Decoded text";
                Decode.Content    = "Decode";
                key = Convert.ToInt32(tbKey.Text);
                if (EncodedText.Text != "")
                {
                    EncodedText.Clear();
                }
                try
                {
                    foreach (var item in charsToRemove)
                    {
                        YourText.Text = YourText.Text.Replace(item, string.Empty);
                    }

                    char[] text = YourText.Text.ToCharArray().Where(s => !char.IsWhiteSpace(s)).ToArray();

                    for (int i = 0; i < text.Length; i++)
                    {
                        for (int j = 0; j <= alphabet.Length && j <= alphabetUpper.Length; j++)
                        {
                            if (text[i].ToString() == alphabet[j].ToString() || text[i].ToString() == alphabetUpper[j].ToString())
                            {
                                char.ToLower(text[i]);

                                EncodedText.Text += Convert.ToChar(alphabet[(j + key) % alphabet.Length]);
                                break;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            // HASHFUNC encode
            if (Cipher.Text == "HashFunc")
            {
                lbDecText.Content = "  Comparable hash";
                Decode.Content    = "Check!";
                string text = YourText.Text;

                if (string.IsNullOrEmpty(text))
                {
                    text = string.Empty;
                }

                using (System.Security.Cryptography.SHA512Managed sha = new System.Security.Cryptography.SHA512Managed())
                {
                    byte[] textData = Encoding.Default.GetBytes(text);
                    byte[] hash     = sha.ComputeHash(textData);
                    EncodedText.Text = BitConverter.ToString(hash).Replace("-", string.Empty);
                }
                current = EncodedText.Text;
            }

            //  Vigenere cipher encode
            if (Cipher.Text == "Vigenere cipher")
            {
                lbDecText.Content = "  Your Decoded text";
                Decode.Content    = "Decode";
                if (EncodedText.Text != "")
                {
                    EncodedText.Clear();
                }
                foreach (var item in charsToRemove)
                {
                    YourText.Text = YourText.Text.Replace(item, string.Empty);
                }
                char[] text = YourText.Text.ToCharArray().Where(s => !char.IsWhiteSpace(s)).ToArray();
                char[] key  = tbKey.Text.ToCharArray();
                try
                {
                    char[,] Vigenere_Table = new char[26, 26];

                    int temp = 0;
                    for (int i = 0; i < alphabet.Length; i++)
                    {
                        for (int j = 0; j < 26; j++)
                        {
                            temp = j + i;
                            if (temp >= 26)
                            {
                                temp = temp % 26;
                            }
                            Vigenere_Table[i, j] = alphabet[temp];
                        }
                    }

                    for (int t = 0, k = 0; t < text.Length || k < key.Length; t++, k++)
                    {
                        if (t >= text.Length)
                        {
                            break;
                        }
                        if (k == key.Length /*t % key.Length == 0*/)
                        {
                            k = 0;
                            for (int y = 0; y <= alphabet.Length; y++)
                            {
                                if (text[t].ToString() == alphabet[y].ToString())
                                {
                                    Ytext = y;
                                    for (int x = 0; x <= alphabet.Length; x++)
                                    {
                                        if (key[k].ToString() == alphabet[x].ToString())
                                        {
                                            Xkey              = x;
                                            EncodedText.Text += Vigenere_Table[Ytext, Xkey].ToString();
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                        else
                        {
                            for (int y = 0; y <= alphabet.Length; y++)
                            {
                                if (text[t].ToString() == alphabet[y].ToString())
                                {
                                    Ytext = y;
                                    for (int x = 0; x <= alphabet.Length; x++)
                                    {
                                        if (key[k].ToString() == alphabet[x].ToString())
                                        {
                                            Xkey              = x;
                                            EncodedText.Text += Vigenere_Table[Ytext, Xkey].ToString();
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
Ejemplo n.º 36
0
 /// <summary>
 /// SHA512加密,不可逆转
 /// </summary>
 /// <param name="str">string str:被加密的字符串</param>
 /// <returns>返回加密后的字符串</returns>
 private string SHA512Encrypt(string str)
 {
     System.Security.Cryptography.SHA512 s512 = new System.Security.Cryptography.SHA512Managed();
     byte[] byte1;
     byte1 = s512.ComputeHash(Encoding.Default.GetBytes(str));
     s512.Clear();
     return Convert.ToBase64String(byte1);
 }
Ejemplo n.º 37
0
        public void parseHello(Commands.HelloCommand h, System.Net.IPEndPoint sender)
        {
            if (App.isMono)
            {
                string newName = "";
                for (int i = 0; i < h.username.Length; i++)
                {
                    if (char.IsLetterOrDigit(h.username[i]) || h.username[i] == ' ' || char.IsPunctuation(h.username[i]))
                    {
                        newName += h.username[i];
                    }
                    else
                    {
                        newName += "?";
                    }
                }
                h.username = newName;

                newName = "";
                for (int i = 0; i < h.description.Length; i++)
                {
                    if (char.IsLetterOrDigit(h.description[i]) || h.description[i] == ' ' || char.IsPunctuation(h.description[i]))
                    {
                        newName += h.description[i];
                    }
                    else
                    {
                        newName += "?";
                    }
                }
                h.description = newName;
            }
            bool         wasQuit     = false;
            List <ulong> channels    = new List <ulong>();
            List <ulong> oldChannels = new List <ulong>();
            string       oldName     = "";
            bool         renamed     = false;
            bool         updated     = false;
            bool         added       = false;

            lock (peers)
            {
                if (peers.ContainsKey(h.id))
                {
                    if (DateTime.Now.Subtract(peers[h.id].timeQuit).TotalSeconds < 3)
                    {
                        return;
                    }
                    wasQuit = peers[h.id].quit;
                    try
                    {
                        System.Net.IPAddress[] ips = new System.Net.IPAddress[h.internalIPs.Length];
                        for (int i = 0; i < ips.Length; i++)
                        {
                            ips[i] = System.Net.IPAddress.Parse(h.internalIPs[i]);
                        }
                        peers[h.id].internalAddress = ips;
                    }
                    catch
                    {
                        //whatever
                        peers[h.id].internalAddress = new System.Net.IPAddress[] { System.Net.IPAddress.Loopback };
                    }
                    if (peers[h.id].quit)
                    {
                        added = true;
                    }
                    peers[h.id].quit           = false;
                    peers[h.id].useUDT         = h.useUDT;
                    peers[h.id].actualEndpoint = sender;
                    if (h.externalIP != null)
                    {
                        peers[h.id].publicAddress = System.Net.IPAddress.Parse(h.externalIP);
                    }
                    if (peers[h.id].share != h.myShare)
                    {
                        peers[h.id].share = h.myShare;
                        updated           = true;
                    }
                    string s1 = "";
                    string s2 = "";
                    foreach (int i in peers[h.id].circles)
                    {
                        s1 += i.ToString() + ", ";
                    }
                    foreach (int i in h.myCircles)
                    {
                        s2 += i.ToString() + ", ";
                    }
                    if (s1 != s2)
                    {
                        oldChannels.AddRange(peers[h.id].circles);
                        peers[h.id].circles = h.myCircles;
                        added = true;
                    }
                }
                else
                {
                    peers[h.id]                = new Peer();
                    peers[h.id].id             = h.id;
                    peers[h.id].actualEndpoint = sender;
                    if (h.externalIP != null)
                    {
                        peers[h.id].publicAddress = System.Net.IPAddress.Parse(h.externalIP);
                    }
                    peers[h.id].username = h.username;
                    peers[h.id].circles  = h.myCircles;
                    added = true;
                }
                if (peers[h.id].description != h.description)
                {
                    peers[h.id].description = h.description;
                    updated = true;
                }
                peers[h.id].addEndpointToHistory(sender);
                peers[h.id].behindDoubleNAT     = h.behindDoubleNAT;
                peers[h.id].externalControlPort = h.externalControlPort;
                peers[h.id].externalDataPort    = h.externalDataPort;
                peers[h.id].localControlPort    = h.internalControlPort;
                peers[h.id].localDataPort       = h.internalDataPort;
                peers[h.id].localUDTPort        = h.internalUdtPort;
                if (peers[h.id].username != h.username)
                {
                    oldName = peers[h.id].username;
                    peers[h.id].username = h.username;
                    renamed = true;
                }
                peers[h.id].quit = false;
                lock (peers[h.id].peerCount)
                    peers[h.id].peerCount = h.peerCount;
                peers[h.id].lastContact = DateTime.Now;
                peers[h.id].buildNumber = h.buildNumber;
                channels.AddRange(peers[h.id].circles);
            }
            if (updated)
            {
                peerUpdated?.Invoke(peers[h.id]);
            }
            if (renamed)
            {
                peerRenamed?.Invoke(oldName, peers[h.id]);
            }
            if (added)
            {
                System.Security.Cryptography.SHA512Managed sha = new System.Security.Cryptography.SHA512Managed();
                ulong lanHash = BitConverter.ToUInt64(sha.ComputeHash(Encoding.UTF8.GetBytes("LAN".ToLower())), 0);

                if (!peers[h.id].quit || DateTime.Now.Subtract(peers[h.id].timeQuit).TotalSeconds > 3)
                {
                    foreach (ulong u in channels)
                    {
                        if (u == lanHash)
                        {
                            if (!oldChannels.Contains(u) && peers[h.id].isLocal)
                            {
                                peerAdded?.Invoke(peers[h.id], u, true);
                            }
                        }
                        else
                        {
                            if (!oldChannels.Contains(u))
                            {
                                peerAdded?.Invoke(peers[h.id], u, true);
                            }
                        }
                    }
                }
                if (DateTime.Now.Subtract(peers[h.id].timeQuit).TotalSeconds > 3)
                {
                    foreach (ulong u in oldChannels)
                    {
                        if (u == lanHash)
                        {
                            if (!channels.Contains(u) && peers[h.id].isLocal)
                            {
                                peerRemoved?.Invoke(peers[h.id], u, !wasQuit);
                            }
                        }
                        else
                        {
                            if (!channels.Contains(u))
                            {
                                peerRemoved?.Invoke(peers[h.id], u, !wasQuit);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 38
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // Factory, Unit, Tank
            modelBuilder.Entity <Factory>().HasData(
                new Factory {
                Id = 1, Name = "МНПЗ", Description = "Московский нефтеперерабатывающий завод"
            },
                new Factory {
                Id = 2, Name = "ОНПЗ", Description = "Омский нефтеперерабатывающий завод"
            }
                );

            modelBuilder.Entity <Unit>().HasData(
                new Unit {
                Id = 1, Name = "ГФУ-1", FactoryId = 1
            },
                new Unit {
                Id = 2, Name = "ГФУ-2", FactoryId = 1
            },
                new Unit {
                Id = 3, Name = "АВТ-6", FactoryId = 2
            }
                );

            modelBuilder.Entity <Tank>().HasData(
                new Tank {
                Id = 1, Name = "Резервуар 1", Volume = 1500, MaxVolume = 2000, UnitId = 1
            },
                new Tank {
                Id = 2, Name = "Резервуар 2", Volume = 2500, MaxVolume = 3000, UnitId = 1
            },
                new Tank {
                Id = 3, Name = "Дополнительный резервуар 24", Volume = 3000, MaxVolume = 3000, UnitId = 2
            },
                new Tank {
                Id = 4, Name = "Резервуар 35", Volume = 3000, MaxVolume = 3000, UnitId = 2
            },
                new Tank {
                Id = 5, Name = "Резервуар 47", Volume = 4000, MaxVolume = 5000, UnitId = 2
            },
                new Tank {
                Id = 6, Name = "Резервуар 256", Volume = 500, MaxVolume = 500, UnitId = 3
            }
                );

            byte[] pwdHash;
            using (var hasher = new System.Security.Cryptography.SHA512Managed())
            {
                pwdHash = hasher.ComputeHash(System.Text.Encoding.UTF8.GetBytes("Test"));
            }

            modelBuilder.Entity <User>().HasData(
                new User
            {
                Id           = 1,
                Username     = "******",
                PasswordHash = pwdHash,
                RoleId       = 1
            });

            modelBuilder.Entity <Role>().HasData(
                new Role {
                Id = 1, Name = "admin"
            },
                new Role {
                Id = 2, Name = "user"
            }
                );

            modelBuilder.Entity <Event>().Property(i => i.Tags).HasConversion(
                i => string.Join(';', i),
                i => i.Split(';', StringSplitOptions.RemoveEmptyEntries)
                );

            modelBuilder.Entity <Event>().Property(i => i.ResponsibleOperators).HasConversion(
                i => JsonConvert.SerializeObject(i),
                i => JsonConvert.DeserializeObject <IEnumerable <UnitOperator> >(i)
                );
        }
Ejemplo n.º 39
0
        public static int Main(string[] args)
        {
            bool interactive = true;
            if (args.Length > 0)
                interactive = false;

            foreach (string arg in args)
                if (arg.Contains("--generatediffs"))
                    gendiffs = true;

            newAssCS = true;

            Console.WriteLine(string.Format("[( Pluton Patcher v{0} )]", Version));
            try {
                plutonAssembly = AssemblyPatcher.FromFile("Pluton.dll");
                rustAssembly = AssemblyPatcher.FromFile("Assembly-CSharp.dll");
            } catch (FileNotFoundException ex) {
                Console.WriteLine("You are missing " + ex.FileName + " did you move the patcher to the managed folder ?");
                if (interactive) {
                    Console.WriteLine("Press any key to continue...");
                }
                return (int)ExitCode.DLL_MISSING;
            } catch (Exception ex) {
                Console.WriteLine("An error occured while reading the assemblies :");
                Console.WriteLine(ex.ToString());
                if (interactive) {
                    Console.WriteLine("Press any key to continue...");
                }
                return (int)ExitCode.DLL_READ_ERROR;
            }

            bNPC = rustAssembly.GetType("BaseNPC");
            bPlayer = rustAssembly.GetType("BasePlayer");
            codeLock = rustAssembly.GetType("CodeLock");
            hooksClass = plutonAssembly.GetType("Pluton.Hooks");
            itemCrafter = rustAssembly.GetType("ItemCrafter");
            pLoot = rustAssembly.GetType("PlayerLoot");

            //Check if patching is required
            TypePatcher plutonClass = rustAssembly.GetType("PlutonPatched");
            if (plutonClass == null) {
                try {
                    if (gendiffs) {
                        string hash = string.Empty;
                        using (var sha512 = new System.Security.Cryptography.SHA512Managed())
                            hash = BitConverter.ToString(sha512.ComputeHash(File.ReadAllBytes("Assembly-CSharp.dll"))).Replace("-", "").ToLower();

                        Directory.CreateDirectory("diffs");

                        string hashpath = "diffs" + Path.DirectorySeparatorChar + "lastHash";

                        if (File.Exists(hashpath)) newAssCS = hash != File.ReadAllText(hashpath);

                        if (newAssCS) {
                            foreach (var difffile in Directory.GetFiles("diffs")) {
                                if (difffile.Contains(".htm")) {
                                    string filename = Path.GetFileName(difffile);
                                    string dirname = Path.GetDirectoryName(difffile);
                                    Directory.CreateDirectory(Path.Combine(dirname, "old"));
                                    File.Move(difffile, difffile.Replace(Path.Combine(dirname, filename), Path.Combine(dirname, "old", filename)));
                                }
                            }
                        }

                        if (gendiffs && newAssCS)
                            File.WriteAllText(hashpath, hash);
                    }
                    PatchASMCSharp();
                    Console.WriteLine("Patched Assembly-CSharp !");
                } catch (Exception ex) {
                    interactive = true;
                    Console.WriteLine("An error occured while patching Assembly-CSharp :");
                    Console.WriteLine();
                    Console.WriteLine(ex.Message.ToString());

                    //Normal handle for the others
                    Console.WriteLine();
                    Console.WriteLine(ex.StackTrace.ToString());
                    Console.WriteLine();

                    if (interactive) {
                        Console.WriteLine("Press any key to continue...");
                    }
                    return (int)ExitCode.ACDLL_GENERIC_PATCH_ERR;
                }
            } else {
                Console.WriteLine("Assembly-CSharp.dll is already patched!");
                return (int)ExitCode.ACDLL_ALREADY_PATCHED;
            }

            try {
                rustAssembly.Write("Assembly-CSharp.dll");
            } catch (Exception ex) {
                Console.WriteLine("An error occured while writing the assembly :");
                Console.WriteLine("Error at: " + ex.TargetSite.Name);
                Console.WriteLine("Error msg: " + ex.Message);

                if (interactive) {
                    Console.WriteLine("Press any key to continue...");
                }

                return (int)ExitCode.DLL_WRITE_ERROR;
            }

            //Successfully patched the server
            Console.WriteLine("Completed !");

            if (interactive)
                System.Threading.Thread.Sleep(250);

            return (int)ExitCode.SUCCESS;
        }
Ejemplo n.º 40
0
        private void HashFiles(System.IO.FileInfo[] files, SortedList<string, string> infoList)
        {
            string directory = null;
            var firstFile = files.FirstOrDefault();
            if (firstFile != null)
            {
                directory = firstFile.Directory.FullName;
            }

            SortedList<string, string> previouslyHashedFiles = GetHashedFiles(directory);

            foreach (var file in files)
            {
                try
                {
                    if (file.Name != "hashes.txt")
                    {
                        string hashString = null;
                        if (previouslyHashedFiles.ContainsKey(file.Name))
                        {
                            hashString = previouslyHashedFiles[file.Name];
                        }
                        var fileHashedAlready = !string.IsNullOrEmpty(hashString);
                        if (!fileHashedAlready)
                        {
                            var sha512 = new System.Security.Cryptography.SHA512Managed();
                            var hash = sha512.ComputeHash(file.OpenRead());
                            hashString = Convert.ToBase64String(hash);
                        }

                        infoList.Add(hashString, file.FullName);

                        UpdateHashFile(previouslyHashedFiles, infoList, file);
                    }

                    backgroundWorker1.ReportProgress(++index);
                }
                catch (Exception ex)
                {
                    // TODO: Log error
                    exception = ex;
                }
            }
        }