File: EncryptionKeyTest.java

package info (click to toggle)
derby 10.14.2.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 79,056 kB
  • sloc: java: 691,961; sql: 42,686; xml: 20,512; sh: 3,373; sed: 96; makefile: 60
file content (661 lines) | stat: -rw-r--r-- 26,162 bytes parent folder | download | duplicates (4)
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
/*
 *
 * Derby - Class org.apache.derbyTesting.functionTests.tests.store.EncryptionKeyTest
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */
package org.apache.derbyTesting.functionTests.tests.store;

import java.io.File;

import java.sql.Connection;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.SQLWarning;

import javax.sql.DataSource;

import org.apache.derbyTesting.functionTests.util.PrivilegedFileOpsForTests;

import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.JDBCDataSource;
import org.apache.derbyTesting.junit.SupportFilesSetup;

/**
 * Tests various connection sequences to encrypted databases.
 * Four kinds of external keys are used:
 *  <ol><li>the correct key
 *      <li>an incorrect key
 *      <li>a key with odd length (in hex representation)
 *      <li>a key containing invalid characters
 *  </ol>
 * <p>
 * The algorithms used for en-/decryption is determined by the subclasses,
 * where a single algorithm and a set of keys are associated with each
 * subclass.
 * <p>
 * Databases are created in the <tt>EXTINOUT</tt> directory. Backups are made
 * to <tt>EXTINOUT/backups</tt> and restored databases are put into
 * <tt>EXTINOUT/restored</tt> <b>if and only if</b> the databases need to be
 * both written and read. Otherwise backups are placed in <tt>EXTOUT</tt>.
 * Testsuites generated from this class must be wrapped in a
 * <code>SupportFileSetup</code> decorator.
 */
 //@NotThreadSafe
