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); }
/// <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); }
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); }
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); } }
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); }
public static byte[] Base58ToByteArray(string base58) { Org.BouncyCastle.Math.BigInteger bi2 = new Org.BouncyCastle.Math.BigInteger("0"); string b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; bool IgnoreChecksum = false; foreach (char c in base58) { if (b58.IndexOf(c) != -1) { bi2 = bi2.Multiply(new Org.BouncyCastle.Math.BigInteger("58")); bi2 = bi2.Add(new Org.BouncyCastle.Math.BigInteger(b58.IndexOf(c).ToString())); } else if (c == '?') { IgnoreChecksum = true; } else { return null; } } byte[] bb = bi2.ToByteArrayUnsigned(); // interpret leading '1's as leading zero bytes foreach (char c in base58) { if (c != '1') break; byte[] bbb = new byte[bb.Length + 1]; Array.Copy(bb, 0, bbb, 1, bb.Length); bb = bbb; } if (bb.Length < 4) return null; if (IgnoreChecksum == false) { SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider(); byte[] checksum = sha256.ComputeHash(bb, 0, bb.Length - 4); checksum = sha256.ComputeHash(checksum); for (int i = 0; i < 4; i++) { if (checksum[i] != bb[bb.Length - 4 + i]) return null; } } byte[] rv = new byte[bb.Length - 4]; Array.Copy(bb, 0, rv, 0, bb.Length - 4); return rv; }
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("-",""); }
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; }
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 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; }
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("-", ""); }
/// <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()); }
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); } }
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; } }
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; }
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); }
public string SHA256(string input) { HashAlgorithm algorithm = new SHA256CryptoServiceProvider(); Byte[] inputBytes = Encoding.UTF8.GetBytes(input); Byte[] hashedBytes = algorithm.ComputeHash(inputBytes); return BitConverter.ToString(hashedBytes); }
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 HashStringSHA256(string valueUTF8) { byte[] valueBytes = Encoding.UTF8.GetBytes(valueUTF8); SHA256CryptoServiceProvider shar2 = new SHA256CryptoServiceProvider(); byte[] hashBytes = shar2.ComputeHash(valueBytes); return BitConverter.ToString(hashBytes).Replace("-", ""); }
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 static string Hash(this string clear_text) { using (HashAlgorithm hash = new SHA256CryptoServiceProvider()) { return Convert.ToBase64String(hash.ComputeHash(Encoding.UTF8.GetBytes(clear_text))); } }
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; }
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()); }
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); }
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); }
/// <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) ; }
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"; } } }
public static string EncryptPassword([NotNull] string plaintext) { if (plaintext == null) throw new ArgumentNullException("plaintext"); var crypto = new SHA256CryptoServiceProvider(); var data = Encoding.ASCII.GetBytes(plaintext); data = crypto.ComputeHash(data); return BitConverter.ToString(data).Replace("-", string.Empty).ToLower(); }
public static string SHA256Encryptor(string plainText) { byte[] data = ASCIIEncoding.ASCII.GetBytes(plainText); SHA256 sha256 = new SHA256CryptoServiceProvider(); byte[] result = sha256.ComputeHash(data); return Convert.ToBase64String(result); }
public string GetPasswordHashAndSalt(string message) { SHA256 sha = new SHA256CryptoServiceProvider(); byte[] dataBytes = encoding.GetBytes(message); byte[] resultBytes = sha.ComputeHash(dataBytes); return encoding.GetString(resultBytes); }
/// <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); } }
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); }
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()); }
public string ShaEncrypt(string Ptext) { string hash = ""; System.Security.Cryptography.SHA256CryptoServiceProvider m1 = new System.Security.Cryptography.SHA256CryptoServiceProvider(); byte[] s1 = System.Text.Encoding.ASCII.GetBytes(Ptext); s1 = m1.ComputeHash(s1); foreach (byte bt in s1) { hash = hash + bt.ToString("x2"); } return(hash); }
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)); } }
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()); }
/// <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()); }
/// <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); } }
private static string GetInt64HashCode(string url) { //#if UNITY_ANDROID Int64 hashCode = 0; if (!string.IsNullOrEmpty(url)) { //Unicode Encode Covering all characterset byte[] byteContents = Encoding.Unicode.GetBytes(url); 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 = hashCodeStart ^ hashCodeMedium ^ hashCodeEnd; } return(hashCode + ""); //#endif //return UnityEngine.Random.Range(0, 999999999) + ""; }
/// <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()); }
/// <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); }