Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 equal byte[] does not return true

Tags:

c#

passwords

byte

I'm trying to verify someone's password when logging in.

I take the entered password and retrieve the users saved hashed password and password salt.

Then I hash the entered password with the saved salt to see if it's equal to the saved password.

However, even though the byte[] storedPassword is exactly like the byte[] enteredPassword, it doesn't return true in a bool and therefore doesn't verify the user. Why is that?

public static bool VerifyPassword(byte[] newPassword, byte[] storedPassword, byte[] storedSalt)
    {
        byte[] password = CreateHashedPassword(newPassword, storedSalt);

        if (!password.Equals(storedPassword))
            return false;

        return true;
    }
like image 682
Jova Avatar asked Feb 26 '10 05:02

Jova


People also ask

Can you print [] byte?

You can simply iterate the byte array and print the byte using System. out. println() method.

How do you know if two byte arrays are equal?

equals(byte[] a, byte[] a2) method returns true if the two specified arrays of bytes are equal to one another. Two arrays are equal if they contain the same elements in the same order. Two array references are considered equal if both are null.

How can I check if two slices are equal?

Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal.

Can a byte array be null?

An array value can be non-empty, empty (cardinality zero), or null. The individual elements in the array can be null or not null. An empty array, an array value of null, and an array for which all elements are the null value are different from each other. An uninitialized array is a null array.


2 Answers

You should compare each byte of your arrays, you can make a simple loop, or use the SequenceEqual Linq Extension method if available:

public static bool VerifyPassword(byte[] newPassword, byte[] storedPassword,
                                  byte[] storedSalt)
{
    byte[] password = CreateHashedPassword(newPassword, storedSalt);

    return password.SequenceEqual(storedPassword);
}
like image 122
Christian C. Salvadó Avatar answered Oct 19 '22 15:10

Christian C. Salvadó


Equals does not byte compare the two byte[] arrays. You have to compare each byte in the two arrays yourself.

like image 26
logicnp Avatar answered Oct 19 '22 15:10

logicnp