Beispiel #1
20
 public static HashAlgorithm GetHashProvider(HashType type)
 {
     HashAlgorithm hash = null;
     switch (type)
     {
         case HashType.MD5:
             {
                 hash = new MD5CryptoServiceProvider();
                 break;
             }
         case HashType.SHA1:
             {
                 hash = new SHA1CryptoServiceProvider();
                 break;
             }
         case HashType.SHA256:
             {
                 hash = new SHA256CryptoServiceProvider();
                 break;
             }
         case HashType.SHA384:
             {
                 hash = new SHA384CryptoServiceProvider();
                 break;
             }
         case HashType.SHA512:
             {
                 hash = new SHA512CryptoServiceProvider();
                 break;
             }
     }
     return hash;
 }
 public static string CreateHashedPassword(string password, string salt)
 {
     var sha256 = new SHA256CryptoServiceProvider();
     byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password + salt);
     byte[] hashedPasswordBytes = sha256.ComputeHash(passwordBytes);
     return Convert.ToBase64String(hashedPasswordBytes);
 }
Beispiel #3
1
 /// <summary>
 /// Hashes the specified arguments.
 /// </summary>
 /// <param name="args">The arguments.</param>
 /// <returns>The hash</returns>
 public static string Hash(params object[] args)
 {
     HashAlgorithm hashAlg = new SHA256CryptoServiceProvider();
     byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(String.Concat(args));
     byte[] bytHash = hashAlg.ComputeHash(bytValue);
     return Convert.ToBase64String(bytHash);
 }
Beispiel #4
1
        static async Task MainAsync(string[] args)
        {
            var keyClient = new KeyVaultClient((authority, resource, scope) =>
            {
                var adCredential = new ClientCredential(applicationId, applicationSecret);
                var authenticationContext = new AuthenticationContext(authority, null);
                return authenticationContext.AcquireToken(resource, adCredential).AccessToken;
            });

            // Get the key details
            var keyIdentifier = "https://testvaultrahul.vault.azure.net/keys/rahulkey/0f653b06c1d94159bc7090596bbf7784";
            var key = await keyClient.GetKeyAsync(keyIdentifier);
            var publicKey = Convert.ToBase64String(key.Key.N);

            using (var rsa = new RSACryptoServiceProvider())
            {
                var p = new RSAParameters() { Modulus = key.Key.N, Exponent = key.Key.E };
                rsa.ImportParameters(p);
                var byteData = Encoding.Unicode.GetBytes(textToEncrypt);
                
                // Encrypt and Decrypt
                var encryptedText = rsa.Encrypt(byteData, true);
                var decryptedData = await keyClient.DecryptDataAsync(keyIdentifier, "RSA_OAEP", encryptedText);
                var decryptedText = Encoding.Unicode.GetString(decryptedData.Result);

                // Sign and Verify
                var hasher = new SHA256CryptoServiceProvider();
                var digest = hasher.ComputeHash(byteData);
                var signature = await keyClient.SignAsync(keyIdentifier, "RS256", digest);
                var isVerified = rsa.VerifyHash(digest, "Sha256", signature.Result);
            }
        }
 internal static string GenerateHash(this string input)
 {
     HashAlgorithm hashAlgorithm = new SHA256CryptoServiceProvider();
     var byteValue = System.Text.Encoding.UTF8.GetBytes(input);
     var byteHash = hashAlgorithm.ComputeHash(byteValue);
     return Convert.ToBase64String(byteHash);
 }
        protected void TestButton_Click(object sender, EventArgs e)
        {
            // Define key and data string.
            var k  = "test key";
            var s  = "Encoding-编码-암호화-表現形式";
            var kb = System.Text.Encoding.UTF8.GetBytes(k);
            var sb = System.Text.Encoding.UTF8.GetBytes(s);

            // Test SHA256.
            WriteLog("// Create SHA256 Algorithm");
            var sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            var hash   = System.BitConverter.ToString(sha256.ComputeHash(sb));

            WriteLog("sha256.ComputeHash('" + s + "') = " + hash);

            //WriteLog("// Create SHA256 Algorithm");
            //var sha2 = new SHA256Managed();
            //hash = System.BitConverter.ToString(sha2.ComputeHash(sb));
            //WriteLog("sha2.ComputeHash('" + s + "') = " + hash);
            //WriteLog(sha2.Log.ToString());

            // Test HMACSHA256.
            Trace.Write("// Create HMAC-SHA256 Algorithm");
            var hmac = new System.Security.Cryptography.HMACSHA256(kb);

            hash = System.BitConverter.ToString(hmac.ComputeHash(sb));
            WriteLog("hmac.ComputeHash('" + k + "','" + s + "') = " + hash);
        }
 protected string GenerateCacheKeyHash(int tabId, string cacheKey)
 {
     byte[] hash = Encoding.ASCII.GetBytes(cacheKey);
     var sha256 = new SHA256CryptoServiceProvider();
     hash = sha256.ComputeHash(hash);
     return string.Concat(tabId.ToString(), "_", ByteArrayToString(hash));
 }
 private String EncriptarPassword(String password)
 {
     byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
     SHA256 sha256 = new SHA256CryptoServiceProvider();
     byte[] hashedPassword = sha256.ComputeHash(passwordBytes);
     return BitConverter.ToString(hashedPassword).Replace("-","");
 }
