SQL Server 2016如何从命令行读取/写入始终加密的列?

时间:2017-05-24 15:34:19

标签: c# command-line sql-server-2016 always-encrypted

我能够读取和写入始终从C#ASP.NET应用程序加密的列。但是,我需要从sqlcmd做到这一点。

经过一些研究后我发现here,你需要-g参数来激活列加密设置,并更新到sqlcmd版本13.1,我做了并用“sqlcmd - ?”验证。

所以,我做了一个测试表:

create table tmp 
(
tmp_id int identity(1,1) not null,
test varchar(500)
COLLATE Latin1_General_BIN2
ENCRYPTED WITH 
   (ENCRYPTION_TYPE = RANDOMIZED, 
    ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', 
    COLUMN_ENCRYPTION_KEY = MY_Encryption_Key)  
null
);

并使用以下内容创建了一个test.sql:

insert into tmp (test) values ('mytest');

我这样称呼sqlcmd:

sqlcmd.exe -g -b -S "localhost\SQL2016" -d "my_db_name" -i "D:\test.sql" -U "my_username" -P "my_password"

但是我得到以下错误,无论我是否使用“-g”:

Operand type clash: varchar is incompatible with varchar(8000) encrypted with (encryption_type = 'RANDOMIZED', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'MY_Encryption_Key', column_encryption_key_database_name = 'my_db_name') collation_name = 'SQL_Latin1_General_CP1_CI_AS'

如果我将test.sql更改为:

declare @test varchar(8000) = 'mytest';
insert into tmp (test) values (@test);

然后我得到另一个错误(仍然有或没有-g):

Encryption scheme mismatch for columns/variables '@test'. The encryption scheme for the columns/variables is (encryption_type = 'PLAINTEXT') and the expression near line '2' expects it to be (encryption_type = 'RANDOMIZED', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'MY_Encryption_Key', column_encryption_key_database_name = 'my_db_name') (or weaker).

我需要这个,因为目前有一个C#app接受一个平面文件,然后通过调用“.sql”文件通过命令行加载到DB中。现在有些列需要加密。因此,我们需要sqlcmd来读取/写入加密列,以避免重写C#.NET中的所有逻辑。

我做错了吗?这甚至可能吗?为什么sqlcmd的“-g”参数没有区别?

2 个答案:

答案 0 :(得分:1)

目前,使用以下语法将数据插入到始终加密的列中仅在SSMS中支持

declare @test varchar(8000) = 'mytest';
insert into tmp (test) values (@test);

您可以找到有关此herehere

的详细信息

答案 1 :(得分:1)

创建表tmp tmp_id int identity(1,1)not null,

测试nvarchar(11)

COLLATE Latin1_General_BIN2 加密    (ENCRYPTION_TYPE = RANDOMIZED,     ALGORITHM ='AEAD_AES_256_CBC_HMAC_SHA_256',     COLUMN_ENCRYPTION_KEY = CEK_Auto1)
);

创建程序[dbo]。[Proc_Test]     @test nvarchar(11) AS

插入tmp(测试)值(@test);

以上代码在SSMS中为我工作。