public static string GetHash(string input)
        {
            HashAlgorithm hashAlgorithm = new SHA256CryptoServiceProvider();

            byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(input);

            byte[] byteHash = hashAlgorithm.ComputeHash(byteValue);

            return Convert.ToBase64String(byteHash);
        }
		/// <summary>
		/// Signs JWT token using the private key and returns the serialized assertion.
		/// </summary>
		/// <param name="payload">the JWT payload to sign.</param>
		private string CreateAssertionFromPayload(JsonWebSignature.Payload payload)
		{
			string serializedHeader = CreateSerializedHeader();
			string serializedPayload = NewtonsoftJsonSerializer.Instance.Serialize(payload);

			StringBuilder assertion = new StringBuilder();
			assertion.Append(UrlSafeBase64Encode(serializedHeader))
				.Append(".")
				.Append(UrlSafeBase64Encode(serializedPayload));

			// Sign the header and the payload.
			var hashAlg = new SHA256CryptoServiceProvider();
			byte[] assertionHash = hashAlg.ComputeHash(Encoding.ASCII.GetBytes(assertion.ToString()));

			var signature = UrlSafeBase64Encode(key.SignHash(assertionHash, "2.16.840.1.101.3.4.2.1" /* SHA256 OIG */)); 
			assertion.Append(".").Append(signature);
			return assertion.ToString();
		}
Ejemplo n.º 3
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            //connect
            using (DefaultConnection1 db = new DefaultConnection1())
            {
                //create user object in memory
                user objI = new user();

                //first get the salt value for this username
                String email = txtEmailLogin.Text;

                objI = (from em in db.users
                        where em.email == email
                        select em).FirstOrDefault();

                //did the email find a match?
                if (objI != null)
                {
                    String salt = objI.salt;


                    //salt and hash the plan text password.
                    String password      = txtPasswordLogin.Text;
                    String pass_and_salt = password + salt;

                    // Create a new instance of the hash crypto service provider.
                    HashAlgorithm hashAlg = new SHA256CryptoServiceProvider();

                    // Convert the data to hash to an array of Bytes.
                    byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(pass_and_salt);

                    // Compute the Hash. This returns an array of Bytes.
                    byte[] bytHash = hashAlg.ComputeHash(bytValue);

                    // Optionally, represent the hash value as a base64-encoded string,
                    // For example, if you need to display the value or transmit it over a network.
                    string base64 = Convert.ToBase64String(bytHash);

                    //check if the password that was just salted and hashed matches the password in the database.
                    if (objI.password == base64)
                    {
                        //Checking if the password was the same, Showing a valid login.
                        //lblError.Text = "Valid Login";

                        //store the identity in the session object
                        Session["user_id"]   = objI.user_id;
                        Session["user_name"] = objI.first_name = " " + objI.last_name;

                        //rediect to logged in homepage.
                        Response.Redirect("login_landing.aspx");
                    }
                    else
                    {
                        lblError.Text = "Invaild Login";
                    }
                }
                else
                {
                    lblError.Text = "Invalid Login";
                }
            }
        }
        static public string getNameFor(string username)
        {
            var sha256 = new SHA256CryptoServiceProvider();

            return(UrlBase64.Encode(sha256.ComputeHash(Encoding.UTF8.GetBytes(username))).ToLower());
        }