Beispiel #9
0
 public static string Encrypt(string clearText)
 {
     byte[] arrbyte = new byte[clearText.Length];
     SHA256 hash = new SHA256CryptoServiceProvider();
     arrbyte = hash.ComputeHash(Encoding.UTF8.GetBytes(clearText));
     return Convert.ToBase64String(arrbyte);
 }
 public static string Hash(this string clear_text)
 {
     using (HashAlgorithm hash = new SHA256CryptoServiceProvider())
     {
         return Convert.ToBase64String(hash.ComputeHash(Encoding.UTF8.GetBytes(clear_text)));
     }
 }
        public string CreateDoctorAcccount(string email, string dname, string pwd, string cfmpwd, string mobileno, string dob, string pip)
        {
            if (dname.Length == 0)
                returnMessage += "Therapist Name cannot be blank <br />";
            if (pwd.Length == 0)
                returnMessage += "Password cannot be blank <br/>";
            if (cfmpwd.Length == 0)
                returnMessage += "Cofirm Passowrd cannot be blank <br/>";
            if (mobileno.Length == 0)
                returnMessage += "Mobile Number cannot be blank <br/>";
            if (dob.Length == 0)
                returnMessage += "Date of Birth cannnot be blank <br/>";
            if (pip.Length == 0)
                returnMessage += "Please Upload an image <br/>";
            if (pwd != cfmpwd)
                returnMessage += "Your passwords dont match <br/>";

            if (returnMessage.Length == 0)
            {
                SHA256 sha = new SHA256CryptoServiceProvider();
                byte[] data = Encoding.ASCII.GetBytes(pwd);
                byte[] result = sha.ComputeHash(data);
                string hashedpwd = Convert.ToBase64String(result);
                AzureUserDAL doc = new AzureUserDAL(email, dname, hashedpwd, mobileno, dob, pip);
                int noofRows = 0;
                noofRows = doc.CreateDoctorProfile();

                if (noofRows > 0)
                    returnMessage = "You Signed Up Succuesfully.";
                else
                    returnMessage = "Error,Please try again";

            }
            return returnMessage;
        }
Beispiel #12
0
        private HashAlgorithm GetHashAlgorithm(string hashType)
        {
            HashAlgorithm hash = null;
            string hashTypeLower = hashType.ToLowerInvariant();

            switch (hashTypeLower)
            {
                case "md5":
                    hash = new MD5CryptoServiceProvider();
                    break;
                case "ripemd160":
                    hash = new RIPEMD160Managed();
                    break;
                case "sha1":
                    hash = new SHA1CryptoServiceProvider();
                    break;
                case "sha256":
                    hash = new SHA256CryptoServiceProvider();
                    break;
                case "sha384":
                    hash = new SHA384CryptoServiceProvider();
                    break;
                case "sha512":
                    hash = new SHA512CryptoServiceProvider();
                    break;
                default:
                    break;
            }

            return hash;
        }
        public static bool ValidatePathWithEncodedRSAPKCS1SignatureAndPublicRSAKey(string path, string base64Signature, string publicKey) {

            try {

                byte[] signature = Convert.FromBase64String(base64Signature);
                byte[] data = File.ReadAllBytes(path);
                SHA256CryptoServiceProvider cryptoTransformSHA256 = new SHA256CryptoServiceProvider();
                byte[] sha256Hash = cryptoTransformSHA256.ComputeHash(data);
                string cleanKey = "";

                string[] lines = publicKey.Split(new char[] {'\n', '\r'});

                foreach (string line in lines) {
                        cleanKey += line.Trim();
                }

                byte[] publicKeyData = Convert.FromBase64String(cleanKey);

                RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
                provider.ImportCspBlob(publicKeyData);
                RSAPKCS1SignatureDeformatter formatter = new RSAPKCS1SignatureDeformatter(provider);
                formatter.SetHashAlgorithm("SHA256");
                return formatter.VerifySignature(sha256Hash, signature);

            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
                return false;
            }

        }
