Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash string in c#

Tags:

string

c#

hash

I have a problem when trying get a hash string in c#.

I already tried a few websites, but most of them are using files to get the hash. Others that are for strings are a bit too complex. I found examples for Windows authentication for web like this:

FormsAuthentication.HashPasswordForStoringInConfigFile(tbxPassword.Text.Trim(), "md5") 

I need to use a hash to make a string that contains a filename more secure. How can I do that?

Example:

string file  = "username"; string hash = ??????(username);  

Should I use another hashing algorithm and not "md5"?

like image 303
Edy Cu Avatar asked Oct 21 '10 03:10

Edy Cu


People also ask

What is a hash string?

Hashing is the process of transforming any given key or a string of characters into another value. This is usually represented by a shorter, fixed-length value or key that represents and makes it easier to find or employ the original string. The most popular use for hashing is the implementation of hash tables.

What is a hash function in C?

The hash function is a function that uses the constant-time operation to store and retrieve the value from the hash table, which is applied on the keys as integers and this is used as the address for values in the hash table.

What is the hash value of a string?

A Hash Value (also called as Hashes or Checksum) is a string value (of specific length), which is the result of calculation of a Hashing Algorithm. Hash Values have different uses.

How do I make a hash string?

In order to create a unique hash from a specific string, it can be implemented using their own string to hash converting function. It will return the hash equivalent of a string. Also, a library named Crypto can be used to generate various types of hashes like SHA1, MD5, SHA256 and many more.


1 Answers

using System.Security.Cryptography;  public static byte[] GetHash(string inputString) {     using (HashAlgorithm algorithm = SHA256.Create())         return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString)); }  public static string GetHashString(string inputString) {     StringBuilder sb = new StringBuilder();     foreach (byte b in GetHash(inputString))         sb.Append(b.ToString("X2"));      return sb.ToString(); } 

Additional Notes

  • Since MD5 and SHA1 are obsolete and insecure algorithms, this solution uses SHA256. Alternatively, you can use BCrypt or Scrypt as pointed out in comments.
  • Also, consider "salting" your hashes and use proven cryptographic algorithms, as pointed out in comments.
like image 175
Dmitry Polomoshnov Avatar answered Oct 09 '22 01:10

Dmitry Polomoshnov