Ejemplo n.º 5
0
        public static void SignXML(string fechaEmision, ref XmlDocument xml, string accountId = "", X509Certificate2 certificate = null)
        {
            XmlDocument xmlDocSignature;

            DataBase.Account accountData;
            X509Certificate2 cert;
            IAccount         accountImp;
            string           singIdentifier, xmlSignature;
            SHA256           sha256;
            SHA1             sha1;

            try
            {
                accountImp      = new AccountImp();
                xmlDocSignature = new XmlDocument();
                sha256          = new SHA256CryptoServiceProvider();
                sha1            = new SHA1CryptoServiceProvider();

                singIdentifier = ConfigurationManager.AppSettings[Constants.Constants.SignIdentifier];

                if (certificate == null)
                {
                    if (!string.IsNullOrEmpty(accountId))
                    {
                        accountData = accountImp.GetAccountById(accountId);
                        if (accountData != null)
                        {
                            cert = new X509Certificate2(Convert.FromBase64String(accountData.certificate), accountData.certificatePIN.ToString());
                        }
                        else
                        {
                            throw new Exception(Constants.Constants.fail_Get_account_data);
                        }
                    }
                    else
                    {
                        throw new Exception(Constants.Constants.fail_CertificateInfo_incomplete);
                    }
                }
                else
                {
                    cert = certificate;
                }

                xmlDocSignature.Load(string.Format(Constants.Constants.RequestApiFormat_2, AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings[Constants.Constants.signTemplate]));

                #region Estructura para firma digital

                /************************************************
                 * 0 : id
                 * 1 : XML document base64
                 * 2 : (no se que es) Properties
                 * 3 : current datetime
                 * 4 : certificate data base64
                 * 5 : X509IssuerName
                 * 6 : X509SerialNumber
                 * 7 : Identifier
                 * 8 : Identifier sha256
                 ***********************************************/
                xmlSignature = xmlDocSignature.OuterXml;
                List <string> parameters = new List <string>();
                parameters.Add(Guid.NewGuid().ToString("N"));                                                                 // 0
                parameters.Add(Convert.ToBase64String(sha256.ComputeHash(Encoding.UTF8.GetBytes(xmlDocSignature.OuterXml)))); // 1
                parameters.Add("5JVZPTwN5Lj0sGTfFzaUeMKCo/xbCAj7fw6TLUFtZIk=");                                               // 2
                parameters.Add(fechaEmision);                                                                                 // 3
                parameters.Add(Convert.ToBase64String(sha1.ComputeHash(Encoding.ASCII.GetBytes(cert.ToString(true)))));       // 4
                parameters.Add(cert.IssuerName.ToString());                                                                   // 5
                parameters.Add(cert.SerialNumber);                                                                            // 6
                parameters.Add(singIdentifier);                                                                               // 7
                parameters.Add(Convert.ToBase64String(sha256.ComputeHash(Encoding.UTF8.GetBytes(singIdentifier))));           // 8

                xmlSignature = string.Format(xmlSignature, parameters.ToArray());

                #endregion

                XmlDocumentFragment xFrag = xml.CreateDocumentFragment();
                xFrag.InnerXml = xmlSignature;
                xml.ChildNodes[0].AppendChild(xFrag);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 6
0
 private string ComputeHash(string input, SHA256CryptoServiceProvider algorithm)
 {
     Byte[] inputBytes  = Encoding.UTF8.GetBytes(input);
     Byte[] hashedBytes = algorithm.ComputeHash(inputBytes);
     return(BitConverter.ToString(hashedBytes));
 }
Ejemplo n.º 7
0
 private void Checksum(string algorithm, byte[] data)
 {
     if (algorithm == @"CRC32")
     {
         long crc = CRC32CryptoServiceProvider.Compute(data);
         OutputText(string.Format(CultureInfo.CurrentCulture, "{0}", crc));
     }
     else if (algorithm == @"CRC64")
     {
         ulong crc = CRC64CryptoServiceProvider.Compute(data);
         OutputText(string.Format(CultureInfo.CurrentCulture, "{0}", crc));
     }
     else if (algorithm == @"MD5")
     {
         using (MD5CryptoServiceProvider hasher = new MD5CryptoServiceProvider())
         {
             byte[]        list = hasher.ComputeHash(data);
             StringBuilder sb   = new StringBuilder();
             for (int i = 0; i < list.Length; i++)
             {
                 sb.Append(list[i].ToString("x2", CultureInfo.CurrentCulture));
             }
             OutputText(string.Format(CultureInfo.CurrentCulture, "{0}", sb.ToString()));
         }
     }
     else if (algorithm == @"SHA1")
     {
         using (SHA1CryptoServiceProvider hasher = new SHA1CryptoServiceProvider())
         {
             byte[]        list = hasher.ComputeHash(data);
             StringBuilder sb   = new StringBuilder();
             for (int i = 0; i < list.Length; i++)
             {
                 sb.Append(list[i].ToString("x2", CultureInfo.CurrentCulture));
             }
             OutputText(string.Format(CultureInfo.CurrentCulture, "{0}", sb.ToString()));
         }
     }
     else if (algorithm == @"SHA256")
     {
         using (SHA256CryptoServiceProvider hasher = new SHA256CryptoServiceProvider())
         {
             byte[]        list = hasher.ComputeHash(data);
             StringBuilder sb   = new StringBuilder();
             for (int i = 0; i < list.Length; i++)
             {
                 sb.Append(list[i].ToString("x2", CultureInfo.CurrentCulture));
             }
             OutputText(string.Format(CultureInfo.CurrentCulture, "{0}", sb.ToString()));
         }
     }
     else if (algorithm == @"SHA384")
     {
         using (SHA384CryptoServiceProvider hasher = new SHA384CryptoServiceProvider())
         {
             byte[]        list = hasher.ComputeHash(data);
             StringBuilder sb   = new StringBuilder();
             for (int i = 0; i < list.Length; i++)
             {
                 sb.Append(list[i].ToString("x2", CultureInfo.CurrentCulture));
             }
             OutputText(string.Format(CultureInfo.CurrentCulture, "{0}", sb.ToString()));
         }
     }
     else if (algorithm == @"SHA512")
     {
         using (SHA512CryptoServiceProvider hasher = new SHA512CryptoServiceProvider())
         {
             byte[]        list = hasher.ComputeHash(data);
             StringBuilder sb   = new StringBuilder();
             for (int i = 0; i < list.Length; i++)
             {
                 sb.Append(list[i].ToString("x2", CultureInfo.CurrentCulture));
             }
             OutputText(string.Format(CultureInfo.CurrentCulture, "{0}", sb.ToString()));
         }
     }
     else if (algorithm == @"RIPEMD160")
     {
         using (RIPEMD160 hasher = RIPEMD160Managed.Create())
         {
             byte[]        list = hasher.ComputeHash(data);
             StringBuilder sb   = new StringBuilder();
             for (int i = 0; i < list.Length; i++)
             {
                 sb.Append(list[i].ToString("x2", CultureInfo.CurrentCulture));
             }
             OutputText(string.Format(CultureInfo.CurrentCulture, "{0}", sb.ToString()));
         }
     }
 }
Ejemplo n.º 8
0
        private void btn_enter_Click(object sender, RoutedEventArgs e)
        {
            ////////////////////تبدیل رمز عبور به رشته در درهم
            SHA256CryptoServiceProvider Sha2 = new SHA256CryptoServiceProvider();

            Byte[] B1;
            Byte[] B2;
            B1 = UTF8Encoding.UTF8.GetBytes(txt_password.Password.Trim());
            B2 = Sha2.ComputeHash(B1);
            string UserPasswordHashed = BitConverter.ToString(B2);
            /////////////////////////////////////////////////بررسی موجود بودن نام کاربری و رمز عبور در دیتابیس
            var query = from U in database.Users
                        where U.UserUserName == txt_username.Text.Trim()
                        where U.UserPassword == UserPasswordHashed
                        where U.UserActive == 1
                        select U;
            var user = query.ToList();

            /////////////////////////////////////////////////
            if (user.Count == 1)
            {
                /////////////////////////////////////////ثبت نام کاربری در رجیستری
                RegistryKey UserNameKey = Registry.CurrentUser.CreateSubKey("Software\\foroosh");
                try
                {
                    UserNameKey.SetValue("UserNameRegister", txt_username.Text.Trim());

                    ////بدست اوردن مشخصات کاربر واردشونده
                    PublicVariable.gUserName   = user[0].UserName;
                    PublicVariable.gUserFamily = user[0].UserFamily;
                    PublicVariable.gUserId     = user[0].UserID;
                    /////////////بدست آوردن اطلاعات کامپیوتر کاربر
                    string      ComputerName = System.Environment.MachineName;
                    string      IP           = "";
                    IPHostEntry iPE          = Dns.GetHostByName(ComputerName);
                    //IPHostEntry iPE = Dns.GetHostEntry(ComputerName);
                    IPAddress[] IpA = iPE.AddressList;
                    IP = IpA[0].ToString();
                    ///////////////////////////////
                    Userlog UL = new Userlog();
                    UL.ComputerName  = ComputerName;
                    UL.IPAddress     = IP;
                    UL.UserId        = PublicVariable.gUserId;
                    UL.EnterDateTime = string.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(calendar_userlog.Text)) + " - " + String.Format("{0:HH:mm:ss}", DateTime.Now);
                    database.Userlogs.Add(UL);
                    database.SaveChanges();
                    ////////////////////////////////////
                }
                catch
                {
                    MessageBox.Show("در هنگام ورود کاربر مشکلی برای سیستم به وجود آمد");
                }
                finally
                {
                    UserNameKey.Close();
                }

                this.Close();
            }
            else
            {
                MessageBox.Show("username or password is wrong! ");
                return;
            }
        }
Ejemplo n.º 9
0
        private static string Hash(string v)
        {
            SHA256 sha = new SHA256CryptoServiceProvider();

            return(Convert.ToBase64String((sha.ComputeHash(Encoding.UTF8.GetBytes(v)))));
        }
Ejemplo n.º 10
0
        public JsonResult OPay()
        {
            string allowedChars   = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
            int    passwordLength = 4;

            char[] chars = new char[passwordLength];
            Random rd    = new Random();

            for (int i = 0; i < passwordLength; i++)
            {
                chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
            }
            string password = new string(chars);
            int    opend    = 2;

            char[] open = new char[opend];
            for (int a = 0; a < opend; a++)
            {
                open[a] = allowedChars[rd.Next(0, allowedChars.Length)];
            }
            string opendd = new string(open);

            //拿購物車
            tcart = HttpContext.Session.GetObject <List <CartModel> >("value");
            //亂數
            string itemname = "";
            int    amount   = 0;

            if (tcart != null)
            {
                foreach (var a in tcart)
                {
                    itemname += a.productName + " " + a.productPrice + "X" + a.productQty + "#";
                    amount   += (int)a.Amount;
                }
                List <Send> send1 = new List <Send>();
                Send        send  = new Send();
                send.itemname        = itemname;
                send.amount          = amount.ToString();
                send.returnurl       = "http://192.168.36.41/Product/ShpList";
                send.succesreturnurl = "http://192.168.36.41/Product/ShpList";
                send.time            = opendd + DateTime.Now.ToString("yyyyMMddhhmmss") + password;
                send.time3           = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
                send.hashkey         = "5294y06JbISpM5x9";
                send.hashiv          = "v77hoKGq4kWxNNIS";
                var    input        = $"HashKey=5294y06JbISpM5x9&ChoosePayment=Credit&ClientBackURL={send.returnurl}&CreditInstallment=&EncryptType=1&InstallmentAmount=&ItemName={send.itemname}&MerchantID=2000132&MerchantTradeDate={send.time3}&MerchantTradeNo={send.time}&PaymentType=aio&Redeem=&ReturnURL={send.succesreturnurl}&StoreID=&TotalAmount={send.amount}&TradeDesc=建立信用卡測試訂單&HashIV=v77hoKGq4kWxNNIS";
                string encoded      = System.Web.HttpUtility.UrlEncode(input).ToLower();
                byte[] messageBytes = Encoding.Default.GetBytes(encoded);
                SHA256 sHA256       = new SHA256CryptoServiceProvider();
                byte[] vs           = sHA256.ComputeHash(messageBytes);
                string result       = BitConverter.ToString(vs).ToUpper();
                result             = result.Replace("-", "");
                send.checkmacvalue = result;
                send1.Add(send);
                return(Json(new { JsonResult = send1 }));
            }
            else
            {
                return(Json(""));
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Get the hashcode from the file.
        /// </summary>
        /// <param name="filename">The path and file name to generate the hash code for.</param>
        /// <param name="hashcodeType">The hash name.</param>
        /// <returns>The generated hash code.</returns>
        public static byte[] GetHashcodeFileRaw(string filename, Nequeo.Cryptography.HashcodeType hashcodeType)
        {
            FileStream file = null;

            byte[] hashValue = null;

            try
            {
                // Open the file to generate the hash code for.
                using (file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    // Select the hash code type.
                    switch (hashcodeType)
                    {
                    case HashcodeType.MD5:
                        // MD5 hashcode.
                        MD5 md5 = new MD5CryptoServiceProvider();
                        hashValue = md5.ComputeHash(file);
                        break;

                    case HashcodeType.SHA1:
                        // SHA1 hashcode.
                        SHA1 sha1 = new SHA1CryptoServiceProvider();
                        hashValue = sha1.ComputeHash(file);
                        break;

                    case HashcodeType.SHA256:
                        // SHA256 hashcode.
                        SHA256 sha256 = new SHA256CryptoServiceProvider();
                        hashValue = sha256.ComputeHash(file);
                        break;

                    case HashcodeType.SHA384:
                        // SHA384 hashcode.
                        SHA384 sha384 = new SHA384CryptoServiceProvider();
                        hashValue = sha384.ComputeHash(file);
                        break;

                    case HashcodeType.SHA512:
                        // SHA512 hashcode.
                        SHA512 sha512 = new SHA512CryptoServiceProvider();
                        hashValue = sha512.ComputeHash(file);
                        break;

                    case HashcodeType.SHA3:
                        // SHA3 hashcode.
                        Sha3.SHA3Managed sha3 = new Sha3.SHA3Managed();
                        hashValue = sha3.ComputeHash(file);
                        break;

                    case HashcodeType.PBKDF2:
                        throw new Exception("PBKDF2 Hashing is not supported.");
                    }

                    // Close the file.
                    file.Close();

                    // Return the hash code.
                    return(hashValue);
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                // Clean-up
                if (file != null)
                {
                    file.Close();
                }
            }
        }