Beispiel #14
0
        public static string CalculateSha256(string text, Encoding enc)
        {
            byte[] buffer = enc.GetBytes(text);

            using (var cryptoTransformSha1 = new SHA256CryptoServiceProvider())
                return BitConverter.ToString(cryptoTransformSha1.ComputeHash(buffer)).Replace("-", "");
        }
 public static void Signature(Stream input, Stream output, string privateKey)
 {
     using (var sha = new SHA256CryptoServiceProvider())
     using (var rsa = new RSACryptoServiceProvider())
     {
         // Compute hash
         var buffer = ReadAllBytes(input);
         var hash = sha.ComputeHash(buffer);
         // RSA Initialize
         rsa.FromXmlString(privateKey);
         // format
         var formatter = new RSAPKCS1SignatureFormatter(rsa);
         formatter.SetHashAlgorithm("SHA256");
         var signature = formatter.CreateSignature(hash);
         // Krile Signature Package
         var magic = MagicStr + ":" + signature.Length + ":";
         var magicbytes = Encoding.UTF8.GetBytes(magic);
         if (magicbytes.Length > 64)
             throw new Exception("Magic bits too long.");
         output.Write(magicbytes, 0, magicbytes.Length);
         var padding = new byte[64 - magicbytes.Length];
         output.Write(padding, 0, padding.Length);
         output.Write(signature, 0, signature.Length);
         output.Write(buffer, 0, buffer.Length);
     }
 }
Beispiel #16
0
		/// <summary>
		/// Encrypts the given string with SHA256.
		/// </summary>
		/// <param name="str">The string</param>
		/// <returns>The encrypted</returns>
		private string Encrypt(string str) {
			UTF8Encoding encoder = new UTF8Encoding() ;
			SHA256CryptoServiceProvider crypto = new SHA256CryptoServiceProvider() ;

			byte[] bytes = crypto.ComputeHash(encoder.GetBytes(str)) ;
			return Convert.ToBase64String(bytes) ;
		}
Beispiel #17
0
 private static string Hash(byte[] clearBuffer, HashAlgorithm algorithm)
 {
     System.Security.Cryptography.HashAlgorithm hashAlgorithm;
     switch (algorithm)
     {
         case HashAlgorithm.MD5:
             hashAlgorithm = new MD5CryptoServiceProvider();
             break;
         case HashAlgorithm.SHA1:
         default:
             hashAlgorithm = new SHA1CryptoServiceProvider();
             break;
         case HashAlgorithm.SHA256:
             hashAlgorithm = new SHA256CryptoServiceProvider();
             break;
         case HashAlgorithm.SHA384:
             hashAlgorithm = new SHA384CryptoServiceProvider();
             break;
         case HashAlgorithm.SHA512:
             hashAlgorithm = new SHA512CryptoServiceProvider();
             break;
     }
     var encryptedBuffer = hashAlgorithm.ComputeHash(clearBuffer);
     return Convert.ToBase64String(encryptedBuffer);
 }
Beispiel #18
0
 private string GenerateCacheKeyHash(int tabModuleId, string cacheKey)
 {
     byte[] hash = Encoding.ASCII.GetBytes(cacheKey);
     var sha256 = new SHA256CryptoServiceProvider();
     hash = sha256.ComputeHash(hash);
     return tabModuleId + "_" + ByteArrayToString(hash);
 }
Beispiel #19
0
 public string SHA256(string input)
 {
     HashAlgorithm algorithm = new SHA256CryptoServiceProvider();
     Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
     Byte[] hashedBytes = algorithm.ComputeHash(inputBytes);
     return BitConverter.ToString(hashedBytes);
 }
 public static string GetHash(string input)
 {
     HashAlgorithm has = new SHA256CryptoServiceProvider();
     byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(input);
     byte[] byteHash = has.ComputeHash(byteValue);
     return Convert.ToBase64String(byteHash);
 }
Beispiel #21
0
 public static string HashStringSHA256(string valueUTF8)
 {
     byte[] valueBytes = Encoding.UTF8.GetBytes(valueUTF8);
     SHA256CryptoServiceProvider shar2 = new SHA256CryptoServiceProvider();
     byte[] hashBytes = shar2.ComputeHash(valueBytes);
     return BitConverter.ToString(hashBytes).Replace("-", "");
 }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            using (DefaultConnection db = new DefaultConnection())
            {
                Instructor objI = new Instructor();

                objI.FirstName = txtFirstName.Text;
                objI.LastName = txtLastName.Text;
                objI.Username = txtUsername.Text;
                objI.DepartmentID = Convert.ToInt32(ddlDepartment.SelectedValue);

                String password = txtPassword.Text;
                String salt = CreateSalt(8);
                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);

                objI.Password = base64;
                objI.Salt = salt;

                db.Instructors.Add(objI);
                db.SaveChanges();
            }
        }
        public static string GenerateToken(string @namespace, string eventHub, string publisher, string sharedAccessKeyName, string sharedAccessKey, DateTimeOffset expiry)
        {
            var unixEpoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
            var timeSinceEpoch = expiry - unixEpoch;
            var timeSinceEpochInMilliseconds = (long)timeSinceEpoch.TotalMilliseconds;

            var url = Helper.BuildUrl(@namespace, eventHub, publisher);
            var encodedUrl = HttpUtility.UrlEncode(url);
            var signatureContent = string.Format("{0}\n{1}", encodedUrl, timeSinceEpochInMilliseconds);

            var signatureContentAsBytes = Encoding.UTF8.GetBytes(signatureContent);
            var provider = new SHA256CryptoServiceProvider();
            var signatureAsBytes = provider.ComputeHash(signatureContentAsBytes);
            var signature = Convert.ToBase64String(signatureAsBytes);

            var token = string.Format(
                "sr={0}&sig={1}&se={2}&skn={3}",
                HttpUtility.UrlEncode(url),
                HttpUtility.UrlEncode(signature),
                timeSinceEpochInMilliseconds,
                HttpUtility.UrlEncode(sharedAccessKeyName)
                );

            return token;
        }
