I made an account on my web app (Symfony2 with FOSUserBundle) and registered with the password "lolwut" (without the quotes).
These are the settings in my security.yml config:
security:
encoders:
FOS\UserBundle\Model\UserInterface:
algorithm: sha512
iterations: 1
encode_as_base64: false
The resulting data:
Hashed password:
f57470574dbf29026821519b19539d1c2237e4315d881fa412da978af554740c6b284062a9a4af7d0295d18ebea8ef2e152cf674b283f792fe0b568a93f969cf
Salt:
kuc5bixg5u88s4k8ggss4osoksko0g8
Now, since the iterations are set on 1, I am assuming that encoding "lolwut" in SHA512 in C# will give me the same result, here's my logic:
string salt = "kuc5bixg5u88s4k8ggss4osoksko0g8";
string input = "lolwut";
string passAndSalt = String.Concat(input, salt);
System.String Hashed = System.BitConverter.ToString(((System.Security.Cryptography.SHA512)new System.Security.Cryptography.SHA512Managed()).ComputeHash(System.Text.Encoding.ASCII.GetBytes(passAndSalt))).Replace("-", "");
return passAndSalt + "<br>" + Hashed;
However, this returns the following value that doesn't match the FOSUserBundle hashed password at all:
82E8CA0408B23DB50EB654EDB50A7926AC73613184054DB82FB6D67CD4186B7A045D265AEDE6E3852CD85B981F15F6615C1C0C6FBF443B1672DF59DE23557BD9
I know I must be doing something wrong somewhere, but I can't for the life of me figure out what it is, and it's driving me nuts. Could anyone help me out here, please?
Symfony merges password and salt as password{salt}, so this code will return the same hash:
string salt = "kuc5bixg5u88s4k8ggss4osoksko0g8";
string input = "lolwut";
string passAndSalt = String.Format("{0}{{{1}}}", input, salt);
System.String Hashed = System.BitConverter.ToString(((System.Security.Cryptography.SHA512)new System.Security.Cryptography.SHA512Managed()).ComputeHash(System.Text.Encoding.ASCII.GetBytes(passAndSalt))).Replace("-", "");
// Hashed.ToLower()
Related
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("-", "");
}
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;
}
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.
I'm currently migrating a CakePhp app to ASP.NET. One thing that is blocking me at this point is that I'm unable to get the right hashing method to get the right password fit so users are able to sign-in from the ASP.NET app.
I have the salt value that is set in config/core.php file.
I've googled to try to determined where to find which hashing algorithm is used, and was not able to find the right query or no result.
here is my C# method so far to hash the password.
public static string ToHash(this string password, string salt)
{
if (string.IsNullOrEmpty(password))
return "";
var provider = new SHA1CryptoServiceProvider();
var encoding = new UnicodeEncoding();
var bytes = provider.ComputeHash(encoding.GetBytes(salt + password));
return Encoding.UTF8.GetString(bytes);
}
I've tried to put the salt before or after the password, it's currently no matching at all, here is the hash password from the cakephp mysql database:
c7fb60ef77dbe3d1681a68e6741ee3a23cc1f41d
Here is what I have from my method
��3[v"���1�:�ѐ��
Not really sure where/how to solve this problem. Any help or hint would be appreciated.
Thanks
I have it!
At least it works for my configuration:
Find salt from Core.php (search for Security.salt in the file). Then, use this code (very similar to the question):
string input = textBox1.Text;
input = "your salt should be here" + input;
var provider = new SHA1CryptoServiceProvider();
var encoding = new UTF8Encoding();
var bytes = provider.ComputeHash(encoding.GetBytes(input));
sha1result.Text = Bin2Hex(bytes);
Helper for Bin2Hex is also here:
public static string Bin2Hex(byte[] ba)
{
string hex = BitConverter.ToString(ba);
return hex.Replace("-", "");
}
It wasn't easy finding it, I searched through some of internet (no results!) and finally resorted to source-digging.
Don't have the Cake sources with me right now, but you should easily be able to look up Cake's hashing and salting method in the source.
The above differences in data look like Cake transforms the hash bytes into a string with the hash's bytes in hex base. Whatever the difference in the hash method, you'll have to convert the C# hash's result into such a string as well before comparing them (or go the other way and parse Cake's hex string and build a byte array out of it).
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.