How to hash with salt then unhash in asp.net C# [duplicate] - c#

This question already has answers here:
How can I unhash a hash using C#?
(4 answers)
Closed 8 years ago.
I have this asp.net project that I need to hash the password (preferably with salt) and save it in sql database then unhash it for comparing with the login password or sth like that....
the thing is I'm not sure what is the best way to do it in a most secure way and how can I code this in C#?

You do not unhash. That's the point of hashing: it cannot be reversed.
You look up the salt, then you hash the password that they entered together with the salt. If the hash is the same as the hash in the database, it's a valid login.
Maybe take a look here:
Salted password hashing

First of all you cannot recover the hashed data. Its one way process. But you can match hashed data. To do so check the code given below :
Do this inside your button click event
string salt = GetSalt(10); // 10 is the size of Salt
string hashedPass = HashPassword(salt, Password.Text);
This are the functions that will help your to hash the password
const string alphanumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
public static string GetSalt(int saltSize)
{
Random r = new Random();
StringBuilder strB = new StringBuilder("");
while ((saltSize--) > 0)
strB.Append(alphanumeric[(int)(r.NextDouble() * alphanumeric.Length)]);
return strB.ToString();
}
public static string HashPassword(string salt, string password)
{
string mergedPass = string.Concat(salt, password);
return EncryptUsingMD5(mergedPass);
}
public static string EncryptUsingMD5(string inputStr)
{
using (MD5 md5Hash = MD5.Create())
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(inputStr));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
sBuilder.Append(data[i].ToString("x2"));
// Return the hexadecimal string.
return sBuilder.ToString();
}
}
Similarly, when you try to match the password to authenticate the user, perform the same method just fetch your hashed password from your database and compare them. If the entered hashed password matches the database hashed password, its an authorized user.
Updated :
When you hash the password of the user for the first time and then store into database in the same table store the salt for that user.
Next time when you try to compare the password, fetch that salt of the user from the database and hash it using to compare with the
hashed password in the database.
Hope that answers your Question.

Related

why does md5 hashing not matching the textual password on log in?