Beispiel #24
0
        public static String SHA256Encrypt(String pwd)
        {
            //Encryption
            //SHA256
            //One-way hash
            //Password Token:
            // (hash(hash(userName+ pwd)+salt))

            String SALT ="buy2easy"; //
            SHA256CryptoServiceProvider provider = new SHA256CryptoServiceProvider();

            // pwd
            Byte[] inputByteArray = Encoding.UTF8.GetBytes(pwd);

            // salt
            Byte[] saltByteArray = Encoding.UTF8.GetBytes(SALT);

            // hash
            Byte[] hashedBytesArray1 = provider.ComputeHash(inputByteArray);

            // Combine salt and input bytes
            Byte[] inputBytesWithSalt = new Byte[hashedBytesArray1.Length + saltByteArray.Length];

            hashedBytesArray1.CopyTo(inputBytesWithSalt, 0);
            saltByteArray.CopyTo(inputBytesWithSalt, hashedBytesArray1.Length);

            // hash again
            Byte[] hashedBytesArray2 = provider.ComputeHash(inputBytesWithSalt);

            // return double hash encrypted string.
            return BitConverter.ToString(hashedBytesArray2);
        }
Beispiel #25
0
        private NewPassword HashPassword(NewPassword np)
        {
            HashAlgorithm hashAlg = null;

            try
            {
                hashAlg = new SHA256CryptoServiceProvider();
                byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(np.GetSaltPassword());
                byte[] bytHash = hashAlg.ComputeHash(bytValue);
                np.SaltedHashedPassword = Convert.ToBase64String(bytHash);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (hashAlg != null)
                {
                    hashAlg.Clear();
                    hashAlg.Dispose();
                    hashAlg = null;
                }
            }

            return np;
        }
Beispiel #26
0
 public static string SHA256(string str)
 {
     byte[] buffer = Encoding.UTF8.GetBytes(str);
     SHA256CryptoServiceProvider SHA256 = new SHA256CryptoServiceProvider();
     byte[] byteArr = SHA256.ComputeHash(buffer);
     return BitConverter.ToString(byteArr);
 }
 public string sha256(string input)
 {
     System.Security.Cryptography.SHA256 sha = new System.Security.Cryptography.SHA256CryptoServiceProvider();
     Byte[] inputBytes  = Encoding.UTF8.GetBytes(input);
     Byte[] hashedBytes = sha.ComputeHash(inputBytes);
     return(BitConverter.ToString(hashedBytes).Replace("-", "").ToLower());
 }
Beispiel #28
0
        /// <summary>
        /// SHA1编码
        /// </summary>
        /// <param name="value">明文</param>
        /// <param name="bit">位长</param>
        /// <returns></returns>
        public static string Get(string value, SHA1Bit bit)
        {
            StringBuilder sBuilder = new StringBuilder();

            if (bit == SHA1Bit.L160)
            {
                System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                // This is one implementation of the abstract class SHA1.
                byte[] result = sha.ComputeHash(Encoding.Default.GetBytes(value));
                sBuilder.Append(BitConverter.ToString(result).Replace("-", ""));
            }
            if (bit == SHA1Bit.L256)
            {
                System.Security.Cryptography.SHA256 sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
                // This is one implementation of the abstract class SHA1.
                byte[] result = sha256.ComputeHash(Encoding.Default.GetBytes(value));
                sBuilder.Append(BitConverter.ToString(result).Replace("-", ""));
            }
            if (bit == SHA1Bit.L384)
            {
                System.Security.Cryptography.SHA384 sha384 = new System.Security.Cryptography.SHA384CryptoServiceProvider();
                // This is one implementation of the abstract class SHA1.
                byte[] result = sha384.ComputeHash(Encoding.Default.GetBytes(value));
                sBuilder.Append(BitConverter.ToString(result).Replace("-", ""));
            }
            return(sBuilder.ToString());
        }
