-
Notifications
You must be signed in to change notification settings - Fork 418
/
AESetup.java
2011 lines (1699 loc) · 76.3 KB
/
AESetup.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Microsoft JDBC Driver for SQL Server Copyright(c) Microsoft Corporation All rights reserved. This program is made
* available under the terms of the MIT License. See the LICENSE file in the project root for more AEInformation.
*/
package com.microsoft.sqlserver.jdbc.AlwaysEncrypted;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.JDBCType;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import java.util.logging.LogManager;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import com.microsoft.sqlserver.jdbc.RandomData;
import com.microsoft.sqlserver.jdbc.RandomUtil;
import com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionAzureKeyVaultProvider;
import com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionJavaKeyStoreProvider;
import com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionKeyStoreProvider;
import com.microsoft.sqlserver.jdbc.SQLServerConnection;
import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement;
import com.microsoft.sqlserver.jdbc.SQLServerStatement;
import com.microsoft.sqlserver.jdbc.SQLServerStatementColumnEncryptionSetting;
import com.microsoft.sqlserver.jdbc.TestResource;
import com.microsoft.sqlserver.jdbc.TestUtils;
import com.microsoft.sqlserver.testframework.AbstractSQLGenerator;
import com.microsoft.sqlserver.testframework.AbstractTest;
import com.microsoft.sqlserver.testframework.Constants;
import com.microsoft.sqlserver.testframework.PrepUtil;
import microsoft.sql.DateTimeOffset;
/**
* Setup for Always Encrypted test This test will work on Azure DevOps as java key store gets created from the .yml
* scripts. Users on their local machine should create the keystore manually and save the alias name in JavaKeyStore.txt
* file. For local test purposes, put this in the target/test-classes directory
*
*/
@RunWith(JUnitPlatform.class)
public class AESetup extends AbstractTest {
static String cmkJks = Constants.CMK_NAME + "_JKS";
static String cmkWin = Constants.CMK_NAME + "_WIN";
static String cmkAkv = Constants.CMK_NAME + "_AKV";
static String cekJks = Constants.CEK_NAME + "_JKS";
static String cekWin = Constants.CEK_NAME + "_WIN";
static String cekAkv = Constants.CEK_NAME + "_AKV";
static SQLServerStatementColumnEncryptionSetting stmtColEncSetting = null;
static String AETestConnectionString;
static String enclaveProperties = "";
static Properties AEInfo;
static Map<String, SQLServerColumnEncryptionKeyStoreProvider> map = new HashMap<String, SQLServerColumnEncryptionKeyStoreProvider>();
public static final String tableName = TestUtils
.escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("AETest_")));
public static final String CHAR_TABLE_AE = TestUtils
.escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("JDBCEncryptedChar")));
public static final String BINARY_TABLE_AE = TestUtils
.escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("JDBCEncryptedBinary")));
public static final String DATE_TABLE_AE = TestUtils
.escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("JDBCEncryptedDate")));
public static final String NUMERIC_TABLE_AE = TestUtils.escapeSingleQuotes(
AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("JDBCEncryptedNumeric")));
public static final String SCALE_DATE_TABLE_AE = TestUtils.escapeSingleQuotes(
AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("JDBCEncryptedScaleDate")));
final static char[] HEXCHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
enum ColumnType {
PLAIN,
RANDOMIZED,
DETERMINISTIC
}
/*
* tables used in the tests {columnName, columnType}
*/
static String binaryTable[][] = {{"Binary", "binary(20)", "BINARY"}, {"Varbinary", "varbinary(50)", "BINARY"},
{"VarbinaryMax", "varbinary(max)", "BINARY"}, {"Binary512", "binary(512)", "BINARY"},
{"Binary8000", "varbinary(8000)", "BINARY"}};
static String charTable[][] = {{"Char", "char(20) COLLATE Latin1_General_BIN2", "CHAR"},
{"Varchar", "varchar(50) COLLATE Latin1_General_BIN2", "CHAR"},
{"VarcharMax", "varchar(max) COLLATE Latin1_General_BIN2", "LONGVARCHAR"},
{"Nchar", "nchar(30) COLLATE Latin1_General_BIN2", "NCHAR"},
{"Nvarchar", "nvarchar(60) COLLATE Latin1_General_BIN2", "NCHAR"},
{"NvarcharMax", "nvarchar(max) COLLATE Latin1_General_BIN2", "LONGNVARCHAR"},
{"Uniqueidentifier", "uniqueidentifier", "GUID"},
{"Varchar8000", "varchar(8000) COLLATE Latin1_General_BIN2", "CHAR"},
{"Nvarchar4000", "nvarchar(4000) COLLATE Latin1_General_BIN2", "NCHAR"},};
static String dateTable[][] = {{"Date", "date", "DATE"}, {"Datetime2Default", "datetime2", "TIMESTAMP"},
{"DatetimeoffsetDefault", "datetimeoffset", "DATETIMEOFFSET"}, {"TimeDefault", "time", "TIME"},
{"Datetime", "datetime", "DATETIME"}, {"Smalldatetime", "smalldatetime", "SMALLDATETIME"}};
static String dateScaleTable[][] = {{"Datetime2", "datetime2(2)", "DATE"}, {"Time", "time(2)", "DATE"},
{"Datetimeoffset", "datetimeoffset(2)", "DATE"}};
static String numericTable[][] = {{"Bit", "bit", "BIT"}, {"Tinyint", "tinyint", "TINYINT"},
{"Smallint", "smallint", "SMALLINT"}, {"Int", "int", "INTEGER"}, {"Bigint", "bigint", "BIGINT"},
{"FloatDefault", "float", "DOUBLE"}, {"Float", "float(30)", "DOUBLE"}, {"Real", "real", "FLOAT"},
{"DecimalDefault", "decimal", "DECIMAL"}, {"Decimal", "decimal(10,5)", "DECIMAL"},
{"NumericDefault", "numeric", "DECIMAL"}, {"Numeric", "numeric(8,2)", "DECIMAL"},
{"SmallMoney", "smallmoney", "SMALLMONEY"}, {"Money", "money", "MONEY"},
{"Decimal2", "decimal(28,4)", "DECIMAL"}, {"Numeric2", "numeric(28,4)", "DECIMAL"},};
static String numericTableSimple[][] = {{"Int", "int", "INT"}};
static String varcharTableSimple[][] = {{"Varchar", "varchar(20) COLLATE LATIN1_GENERAL_BIN2", "VARCHAR"}};
// CREATE TABLE tableName (columns) NULL"
static String createSql = "CREATE TABLE %s (%s)";
// ENCRYPTED WITH (ENCRYPTION_TYPE = encryptionType, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256',
// COLUMN_ENCRYPTION_KEY = cekName
static String encryptSql = " ENCRYPTED WITH (ENCRYPTION_TYPE = %s, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = %s";
/*
* List of all the randomized columns in the tests
*/
static String[] randomizedColumns = {"PlainBinary binary(20)", "PlainVarbinary varbinary(50)",
"PlainVarbinaryMax varbinary(max)", "PlainBinary512 binary(512)", "PlainBinary8000 varbinary(8000)",
"PlainChar char(20)", "PlainVarchar varchar(50)", "PlainVarcharMax varchar(max)", "PlainNchar nchar(30)",
"PlainNvarchar nvarchar(60)", "PlainNvarcharMax nvarchar(max)", "PlainUniqueidentifier uniqueidentifier",
"PlainVarchar8000 varchar(8000)", "PlainNvarchar4000 nvarchar(4000)", "PlainDate date",
"PlainDatetime2Default datetime2", "PlainDatetimeoffsetDefault datetimeoffset", "PlainTimeDefault time",
"PlainDatetime datetime", "PlainSmalldatetime smalldatetime", "PlainDatetime2 datetime2(0)",
"PlainDatetime2Default datetime2", "PlainDatetimeoffsetDefault datetimeoffset", "PlainTimeDefault time",
"PlainTime time(0)", "PlainDatetimeoffset datetimeoffset(0)", "PlainDatetime2 datetime2(2)",
"PlainTime time(2)", "PlainDatetimeoffset datetimeoffset(2)", "PlainBit bit", "PlainTinyint tinyint",
"PlainSmallint smallint", "PlainInt int", "PlainBigint bigint", "PlainFloatDefault float",
"PlainFloat float(30)", "PlainReal real", "PlainDecimalDefault decimal", "PlainDecimal decimal(10,5)",
"PlainNumericDefault numeric", "PlainNumeric numeric(8,2)", "PlainSmallMoney smallmoney",
"PlainMoney money", "PlainDecimal2 decimal(28,4)", "PlainNumeric2 numeric(28,4)", "PlainFloat float(30)",
"PlainDecimal decimal(30)", "PlainNumeric numeric(30)"};
// junit test parameters: serverName, enclaveAttestationUrl, enclaveAttestationProtocol
static String[][] param = new String[(null == AbstractTest.enclaveServer ? 0
: AbstractTest.enclaveServer.length)][3];
/**
* This provides the arguments (serverName, enclaveAttestationUrl, enclaveAttestationProtocol) for the parameterized
* tests using MethodSource parameters
*
* @return parameters for the tests
* @throws Exception
*/
static String[][] enclaveParams() throws Exception {
return param;
}
/**
* Get the AE connection string
*
* @param serverName
* @param url
* @param protocol
*/
static void setAEConnectionString(String serverName, String url, String protocol) {
// AEv2 is not supported on Linux servers
if (!isSqlLinux() && null != serverName && null != url && null != protocol) {
enclaveProperties = "serverName=" + serverName + ";" + Constants.ENCLAVE_ATTESTATIONURL + "=" + url + ";"
+ Constants.ENCLAVE_ATTESTATIONPROTOCOL + "=" + protocol;
AETestConnectionString = connectionString + ";sendTimeAsDateTime=false;columnEncryptionSetting=enabled;"
+ enclaveProperties;
// show progress if testing multiple servers
if (enclaveServer.length > 1) {
System.out.println("Testing enclave: " + enclaveProperties);
}
// remove the password in connection string
// this is necessary as updateDataSource will only use 1st occurrence
String password = getConfiguredProperty("enclaveServerPassword");
AETestConnectionString = TestUtils.removeProperty(AETestConnectionString, Constants.PASSWORD);
AETestConnectionString = TestUtils.addOrOverrideProperty(AETestConnectionString, Constants.PASSWORD,
password);
} else {
AETestConnectionString = connectionString + ";sendTimeAsDateTime=false;columnEncryptionSetting=enabled;";
}
// TODO: update AE test servers to support
AETestConnectionString += ";encrypt=false;trustServerCertificate=true;";
}
@BeforeAll
public static void setupAETest() throws Exception {
setConnection();
readFromFile(Constants.JAVA_KEY_STORE_FILENAME, "Alias name");
stmtColEncSetting = SQLServerStatementColumnEncryptionSetting.ENABLED;
AEInfo = new Properties();
AEInfo.setProperty("ColumnEncryptionSetting", Constants.ENABLED);
AEInfo.setProperty("keyStoreAuthentication", Constants.JAVA_KEY_STORE_SECRET);
AEInfo.setProperty("keyStoreLocation", javaKeyPath);
AEInfo.setProperty("keyStoreSecret", Constants.JKS_SECRET);
// reset logging to avoid severe logs due to negative testing
LogManager.getLogManager().reset();
// setup test params and encryption keys on each server
for (int i = 0; i < enclaveServer.length; i++) {
String serverName = enclaveServer[i];
String url = null != enclaveAttestationUrl ? enclaveAttestationUrl[i] : null;
String protocol = null != enclaveAttestationProtocol ? enclaveAttestationProtocol[i] : null;
param[i][0] = serverName;
param[i][1] = url;
param[i][2] = protocol;
setAEConnectionString(serverName, url, protocol);
createCMK(AETestConnectionString, cmkJks, Constants.JAVA_KEY_STORE_NAME, javaKeyAliases,
TestUtils.byteToHexDisplayString(jksProvider.signColumnMasterKeyMetadata(javaKeyAliases, true)));
createCEK(AETestConnectionString, cmkJks, cekJks, jksProvider);
if (null != keyIDs && !keyIDs[0].isEmpty()) {
createCMK(AETestConnectionString, cmkAkv, Constants.AZURE_KEY_VAULT_NAME, keyIDs[0],
TestUtils.byteToHexDisplayString(akvProvider.signColumnMasterKeyMetadata(keyIDs[0], true)));
createCEK(AETestConnectionString, cmkAkv, cekAkv, akvProvider);
}
if (null != windowsKeyPath) {
createCMK(AETestConnectionString, cmkWin, Constants.WINDOWS_KEY_STORE_NAME, windowsKeyPath,
Constants.CMK_SIGNATURE_WIN);
createCEK(AETestConnectionString, cmkWin, cekWin, null);
}
}
}
/**
* Dropping all CMKs and CEKs and any open resources. Technically, dropAll depends on the state of the class so it
* shouldn't be static, but the AfterAll annotation requires it to be static.
*
* @throws SQLException
*/
public static void dropAll() throws Exception {
try (Statement stmt = connection.createStatement()) {
dropTables(stmt);
dropCEK(cekJks, stmt);
dropCMK(cmkJks, stmt);
if (null != cekWin) {
dropCEK(cekWin, stmt);
dropCMK(cmkWin, stmt);
}
if (null != cekAkv) {
dropCEK(cekAkv, stmt);
dropCMK(cmkAkv, stmt);
}
}
}
/**
* Dropping all CMKs and CEKs and any open resources. Technically, dropAll depends on the state of the class so it
* shouldn't be static, but the AfterAll annotation requires it to be static.
*
* @throws SQLException
*/
@AfterAll
public static void cleanUp() throws Exception {
dropAll();
if (null != connection) {
connection.close();
}
}
/**
* Read the alias from file which is created during creating jks If the jks and alias name in JavaKeyStore.txt does
* not exists, will not run!
*
* @param inputFile
* @param lookupValue
* @throws IOException
*/
private static void readFromFile(String inputFile, String lookupValue) throws IOException {
String filePath = TestUtils.getCurrentClassPath();
try {
File f = new File(filePath + inputFile);
try (BufferedReader buffer = new BufferedReader(new FileReader(f))) {
String readLine = "";
String[] linecontents;
while ((readLine = buffer.readLine()) != null) {
if (readLine.trim().contains(lookupValue)) {
linecontents = readLine.split(" ");
javaKeyAliases = linecontents[2];
break;
}
}
}
} catch (IOException e) {
fail(e.getMessage());
}
}
/**
* Create AE test tables
*
* @param tableName
* name of test table
* @param table
* 2d array containing table column definitions
* @throws SQLException
*/
protected static void createTable(String tableName, String cekName, String table[][]) throws SQLException {
try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo);
SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) {
String sql = "";
for (int i = 0; i < table.length; i++) {
sql += ColumnType.PLAIN.name() + table[i][0] + " " + table[i][1] + " NULL,";
sql += ColumnType.DETERMINISTIC.name() + table[i][0] + " " + table[i][1]
+ String.format(encryptSql, ColumnType.DETERMINISTIC.name(), cekName) + ") NULL,";
sql += ColumnType.RANDOMIZED.name() + table[i][0] + " " + table[i][1]
+ String.format(encryptSql, ColumnType.RANDOMIZED.name(), cekName) + ") NULL,";
}
TestUtils.dropTableIfExists(tableName, stmt);
sql = String.format(createSql, tableName, sql);
stmt.execute(sql);
stmt.execute("DBCC FREEPROCCACHE");
} catch (SQLException e) {
fail(e.getMessage());
}
}
protected static void createPrecisionTable(String tableName, String table[][], String cekName, int floatPrecision,
int precision, int scale) throws SQLException {
try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo);
SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) {
String sql = "";
for (int i = 0; i < table.length; i++) {
if ("float" == table[i][1]) {
sql += ColumnType.PLAIN.name() + table[i][0] + "Precision " + table[i][1] + "(" + floatPrecision
+ ") NULL,";
sql += ColumnType.RANDOMIZED.name() + table[i][0] + "Precision " + table[i][1] + "("
+ floatPrecision + ") " + String.format(encryptSql, ColumnType.RANDOMIZED.name(), cekName)
+ ") NULL,";
sql += ColumnType.DETERMINISTIC.name() + table[i][0] + "Precision " + table[i][1] + "("
+ floatPrecision + ") "
+ String.format(encryptSql, ColumnType.DETERMINISTIC.name(), cekName) + ") NULL,";
} else {
sql += ColumnType.PLAIN.name() + table[i][0] + "Precision " + table[i][1] + "(" + precision + ","
+ scale + ") NULL,";
sql += ColumnType.RANDOMIZED.name() + table[i][0] + "Precision " + table[i][1] + "(" + precision
+ "," + scale + ") " + String.format(encryptSql, ColumnType.RANDOMIZED.name(), cekName)
+ ") NULL,";
sql += ColumnType.DETERMINISTIC.name() + table[i][0] + "Precision " + table[i][1] + "(" + precision
+ "," + scale + ") " + String.format(encryptSql, ColumnType.DETERMINISTIC.name(), cekName)
+ ") NULL,";
}
}
sql = String.format(createSql, tableName, sql);
stmt.execute(sql);
stmt.execute("DBCC FREEPROCCACHE");
} catch (SQLException e) {
fail(e.getMessage());
}
}
protected static void createScaleTable(String tableName, String table[][], String cekName,
int scale) throws SQLException {
try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo);
SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) {
String sql = "";
for (int i = 0; i < table.length; i++) {
sql += ColumnType.PLAIN.name() + table[i][0] + "Scale " + table[i][1] + "(" + scale + ") NULL,";
sql += ColumnType.RANDOMIZED.name() + table[i][0] + "Scale " + table[i][1] + "(" + scale + ") "
+ String.format(encryptSql, ColumnType.RANDOMIZED.name(), cekName) + ") NULL,";
sql += ColumnType.DETERMINISTIC.name() + table[i][0] + "Scale " + table[i][1] + "(" + scale + ") "
+ String.format(encryptSql, ColumnType.DETERMINISTIC.name(), cekName) + ") NULL,";
sql += ColumnType.PLAIN.name() + table[i][0] + " " + table[i][1] + " NULL,";
sql += ColumnType.RANDOMIZED.name() + table[i][0] + " " + table[i][1]
+ String.format(encryptSql, ColumnType.RANDOMIZED.name(), cekName) + ") NULL,";
sql += ColumnType.DETERMINISTIC.name() + table[i][0] + " " + table[i][1]
+ String.format(encryptSql, ColumnType.DETERMINISTIC.name(), cekName) + ") NULL,";
}
sql = String.format(createSql, tableName, sql);
stmt.execute(sql);
stmt.execute("DBCC FREEPROCCACHE");
} catch (SQLException e) {
fail(e.getMessage());
}
}
/**
* Create a list of binary values
*
* @param nullable
*/
protected static LinkedList<byte[]> createBinaryValues(boolean nullable) {
boolean encrypted = true;
RandomData.returnNull = nullable;
byte[] binary20 = RandomData.generateBinaryTypes("20", nullable, encrypted);
byte[] varbinary50 = RandomData.generateBinaryTypes("50", nullable, encrypted);
byte[] varbinarymax = RandomData.generateBinaryTypes("max", nullable, encrypted);
byte[] binary512 = RandomData.generateBinaryTypes("512", nullable, encrypted);
byte[] varbinary8000 = RandomData.generateBinaryTypes("8000", nullable, encrypted);
LinkedList<byte[]> list = new LinkedList<>();
list.add(binary20);
list.add(varbinary50);
list.add(varbinarymax);
list.add(binary512);
list.add(varbinary8000);
return list;
}
/**
* Create a list of char values
*
* @param nullable
*/
protected static String[] createCharValues(boolean nullable) {
boolean encrypted = true;
String char20 = RandomData.generateCharTypes("20", nullable, encrypted);
String varchar50 = RandomData.generateCharTypes("50", nullable, encrypted);
String varcharmax = RandomData.generateCharTypes("max", nullable, encrypted);
String nchar30 = RandomData.generateNCharTypes("30", nullable, encrypted);
String nvarchar60 = RandomData.generateNCharTypes("60", nullable, encrypted);
String nvarcharmax = RandomData.generateNCharTypes("max", nullable, encrypted);
String varchar8000 = RandomData.generateCharTypes("8000", nullable, encrypted);
String nvarchar4000 = RandomData.generateNCharTypes("4000", nullable, encrypted);
String[] values = {char20.trim(), varchar50, varcharmax, nchar30, nvarchar60, nvarcharmax, Constants.UID,
varchar8000, nvarchar4000};
return values;
}
/**
* Create a list of numeric values
*
* @param nullable
*/
protected static String[] createNumericValues(boolean nullable) {
Boolean boolValue = RandomData.generateBoolean(nullable);
Short tinyIntValue = RandomData.generateTinyint(nullable);
Short smallIntValue = RandomData.generateSmallint(nullable);
Integer intValue = RandomData.generateInt(nullable);
Long bigintValue = RandomData.generateLong(nullable);
Double floatValue = RandomData.generateFloat(24, nullable);
Double floatValuewithPrecision = RandomData.generateFloat(53, nullable);
Float realValue = RandomData.generateReal(nullable);
BigDecimal decimal = RandomData.generateDecimalNumeric(18, 0, nullable);
BigDecimal decimalPrecisionScale = RandomData.generateDecimalNumeric(10, 5, nullable);
BigDecimal numeric = RandomData.generateDecimalNumeric(18, 0, nullable);
BigDecimal numericPrecisionScale = RandomData.generateDecimalNumeric(8, 2, nullable);
BigDecimal smallMoney = RandomData.generateSmallMoney(nullable);
BigDecimal money = RandomData.generateMoney(nullable);
BigDecimal decimalPrecisionScale2 = RandomData.generateDecimalNumeric(28, 4, nullable);
BigDecimal numericPrecisionScale2 = RandomData.generateDecimalNumeric(28, 4, nullable);
String[] numericValues = {"" + boolValue, "" + tinyIntValue, "" + smallIntValue, "" + intValue,
"" + bigintValue, "" + floatValue, "" + floatValuewithPrecision, "" + realValue, "" + decimal,
"" + decimalPrecisionScale, "" + numeric, "" + numericPrecisionScale, "" + smallMoney, "" + money,
"" + decimalPrecisionScale2, "" + numericPrecisionScale2};
return numericValues;
}
/**
* Create a list of temporal values
*
* @param nullable
*/
protected static LinkedList<Object> createTemporalTypes(boolean nullable) {
Date date = RandomData.generateDate(nullable);
Timestamp datetime2 = RandomData.generateDatetime2(7, nullable);
DateTimeOffset datetimeoffset = RandomData.generateDatetimeoffset(7, nullable);
Time time = RandomData.generateTime(7, nullable);
Timestamp datetime = RandomData.generateDatetime(nullable);
Timestamp smalldatetime = RandomData.generateSmalldatetime(nullable);
LinkedList<Object> list = new LinkedList<>();
list.add(date);
list.add(datetime2);
list.add(datetimeoffset);
list.add(time);
list.add(datetime);
list.add(smalldatetime);
return list;
}
/**
* Create column master key
*
* @param keyStoreName
* @param keyPath
* @throws SQLException
*/
protected static void createCMK(String connectionString, String cmkName, String keyStoreName, String keyPath,
String signature) throws SQLException {
try (SQLServerConnection con = (SQLServerConnection) PrepUtil
.getConnection(connectionString + ";sendTimeAsDateTime=false", AEInfo);
SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) {
String sql = " if not exists (SELECT name from sys.column_master_keys where name='" + cmkName + "')"
+ " begin" + " CREATE COLUMN MASTER KEY " + cmkName + " WITH (KEY_STORE_PROVIDER_NAME = '"
+ keyStoreName + "', KEY_PATH = '" + keyPath + "'"
+ (TestUtils.isAEv2(con) ? ",ENCLAVE_COMPUTATIONS (SIGNATURE = " + signature + ")) end" : ") end");
stmt.execute(sql);
}
}
/**
* Create column encryption key
*
* @param storeProvider
* @param certStore
* @throws SQLException
*/
protected static void createCEK(String connectionString, String cmkName, String cekName,
SQLServerColumnEncryptionKeyStoreProvider storeProvider) throws SQLException {
try (SQLServerConnection con = (SQLServerConnection) PrepUtil
.getConnection(connectionString + ";sendTimeAsDateTime=false", AEInfo);
SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) {
byte[] valuesDefault = Constants.CEK_STRING.getBytes();
String encryptedValue;
if (storeProvider instanceof SQLServerColumnEncryptionJavaKeyStoreProvider) {
byte[] key = storeProvider.encryptColumnEncryptionKey(javaKeyAliases, Constants.CEK_ALGORITHM,
valuesDefault);
encryptedValue = "0x" + TestUtils.bytesToHexString(key, key.length);
} else if (storeProvider instanceof SQLServerColumnEncryptionAzureKeyVaultProvider) {
byte[] key = storeProvider.encryptColumnEncryptionKey(keyIDs[0], Constants.CEK_ALGORITHM,
valuesDefault);
encryptedValue = "0x" + TestUtils.bytesToHexString(key, key.length);
} else {
encryptedValue = Constants.CEK_ENCRYPTED_VALUE;
}
String sql = "if not exists (SELECT name from sys.column_encryption_keys where name='" + cekName + "')"
+ " begin" + " CREATE COLUMN ENCRYPTION KEY " + cekName + " WITH VALUES " + "(COLUMN_MASTER_KEY = "
+ cmkName + ", ALGORITHM = '" + Constants.CEK_ALGORITHM + "', ENCRYPTED_VALUE = " + encryptedValue
+ ") end;";
stmt.execute(sql);
}
}
/**
* Drop all tables that are in use by AE
*
* @throws SQLException
*/
protected static void dropTables(Statement stmt) throws SQLException {
TestUtils.dropTableIfExists(NUMERIC_TABLE_AE, stmt);
TestUtils.dropTableIfExists(CHAR_TABLE_AE, stmt);
TestUtils.dropTableIfExists(BINARY_TABLE_AE, stmt);
TestUtils.dropTableIfExists(DATE_TABLE_AE, stmt);
}
/**
* Populate binary data.
*
* @param byteValues
* @throws SQLException
*/
protected static void populateBinaryNormalCase(LinkedList<byte[]> byteValues) throws SQLException {
String sql = "insert into " + BINARY_TABLE_AE + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?,"
+ "?,?,?" + ")";
try (SQLServerConnection con = (SQLServerConnection) PrepUtil
.getConnection(AETestConnectionString + ";sendTimeAsDateTime=false", AEInfo);
SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql,
stmtColEncSetting)) {
// binary20
for (int i = 1; i <= 3; i++) {
if (null == byteValues) {
pstmt.setBytes(i, null);
} else {
pstmt.setBytes(i, byteValues.get(0));
}
}
// varbinary50
for (int i = 4; i <= 6; i++) {
if (null == byteValues) {
pstmt.setBytes(i, null);
} else {
pstmt.setBytes(i, byteValues.get(1));
}
}
// varbinary(max)
for (int i = 7; i <= 9; i++) {
if (null == byteValues) {
pstmt.setBytes(i, null);
} else {
pstmt.setBytes(i, byteValues.get(2));
}
}
// binary(512)
for (int i = 10; i <= 12; i++) {
if (null == byteValues) {
pstmt.setBytes(i, null);
} else {
pstmt.setBytes(i, byteValues.get(3));
}
}
// varbinary(8000)
for (int i = 13; i <= 15; i++) {
if (null == byteValues) {
pstmt.setBytes(i, null);
} else {
pstmt.setBytes(i, byteValues.get(4));
}
}
pstmt.execute();
}
}
/**
* Populate binary data using set object.
*
* @param byteValues
* @throws SQLException
*/
protected static void populateBinarySetObject(LinkedList<byte[]> byteValues) throws SQLException {
String sql = "insert into " + BINARY_TABLE_AE + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?,"
+ "?,?,?" + ")";
try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo);
SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql,
stmtColEncSetting)) {
// binary(20)
for (int i = 1; i <= 3; i++) {
if (null == byteValues) {
pstmt.setObject(i, null, java.sql.Types.BINARY);
} else {
pstmt.setObject(i, byteValues.get(0));
}
}
// varbinary(50)
for (int i = 4; i <= 6; i++) {
if (null == byteValues) {
pstmt.setObject(i, null, java.sql.Types.BINARY);
} else {
pstmt.setObject(i, byteValues.get(1));
}
}
// varbinary(max)
for (int i = 7; i <= 9; i++) {
if (null == byteValues) {
pstmt.setObject(i, null, java.sql.Types.BINARY);
} else {
pstmt.setObject(i, byteValues.get(2));
}
}
// binary(512)
for (int i = 10; i <= 12; i++) {
if (null == byteValues) {
pstmt.setObject(i, null, java.sql.Types.BINARY);
} else {
pstmt.setObject(i, byteValues.get(3));
}
}
// varbinary(8000)
for (int i = 13; i <= 15; i++) {
if (null == byteValues) {
pstmt.setObject(i, null, java.sql.Types.BINARY);
} else {
pstmt.setObject(i, byteValues.get(4));
}
}
pstmt.execute();
}
}
/**
* Populate binary data using set object with JDBC type.
*
* @param byteValues
* @throws SQLException
*/
protected static void populateBinarySetObjectWithJDBCType(LinkedList<byte[]> byteValues) throws SQLException {
String sql = "insert into " + BINARY_TABLE_AE + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?,"
+ "?,?,?" + ")";
try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo);
SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql,
stmtColEncSetting)) {
// binary(20)
for (int i = 1; i <= 3; i++) {
if (null == byteValues) {
pstmt.setObject(i, null, JDBCType.BINARY);
} else {
pstmt.setObject(i, byteValues.get(0), JDBCType.BINARY);
}
}
// varbinary(50)
for (int i = 4; i <= 6; i++) {
if (null == byteValues) {
pstmt.setObject(i, null, JDBCType.VARBINARY);
} else {
pstmt.setObject(i, byteValues.get(1), JDBCType.VARBINARY);
}
}
// varbinary(max)
for (int i = 7; i <= 9; i++) {
if (null == byteValues) {
pstmt.setObject(i, null, JDBCType.VARBINARY);
} else {
pstmt.setObject(i, byteValues.get(2), JDBCType.VARBINARY);
}
}
// binary(512)
for (int i = 10; i <= 12; i++) {
if (null == byteValues) {
pstmt.setObject(i, null, JDBCType.BINARY);
} else {
pstmt.setObject(i, byteValues.get(3), JDBCType.BINARY);
}
}
// varbinary(8000)
for (int i = 13; i <= 15; i++) {
if (null == byteValues) {
pstmt.setObject(i, null, JDBCType.VARBINARY);
} else {
pstmt.setObject(i, byteValues.get(4), JDBCType.VARBINARY);
}
}
pstmt.execute();
}
}
/**
* Populate binary data using set null.
*
* @throws SQLException
*/
protected static void populateBinaryNullCase() throws SQLException {
String sql = "insert into " + BINARY_TABLE_AE + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?,"
+ "?,?,?" + ")";
try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo);
SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql,
stmtColEncSetting)) {
// binary
for (int i = 1; i <= 3; i++) {
pstmt.setNull(i, java.sql.Types.BINARY);
}
// varbinary, varbinary(max)
for (int i = 4; i <= 9; i++) {
pstmt.setNull(i, java.sql.Types.VARBINARY);
}
// binary512
for (int i = 10; i <= 12; i++) {
pstmt.setNull(i, java.sql.Types.BINARY);
}
// varbinary(8000)
for (int i = 13; i <= 15; i++) {
pstmt.setNull(i, java.sql.Types.VARBINARY);
}
pstmt.execute();
}
}
/**
* Populate char data.
*
* @param charValues
* @throws SQLException
*/
protected static void populateCharNormalCase(String[] charValues) throws SQLException {
String sql = "insert into " + CHAR_TABLE_AE + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?,"
+ "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")";
try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo);
SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql,
stmtColEncSetting)) {
// char
for (int i = 1; i <= 3; i++) {
pstmt.setString(i, charValues[0]);
}
// varchar
for (int i = 4; i <= 6; i++) {
pstmt.setString(i, charValues[1]);
}
// varchar(max)
for (int i = 7; i <= 9; i++) {
pstmt.setString(i, charValues[2]);
}
// nchar
for (int i = 10; i <= 12; i++) {
pstmt.setNString(i, charValues[3]);
}
// nvarchar
for (int i = 13; i <= 15; i++) {
pstmt.setNString(i, charValues[4]);
}
// varchar(max)
for (int i = 16; i <= 18; i++) {
pstmt.setNString(i, charValues[5]);
}
// uniqueidentifier
for (int i = 19; i <= 21; i++) {
if (null == charValues[6]) {
pstmt.setUniqueIdentifier(i, null);
} else {
pstmt.setUniqueIdentifier(i, Constants.UID);
}
}
// varchar8000
for (int i = 22; i <= 24; i++) {
pstmt.setString(i, charValues[7]);
}
// nvarchar4000
for (int i = 25; i <= 27; i++) {
pstmt.setNString(i, charValues[8]);
}
pstmt.execute();
}
}
/**
* Populate char data using set object.
*
* @param charValues
* @throws SQLException
*/
protected static void populateCharSetObject(String[] charValues) throws SQLException {
String sql = "insert into " + CHAR_TABLE_AE + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?,"
+ "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")";
try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo);
SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql,
stmtColEncSetting)) {
// char
for (int i = 1; i <= 3; i++) {
pstmt.setObject(i, charValues[0]);
}
// varchar
for (int i = 4; i <= 6; i++) {
pstmt.setObject(i, charValues[1]);
}
// varchar(max)
for (int i = 7; i <= 9; i++) {
pstmt.setObject(i, charValues[2], java.sql.Types.LONGVARCHAR);
}
// nchar
for (int i = 10; i <= 12; i++) {
pstmt.setObject(i, charValues[3], java.sql.Types.NCHAR);
}
// nvarchar
for (int i = 13; i <= 15; i++) {
pstmt.setObject(i, charValues[4], java.sql.Types.NCHAR);
}
// nvarchar(max)
for (int i = 16; i <= 18; i++) {
pstmt.setObject(i, charValues[5], java.sql.Types.LONGNVARCHAR);
}
// uniqueidentifier
for (int i = 19; i <= 21; i++) {
pstmt.setObject(i, charValues[6], microsoft.sql.Types.GUID);
}
// varchar8000
for (int i = 22; i <= 24; i++) {
pstmt.setObject(i, charValues[7]);
}
// nvarchar4000
for (int i = 25; i <= 27; i++) {
pstmt.setObject(i, charValues[8], java.sql.Types.NCHAR);
}
pstmt.execute();
}
}
/**
* Populate char data using set object with JDBC types.
*
* @param charValues
* @throws SQLException
*/
protected static void populateCharSetObjectWithJDBCTypes(String[] charValues) throws SQLException {
String sql = "insert into " + CHAR_TABLE_AE + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?,"
+ "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")";
try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo);
SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql,
stmtColEncSetting)) {
// char
for (int i = 1; i <= 3; i++) {
pstmt.setObject(i, charValues[0], JDBCType.CHAR);
}
// varchar
for (int i = 4; i <= 6; i++) {
pstmt.setObject(i, charValues[1], JDBCType.VARCHAR);
}
// varchar(max)
for (int i = 7; i <= 9; i++) {
pstmt.setObject(i, charValues[2], JDBCType.LONGVARCHAR);
}
// nchar
for (int i = 10; i <= 12; i++) {
pstmt.setObject(i, charValues[3], JDBCType.NCHAR);
}
// nvarchar
for (int i = 13; i <= 15; i++) {
pstmt.setObject(i, charValues[4], JDBCType.NVARCHAR);
}
// nvarchar(max)
for (int i = 16; i <= 18; i++) {
pstmt.setObject(i, charValues[5], JDBCType.LONGNVARCHAR);
}
// uniqueidentifier
for (int i = 19; i <= 21; i++) {
pstmt.setObject(i, charValues[6], microsoft.sql.Types.GUID);
}
// varchar8000
for (int i = 22; i <= 24; i++) {
pstmt.setObject(i, charValues[7], JDBCType.VARCHAR);
}
// vnarchar4000
for (int i = 25; i <= 27; i++) {
pstmt.setObject(i, charValues[8], JDBCType.NVARCHAR);
}
pstmt.execute();
}
}