I am trying to store the hashed password in the database. Like given below.
Md5Encrypt.Md5EncryptPassword(viewModel.User.PasswordHash);
Textual Password : TestBasant1900
And it get stored in my Database table in sql server like this after passing this into Md5Encrypt : zb??"??8?(Y???0z
When I am trying to check the password in Database and current user logged in password :
public bool Login(string userName, string password)
{
try
{
using (var db1 = new DBEnitityObj)
{
var user = (from u in db1.ftUsers
where (u.UserName == userName && u.IsApproved == true)
select u).First();
var PasswordHash1 = user.PasswordHash;
var encoded = Md5Encrypt.Md5EncryptPassword(password);
// It fails in the below condition
return user.PasswordHash.Equals(encoded);
}
}
catch
{
return false;
}
}
It fails in the below condition since the hashed password over here will return this : zb��"��8�(Y���0z
I am using this for md5 Hashing
public static string Md5EncryptPassword(string data)
{
var encoding = new ASCIIEncoding();
var bytes = encoding.GetBytes(data);
var hashed = MD5.Create().ComputeHash(bytes);
return Encoding.UTF8.GetString(hashed);
}
Can any one please tell me what is hashed password is not getting matched with password which I enter on the user interface
zb��"��8�(Y���0z is not equal to zb??"??8?(Y???0z
Can some one guide me what to do guys. Thanks in advance.
You store the data as VARCHAR, which is a string (text). MD5 gives you bytes. It is not guaranteed that these bytes are convertible to a string (text). The � character is the Unicode replacement character and means that there was an illegal character.
You either want to store the result as binary data (BLOB) or you want to ensure that it becomes simple text by encoding it in Base64 or hex for example.

Trouble matching SHA512 hash from PHP with C# counterpart formula

This should be so simple but I've spent 4 hours fiddling with this code and I just can't seem to get it to work.
The PHP code works as follows (I didn't write it and I can't change it, so I'm stuck with it):
$password = hash('sha512', "HelloWorld1");
$salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true);
$hashed = hash('sha512', $password.$salt);
$hashed and $salt are stored in the DB as is. That means $salt is already hashed for later on.
I have no idea why they decided to hash everything but what's done is done.
In this case, the result is
Pswd: ab3e648d69a71b33d0420fc3bfc9e2e8e3ef2a300385ea26bc22057a84cd9a5c359bd15c4a0a552122309e58938ce310839cd9d2ecad5f294266015d823331dd
Salt: fb5a0f741db0be2439dc14662aae3fc68eb5e16b446385d3ddd319b862d5e2d4f50488a39487b27fdd8ff7b7b76420fc3ebef2bce9e082ac15c9f2d6fe7d87fc
Now the login code on the C# side just needs to match a plain text hashed password along with the already hashed salt.
string password = "HelloWorld1";
string storedSalt = "fb5a0f741db0be2439dc14662aae3fc68eb5e16b446385d3ddd319b862d5e2d4f50488a39487b27fdd8ff7b7b76420fc3ebef2bce9e082ac15c9f2d6fe7d87fc";
using(SHA512 shaManaged = new SHA512Managed())
{
byte[] hashPassword = shaManaged.ComputeHash(Encoding.UTF8.GetBytes(password));
string hashPasswordString = BitConverter.ToString(hashPassword).Replace("-", "");
byte[] finalHash = shaManaged.ComputeHash(Encoding.UTF8.GetBytes(hashPasswordString + storedSalt));
Debug.WriteLine("Calculated Hash Password: " + BitConverter.ToString(finalHash).Replace("-", ""));
}
Essentially the idea is to
Hash the plain text password first (same as with the PHP code).
Convert the byte array to a string that matches the PHP format of hashing.
Then hash the hashed password and previously hashed salt together.
The result is as follows:
Stored Hash Password: AB3E648D69A71B33D0420FC3BFC9E2E8E3EF2A300385EA26BC22057A84CD9A5C359BD15C4A0A552122309E58938CE310839CD9D2ECAD5F294266015D823331DD
Calculated Hash Password: 189ABBA71AAEDDE5C8154558B68D59500A72E64D5F3F3C07EFA94F0126571FBB68C6ADD105E0C029BABF30CADD8A6A6B6E4749075854461A88EE1CE545E84507
Hopefully someone can spot where I'm going wrong :)
You have to tweak your code a little bit. Note the ToLowerInvariant(). C# returns upper case letters as string. As you see in your original code $salt and $password are returned with lower case letters, so your self calculated password hash hashPasswordString must also be lower case before concatenating with your storedSalt to gain the correct finalHash. Your shown expected result again uses upper case letters (maybe before stored it was converted in PHP?) so you don't need ToLowerCaseInvariant() on your final hash string.
Here is the code:
string password = "HelloWorld1";
string storedSalt = "fb5a0f741db0be2439dc14662aae3fc68eb5e16b446385d3ddd319b862d5e2d4f50488a39487b27fdd8ff7b7b76420fc3ebef2bce9e082ac15c9f2d6fe7d87fc";
using (SHA512 shaManaged = new SHA512Managed())
{
byte[] hashPassword = shaManaged.ComputeHash(Encoding.UTF8.GetBytes(password));
string hashPasswordString = BitConverter.ToString(hashPassword).Replace("-", "").ToLowerInvariant(); // Note the ToLowerInvariant();
byte[] finalHash = shaManaged.ComputeHash(Encoding.UTF8.GetBytes(hashPasswordString + storedSalt));
return BitConverter.ToString(finalHash).Replace("-", "");
}

Validate symfony created password in C#

I need to validate (not decrypt) a password created in Symfony 2 in C#.
An existing application built in Symfony 2 is being rewritten in C#. The security token is stored in a local database.
The current Symfony password settings are
security:
encoders:
Symfony\Component\Security\Core\User\User: plaintext
API\CoreEntityBundle\Entity\User:
algorithm: sha512
iterations: 512
encode_as_base64: true
How can I reliably hash the given password and compare against the stored token to determine if the password supplied is correct?
If your password is salted: Concatenate the password with the "{salt}" (such that "EncodedPassword{SaltUsed}" is the final string), store in salted. If it's not just store the password in salted.
Hash salted using sha512, store in digest
Repeat iterations - 1 times (511 in your case):
Concatenate digest and salted
Hash concatenation using sha512, store result in digest for next iteration
Base64 Encode the final digest.
You can also take a look at Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder for the implementation.
This is a working version.
string CalculateHash(string plain, string salt)
{
var salted = $"{plain}{{{salt}}}";
var saltedBytes = Encoding.UTF8.GetBytes(salted);
using (var sha512 = SHA512.Create())
{
var digest = sha512.ComputeHash(saltedBytes);
var outputBytes = new byte[digest.Length + saltedBytes.Length];
for (var iteration = 1; iteration < 512; iteration++)
{
Buffer.BlockCopy(digest, 0, outputBytes, 0, digest.Length);
Buffer.BlockCopy(saltedBytes, 0, outputBytes, digest.Length, saltedBytes.Length);
digest = sha512.ComputeHash(outputBytes);
}
var result = Convert.ToBase64String(digest);
return result;
}

Password Decryption Issue using SHA1 [duplicate]

This question already has answers here:
Is it possible to decrypt MD5 hashes?
(24 answers)
Closed 6 years ago.
I am encrypting my password using below code.
public static string GetSHA1HashData(string password)
{
//create new instance of md5
SHA1 sha1 = SHA1.Create();
//convert the input text to array of bytes
byte[] hashData = sha1.ComputeHash(Encoding.Default.GetBytes(password));
//create new instance of StringBuilder to save hashed data
StringBuilder returnValue = new StringBuilder();
//loop for each byte and add it to StringBuilder
for (int i = 0; i < hashData.Length; i++)
{
returnValue.Append(hashData[i].ToString());
}
// return hexadecimal string
return returnValue.ToString();
}
But I also want to create code for Decryption. I've tried, but couldn't a good solution. So could you help me on this?
Here I used System.Security.Cryptography => SHA1 : HashAlgorithm
Thanks in advance.
Hash value can't be decrypted:
Hash is short (say, 256-bit only), while String is arbitrary long (up to 2GB), so there're many Strings with the same hash (ambiguity)
Hash algorithm (SHA1) has been specially designed such that it's a difficult task to find out a string that has given hash value (complexity)
Instead of decrypting, compare hash values: if user provides a password that has the same hash value that a stored hash, then the password is correct one.

UTF8 encoded password Byte[] with SHA512 encryption to string conversion

I have created a web form in c# that accepts username and password and stores password in MSSQL 2005 db in 'image' format. The password is merged with salt, encoded in UTF8 and lastly it is applied with a SHA512 encryption. I want to be able to see the passwords in string format when I pull them up back from the database. How should my decrypt function be, if the following is how I encrypted the password? Is that possible? :
string loginID = "";//This will be stored in varchar format in MSSQL..(Unrelated to the question)
string password =""; //This is where I store password inputted by user.
Random r = new Random();
int salt = r.Next((int)Math.Pow(2, 16));
int verifyCode = r.Next((int)Math.Pow(2, 16));
string tmpPwd = password.ToLower() + salt.ToString();
UTF8Encoding textConverter = new UTF8Encoding();
byte[] passBytes = textConverter.GetBytes(tmpPwd);
byte[] hashedPWD = new SHA512Managed().ComputeHash(passBytes);
The value in hashedPWD is stored in MSSQL as image datatype and salt is stored as int.
You can't - that's what a hash function is, by definition - a one-way function. Up until the last line, you can get the password back, but after the hash function, all you can do is generate a second hash and compare the two to see if they've produced the same result, in which case you can presume that the source strings were the same.

Categories

Resources