Beispiel #29
0
        public static string Sha256(string text)
        {
            var bits = Encoding.UTF8.GetBytes(text);
            var hash = new SHA256CryptoServiceProvider().ComputeHash(bits);

            return BitConverter.ToString(hash).Replace("-", "").ToLower();
        }
Beispiel #30
0
        public static string EncryptString(string message, string passphrase = null)
        {
            if (string.IsNullOrEmpty(message))
            {
                throw new ArgumentException("message is empty!", message);
            }

            if (string.IsNullOrEmpty(passphrase))
            {
                passphrase = ConfigurationManager.AppSettings.Get("Common.Cryptography.DefaultPassPhrase");
            }

            // First hash the passphrase to get a 256bit key
            var sha = new SHA256CryptoServiceProvider();
            var passphraseHash = sha.ComputeHash(Encoding.UTF8.GetBytes(passphrase));

            var aes = new AesCryptoServiceProvider { KeySize = 256, Key = passphraseHash };

            var memoryStream = new MemoryStream();

            var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write);

            using (var writer = new StreamWriter(cryptoStream, Encoding.UTF8))
            {
                writer.Write(message);
            }

            var results = memoryStream.ToArray();

            var finalArray = new byte[aes.IV.Length + results.Length];
            Array.Copy(aes.IV, 0, finalArray, 0, aes.IV.Length);
            Array.Copy(results, 0, finalArray, aes.IV.Length, results.Length);

            return HttpServerUtility.UrlTokenEncode(finalArray);
        }
        public static string HashPassword(string password, string saltValue)
        {
            if (String.IsNullOrEmpty(password)) throw new ArgumentException("Password is null");

            var encoding = new UnicodeEncoding();
            var hash = new SHA256CryptoServiceProvider();

            if (saltValue == null)
            {
                saltValue = GenerateSaltValue();
            }

            byte[] binarySaltValue = Convert.FromBase64String(saltValue);
            byte[] valueToHash = new byte[SaltValueSize + encoding.GetByteCount(password)];
            byte[] binaryPassword = encoding.GetBytes(password);

            binarySaltValue.CopyTo(valueToHash, 0);
            binaryPassword.CopyTo(valueToHash, SaltValueSize);

            byte[] hashValue = hash.ComputeHash(valueToHash);
            var hashedPassword = String.Empty;
            foreach (byte hexdigit in hashValue)
            {
                hashedPassword += hexdigit.ToString("X2", CultureInfo.InvariantCulture.NumberFormat);
            }

            return hashedPassword;
        }
Beispiel #32
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            //connect
            using (DefaultConnection db = new DefaultConnection())
            {
                //create instructor object
                Staff objS = new Staff();

                //first get salt value for this username
                String username = txtUsername.Text;

                objS = (from s in db.Staff
                        where s.username == username
                        select s).FirstOrDefault();

                //did we find this username?
                if (objS != null)
                {
                    String salt = objS.salt;

                    //salt and hash the plain text password
                    String password = txtPassword.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 we just salted and hashed matches the password in the db
                    if (objS.hashed == base64)
                    {
                        //lblError.Text = "Valid Login";
                        //store the identity in the session object
                        Session["AdminID"] = objS.AdminID;

                        //redirect to departments page
                        Response.Redirect("welcome.aspx");
                    }
                    else
                    {
                        lblError.Text = "Invalid Login";
                    }
                }
                else
                {
                    lblError.Text = "Invalid Login";
                }
            }
        }
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            //connect
            using (DefaultConnection db = new DefaultConnection())
            {
                //create user object
                User objU = new User();

                //get salt value for this username
                String Username = txtUsername.Text;

                objU = (from u in db.Users where u.Username == Username select u).FirstOrDefault();

                //find match for username
                if (objU != null)
                {
                    String salt = objU.Salt;

                    //salt and hash plain text pw
                    String password = txtPassword.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 passwords match
                    if (objU.Password == base64)
                    {

                        //store identity in session obj
                        Session["UserID"] = objU.UserID;
                        Session["Name"] = objU.Name;

                        //redirect to standings page
                        Response.Redirect("standings.aspx");

                    }
                    else
                    {
                        lblError.Text = "Invalid Login";
                    }
                }
                else
                {
                    lblError.Text = "Invalid Login";
                }

            }
        }
