简体   繁体   中英

How can I store a hash in a SQL Server database using C#?

I'm trying to make a website with a log on / log off feature and I plan on properly hashing and salting the password. The problem I'm facing, however, is how I'd go about storing the password in the database. I know that I need to store the hashed + salted password in the database (not in plain text or plain encrypted), but I don't know how to technically get around inserting the binary data into the database.

In my early attempts, the only way I could get the data in the database would be to have the binary data converted to a base64 string and inserted into the varchar password field, but something is telling me that's not the correct way to do it.

The password field in the database is currently a varchar but as I understand it, a hashed password is binary. So even if I changed the password field to a binary object, I still don't know how to actually insert it!

If I'm not making any sense please ask for clarification and I'll get back to you.

In Microsoft SQL Server you can store binary data in columns having a binary data type (or varbinary if you need variable length data). You can use that for you hashed and salted passwords. If you use a 512 bit hash function and also want to use a 512 bit salt you need 2*512/8 = 128 bytes (eg binary(128) to store salt and hash.

Normally whatever API you use to read and write the database should assist you in reading and writing binary data. However, perhaps you want to use some SQL to directly insert a binary value into a table. You can use syntax like this:

insert into MyTable values (0x123456789ABCDEF)

Not really an answer to your question, but if you struggle with implementing you own password feature you could consider using a prebuilt industrial strength component to avoid embarrasing errors in the future. ASP.NET has a membership provider for instance.

No, a hashed password doesnt have to be stored in a varbinary field, you can encode it and store it in a varchar field. Base64 is a good alternative for encoding any kind of characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM