简体   繁体   中英

Inserting a byte array into SQL Server database table

I'm using the PBKDF2 hashing algorithm for passwords which produces a byte array from my user supplied password, like so:

var DeriveBytes = new Rfc2898DeriveBytes(_Password, 20);
byte[] _Salt = DeriveBytes.Salt;
byte[] _Key = DeriveBytes.GetBytes(20);  // derive a 20-byte key

I want to save these into my database, but I'm not sure what data type to use. From what I can see there's no data type used for byte arrays and I'm pretty sure I can't just convert it to a string and store it with varchar , or can I?

binary and varbinary are pretty much explicitly designed to store byte arrays.

MSDN link

You define the column in your SQL table as binary or varbinary , then add it to the parameter property of your ado command object using one of the overloads that require a SqlDbType parameter to communicate this is a binary value.

option 2:

You define the column in your SQL table as nvarchar(max) , convert your byte array to a base 64 string, ie System.Convert.ToBase64String(mybytes) . When it's time to retrieve it from the database,

mybytes = System.Convert.FromBase64String((byte[])dr[i]);

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