Beispiel #34
0
        /// <summary>
        /// 计算SHA-256码
        /// </summary>
        /// <param name="word">字符串</param>
        /// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param>
        /// <returns></returns>
        public string Hash_SHA_256(string word, bool toUpper = true)
        {
            try
            {
                byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word);
                System.Security.Cryptography.SHA256CryptoServiceProvider SHA256
                    = new System.Security.Cryptography.SHA256CryptoServiceProvider();

                byte[] bytHash = SHA256.ComputeHash(bytValue);
                SHA256.Clear();

                StringBuilder sb = new StringBuilder();

                foreach (var b in bytHash)
                {
                    sb.Append(b.ToString("X2"));
                }
                string sHash = sb.ToString();

                #region
                //根据计算得到的Hash码翻译为SHA-1码

                /*string sHash = "", sTemp = "";
                 * for (int counter = 0; counter < bytHash.Count(); counter++)
                 * {
                 *  long i = bytHash[counter] / 16;
                 *  if (i > 9)
                 *  {
                 *      sTemp = ((char)(i - 10 + 0x41)).ToString();
                 *  }
                 *  else
                 *  {
                 *      sTemp = ((char)(i + 0x30)).ToString();
                 *  }
                 *  i = bytHash[counter] % 16;
                 *  if (i > 9)
                 *  {
                 *      sTemp += ((char)(i - 10 + 0x41)).ToString();
                 *  }
                 *  else
                 *  {
                 *      sTemp += ((char)(i + 0x30)).ToString();
                 *  }
                 *  sHash += sTemp;
                 * }*/
                #endregion

                //根据大小写规则决定返回的字符串
                return(toUpper ? sHash : sHash.ToLower());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Beispiel #35
0
        private string EncryptSHA256(string pass)
        {
            System.Security.Cryptography.SHA256CryptoServiceProvider x = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            //However in WinXp says "SHA256CryptoServiceProvider not supported for this platform"
            //System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] data = System.Text.Encoding.ASCII.GetBytes(pass);
            data = x.ComputeHash(data);
            String sha256Hash = System.Text.Encoding.ASCII.GetString(data);

            return(sha256Hash);
        }
        public static string GetSHA256(byte[] data)
        {
            System.Security.Cryptography.SHA256 sha = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            byte[] bytResult = sha.ComputeHash(data);
            //转换成字符串,32位
            string strResult = BitConverter.ToString(bytResult);

            //BitConverter转换出来的字符串会在每个字符中间产生一个分隔符,需要去除掉
            strResult = strResult.Replace("-", "");

            return(strResult);
        }
Beispiel #37
0
        public static string SHA256(byte[] data)
        {
            SHA256CryptoServiceProvider x = new System.Security.Cryptography.SHA256CryptoServiceProvider();

            byte[] bs = data;
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            return(s.ToString());
        }
Beispiel #38
0
 public static String PlainToSHA256(String Stringa)
 {
     if (Stringa == null || String.IsNullOrEmpty(Stringa))
     {
         return(null);
     }
     else
     {
         System.Security.Cryptography.SHA256 sha = new System.Security.Cryptography.SHA256CryptoServiceProvider();
         System.Text.Encoding objEncoding        = System.Text.Encoding.UTF8;
         byte[] pwHashed = sha.ComputeHash(objEncoding.GetBytes(Stringa));
         return(System.Convert.ToBase64String(pwHashed));
     }
 }
Beispiel #39
0
        static byte[] Get8BytesHashCode(string strText)
        {
            byte[] hashCode = null;
            if (!string.IsNullOrEmpty(strText))
            {
                byte[] byteContents = Encoding.Unicode.GetBytes(strText);
                System.Security.Cryptography.SHA256 hash = new System.Security.Cryptography.SHA256CryptoServiceProvider();
                byte[] hashText = hash.ComputeHash(byteContents);

                Int64 hashCodeStart  = BitConverter.ToInt64(hashText, 0);
                Int64 hashCodeMedium = BitConverter.ToInt64(hashText, 8);
                Int64 hashCodeEnd    = BitConverter.ToInt64(hashText, 24);
                hashCode = BitConverter.GetBytes(hashCodeStart ^ hashCodeMedium ^ hashCodeEnd);
            }
            return(hashCode);
        }
        /*************************************************************************************************************
         **************************************************************************************************************
         **************************************************************************************************************/



        public string GetSHA256Hash(string input)
        {
            //Umwandlung des Eingastring in den SHA256 Hash
            System.Security.Cryptography.SHA256 SHA256 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            byte[] textToHash = Encoding.Default.GetBytes(input);
            byte[] result     = SHA256.ComputeHash(textToHash);

            //SHA256 Hash in String konvertieren
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in result)
            {
                s.Append(b.ToString("x2").ToLower());
            }

            return(s.ToString());
        }
        public bool VerifySHA256Hash(string input, string hash)
        {
            System.Security.Cryptography.SHA256 SHA256 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            // Hash the input.
            string hashOfInput = GetSHA256Hash(input);

            // Create a StringComparer an compare the hashes.
            StringComparer comparer = StringComparer.CurrentCulture;//.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfInput, hash))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #42
0
        /// <summary>
        /// 获取文本SHA256
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string GetTextSHA_256(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return("");
            }
            System.Security.Cryptography.SHA256CryptoServiceProvider SHA256CSP = new System.Security.Cryptography.SHA256CryptoServiceProvider();

            byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(text);
            byte[] bytHash  = SHA256CSP.ComputeHash(bytValue);
            SHA256CSP.Clear();

            //根据计算得到的Hash码翻译为SHA-1码
            string sHash = ConvertHashBytes(bytHash);

            //根据大小写规则决定返回的字符串
            return(sHash.ToLower());
        }
Beispiel #43
0
        /// <summary>
        /// 计算SHA-256码
        /// </summary>
        /// <param name="word">字符串</param>
        /// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param>
        /// <returns></returns>
        public static string Hash_SHA_256(string word, bool toUpper = true)
        {
            try
            {
                System.Security.Cryptography.SHA256CryptoServiceProvider SHA256CSP
                    = new System.Security.Cryptography.SHA256CryptoServiceProvider();

                byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word);
                byte[] bytHash  = SHA256CSP.ComputeHash(bytValue);
                SHA256CSP.Clear();

                //根据计算得到的Hash码翻译为SHA-1码
                string sHash = "", sTemp = "";
                for (int counter = 0; counter < bytHash.Count(); counter++)
                {
                    long i = bytHash[counter] / 16;
                    if (i > 9)
                    {
                        sTemp = ((char)(i - 10 + 0x41)).ToString();
                    }
                    else
                    {
                        sTemp = ((char)(i + 0x30)).ToString();
                    }
                    i = bytHash[counter] % 16;
                    if (i > 9)
                    {
                        sTemp += ((char)(i - 10 + 0x41)).ToString();
                    }
                    else
                    {
                        sTemp += ((char)(i + 0x30)).ToString();
                    }
                    sHash += sTemp;
                }

                //根据大小写规则决定返回的字符串
                return(toUpper ? sHash : sHash.ToLower());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Beispiel #44
0
        /// <summary>
        /// Makes the Int64 hash code from the provided string.
        /// </summary>
        /// <param name="str">The string.</param>
        /// <returns></returns>
        public static long MakeInt64HashCode(this string str)
        {
            // http://www.codeproject.com/Articles/34309/Convert-String-to-64bit-Integer
            long hashCode = 0;

            if (!string.IsNullOrEmpty(str))
            {
                // Unicode Encode Covering all characterset
                byte[] byteContents = Encoding.Unicode.GetBytes(str);
                System.Security.Cryptography.SHA256 hash =
                    new System.Security.Cryptography.SHA256CryptoServiceProvider();
                byte[] hashText = hash.ComputeHash(byteContents);

                long hashCodeStart  = BitConverter.ToInt64(hashText, 0);
                long hashCodeMedium = BitConverter.ToInt64(hashText, 8);
                long hashCodeEnd    = BitConverter.ToInt64(hashText, 24);
                hashCode = hashCodeStart ^ hashCodeMedium ^ hashCodeEnd;
            }

            return(hashCode);
        }
        /// <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.
            //SHA256CryptoServiceProvider
            var hashAlg = new
                          System.Security.Cryptography.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());
        }
Beispiel #46
0
        /// <summary>
        /// Return unique Int64 value for input string
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static Int64 GetInt64HashCode(string text)
        {
            Int64 hashCode = 0;

            if (!string.IsNullOrEmpty(text))
            {
                //Unicode Encode Covering all characterset
                byte[] byteContents = Encoding.Unicode.GetBytes(text);
                System.Security.Cryptography.SHA256 hash =
                    new System.Security.Cryptography.SHA256CryptoServiceProvider();
                byte[] hashText = hash.ComputeHash(byteContents);
                //32Byte hashText separate
                //hashCodeStart = 0~7  8Byte
                //hashCodeMedium = 8~23  8Byte
                //hashCodeEnd = 24~31  8Byte
                //and Fold
                Int64 hashCodeStart  = BitConverter.ToInt64(hashText, 0);
                Int64 hashCodeMedium = BitConverter.ToInt64(hashText, 8);
                Int64 hashCodeEnd    = BitConverter.ToInt64(hashText, 24);
                hashCode = hashCodeStart ^ hashCodeMedium ^ hashCodeEnd;
            }
            return(hashCode);
        }
