SQL Server 2016 How to read / write to an encrypted column from the command line?

I can read and write to a column that is always encrypted from a C # ASP.NET application. However, I need to do this from sqlcmd.

After some research I found here that you need the -g option to activate the column encryption setting and update sqlcmd version 13.1 which I did and validated with "sqlcmd -?".

So, I made a test table:

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
);

      

And did test.sql with the following:

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

      

I am calling sqlcmd like this:

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

      

But I am getting the following error whether I use -g or not:

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'

      

If I change test.sql to:

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

      

Then I get another error (still with or without -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).

      

I need this because there is currently a C # application that takes a flat file and then loads it into the DB via the command line, invoking the ".sql" files. Certain columns should now be encrypted. So we need sqlcmd to read / write encrypted columns to avoid rewriting all logic in C # .NET.

Am I doing something wrong? Is it possible? Why is the sqlcmd "-g" parameter irrelevant?

+3


source to share


2 answers


Currently, inserting data into an always encrypted column using the following syntax is only supported in SSMS .

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

      



Details on this here and here

+1


source


create table tmp

(

tmp_id int identity (1,1) is not null,

test nvarchar (11)

COLLATE Latin1_General_BIN2

ENCRYPTED WITH

 (ENCRYPTION_TYPE = RANDOMIZED,

  ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256',

  COLUMN_ENCRYPTION_KEY = CEK_Auto1)
zero

);



Create procedure [dbo]. [Proc_Test]

  @test nvarchar (11)

AS

insert into values ​​tmp (test) (@test);

the code above works for me in SSMS.

+1


source







All Articles