0

I'm trying to store hashes and salts in a database using entity framework. But when I try to call this code to return one of the salts.

var salt = (from u in db.Users
            join p in db.Passwords on u.Name equals p.UserName
            where u.Name == username
            select p.Salt).First();

I get thrown this exception: System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'System.Byte[]'.'

My Password entity looks like this:

    class Password
    {
        [Key]
        public string UserName { get; set; }
        public byte[] Hash { get; set; }
        public byte[] Salt { get; set; }
        public User User{ get; set;}
    }
7
  • What are the actual data types in your database for the columns? Commented Oct 13, 2020 at 16:06
  • What is the definition of Hash and Salt in the passwords table? Commented Oct 13, 2020 at 16:06
  • @jeroenh they are nvarchar Commented Oct 13, 2020 at 16:09
  • 4
    Then that is your error. Why do you define them as byte[] in code? LINQ can not magically cast string to byte[] Commented Oct 13, 2020 at 16:10
  • @jeroenh allright thanks Commented Oct 13, 2020 at 16:11

1 Answer 1

2

Your table's columns are likely varchar or something similar, rather than binary/varbinary data types - or whatever term your database server uses for storing binary data.

If you are using EF core, then see value converters. There's a StringToBytesConverter available.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.