Beispiel #47
0
        public void TestRfc7515Example_A_2_1()
        {
            string protectedSample = // From the RFC example
                                     "{\"alg\":\"RS256\"}";

            byte[] protectedBytesExpected = // From the RFC example
            {
                123, 34, 97, 108, 103, 34, 58, 34, 82, 83, 50, 53, 54, 34, 125
            };
            byte[] protectedBytesActual = Encoding.UTF8.GetBytes(protectedSample);
            CollectionAssert.AreEqual(protectedBytesExpected, protectedBytesActual);

            string protectedB64uExpected = "eyJhbGciOiJSUzI1NiJ9"; // From the RFC example
            string protectedB64uActual   = CryptoHelper.Base64.UrlEncode(protectedBytesActual);

            Assert.AreEqual(protectedB64uExpected, protectedB64uActual);

            string payloadSample = // From the RFC example
                                   "{\"iss\":\"joe\",\r\n" +
                                   " \"exp\":1300819380,\r\n" +
                                   " \"http://example.com/is_root\":true}";

            byte[] payloadBytesActual = Encoding.UTF8.GetBytes(payloadSample);
            string payloadB64uActual  = CryptoHelper.Base64.UrlEncode(payloadBytesActual);
            string signingInput       = $"{protectedB64uActual}.{payloadB64uActual}";

            byte[] signingBytesExpected = // From the RFC example
            {
                101, 121,  74, 104,  98,  71,  99, 105,  79, 105,  74, 83,  85, 122,  73,
                49,   78, 105,  74,  57,  46, 101, 121,  74, 112,  99, 51,  77, 105,  79,105,
                74,  113,  98,  50,  85, 105,  76,  65,  48,  75,  73, 67,  74, 108, 101, 72,
                65,  105,  79, 106,  69, 122,  77,  68,  65,  52,  77, 84, 107, 122,  79, 68,
                65,  115,  68,  81, 111, 103,  73, 109, 104,  48, 100, 72,  65,  54,  76,
                121,  57, 108, 101,  71,  70, 116,  99,  71, 120, 108, 76, 109,  78, 118,
                98,   83,  57, 112,  99,  49,  57, 121,  98,  50,  57, 48,  73, 106, 112, 48,
                99,  110,  86, 108, 102, 81
            };
            byte[] signingBytesActual = Encoding.ASCII.GetBytes(signingInput);
            CollectionAssert.AreEqual(signingBytesExpected, signingBytesActual);


            byte[] sigExpected = // From the RFC example
            {
                112,  46,  33, 137,  67, 232, 143, 209,  30, 181, 216,  45, 191, 120,  69,
                243,  65,   6, 174,  27, 129, 255, 247, 115,  17,  22, 173, 209, 113, 125,
                131, 101, 109,  66,  10, 253,  60, 150, 238, 221, 115, 162, 102,  62,  81,
                102, 104, 123,   0,  11, 135,  34, 110,   1, 135, 237,  16, 115, 249,  69,
                229, 130, 173, 252, 239,  22, 216,  90, 121, 142, 232, 198, 109, 219,
                61,  184, 151,  91,  23, 208, 148,   2, 190, 237, 213, 217, 217, 112,   7,
                16,  141, 178, 129,  96, 213, 248,   4,  12, 167,  68,  87,  98, 184,  31,
                190, 127, 249, 217,  46,  10, 231, 111,  36, 242,  91,  51, 187, 230, 244,
                74,  230,  30, 177,   4,  10, 203,  32,   4,  77,  62, 249,  18, 142, 212,1,
                48,  121,  91, 212, 189,  59,  65, 238, 202, 208, 102, 171, 101,  25, 129,
                253, 228, 141, 247, 127,  55,  45, 195, 139, 159, 175, 221,  59, 239,
                177, 139,  93, 163, 204,  60,  46, 176,  47, 158,  58,  65, 214,  18, 202,
                173,  21, 145,  18, 115, 160,  95,  35, 185, 232,  56, 250, 175, 132, 157,
                105, 132,  41, 239,  90,  30, 136, 121, 130,  54, 195, 212,  14,  96,  69,
                34,  165,  68, 200, 242, 122, 122,  45, 184,   6,  99, 209, 108, 247, 202,
                234,  86, 222,  64,  92, 178,  33,  90,  69, 178, 194,  85, 102, 181,  90,
                193, 167,  72, 160, 112, 223, 200, 163,  42,  70, 149,  67, 208,  25, 238,
                251, 71
            };
            byte[] sigActual = null;
            using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider())
            {
                rsa.ImportParameters(GetRsaParamsForRfc7515Example_A_2_1());
                using (var sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider())
                {
                    sigActual = rsa.SignData(signingBytesExpected, sha256);
                }
            }
            CollectionAssert.AreEqual(sigExpected, sigActual);

            string sigB64uExpected = // From the RFC example
                                     "cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7" +
                                     "AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4" +
                                     "BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K" +
                                     "0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqv" +
                                     "hJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrB" +
                                     "p0igcN_IoypGlUPQGe77Rw";
            string sigB64uActual = CryptoHelper.Base64.UrlEncode(sigActual);

            Assert.AreEqual(sigB64uExpected, sigB64uActual);
        }