public abstract class EncryptionKeyTest
    extends BaseJDBCTestCase {

    /** Correct key constant. */
    protected static final int CORRECT_KEY = 0;
    /** Wrong key constant. */
    protected static final int WRONG_KEY = 1;
    /** Odd length key constant. */
    protected static final int ODD_LENGTH_KEY = 2;
    /** Invalid char key constant. */
    protected static final int INVALID_CHAR_KEY = 3;

    /** Table holding the test data. */
    private static final String TABLE = "encryptionkeytestdata";
    /** Test data inserted into database and used for verification. */
    private static final int[] DATA = {9,4,2,34,6543,3,123,434,5436,-123,0,123};

    /** The algorithm used by the fixture. */
    private final String algorithm;

    /** The correct key. */
    private final String keyCorrect;
    /** An incorrect key. */
    private final String keyWrong;
    /** A key with odd length. */
    private final String keyOddLength;
    /** A key with an invalid char in it. */
    private final String keyInvalidChar;

    /**
     * Variable to hold the various connections.
     * No guarantee is made about the state of this connection, but it is
     * closed at tear-down.
     */
    private Connection con = null;

    /**
     * Configures a new setup by specifying the encryption properties.
     *
     * @param name name of the fixture
     * @param algorithm encryption algorithm to use
     * @param correctKey the correct encryption key
     * @param wrongKey an incorrect encryption key
     * @param oddLengthKey a key of odd length
     * @param invalidCharKey a key with invalid characters
     */
    public EncryptionKeyTest(String name,
                             String algorithm,
                             String correctKey,
                             String wrongKey,
                             String oddLengthKey,
                             String invalidCharKey) {
        super(name);
        this.algorithm = algorithm;
        this.keyCorrect = correctKey;
        this.keyWrong = wrongKey;
        this.keyOddLength = oddLengthKey;
        this.keyInvalidChar = invalidCharKey;
    }

    /**
     * Clean up the connection maintained by this test.
     */
    protected void tearDown()
            throws java.lang.Exception {
        if (con != null && !con.isClosed()) {
            con.rollback();
            con.close();
        }
        con = null;
        super.tearDown();
    }

    /**
     * Test a sequence of connections and connection attempts.
     * Sequence: Create database, connect to database using correct key,
     * try to connect using incorrect key, connect using correct key.
     */
    public void testConnectionSequence1()
            throws SQLException {
        String dbName = "encryptedDB_ConnectionSequence1";
        // Create database.
        con = createAndPopulateDB(dbName);
        validateDBContents(con);
        // Shutdown the database.
        con.close();
        shutdown(dbName);
        // Connect using correct key.
        con = getConnection(dbName, CORRECT_KEY);
        validateDBContents(con);
        con.close();
        // Shutdown the database.
        shutdown(dbName);
        // Try to connect using wrong key.
        try {
            getConnection(dbName, WRONG_KEY);
            fail("Booting with an incorrect encryption key should fail.");
        } catch (SQLException sqle) {
            assertSQLState("XJ040", sqle);
            assertSQLState("XBCXK", getLastSQLException(sqle));
        }
        // Connect using correct key.
        con = getConnection(dbName, CORRECT_KEY);
        validateDBContents(con);
        con.close();
        // Shutdown the database.
        shutdown(dbName);
    }

    /**
     * Test a sequence of connections and connection attempts.
     * Sequence: Create database, connect to database using odd length key,
     * try to connect using incorrect key, connect using correct key.
     */
    public void testConnectionSequence2()
            throws SQLException {
        String dbName = "encryptedDB_ConnectionSequence2";
        // Create database.
        con = createAndPopulateDB(dbName);
        validateDBContents(con);
        // Shutdown the database.
        con.close();
        shutdown(dbName);
        // Connect using odd length key.
        try {
            con = getConnection(dbName, ODD_LENGTH_KEY);
            fail("Connected with an odd length key.");
        } catch (SQLException sqle) {
            assertSQLState("XJ040", sqle);
            SQLException lastSQLE = getLastSQLException(sqle);
            String sqlState = lastSQLE.getSQLState();
            // The state of this exception varies with the security provider
            // the test is run with.
            // Briefly stated, the deciding factor is whether the error is
            // caught by checks in the Derby code, or by the checks in the
            // security provider. For instance, the (current Sun JCE) DES
            // key implementation does not verify the key length, whereas the
            // AES key implementation does. For other providers, the situation
            // might be different.
            // XBCX0 : A general crypto exception, wraps the exception from the
            //         security provider.
            // XBCXM : A specific Derby exception for external keys of invalid
            //         lengths.
            if (!sqlState.equals("XBCX0") && !sqlState.equals("XBCXM")) {
                throw lastSQLE;
            }
        }
        confirmNonBootedDB(dbName);
        // Try to connect using wrong key.
        try {
            getConnection(dbName, WRONG_KEY);
            fail("Booting with an incorrect encryption key should fail.");
        } catch (SQLException sqle) {
            assertSQLState("XJ040", sqle);
            assertSQLState("XBCXK", getLastSQLException(sqle));
        }
        // Connect using correct key.
        con = getConnection(dbName, CORRECT_KEY);
        validateDBContents(con);
        con.close();
        // Shutdown the database.
        shutdown(dbName);
    }

    /**
     * Backup an encrypted database.
     */
    public void testBackupEncryptedDatabase()
            throws SQLException {
        String dbName = "encryptionKeyDBToBackup";
        // Create the database.
        con = createAndPopulateDB(dbName);
        validateDBContents(con);
        CallableStatement cs = con.prepareCall(
                "CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE(?)");
        cs.setString(1,
                new File(SupportFilesSetup.EXTINOUT, "backups").getPath());
        // Perform backup.
        cs.execute();
        cs.close();
        con.close();
        shutdown(dbName);
        // Connect to original database after backup.
        con = getConnection(dbName, CORRECT_KEY);
        validateDBContents(con);
        con.close();
        shutdown(dbName);
    }

    /**
     * Create a new database from a backup image.
     */
    public void testCreateDbFromBackup()
            throws SQLException {
        // No ordering imposed by JUnit, so we create our own db and backup.
        // Setup paths and names.
        final String dbName = "encryptionKeyDBToCreateFrom";
        final String backupDbLocation =
            SupportFilesSetup.getReadWrite(
                    new File("backups", "encryptionKeyDBToCreateFrom").getPath()
                ).getPath();
        // Create the database.
        con = createAndPopulateDB(dbName);
        validateDBContents(con);
        CallableStatement cs = con.prepareCall(
                "CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE(?)");
        cs.setString(1, 
                     new File(SupportFilesSetup.EXTINOUT, "backups").getPath());
        // Perform backup.
        cs.execute();
        cs.close();
        con.close();
        shutdown(dbName);
        // Create a new database from backup.
        String dbNameRestored = dbName + "Restored";
        con = getConnection(dbNameRestored, CORRECT_KEY,
                "createFrom=" + backupDbLocation);
        validateDBContents(con);
        con.close();
        shutdown(dbNameRestored, "restored");
        // Try to create a new database from backup with the wrong key.
        dbNameRestored = dbName + "RestoreAttemptedWrongKey";
        try {
            con = getConnection(dbNameRestored, WRONG_KEY,
                    "createFrom=" + backupDbLocation);
            fail("Created database from encrypted backup with wrong key.");
        } catch (SQLException sqle) {
            assertSQLState("XJ040", sqle);
            assertSQLState("XBCXK", getLastSQLException(sqle));
        }
        assertTrue(con.isClosed());
        // Try to create a new database from backup with an invalid key.
        dbNameRestored = dbName + "RestoreAttemptedInvalidKey";
        try {
            con = getConnection(dbNameRestored, INVALID_CHAR_KEY,
                    "createFrom=" + backupDbLocation);
            fail("Created database from encrypted backup with an invalid key.");
        } catch (SQLException sqle) {
            assertSQLState("XJ040", sqle);
            assertSQLState("XBCXN", getLastSQLException(sqle));
        }
        assertTrue(con.isClosed());
        // Try to create a new database from backup with an odd length key.
        dbNameRestored = dbName + "RestoreAttemptedOddLengthKey";
        try {
            con = getConnection(dbNameRestored, ODD_LENGTH_KEY,
                    "createFrom=" + backupDbLocation);
            fail("Created db from encrypted backup with an odd length key.");
        } catch (SQLException sqle) {
            assertSQLState("XJ040", sqle);
            SQLException lastSQLE = getLastSQLException(sqle);
            String sqlState = lastSQLE.getSQLState();
            // The state of this exception varies with the security provider
            // the test is run with.
            // Briefly stated, the deciding factor is whether the error is
            // caught by checks in the Derby code, or by the checks in the
            // security provider. For instance, the (current Sun JCE) DES
            // key implementation does not verify the key length, whereas the
            // AES key implementation does. For other providers, the situation
            // might be different.
            // XBCX0 : A general crypto exception, wraps the exception from the
            //         security provider.
            // XBCXM : A specific Derby exception for external keys of invalid
            //         lengths.
            if (!sqlState.equals("XBCX0") && !sqlState.equals("XBCXM")) {
                throw lastSQLE;
            }
        }
        assertTrue(con.isClosed());
        // Create a new database from backup again.
        dbNameRestored = dbName + "RestoredOnceMore";
        con = getConnection(dbNameRestored, CORRECT_KEY,
                "createFrom=" + backupDbLocation);
        validateDBContents(con);
        con.close();
        shutdown(dbNameRestored, "restored");
    }

    /**
     * Recover the database using <tt>restoreFrom</tt>.
     */
    public void testRestoreFrom()
            throws SQLException {
        // No ordering imposed by JUnit, so we create our own db and backup.
        String dbName = "encryptionKeyDBToRestoreFrom";
        String dbNameRestored = dbName + "Restored";
        createBackupRestore(dbName, dbNameRestored);
        shutdown(dbNameRestored, "restored");
    }

    /**
     * Try to recover database with an invalid key.
     * <p>
     * It should be noted that the existing database, which has been previously
     * recovered from the same backup image, is deleted/overwritten even though
     * Derby is unable to boot the backup image.
     */
    public void testInvalidRestoreFrom()
            throws SQLException {
        // No ordering imposed by JUnit, so we create our own db and backup.
        String dbName = "encryptionKeyDBToInvalidRestoreFrom";
        String dbNameRestored = dbName + "Restored";
        createBackupRestore(dbName, dbNameRestored);
        shutdown(dbNameRestored, "restored");
        // Check that the database is not booted.
        confirmNonBootedDB("restored/" + dbNameRestored);
        // Validate the existing database.
        con = getConnection("restored/" + dbNameRestored, CORRECT_KEY);
        validateDBContents(con);
        con.close();
        shutdown(dbNameRestored, "restored");
        // Confirm that trying a restore with an invalid key will overwrite
        // the existing database we are trying to restore to/into. This is
        // expected behavior currently, but should maybe change?
        try {
            con = getConnection(dbNameRestored, INVALID_CHAR_KEY,
                    ";restoreFrom=" + obtainDbName(dbName, null));
            fail("Restored database with an invalid key.");
        } catch (SQLException sqle) {
            assertSQLState("XBCXN", sqle);
        }
        // The database should no longer exist.
        try {
            // The "" is a hack to avoid using "create=true".
            con = getConnection("restored/" + dbNameRestored, CORRECT_KEY, "");
            fail("Expected connection to fail due to non-existent database.");
        } catch (SQLException sqle) {
            assertSQLState("XJ004", sqle);
        }
    }

    /**
     * Try to create database with a key of odd length.
     */
    public void testCreateWithOddEncryptionKeyLength()
            throws SQLException {
        try {
            getConnection("encryptedDB_oddKeyLength", ODD_LENGTH_KEY);
            fail("Database creation with odd key length should fail.");
        } catch (SQLException sqle) {
            assertSQLState("XJ041", sqle);
            SQLException lastSQLE = getLastSQLException(sqle);
            String sqlState = lastSQLE.getSQLState();
            // The state of this exception varies with the security provider
            // the test is run with. In general, it depends on whether it is
            // Derby code or the security provider code that detects the
            // problem with the encryption key.
            if (!sqlState.equals("XBCXM") && !sqlState.equals("XJ001")) {
                throw lastSQLE;
            }
        }
    }

    /**
     * Try to create database with a key containing one or more invalid chars.
     */
    public void testCreateWithInvalidEncryptionKey() {
        try {
            getConnection("encryptedDB_invkeyChar", INVALID_CHAR_KEY);
            fail("Database creation with invalid key should fail.");
        } catch (SQLException sqle)  {
            assertSQLState("XJ041", sqle);
            assertSQLState("XBCXN", getLastSQLException(sqle));
        }
    }

    /* ********************************************************************* *
     *                     H E L P E R  M E T H O D S                        *
     * ********************************************************************* */

    /**
     * Obtain absolute path for the specified database name.
     * <p>
     * This absolute path is the name of the database (specified) prefixed with
     * the absolute path to the EXTINOUT directory. The latter is determined by
     * consulting <code>SupportFilesSetup</code>.
     *
     * @param dbName name of the database
     * @param subdirectory directory to prefix the database name with (can be
     *      <code>null</code>). Note that the database name will be prefixed
     *      with the path to the EXTINOUT directory even if this parameter is
     *      <code>null</code>.
     * @return A string with the absolute path to the database.
     * @see SupportFilesSetup
     */
    String obtainDbName(String dbName, String subdirectory) {
        File tmp = new File(dbName);
        if (subdirectory != null) {
            tmp = new File(subdirectory, dbName);
        }
        return PrivilegedFileOpsForTests.getAbsolutePath(
                new File(SupportFilesSetup.EXTINOUT, tmp.getPath()));
    }

    /**
     * Create encrypted database, validate it, backup, restore and validate
     * recovered database.
     * <p>
     * The source db is shutdown, the recovered db is left booted.
     *
     * @param sourceDb the original database to create
     * @param targetDb the database to recover to
     */
    private void createBackupRestore(String sourceDb, String targetDb)
            throws SQLException {
        // Create the database.
        con = createAndPopulateDB(sourceDb);
        validateDBContents(con);
        CallableStatement cs = con.prepareCall(
                "CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE(?)");
        cs.setString(1,
                     new File(SupportFilesSetup.EXTINOUT, "backups").getPath());
        // Perform backup.
        cs.execute();
        con.close();
        shutdown(sourceDb);
        confirmNonBootedDB(sourceDb);
        // Use the restoreFrom attribute.
        con = getConnection(targetDb, CORRECT_KEY,
                ";restoreFrom=" + obtainDbName(sourceDb, "backups"));
        validateDBContents(con);
        con.close();
    }

    /**
     * Confirm that the specified encrypted database has not been booted.
     *
     * @param dbName name of an encrypted database
     * @throws junit.framework.AssertionFailedError if the database has been
     *      booted (connection may or may not be established)
     */
    private void confirmNonBootedDB(String dbName) {
        DataSource ds = JDBCDataSource.getDataSource(obtainDbName(dbName, null));
        try {
            ds.getConnection();
        } catch (SQLException sqle) {
            assertSQLState("Database booted? <state:" + sqle.getSQLState() +
                    ", msg:" + sqle.getMessage() + ">", "XJ040", sqle);
        }
    }

    /**
     * Try to establish a connection to the named database with the
     * specified type of key.
     *
     * @param dbName name of the database
     * @param keyMode what kind of key to use (correct, wrong, invalid, odd)
     * @return A connection to the database.
     * @throws SQLException if connection fails
     */
    private Connection getConnection(String dbName, int keyMode)
            throws SQLException {
        return getConnection(dbName, keyMode, null);
    }

    /**
     * Create a new connection to the specified database, using the given
     * connection attributes.
     *
     * @param dbName name of the database
     * @param keyMode what kind of key to use (correct, wrong, invalid, odd)
     * @param recoveryAttribute attribute to recover a database from a backup,
     *      for instance <code>createFrom</code> or <code>restoreFrom</code>.
     *      Both the attribute and its value is expected.
     * @return A connection to the database.
     * @throws SQLException if connection fails
     */
    private Connection getConnection(String dbName,
                                     int keyMode,
                                     String recoveryAttribute)
            throws SQLException {
        DataSource ds = JDBCDataSource.getDataSource(
                obtainDbName(dbName, 
                             recoveryAttribute == null ? null : "restored"));
        StringBuffer str = new StringBuffer(75);
        if (recoveryAttribute == null) {
            // Enable data encryption is this database is being created.
            JDBCDataSource.setBeanProperty(ds, "CreateDatabase", "create");
            str.append("dataEncryption=true;");
        } else {
            str.append(recoveryAttribute);
            str.append(";");
        }
        // Add the encryption algorithm.
        str.append("encryptionAlgorithm=");
        str.append(algorithm);
        str.append(";");
        // Add the key.
        str.append("encryptionKey=");
        switch (keyMode) {
            case CORRECT_KEY:
                str.append(keyCorrect);
                break;
            case WRONG_KEY:
                str.append(keyWrong);
                break;
            case ODD_LENGTH_KEY:
                str.append(keyOddLength);
                break;
            case INVALID_CHAR_KEY:
                str.append(keyInvalidChar);
                break;
            default:
                throw new IllegalArgumentException(
                        "Invalid key mode specified: " + keyMode);
        }
        str.append(";");
        JDBCDataSource.setBeanProperty(
                ds, "connectionAttributes", str.toString());
        return ds.getConnection();
    }

    /**
     * Shutdown the specified database.
     *
     * @param databaseName the name of the database
     */
    protected void shutdown(String databaseName)
            throws SQLException {
        shutdown(databaseName, null);
    }

    /**
     * Shutdown the database, specified by the database name and prefix.
     *
     * @param databaseName the name of the database
     * @param dir sub-directory prefix for the database
     */
    protected void shutdown(String databaseName, String dir)
            throws SQLException {
        DataSource ds = JDBCDataSource.getDataSource(
                obtainDbName(databaseName, dir));
        JDBCDataSource.shutdownDatabase(ds);
    }

    /**
     * Create a new database and populate it.
     * <p>
     * The method fails with an exception if the database already exists.
     * This is because it is the creation process that is to be tested.
     *
     * @param dbName name of the database to create
     * @return A connection the to the newly created database.
     * @throws SQLException if the database already exist, or
     *      a general error happens during database interaction
     */
    protected Connection createAndPopulateDB(String dbName)
            throws SQLException {
        Connection newCon = getConnection(dbName, CORRECT_KEY);
        SQLWarning warning = newCon.getWarnings();
        // If the database already exists, fail the test.
        if (warning != null) {
            if ("01J01".equals(warning.getSQLState())) {
                fail("Refusing to continue, database already exists <" +
                        warning.getMessage() + ">");
            }
        }
        Statement stmt = newCon.createStatement();
        stmt.executeUpdate("CREATE TABLE " + TABLE + " (id int NOT NULL, " +
                "val int NOT NULL, PRIMARY KEY(id))");
        stmt.close();
        PreparedStatement ps = newCon.prepareStatement("INSERT INTO " + TABLE +
                " (id, val) VALUES (?,?)");
        for (int i=0; i < DATA.length; i++) {
            ps.setInt(1, i);
            ps.setInt(2, DATA[i]);
            ps.executeUpdate();
        }
        ps.close();
        return newCon;
    }

    /**
     * Validate the data in the database against the data model.
     *
     * @param con the database to validate the contents of
     * @throws junit.framework.AssertionFailedError if there is a mismatch
     *      between the data in the database and the model
     */
    protected void validateDBContents(Connection con)
            throws SQLException {
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT id, val FROM " + TABLE +
                                            " ORDER BY id");
        int id, val;
        while (rs.next()) {
            id = rs.getInt(1);
            val = rs.getInt(2);
            if (id >= DATA.length) {
                fail("Id in database out of bounds for data model; " +
                        id + " >= " + DATA.length);
            }
            if (val != DATA[id]) {
                fail("Mismatch between db and model for id " + id + ";" +
                        val + " != " + DATA[id]);
            }
        }
        rs.close();
        stmt.close();
    }
} // End EncryptionKeyTest