简体   繁体   English

将字节数组插入SQL Server数据库表

[英]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: 我正在使用PBKDF2散列算法来生成密码,该算法从我的用户提供的密码生成一个字节数组,如下所示:

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? 从我所看到的,没有用于字节数组的数据类型,我很确定我不能只将它转换为字符串并用varchar存储它,或者我可以吗?

binary and varbinary are pretty much explicitly designed to store byte arrays. binaryvarbinary几乎被明确地设计用于存储字节数组。

MSDN link MSDN链接

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. 您可以将SQL表中的列定义为binaryvarbinary ,然后使用需要SqlDbType参数进行通信的重载之一将其添加到ado命令对象的parameter属性中,这是一个二进制值。

option 2: 选项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) . 您将SQL表中的列定义为nvarchar(max) ,将您的字节数组转换为基本64字符串,即System.Convert.ToBase64String(mybytes) When it's time to retrieve it from the database, 是时候从数据库中检索它了,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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