db-derby-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From banda...@apache.org
Subject svn commit: r407366 - in /db/derby/code/trunk/java: engine/org/apache/derby/iapi/services/crypto/ engine/org/apache/derby/iapi/services/io/ engine/org/apache/derby/iapi/store/raw/ engine/org/apache/derby/iapi/store/raw/data/ engine/org/apache/derby/iap...
Date Wed, 17 May 2006 20:17:46 GMT
Author: bandaram
Date: Wed May 17 13:17:45 2006
New Revision: 407366

URL: http://svn.apache.org/viewvc?rev=407366&view=rev
Log:
DERBY-1156: Committing this for Suresh, reviewed by Mike Matrigali.

Here is Mike's review comments:
I have reviewed this patch and run a full set of tests on windows XP / sun jdk1.4.2 which passed. I think this patch should be committed as is. It is a good incremental checkin for this feature. It provides a set of tools for the rest of the project, and gets the code to the point that it can encrypt an existing unencrypted db. Future checkins should address a couple of things:
1) obviously more testing. Some quick notes, the current tests may want to show that accessing the newly encrypted db with a bad password does not work - just to insure all the url;s are not just being totally ignored. Also want to test abort - probably need a testing codepoint to cause the failure at the right time.
2) fix up the comments, there are some typo's .
3) usual nit - some greater than 80 char lines.

I would have committed this change now, but svn still is not back.

Patch submitted by Suresh Thalamati (suresh.thalamati@gmail.com)


Added:
    db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptContainerOperation.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptContainerUndoOperation.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptData.java   (with props)
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/encryptDatabaseTest1.out   (with props)
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/encryptDatabaseTest1.sql   (with props)
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/encryptDatabaseTest1_app.properties   (with props)
Modified:
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/services/crypto/CipherFactory.java
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/services/io/RegisteredFormatIds.java
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/services/io/StoredFormatIds.java
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/RawStoreFactory.java
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/data/DataFactory.java
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/data/RawContainerHandle.java
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/log/LogFactory.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/services/jce/JCECipherFactory.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/RawStore.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/BaseContainer.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/BaseContainerHandle.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/BaseDataFileFactory.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/FileContainer.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/InputStreamContainer.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/RAFContainer.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/StreamFileContainer.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/log/LogToFile.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/log/ReadOnly.java
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/suites/encryptionAll.runall
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/copyfiles.ant

Modified: db/derby/code/trunk/java/engine/org/apache/derby/iapi/services/crypto/CipherFactory.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/iapi/services/crypto/CipherFactory.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/services/crypto/CipherFactory.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/services/crypto/CipherFactory.java Wed May 17 13:17:45 2006
@@ -89,6 +89,8 @@
 	public void verifyKey(boolean create, StorageFactory storageFactory,Properties properties)
 		throws StandardException;
 
+    public void saveProperties(Properties properties);
+
 }
 
 

Modified: db/derby/code/trunk/java/engine/org/apache/derby/iapi/services/io/RegisteredFormatIds.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/iapi/services/io/RegisteredFormatIds.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/services/io/RegisteredFormatIds.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/services/io/RegisteredFormatIds.java Wed May 17 13:17:45 2006
@@ -518,6 +518,8 @@
 		/* 455 */   "org.apache.derby.catalog.types.SynonymAliasInfo",
         /* 456 */   "org.apache.derby.iapi.types.DTSClassInfo", //InstanceGetter, XML_TYPE_ID
         /* 457 */   "org.apache.derby.catalog.types.TypesImplInstanceGetter", // XML_TYPE_ID_IMPL
-        /* 458 */   "org.apache.derby.iapi.types.DTSClassInfo" //InstanceGetter, XML_ID
+        /* 458 */   "org.apache.derby.iapi.types.DTSClassInfo", //InstanceGetter, XML_ID
+        /* 459 */   "org.apache.derby.impl.store.raw.data.EncryptContainerOperation",
+        /* 460 */   "org.apache.derby.impl.store.raw.data.EncryptContainerUndoOperation",
 };
 }

Modified: db/derby/code/trunk/java/engine/org/apache/derby/iapi/services/io/StoredFormatIds.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/iapi/services/io/StoredFormatIds.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/services/io/StoredFormatIds.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/services/io/StoredFormatIds.java Wed May 17 13:17:45 2006
@@ -1707,6 +1707,13 @@
         public static final int LOGOP_COMPRESS_SPACE =
                 (MIN_ID_2 + 454);
 
+   		/* org.apache.derby.impl.store.raw.data.EncryptContainerOperation */
+        public static final int LOGOP_ENCRYPT_CONTAINER =
+                (MIN_ID_2 + 459);
+
+  		/* org.apache.derby.impl.store.raw.data.EncryptContainerUndoOperation */
+        public static final int LOGOP_ENCRYPT_CONTAINER_UNDO =
+                (MIN_ID_2 + 460);
 
         /*******************************************************************
         **
@@ -1827,7 +1834,7 @@
          * Make sure this is updated when a new module is added
          */
         public static final int MAX_ID_2 =
-                (MIN_ID_2 + 458);
+                (MIN_ID_2 + 460);
 
         // DO NOT USE 4 BYTE IDS ANYMORE
         static public final int MAX_ID_4 =

Modified: db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/RawStoreFactory.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/RawStoreFactory.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/RawStoreFactory.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/RawStoreFactory.java Wed May 17 13:17:45 2006
@@ -798,7 +798,8 @@
 		@exception StandardException Standard Cloudscape Error Policy
 	 */
 	public int encrypt(byte[] cleartext, int offset, int length, 
-					   byte[] ciphertext, int outputOffset) 
+					   byte[] ciphertext, int outputOffset,
+                       boolean newEngine) 
 		 throws StandardException ;
 
 	/**

Modified: db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/data/DataFactory.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/data/DataFactory.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/data/DataFactory.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/data/DataFactory.java Wed May 17 13:17:45 2006
@@ -269,7 +269,8 @@
 		@exception StandardException Standard Cloudscape Error Policy
 	 */
 	public int encrypt(byte[] cleartext, int offset, int length,
-					   byte[] ciphertext, int outputOffset)
+					   byte[] ciphertext, int outputOffset, 
+                       boolean newEngine)
 		 throws StandardException ;
 
 	/**
@@ -281,6 +282,19 @@
 	public int decrypt(byte[] ciphertext, int offset, int length,
 					   byte[] cleartext, int outputOffset)
 		 throws StandardException ;
+
+    /**
+	 * Encrypt all the containers in the data segment.
+     * @param t the transaction that is encrypting the containers.
+     * @exception StandardException Standard Derby Error Policy
+	 */
+	public void encryptAllContainers(RawTransaction t) 
+        throws StandardException;
+
+    /*
+     * Set that the database is encrypted.
+     */
+    public void setDatabaseEncrypted();
 
 	/**
 		Return the encryption block size used by the algorithm at time of

Modified: db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/data/RawContainerHandle.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/data/RawContainerHandle.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/data/RawContainerHandle.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/data/RawContainerHandle.java Wed May 17 13:17:45 2006
@@ -120,4 +120,13 @@
 	 */
 	public void preDirty(boolean preDirtyOn) throws StandardException;
 
+
+    /**
+     * Create encrypted version of the container with the 
+     * user specified encryption properties.  
+     * @param newFilePath file to store the new encrypted version of the container
+	 * @exception StandardException	Standard Cloudscape error policy
+     */
+	public void encryptContainer(String newFilePath) throws StandardException;
+
 }

Modified: db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/log/LogFactory.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/log/LogFactory.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/log/LogFactory.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/store/raw/log/LogFactory.java Wed May 17 13:17:45 2006
@@ -281,6 +281,17 @@
 	 **/
 	public void abortLogBackup();
 
+    /*
+     * Set that the database is encrypted , all the transaction log has 
+     * to be encrypted.
+     */
+    public void setDatabaseEncrypted();
+    
+    /*
+     * setup transaction log for encryption. 
+     */
+    public  void setupLogEncryption() throws StandardException;
+
 
 }
 

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/services/jce/JCECipherFactory.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/services/jce/JCECipherFactory.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/services/jce/JCECipherFactory.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/services/jce/JCECipherFactory.java Wed May 17 13:17:45 2006
@@ -37,7 +37,7 @@
 import org.apache.derby.iapi.util.StringUtil;
 
 import java.util.Properties;
-
+import java.util.Enumeration;
 import java.security.Key;
 import java.security.Provider;
 import java.security.SecureRandom;
@@ -99,6 +99,11 @@
 	private SecretKey mainSecretKey;
 	private byte[] mainIV;
 
+    // properties that needs to be stored in the
+    // in the service.properties file.
+    private Properties persistentProperties;
+
+
 	/**
 	    Amount of data that is used for verification of external encryption key
 	    This does not include the MD5 checksum bytes
@@ -378,6 +383,7 @@
 
         boolean provider_or_algo_specified = false;
 		boolean storeProperties = create;
+        persistentProperties = new Properties();
 
 		String externalKey = properties.getProperty(Attribute.CRYPTO_EXTERNAL_KEY);
 		if (externalKey != null) {
@@ -435,7 +441,8 @@
 		// explictly putting the properties back into the properties
 		// saves then in service.properties at create time.
         if (storeProperties)
-			properties.put(Attribute.CRYPTO_ALGORITHM, cryptoAlgorithm);
+			persistentProperties.put(Attribute.CRYPTO_ALGORITHM, 
+                                     cryptoAlgorithm);
 
         int firstSlashPos = cryptoAlgorithm.indexOf('/');
         int lastSlashPos = cryptoAlgorithm.lastIndexOf('/');
@@ -559,7 +566,8 @@
 
 				generatedKey = handleBootPassword(create, properties);
 				if(create)
-				   properties.put(Attribute.CRYPTO_KEY_LENGTH,keyLengthBits+"-"+generatedKey.length);
+				   persistentProperties.put(Attribute.CRYPTO_KEY_LENGTH,
+                                            keyLengthBits+"-"+generatedKey.length);
 			}
 
 			// Make a key and IV object out of the generated key
@@ -568,12 +576,14 @@
 
 			if (create)
 			{
-				properties.put(Attribute.DATA_ENCRYPTION, "true");
+				persistentProperties.put(Attribute.DATA_ENCRYPTION, "true");
 
 				// Set two new properties to allow for future changes to the log and data encryption
 				// schemes. This property is introduced in version 10 , value starts at 1.
-				properties.put(RawStoreFactory.DATA_ENCRYPT_ALGORITHM_VERSION,String.valueOf(1));
-				properties.put(RawStoreFactory.LOG_ENCRYPT_ALGORITHM_VERSION,String.valueOf(1));
+				persistentProperties.put(RawStoreFactory.DATA_ENCRYPT_ALGORITHM_VERSION,
+                                               String.valueOf(1));
+				persistentProperties.put(RawStoreFactory.LOG_ENCRYPT_ALGORITHM_VERSION,
+                                               String.valueOf(1));
 			}
 
 			return;
@@ -633,7 +643,8 @@
 			//
 			generatedKey = generateUniqueBytes();
 
-			properties.put(RawStoreFactory.ENCRYPTED_KEY, saveSecretKey(generatedKey, bootPassword));
+			persistentProperties.put(RawStoreFactory.ENCRYPTED_KEY, 
+                                           saveSecretKey(generatedKey, bootPassword));
 
 		}
 		else
@@ -648,6 +659,27 @@
 	{
 
 	}
+
+    /* 
+     * put all the encyrpion cipger related properties that has to 
+     * be made peristent into the database service properties list.
+     * @param  properties  properties object that is used to store 
+     *                     cipher properties persistently. 
+     */
+    public void saveProperties(Properties properties) 
+    {
+        // put the cipher properties to be persistent into the 
+        // system perisistent properties. 
+        for (Enumeration e = persistentProperties.keys(); 
+             e.hasMoreElements(); ) 
+        {
+            String key = (String) e.nextElement();
+            properties.put(key, persistentProperties.get(key));
+		}
+
+        // clear the cipher properties to be persistent. 
+        persistentProperties = null;
+    }
 
 
 	/**

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/RawStore.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/RawStore.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/RawStore.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/RawStore.java Wed May 17 13:17:45 2006
@@ -108,8 +108,11 @@
 
 	private SecureRandom random;
 	private boolean databaseEncrypted;
+    private boolean encryptDatabase;
 	private CipherProvider encryptionEngine;
 	private CipherProvider decryptionEngine;
+    private CipherProvider newEncryptionEngine;
+	private CipherProvider newDecryptionEngine;
 	private CipherFactory cipherFactory;
 	private int counter_encrypt;
 	private int counter_decrypt;
@@ -163,7 +166,6 @@
 		throws StandardException
 	{
 		dataDirectory = properties.getProperty(PersistentService.ROOT);
-
 		DaemonFactory daemonFactory =
 			(DaemonFactory)Monitor.startSystemModule(org.apache.derby.iapi.reference.Module.DaemonFactory);
 		rawStoreDaemon = daemonFactory.createNewDaemon("rawStoreDaemon");
@@ -176,68 +178,140 @@
 					  create, this, getDataFactoryModule(), properties);
 		storageFactory = dataFactory.getStorageFactory();
 
+        String restoreFromBackup = null;
+
 		if (properties != null)
 		{
+            // check if this is a restore from a backup copy. 
+            restoreFromBackup = properties.getProperty(Attribute.CREATE_FROM);
+            if(restoreFromBackup == null)
+                restoreFromBackup = properties.getProperty(Attribute.RESTORE_FROM);
+            if(restoreFromBackup == null)
+                restoreFromBackup =
+                    properties.getProperty(Attribute.ROLL_FORWARD_RECOVERY_FROM);
+
 
 			/***********************************************
 			 * encryption
 			 **********************************************/
+            
+            // check if user has requested to encrypt the database or it is an
+            // encrypted database.
 
-			String dataEncryption = properties.getProperty(Attribute.DATA_ENCRYPTION);
-			databaseEncrypted = Boolean.valueOf(dataEncryption).booleanValue();
+            String dataEncryption = 
+                properties.getProperty(Attribute.DATA_ENCRYPTION);
+            databaseEncrypted = Boolean.valueOf(dataEncryption).booleanValue(); 
+
+            if (!create && restoreFromBackup == null) {
+                // check if database is already encrypted, by directly peeking at the
+                // database service propertes instead of the properties passed 
+                // to this method. By looking at properties to the boot method ,
+                // one can not differentiate if user is requesting for database
+                // encryption or the database is already encrypted because 
+                // Attribute.DATA_ENCRYPTION is used  to store in the 
+                // service properties to indicate that database
+                // is encrypted and also users can specify it as URL attribute 
+                // to encrypt and existing database. 
+                               
+                String name = Monitor.getMonitor().getServiceName(this);
+                PersistentService ps = Monitor.getMonitor().getServiceType(this);
+                String canonicalName = ps.getCanonicalServiceName(name);
+                Properties serviceprops = ps.getServiceProperties(canonicalName, 
+                                                                  (Properties)null);
+                dataEncryption = serviceprops.getProperty(Attribute.DATA_ENCRYPTION);
+                boolean encryptedDatabase = Boolean.valueOf(dataEncryption).booleanValue();
+
+                if (!encryptedDatabase  && databaseEncrypted) {
+                    // it it not an encrypted database, user is asking to 
+                    // encrypt an un-encrypted database. 
+                    encryptDatabase = true;
+                    // set database as un-encrypted, we will set it as encrypted 
+                    // after encrypting the existing data. 
+                    databaseEncrypted = false;
+                }
+                
+                // NOTE: if user specifies Attribute.DATA_ENCRYPTION on the
+                // connection URL by mistake on an already encrypted database, 
+                // it is ignored.
+            }
 
-			if (databaseEncrypted)
+            // setup encryption engines. 
+			if (databaseEncrypted || encryptDatabase)
 			{
-					cipherFactory =
-                        (CipherFactory)Monitor.bootServiceModule(create, this,
+                // check if database is configured for encryption, during
+                // configuration  some of the properties database; so that
+                // user does not have to specify them on the URL everytime.
+                boolean setupEncryption = create || encryptDatabase; 
+
+                cipherFactory =
+                    (CipherFactory)Monitor.bootServiceModule(setupEncryption, this,
 						org.apache.derby.iapi.reference.Module.CipherFactory, properties);
 
-					// The database can be encrypted using an encryption key that is given at
-					// connection url. For security reasons, this key is not made persistent
-					// in the database. But it is necessary to verify the encryption key 
-					// whenever booting the database if it is similar to the key that was used
-					// during creation time. This needs to happen before we access the data/logs to 
-					// avoid the risk of corrupting the database because of a wrong encryption key.
-
-					// Please note this verification process does not provide any added security
-				        // but is intended to allow to fail gracefully if a wrong encryption key 
-					// is used during boot time
+                // The database can be encrypted using an encryption key that is given at
+                // connection url. For security reasons, this key is not made persistent
+                // in the database. But it is necessary to verify the encryption key 
+                // whenever booting the database if it is similar to the key that was used
+                // during creation time. This needs to happen before we access the data/logs to 
+                // avoid the risk of corrupting the database because of a wrong encryption key.
+                
+                // Please note this verification process does not provide any added security
+                // but is intended to allow to fail gracefully if a wrong encryption key 
+                // is used during boot time
   
-					cipherFactory.verifyKey(create,storageFactory,properties);
 
-					// Initializes the encryption and decryption engines
-					encryptionEngine = cipherFactory.
-						createNewCipher(CipherFactory.ENCRYPT);
-
-	                                // At creation time of an encrypted database, store the encryption block size
-					// for the algorithm. Store this value as property given by  
-	                                // RawStoreFactory.ENCRYPTION_BLOCKSIZE. This value
-	                                // is made persistent by storing it in service.properties
-	                                // To connect to an existing database, retrieve the value and use it for
-	                                // appropriate padding.
-	                                // The  default value of encryption block size is 8,
-					// to allow for downgrade issues
-					// Before support for AES (beetle6023), default encryption block size supported
-					// was 8
+                cipherFactory.verifyKey(setupEncryption,storageFactory,properties);
 
-					if(create)
-					{
-						encryptionBlockSize = encryptionEngine.getEncryptionBlockSize();
-						properties.put(RawStoreFactory.ENCRYPTION_BLOCKSIZE,
-								String.valueOf(encryptionBlockSize));
-					}
-					else
-					{
-						if(properties.getProperty(RawStoreFactory.ENCRYPTION_BLOCKSIZE) != null)
-						    encryptionBlockSize = Integer.parseInt(properties.getProperty
-										(RawStoreFactory.ENCRYPTION_BLOCKSIZE));
-					}
-
-					decryptionEngine = cipherFactory.
-						createNewCipher(CipherFactory.DECRYPT);
+                // Initializes the encryption and decryption engines
+                encryptionEngine = cipherFactory.
+                    createNewCipher(CipherFactory.ENCRYPT);
+                
+                // At creation time of an encrypted database, store the encryption block size
+                // for the algorithm. Store this value as property given by  
+                // RawStoreFactory.ENCRYPTION_BLOCKSIZE. This value
+                // is made persistent by storing it in service.properties
+                // To connect to an existing database, retrieve the value and use it for
+                // appropriate padding.
+                // The  default value of encryption block size is 8,
+                // to allow for downgrade issues
+                // Before support for AES (beetle6023), default encryption block size supported
+                // was 8
 
-					random = cipherFactory.getSecureRandom();
+                if(setupEncryption) 
+                {
+                    encryptionBlockSize = encryptionEngine.getEncryptionBlockSize();
+                    // in case of database create, store the encryption block
+                    // size. Incase of reconfiguring the existing datbase, this
+                    // will be saved after encrypting the exisiting data. 
+                    if (create)
+                        properties.put(RawStoreFactory.ENCRYPTION_BLOCKSIZE,
+                                       String.valueOf(encryptionBlockSize));
+                }
+                else
+                {
+                    if(properties.getProperty(RawStoreFactory.ENCRYPTION_BLOCKSIZE) != null)
+                        encryptionBlockSize = Integer.parseInt(properties.getProperty
+                                                               (RawStoreFactory.ENCRYPTION_BLOCKSIZE));
+                    else
+                        encryptionBlockSize = encryptionEngine.getEncryptionBlockSize();
+                }   
+
+                decryptionEngine = cipherFactory.
+                    createNewCipher(CipherFactory.DECRYPT);
+
+                random = cipherFactory.getSecureRandom();
+                    
+                if (encryptDatabase) {
+                    // for now there is only one encryption engine, 
+                    // configuring an unencrypted database for encryption 
+                    // is supported at this moment.
+                    newDecryptionEngine = decryptionEngine;   
+                    newEncryptionEngine = encryptionEngine;
+                }
 
+                // save the encryption properties if encryption is enabled 
+                // at database creation time. 
+                if(create)
+                    cipherFactory.saveProperties(properties) ;
 			}
 		}
 
@@ -259,13 +333,12 @@
 		// log factory is booted by the data factory
 		logFactory =(LogFactory) Monitor.findServiceModule(this, getLogFactoryModule());
 
-		String restoreFromBackup =null;
-		restoreFromBackup = properties.getProperty(Attribute.CREATE_FROM);
-		if(restoreFromBackup == null)
-			restoreFromBackup = properties.getProperty(Attribute.RESTORE_FROM);
-		if(restoreFromBackup == null)
-			restoreFromBackup =
-				properties.getProperty(Attribute.ROLL_FORWARD_RECOVERY_FROM);
+        if (databaseEncrypted) {
+            // let log factory know if the database is encrypted . 
+            logFactory.setDatabaseEncrypted();
+            // let data factory know if the database is encrypted. 
+            dataFactory.setDatabaseEncrypted();
+        }
 
 
 		//save the service properties to a file if we are doing a restore from
@@ -320,6 +393,7 @@
 		}
 
 
+
 		/**
 		 * Note: service.properties file acts as flags to indicate
 		 * that the copy from backup is successful.
@@ -335,6 +409,11 @@
 		// after the factories are loaded, recover the database
 		logFactory.recover(this, dataFactory, xactFactory);
 
+        // if user requested to encrpty an unecrypted database or encrypt with
+        // new alogorithm then do that now.  
+        if (encryptDatabase) {
+            configureDatabaseForEncryption(properties);
+        }
 	}
 
 	public void	stop() {
@@ -1069,6 +1148,7 @@
 	** data encryption/decryption support
 	*/
 
+
 	/**
 		Encrypt cleartext into ciphertext.
 
@@ -1077,10 +1157,12 @@
 		@exception StandardException Standard Cloudscape Error Policy
 	 */
 	public int encrypt(byte[] cleartext, int offset, int length,
-					   byte[] ciphertext, int outputOffset)
+					   byte[] ciphertext, int outputOffset, 
+                       boolean newEngine)
 		 throws StandardException
 	{
-		if (databaseEncrypted == false || encryptionEngine == null)
+		if (databaseEncrypted == false && encryptDatabase == false || 
+            encryptionEngine == null && newEncryptionEngine == null)
         {
             throw StandardException.newException(
                         SQLState.STORE_FEATURE_NOT_IMPLEMENTED);
@@ -1088,8 +1170,13 @@
 
 		counter_encrypt++;
 
-		return encryptionEngine.encrypt(cleartext, offset, length,
-										ciphertext, outputOffset);
+        if (newEngine) {
+            return newEncryptionEngine.encrypt(cleartext, offset, length,
+                                            ciphertext, outputOffset);
+        } else {
+            return encryptionEngine.encrypt(cleartext, offset, length,
+                                            ciphertext, outputOffset);
+        }
 	}
 
 	/**
@@ -1100,7 +1187,7 @@
 		@exception StandardException Standard Cloudscape Error Policy
 	 */
 	public int decrypt(byte[] ciphertext, int offset, int length,
-					   byte[] cleartext, int outputOffset)
+					   byte[] cleartext, int outputOffset) 
 		 throws StandardException
 	{
 		if (databaseEncrypted == false || decryptionEngine == null)
@@ -1110,9 +1197,8 @@
         }
 
 		counter_decrypt++;
-
-		return decryptionEngine.decrypt(ciphertext, offset, length,
-										cleartext, outputOffset);
+        return decryptionEngine.decrypt(ciphertext, offset, length,
+                                            cleartext, outputOffset);
 	}
 
 	/**
@@ -1152,6 +1238,91 @@
 		return cipherFactory.changeBootPassword((String)changePassword, properties, encryptionEngine);
 
 	}
+
+
+
+    /*
+     * Configure the database for encryption, with the  specified 
+     * encryption  properties.
+     *
+     * Basic idea is to encrypt all the containers with new password/key 
+     * specified by the user and keep old versions of the data to 
+     * rollback the database to the state before the configuration of database 
+     * with new encryption attributes. Users can configure the database with 
+     * new encryption  attributes at boot time only; advantage of this approach
+     * is that there will not be any concurrency issues to handle because
+     * no users will be modifying the data. 
+
+     * First step is to encrypt the existing data with new encryption 
+     * attributes  and then update the encryption properties for 
+     * the database. Configuring  an un-encrypted database for 
+     * encryption problem is a minor variation of  re-encrypting an 
+     * encrypted database with new encryption key. The database 
+     * reconfiguration with new encryption attributes is done under one
+     * transaction, if there is a crash/error before it is committed, 
+     * then it  is rolled back and the database will be brought back to the
+     * state it was before the encryption.  
+     * @param properties  properties related to this database.
+     * @exception StandardException Standard Cloudscape Error Policy
+     */
+    public void configureDatabaseForEncryption(Properties properties) 
+        throws StandardException 
+    {
+
+        // check point the datase, so that encryption does not have
+        // to encrypt the existing transactions logs. 
+ 
+        logFactory.checkpoint(this, dataFactory, xactFactory, true);
+
+        // start a transaction that is to be used for encryting the database
+        RawTransaction transaction =
+            xactFactory.startTransaction(
+                   this,
+                    ContextService.getFactory().getCurrentContextManager(),
+                    AccessFactoryGlobals.USER_TRANS_NAME);
+        boolean error = true;
+        try {
+            dataFactory.encryptAllContainers(transaction);
+            error = false;
+        }finally {
+            
+            // encryption is finished. close the transaction.
+            if (error) { 
+                transaction.abort();
+            }
+            else {
+                transaction.commit();
+
+                // TODO : handle the case where if engine crashes
+                // after the commit but before the new database
+                // encryption properties are made persistent. 
+                
+                // let log factory and data factory know that 
+                // database is encrypted.
+                logFactory.setDatabaseEncrypted();
+                logFactory.setupLogEncryption();
+                dataFactory.setDatabaseEncrypted();
+                
+                // mark in the raw store that the database is 
+                // encrypted. 
+                databaseEncrypted = true;
+                encryptDatabase = false;
+                //switch the encryption/decryption engine to the new ones.
+                decryptionEngine = newDecryptionEngine;  
+                encryptionEngine = newEncryptionEngine;
+                //force a checkpoint with new encryption algorithm
+                logFactory.checkpoint(this, dataFactory, xactFactory, true);
+                // store the encryption block size;
+                properties.put(RawStoreFactory.ENCRYPTION_BLOCKSIZE,
+                               String.valueOf(encryptionBlockSize));
+                // save the encryption properties.
+                cipherFactory.saveProperties(properties) ;
+            }                
+            newDecryptionEngine = null;   
+            newEncryptionEngine = null;
+            transaction.close(); 
+        }
+    }
 
 
 	/*

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/BaseContainer.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/BaseContainer.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/BaseContainer.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/BaseContainer.java Wed May 17 13:17:45 2006
@@ -873,6 +873,19 @@
 											 String backupContainerPath) throws StandardException ;
 
 
+    /**
+     * Create encrypted version of the  container with the 
+     * user specified encryption properties. 
+     *
+     * @param handle the container handle.
+     * @param newFilePath file to store the new encrypted version of the container
+     * @exception StandardException Standard Derby error policy 
+     */
+	protected abstract void  encryptContainer(BaseContainerHandle handle, 
+                                              String newFilePath) 
+        throws StandardException ;
+
+
 	/*
 	** Methods to be used by sub-classes.
 	*/

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/BaseContainerHandle.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/BaseContainerHandle.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/BaseContainerHandle.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/BaseContainerHandle.java Wed May 17 13:17:45 2006
@@ -1023,6 +1023,20 @@
 		container.backupContainer(this, backupContainerPath);
 	}
 
+
+
+    /**
+     * Create encrypted version of the  container with the 
+     * user specified encryption properties.        
+     * @param newFilePath file to store the new encrypted version of the container
+     * @exception StandardException	Standard Derby error policy
+     */
+    public void encryptContainer(String newFilePath) throws StandardException 
+    {
+        checkOpen();
+        container.encryptContainer(this, newFilePath);
+    }
+
     
     public String toString()
     {

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/BaseDataFileFactory.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/BaseDataFileFactory.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/BaseDataFileFactory.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/BaseDataFileFactory.java Wed May 17 13:17:45 2006
@@ -324,12 +324,6 @@
 		if (!isReadOnly())		// read only db, not interested in filelock
 			getJBMSLockOnDB(identifier, uf, dataDirectory);
 
-		// restoreFrom and createFrom operations also need to know if database 
-        // is encrypted
-		String dataEncryption = 
-            startParams.getProperty(Attribute.DATA_ENCRYPTION);
-
-		databaseEncrypted = Boolean.valueOf(dataEncryption).booleanValue();
 
 		//If the database is being restored/created from backup
 		//the restore the data directory(seg*) from backup
@@ -344,6 +338,11 @@
 		{
 			try
             {
+                // restoreFrom and createFrom operations also need to know if database 
+                // is encrypted
+                String dataEncryption = 
+                    startParams.getProperty(Attribute.DATA_ENCRYPTION);
+                databaseEncrypted = Boolean.valueOf(dataEncryption).booleanValue();
 				restoreDataDirectory(restoreFrom);
 			}
             catch(StandardException se)
@@ -2102,16 +2101,24 @@
 		return databaseEncrypted;
 	}
 
+    public void setDatabaseEncrypted()
+	{
+		databaseEncrypted = true;
+	}
+
 	public int encrypt(
     byte[]  cleartext, 
     int     offset, 
     int     length, 
     byte[]  ciphertext, 
-    int     outputOffset)
+    int     outputOffset,
+    boolean newEngine)
 		 throws StandardException
 	{
 		return rawStoreFactory.encrypt(
-                    cleartext, offset, length, ciphertext, outputOffset);
+                    cleartext, offset, length, 
+                    ciphertext, outputOffset, 
+                    newEngine);
 	}
 
 	public int decrypt(
@@ -2126,6 +2133,13 @@
                 ciphertext, offset, length, cleartext, outputOffset);
 	}
 
+    public void encryptAllContainers(RawTransaction t) throws StandardException
+    {
+        EncryptData ed = new EncryptData(this);
+        // encrypt all the conatiners in the databse
+        ed.encryptAllContainers(t);
+    }
+
 	/**
 		Returns the encryption block size used by the algorithm at time of
 		creation of an encrypted database
@@ -2422,7 +2436,7 @@
      * with other privileged actions execution in this class.
      * @return An array of all the file names in seg0.
      **/
-	private synchronized String[] getContainerNames()
+    synchronized String[] getContainerNames()
 	{
         actionCode = GET_CONTAINER_NAMES_ACTION;
         try{

Added: db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptContainerOperation.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptContainerOperation.java?rev=407366&view=auto
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptContainerOperation.java (added)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptContainerOperation.java Wed May 17 13:17:45 2006
@@ -0,0 +1,213 @@
+/*
+
+   Derby - Class org.apache.derby.impl.store.raw.data.EncryptContainerOperation
+
+   Copyright 1997, 2006 The Apache Software Foundation or its licensors, as applicable.
+
+   Licensed 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.derby.impl.store.raw.data;
+
+import org.apache.derby.iapi.services.io.StoredFormatIds;
+import org.apache.derby.iapi.services.sanity.SanityManager;
+import org.apache.derby.iapi.store.raw.Compensation;
+import org.apache.derby.iapi.store.raw.Transaction;
+import org.apache.derby.iapi.store.raw.Undoable;
+import org.apache.derby.iapi.store.raw.Loggable;
+import org.apache.derby.iapi.store.raw.data.RawContainerHandle;
+import org.apache.derby.iapi.store.raw.xact.RawTransaction;
+import org.apache.derby.iapi.store.raw.log.LogInstant;
+import org.apache.derby.iapi.store.raw.ContainerKey;
+import org.apache.derby.iapi.error.StandardException;
+
+import org.apache.derby.iapi.util.ByteArray;
+
+import java.io.ObjectOutput;
+import java.io.ObjectInput;
+import java.io.IOException;
+import org.apache.derby.iapi.services.io.LimitObjectInput;
+
+/**
+ * Log operation to encrypt a container with a new encryption key or to encrypt
+ * an unencrypted container while configuring the database for
+ * encryption. Container is  synced to the disk when encryption is 
+ * is successfull, there is nothing to do on a redo. If there is crash/error
+ * while configuring a database for encryption; original version of the
+ * container is put backup during undo. 
+ *
+ * <PRE>
+ *  @format_id	LOGOP_ENCRYPT_CONTAINER
+ * 	the formatId is written by FormatIdOutputStream when this object is
+ *	written out by writeObject
+ * @purpose to record enctyption of container with a new encryption key.
+ * @upgrade
+ * @disk_layout
+ *      containerId(ContainerKey)  the id of the container this operation applies to
+ *	@end_format
+ *  </PRE>
+ *
+ *	@author  Suresh Thalamati
+ *  @see Undoable
+ */
+public class EncryptContainerOperation implements Undoable
+{
+
+	private ContainerKey containerId;
+
+	protected EncryptContainerOperation(RawContainerHandle hdl) 
+        throws StandardException
+	{
+		containerId = hdl.getId();
+	}
+
+    /*
+     * Formatable methods
+     */
+
+    // no-arg constructor, required by Formatable
+    public EncryptContainerOperation() { super(); }
+
+    public void writeExternal(ObjectOutput out) throws IOException
+    {
+        containerId.writeExternal(out);
+    }
+
+    public void readExternal(ObjectInput in) 
+        throws IOException, ClassNotFoundException 
+    {
+        containerId = ContainerKey.read(in);
+    }
+
+
+	/**
+		Loggable methods
+	*/
+
+    /**
+       the default for prepared log is always null for all the operations
+       that don't have optionalData.  If an operation has optional data,
+       the operation need to prepare the optional data for this method.
+       
+       Encrypt Operation has no optional data to write out
+	*/
+    public ByteArray getPreparedLog()
+    {
+        return (ByteArray) null;
+    }
+
+    public void releaseResource(Transaction tran)
+    {
+        // no resources held to release.
+    }
+
+    /**
+       A space operation is a RAWSTORE log record
+    */
+    public int group()
+    {
+        return Loggable.RAWSTORE;
+    }
+
+
+    /**
+     * Check if this operation needs to be redone during recovery redo. 
+     * Returns true if this op should be redone during recovery redo,
+     * @param xact	the transaction that is doing the rollback
+     * @return  true, if this operation needs to be redone during recovery.       
+     * @exception StandardException Standard Derby error policy
+	*/
+	public boolean needsRedo(Transaction xact)
+		 throws StandardException
+	{
+        // this opeation should not be redone during recovery. Encrypted version
+        // of the container are synced to the disk when it is complete. In case 
+        // rollback containers are replaced with the origincal version. 
+        return false;
+	}
+
+
+    /**
+       Return my format identifier.
+    */
+    public int getTypeFormatId() {
+        return StoredFormatIds.LOGOP_ENCRYPT_CONTAINER;
+    }
+
+
+    /**
+     * Containers are not encryped on a redo. Nothing to do in this method.
+     * @param tran      transaction doing the operation.
+     * @param instant   log instant for this operation.
+     * @param in        unused by this log operation.
+     *
+     * @exception StandardException Standard Cloudscape error policy
+     */
+    public final void doMe(Transaction tran, LogInstant instant, 
+                           LimitObjectInput in)
+		 throws StandardException
+	{
+
+        // nothing to do here, containers are not encrypted on redo, 
+        // if confuring the database for encryption fails. it is  
+        // undone during  recovery. Encryption of the container is done 
+        // after the log record is flushed to the disk. 
+
+        releaseResource(tran);
+	}
+
+
+    /**
+       Undo of encrytpion of the container. Original version of the container
+       that existed before the start of the database encryption is put back.
+        
+       @param tran the transaction that is undoing this operation
+       @exception StandardException Standard Cloudscape error policy
+    */
+    public void undoMe(Transaction tran) throws StandardException
+    {
+        // restore the container to the state it was before the encrytpion.
+        BaseDataFileFactory bdff = 
+            (BaseDataFileFactory) ((RawTransaction) tran).getDataFactory();
+        EncryptData ed = new EncryptData(bdff);
+        ed.restoreContainer(containerId);
+        releaseResource(tran);
+
+	}
+
+	/**
+     * Generate a Compensation (EncryptContainerUndoOperation) that 
+     * will rollback the changes made to the container during container 
+     * encryption.
+     * @param tran	the transaction doing the compensating
+	 * @param in	optional input; not used by this operation.
+     * @exception StandardException Standard Cloudscape error policy
+     */
+    public Compensation generateUndo(Transaction tran, LimitObjectInput in)
+        throws StandardException
+    {
+        return new EncryptContainerUndoOperation(this);
+    }
+
+    /** debug */
+    public String toString()
+    {
+        if (SanityManager.DEBUG)
+        {
+            return  "Encrypt container " + containerId;
+        }
+        
+        return null;
+    }
+}

Propchange: db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptContainerOperation.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptContainerUndoOperation.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptContainerUndoOperation.java?rev=407366&view=auto
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptContainerUndoOperation.java (added)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptContainerUndoOperation.java Wed May 17 13:17:45 2006
@@ -0,0 +1,181 @@
+/*
+
+   Derby - Class org.apache.derby.impl.store.raw.data.EncryptContainerUndoOperation
+
+   Copyright 1998, 2006 The Apache Software Foundation or its licensors, as applicable.
+
+   Licensed 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.derby.impl.store.raw.data;
+
+import org.apache.derby.iapi.services.sanity.SanityManager;
+import org.apache.derby.iapi.services.io.StoredFormatIds;
+
+import org.apache.derby.iapi.store.raw.Compensation;
+import org.apache.derby.iapi.store.raw.Loggable;
+import org.apache.derby.iapi.store.raw.Transaction;
+import org.apache.derby.iapi.store.raw.Undoable;
+import org.apache.derby.iapi.util.ByteArray;
+import org.apache.derby.iapi.store.raw.log.LogInstant;
+import org.apache.derby.iapi.error.StandardException;
+
+import java.io.ObjectOutput;
+import java.io.ObjectInput;
+import java.io.IOException;
+import org.apache.derby.iapi.services.io.LimitObjectInput;
+
+/** A Encrypt Container undo operation rolls back the change of a 
+ *  Encrypt Container operation 
+ */
+public class EncryptContainerUndoOperation implements Compensation 
+{
+	// the operation to rollback 
+	transient private	EncryptContainerOperation undoOp;
+
+	/** During redo, the whole operation will be reconstituted from the log */
+
+	/** 
+     *	Set up a Encrypt Container undo operation during run time rollback
+     *  @param op Encrypt contaner operatation that is to be undone. 
+     */
+	public EncryptContainerUndoOperation(EncryptContainerOperation op) 
+	{
+		undoOp = op;
+	}
+
+	/*
+	 * Formatable methods
+	 */
+
+	// no-arg constructor, required by Formatable 
+	public EncryptContainerUndoOperation() { super(); }
+
+	public void writeExternal(ObjectOutput out) throws IOException 
+	{
+        // nothing to write.
+	}
+
+	/**
+		@exception IOException cannot read log record from log stream
+		@exception ClassNotFoundException cannot read ByteArray object
+	 */
+	public void readExternal(ObjectInput in) 
+		 throws IOException, ClassNotFoundException
+	{
+        // nothing to read.
+	}
+
+	/**
+		Return my format identifier.
+	*/
+	public int getTypeFormatId() {
+		return StoredFormatIds.LOGOP_ENCRYPT_CONTAINER_UNDO;
+	}
+
+	/** 
+		Compensation method
+	*/
+
+	/** Set up a Container undo operation during recovery redo. */
+	public void setUndoOp(Undoable op)
+	{
+		if (SanityManager.DEBUG) {
+			SanityManager.ASSERT(op instanceof EncryptContainerOperation);
+		}
+
+		undoOp = (EncryptContainerOperation)op;
+	}
+
+	/**
+		Loggable methods
+	*/
+
+    
+    /**
+     * Check if this operation needs to be redone during recovery redo. 
+     * Returns true if this op should be redone during recovery redo,
+     * @param xact	the transaction that is doing the rollback
+     * @return  true, if this operation needs to be redone during recovery.
+     * @exception StandardException Standard Derby error policy
+     */
+    public boolean needsRedo(Transaction xact)
+        throws StandardException
+    {
+        return true;
+    }
+
+    /**
+       the default for prepared log is always null for all the operations
+       that don't have optionalData.  If an operation has optional data,
+       the operation need to prepare the optional data for this method.
+
+       Encrypt Conatainer Undo Operation has no optional data to write out
+	*/
+    public ByteArray getPreparedLog()
+    {
+        return (ByteArray) null;
+    }
+
+
+    /** Apply the undo operation, in this implementation of the
+        RawStore, it can only call the undoMe method of undoOp
+        @param xact			the Transaction that is doing the rollback
+        @param instant		the log instant of this compenstaion operation
+        @param in			optional data
+        @exception IOException Can be thrown by any of the methods of ObjectInput.
+        @exception StandardException Standard Derby policy.
+
+        @see EncryptContainerOperation#generateUndo
+    */
+    public final void doMe(Transaction xact, LogInstant instant, 
+                           LimitObjectInput in) 
+        throws StandardException, IOException
+	{
+        undoOp.undoMe(xact);
+        releaseResource(xact);
+    }
+
+    /* make sure resource found in undoOp is released */
+    public void releaseResource(Transaction xact)
+	{
+        if (undoOp != null)
+            undoOp.releaseResource(xact);
+    }
+
+    /* Undo operation is a COMPENSATION log operation */
+    public int group()
+    {
+        return Loggable.COMPENSATION | Loggable.RAWSTORE;
+    }
+
+    /**
+	  DEBUG: Print self.
+	*/
+    public String toString()
+    {
+        if (SanityManager.DEBUG)
+        {
+            String str = "CLR (Encrypt Container Undo): " ;
+            if (undoOp != null)
+                str += undoOp.toString();
+            else
+                str += "undo Operation not set";
+
+            return str;
+        }
+        else
+            return null;
+    }
+}

Propchange: db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptContainerUndoOperation.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptData.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptData.java?rev=407366&view=auto
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptData.java (added)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptData.java Wed May 17 13:17:45 2006
@@ -0,0 +1,348 @@
+/*
+
+   Derby - Class org.apache.derby.impl.store.raw.data.EncryptData
+
+   Copyright 1999, 2006 The Apache Software Foundation or its licensors, as applicable.
+
+   Licensed 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.derby.impl.store.raw.data;
+import org.apache.derby.iapi.reference.SQLState;
+import org.apache.derby.iapi.services.context.ContextManager;
+import org.apache.derby.iapi.services.daemon.Serviceable;
+import org.apache.derby.iapi.services.sanity.SanityManager;
+import org.apache.derby.iapi.error.StandardException;
+import org.apache.derby.iapi.store.raw.data.RawContainerHandle;
+import org.apache.derby.iapi.store.raw.ContainerKey;
+import org.apache.derby.iapi.store.raw.LockingPolicy;
+import org.apache.derby.iapi.store.raw.Transaction;
+import org.apache.derby.iapi.store.raw.xact.RawTransaction;
+import org.apache.derby.iapi.store.raw.ContainerHandle;
+import org.apache.derby.iapi.store.access.TransactionController;
+
+import org.apache.derby.io.StorageFactory;
+import org.apache.derby.io.StorageFile;
+
+/**
+ * This class is used to encrypt all the containers in the data segment with a 
+ * new encryption key when password/key is changed or when an existing database 
+ * is reconfigured for encryption. 
+ *  
+ * Encryption of existing data in the data segments is done by doing the 
+ * following:
+ *  Find all the containers in data segment (seg0) and encrypt all of them
+ *  with the new  encryption key, the process for each container is:
+ *   1.Write a log record to indicate that the container is getting encrypted. 
+ *   2.Read all the pages of the container through the page cache and
+ *       encrypt each page with new encryption key and then write to a 
+ *       temporary file(n<cid>.dat) in the data segment itself.
+ *   3.	Rename the current container file (c<cid>.dat) to 
+ *                                         another file (o<cid>.dat)
+ *   4.	Rename the new encrypted version of the file (n<cid).dat) to be 
+ *                                    the current container file (c<cid>.dat).
+ *   5.	Submit a post commit work to remove the old version of 
+ *                                      the container (o<cid>.dat) file. 
+ *   
+ * 	@author  Suresh Thalamati
+ */
+
+public class EncryptData {
+
+    private BaseDataFileFactory dataFactory;
+    private StorageFactory storageFactory;
+
+	public EncryptData(BaseDataFileFactory dataFactory) {
+		this.dataFactory = dataFactory;
+        this.storageFactory = dataFactory.getStorageFactory();
+	}
+
+
+    /*
+     * Find all the all the containers stored in the data directory and 
+     * encrypt them.
+     * @param t the transaction that is used to configure the database 
+     *          with new encryption properties.
+     * @exception StandardException Standard Derby error policy
+	 */
+	public void encryptAllContainers(RawTransaction t) 
+        throws StandardException {
+
+        /*
+		 * List of containers that needs to be encrypted are identified by 
+		 * simply reading the list of files in seg0. 
+		 */
+
+		String[] files = dataFactory.getContainerNames();
+		if (files != null) {
+            StorageFile[] oldFiles = new StorageFile[files.length];
+            int count = 0;
+			long segmentId = 0;
+
+            // loop through all the files in seg0 and 
+            // encrypt all valid containers.
+			for (int f = files.length-1; f >= 0 ; f--) {
+				long containerId;
+				try	{
+					containerId = 
+						Long.parseLong(files[f].substring(1, 
+                                       (files[f].length() -4)), 16);
+				}
+				catch (Throwable th)
+				{
+                    // ignore errors from parse, it just means 
+                    // that someone put a file in seg0 that we 
+                    // didn't expect.  Continue with the next one.
+					continue;
+				}
+
+				ContainerKey ckey = new ContainerKey(segmentId, 
+                                                     containerId);
+                oldFiles[count++] = encryptContainer(t, ckey);
+			}
+
+            // remove all the old versions of the 
+            // container files on post-commit.
+            Serviceable removeOldFiles = new RemoveFiles(oldFiles, count);
+            t.addPostCommitWork(removeOldFiles);
+            
+		} else
+		{
+			if (SanityManager.DEBUG) 
+				SanityManager.THROWASSERT("encryption process is unable to" +
+                                          "read container names in seg0");
+		}
+
+    }
+
+
+	/** Encrypt a container.
+     * @param t    the transaction that is used to configure the database 
+     *             with new encryption properties.
+     * @param ckey the key of the container that is being encrypted.
+     * @return     file handle to the old copy  of the container.
+     * @exception StandardException Standard Derby error policy
+     */
+	private StorageFile encryptContainer(RawTransaction  t, 
+                                         ContainerKey    ckey)
+        throws StandardException
+	{
+
+        LockingPolicy cl = 
+            t.newLockingPolicy(
+                               LockingPolicy.MODE_CONTAINER,
+                               TransactionController.ISOLATION_SERIALIZABLE, 
+                               true);
+		
+        if (SanityManager.DEBUG )
+            SanityManager.ASSERT(cl != null);
+
+        RawContainerHandle containerHdl = (RawContainerHandle)
+            t.openContainer(ckey, cl, ContainerHandle.MODE_FORUPDATE);
+
+        if (SanityManager.DEBUG )
+            SanityManager.ASSERT(containerHdl != null);
+
+        EncryptContainerOperation lop = 
+            new EncryptContainerOperation(containerHdl);
+        t.logAndDo(lop);
+        
+        // flush the log to reduce the window between where
+        // the encrypted container is created & synced and the 
+        // log record for it makes it to disk. if we fail during 
+        // encryption of the container, log record will make sure 
+        // container is restored to the original state and 
+        // any temporary files are cleaned up. 
+        dataFactory.flush(t.getLastLogInstant());
+
+        // encrypt the container.
+        String newFilePath = getFilePath(ckey, false);
+        StorageFile newFile = storageFactory.newStorageFile(newFilePath);
+        containerHdl.encryptContainer(newFilePath);
+        containerHdl.close();
+
+                    
+        /*
+         * Replace the current container file with the new container file after
+         * keeping a copy of the current container file, it will be removed on 
+         * post-commit or on a rollback this copy will be replace the container 
+         * file to bring the database back to the state before encryption 
+         * process started.  
+         */
+
+        // discard pages in the cache related to this container. 
+        if (!dataFactory.getPageCache().discard(ckey)) {
+            if (SanityManager.DEBUG )
+                SanityManager.THROWASSERT("unable to discard pages releated to " + 
+                                          "container " + ckey  + 
+                                          " from the page cache");
+        }
+
+
+        // get rid of the container entry from conatainer cache
+        if (!dataFactory.getContainerCache().discard(ckey)) {
+            if (SanityManager.DEBUG )
+                SanityManager.THROWASSERT("unable to discard a container " + 
+                                          ckey + " from the container cache");
+        }
+
+        StorageFile currentFile =  dataFactory.getContainerPath(ckey , false);
+        StorageFile oldFile = getFile(ckey, true);
+
+        if (!currentFile.renameTo(oldFile)) {
+                throw StandardException.
+                    newException(SQLState.RAWSTORE_ERROR_RENAMING_FILE,
+                                 currentFile, oldFile);
+            }
+
+        // now replace current container file with the new file. 
+        if (!newFile.renameTo(currentFile)) {
+            throw StandardException.
+                newException(SQLState.RAWSTORE_ERROR_RENAMING_FILE,
+                             newFile, currentFile);
+                
+        }
+
+        return oldFile ;
+    }
+
+    
+    /**
+     * Get file handle to a container file that is used to keep 
+     * temporary versions of the container file.  
+     */
+    private StorageFile getFile(ContainerKey containerId, boolean old) {
+        String path = getFilePath(containerId, old);
+        return storageFactory.newStorageFile(getFilePath(containerId, 
+                                                         old));
+    }
+
+    /**
+     * Get path to a container file that is used to keep temporary versions of
+     * the container file.  
+     */
+    private String getFilePath(ContainerKey containerId, boolean old) {
+        StringBuffer sb = new StringBuffer("seg");
+        sb.append(containerId.getSegmentId());
+        sb.append(storageFactory.getSeparator());
+        sb.append(old ? 'o' : 'n');
+        sb.append(Long.toHexString(containerId.getContainerId()));
+        sb.append(".dat");
+        return sb.toString();
+    }
+
+    /* Restore the contaier to the state it was before 
+     * it was encrypted with new encryption key. This function is 
+     * called during undo of the EncryptContainerOperation log record 
+     * incase of a error/crash before database was successfuly configured with
+     * new encryption properties.
+     * @param ckey the key of the container that needs to be restored.
+     * @exception StandardException Standard Derby error policy
+     */
+    void restoreContainer(ContainerKey containerId) 
+        throws StandardException 
+    {
+
+        // get rid of the container entry from conatainer cache,
+        // this will make sure there are no file opens on the current 
+        // container file. 
+        
+        if (!dataFactory.getContainerCache().discard(containerId)) {
+            if (SanityManager.DEBUG )
+                SanityManager.THROWASSERT(
+                  "unable to discard  container from cache:" + 
+                  containerId);
+        }
+
+        StorageFile currentFile = dataFactory.getContainerPath(containerId, 
+                                                               false);
+        StorageFile oldFile = getFile(containerId, true);
+        StorageFile newFile = getFile(containerId, false);
+        
+        // if backup of the original container file exists, replace the 
+        // container with the backup copy.
+        if (oldFile.exists()) {
+            if (currentFile.exists()) {
+                // rename the current container file to be the new file.
+                if (!currentFile.renameTo(newFile)) {
+                    throw StandardException.
+                        newException(SQLState.RAWSTORE_ERROR_RENAMING_FILE,
+                                     currentFile, newFile);
+                }
+            }
+
+            if (!oldFile.renameTo(currentFile)) {
+                throw StandardException.
+                    newException(SQLState.RAWSTORE_ERROR_RENAMING_FILE,
+                                 oldFile, currentFile);
+            }
+        }
+
+        // if the new copy of the container file exists, remove it.
+        if (newFile.exists()) {
+
+            if (!newFile.delete())
+                throw StandardException.newException(
+                                                 SQLState.UNABLE_TO_DELETE_FILE, 
+                                                 newFile);
+        }
+    }
+}
+
+
+/**
+ * This is a helper class to remove old versions of the 
+ * container files during  the post-commit of the transaction 
+ * that is used to configure database with new encryption properties.
+ */
+class RemoveFiles implements Serviceable 
+{
+	private StorageFile filesToGo[];
+    private int noFiles = 0 ;
+
+	RemoveFiles(StorageFile filesToGo[], int size) {
+        this.filesToGo = filesToGo;
+        this.noFiles = size;
+	}
+
+	public int performWork(ContextManager context)
+        throws StandardException  {
+        
+        for (int i = 0; i < noFiles; i++) {
+            if (filesToGo[i].exists())
+            {
+                if (!filesToGo[i].delete())
+                {
+                    throw StandardException.newException(
+                    SQLState.FILE_CANNOT_REMOVE_FILE, filesToGo[i]);
+                }
+            }
+            
+        }
+        return Serviceable.DONE;
+    }
+
+
+	public boolean serviceASAP() {
+		return false;
+	}
+
+    /**
+     * delete the files immediately during the post commit.
+     * @return true, this work needs to done on user thread. 
+     */
+	public boolean serviceImmediately()	{
+		return true;
+	}	
+}

Propchange: db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/EncryptData.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/FileContainer.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/FileContainer.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/FileContainer.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/FileContainer.java Wed May 17 13:17:45 2006
@@ -2983,7 +2983,7 @@
 
 
 	/** 
-	 *  Get a latched page to write to the backup. Page Latch is necessary to 
+	 *  Get a latched page. Incase of backup page Latch is necessary to 
 	 *  prevent modification to the page when it is being written to the backup.
 	 *  Backup process relies on latches to get consistent snap
 	 *  shot of the page , user level table/page/row locks are NOT 
@@ -2994,7 +2994,7 @@
      *  @return the latched page
 	 *	@exception StandardException Standard Derby error policy
 	 */
-	protected BasePage getPageForBackup(BaseContainerHandle handle, 
+	protected BasePage getLatchedPage(BaseContainerHandle handle, 
                                         long pageNumber) 
 		throws StandardException 
 	{
@@ -3173,7 +3173,8 @@
 	 */
 	protected byte[] encryptPage(byte[] pageData, 
                                  int pageSize, 
-                                 byte[] encryptionBuffer)
+                                 byte[] encryptionBuffer,
+                                 boolean newEngine)
         throws StandardException
 	{
 		// because all our page header looks identical, move the
@@ -3184,7 +3185,7 @@
 		System.arraycopy(pageData, 0, encryptionBuffer, 8, pageSize-8);
 
 		int len = dataFactory.encrypt(encryptionBuffer, 0, pageSize,
-									  encryptionBuffer, 0);
+									  encryptionBuffer, 0, newEngine);
 
         if (SanityManager.DEBUG)
     		SanityManager.ASSERT(len == pageSize,

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/InputStreamContainer.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/InputStreamContainer.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/InputStreamContainer.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/InputStreamContainer.java Wed May 17 13:17:45 2006
@@ -250,4 +250,19 @@
                 SQLState.STORE_FEATURE_NOT_IMPLEMENTED);
 	}
 
+
+    /**
+     * Encrypt the container.  There is no support to encrypt 
+     * this type of containers. 
+     * 
+     * @exception StandardException Standard Derby error policy 
+     */
+	protected void encryptContainer(BaseContainerHandle handle, 
+                                    String newFilePath)
+	    throws StandardException
+	{
+        throw StandardException.newException(
+                SQLState.STORE_FEATURE_NOT_IMPLEMENTED);
+	}
+
 }

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/RAFContainer.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/RAFContainer.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/RAFContainer.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/RAFContainer.java Wed May 17 13:17:45 2006
@@ -394,7 +394,8 @@
 
 				byte[] dataToWrite = updatePageArray(pageNumber, 
                                                      pageData, 
-                                                     encryptionBuf);
+                                                     encryptionBuf, 
+                                                     false);
 
 				dataFactory.writeInProgress();
 				try
@@ -466,7 +467,8 @@
      */
     private byte[] updatePageArray(long pageNumber, 
                                    byte[] pageData, 
-                                   byte[] encryptionBuf) 
+                                   byte[] encryptionBuf, 
+                                   boolean encryptWithNewEngine) 
         throws StandardException, IOException
     {
         if (pageNumber == FIRST_ALLOC_PAGE_NUMBER)
@@ -489,9 +491,12 @@
 
         } else 
         {
-            if (dataFactory.databaseEncrypted()) 
+            if (dataFactory.databaseEncrypted() || encryptWithNewEngine) 
            {
-                return encryptPage(pageData, pageSize, encryptionBuf);
+                return encryptPage(pageData, 
+                                   pageSize, 
+                                   encryptionBuf, 
+                                   encryptWithNewEngine);
             } else
                 return pageData;
         }
@@ -1159,7 +1164,7 @@
                     // to the backup location by reading through the page cache.
                     for (long pageNumber = FIRST_ALLOC_PAGE_NUMBER; 
                          pageNumber <= lastPageNumber; pageNumber++) {
-                        page = getPageForBackup(handle, pageNumber);
+                        page = getLatchedPage(handle, pageNumber);
                         
                         // update the page array before writing to the disk 
                         // with container header and encrypt it if the database 
@@ -1167,7 +1172,7 @@
                         
                         byte[] dataToWrite = updatePageArray(pageNumber, 
                                                              page.getPageArray(), 
-                                                             encryptionBuf);
+                                                             encryptionBuf, false);
                         backupRaf.write(dataToWrite, 0, pageSize);
 
                         // unlatch releases page from cache, see 
@@ -1245,6 +1250,77 @@
             }
         }
     }
+
+
+
+
+    /**
+     * Create encrypted version of the  container with the 
+     * user specified encryption properties. 
+     * 
+     * Read all the pages of the container from the original container 
+     * through the page cache, encrypt each page data with new encryption 
+     * mechanism and  write to the specified container file.
+     *
+     * @param handle the container handle.
+     * @param newFilePath file to store the new encrypted version of 
+     *                    the container
+     * @exception StandardException Derby Standard error policy
+     *
+     */
+    protected void encryptContainer(BaseContainerHandle handle, 
+                                    String newFilePath)	
+        throws StandardException 
+    {
+        BasePage page = null; 
+        StorageFile newFile = 
+            dataFactory.getStorageFactory().newStorageFile(newFilePath);
+        try {
+            long lastPageNumber= getLastPageNumber(handle);
+ 
+            StorageRandomAccessFile newRaf = newFile.getRandomAccessFile("rw");
+
+            byte[] encryptionBuf = null;
+            encryptionBuf = new byte[pageSize];
+
+            // copy all the pages from the current container to the 
+            // new container file after encryting the pages. 
+            for (long pageNumber = FIRST_ALLOC_PAGE_NUMBER; 
+                 pageNumber <= lastPageNumber; pageNumber++) 
+            {
+
+                page = getLatchedPage(handle, pageNumber);
+                        
+                // update the page array before writing to the disk 
+                // with container header and encrypt it.
+                        
+                byte[] dataToWrite = updatePageArray(pageNumber, 
+                                                     page.getPageArray(), 
+                                                     encryptionBuf, 
+                                                     true);
+                newRaf.write(dataToWrite, 0, pageSize);
+
+                // unlatch releases page from cache.
+                page.unlatch();
+                page = null;
+            }
+
+            newRaf.close();
+            
+        }catch (IOException ioe) {
+            throw StandardException.newException(
+                                    SQLState.FILE_CONTAINER_EXCEPTION, 
+                                    ioe, 
+                                    newFile);
+        } finally {
+
+            if (page != null) {
+                page.unlatch();
+                page = null;
+            }
+        }
+    }
+
 
 
      // PrivilegedExceptionAction method

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/StreamFileContainer.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/StreamFileContainer.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/StreamFileContainer.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/data/StreamFileContainer.java Wed May 17 13:17:45 2006
@@ -633,7 +633,7 @@
 				}
 
 				dataFactory.encrypt(
-                    out.getByteArray(), startByte, encryptedLen, ciphertext, 0);
+                    out.getByteArray(), startByte, encryptedLen, ciphertext, 0, false);
 
 				// write out the actual length, then the encrypted bytes.
 				CompressedNumber.writeInt(fileOut, realLen);

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/log/LogToFile.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/log/LogToFile.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/log/LogToFile.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/log/LogToFile.java Wed May 17 13:17:45 2006
@@ -2876,11 +2876,6 @@
 												   DEFAULT_LOG_BUFFER_SIZE);
 		jbmsVersion = Monitor.getMonitor().getEngineVersion();
 
-		String dataEncryption = 
-            startParams.getProperty(Attribute.DATA_ENCRYPTION);
-
-		databaseEncrypted = Boolean.valueOf(dataEncryption).booleanValue();
-
 		
 		String logArchiveMode = 
             startParams.getProperty(Property.LOG_ARCHIVE_MODE);
@@ -3959,6 +3954,27 @@
 		return databaseEncrypted;
 	}
 
+
+    /*
+     * Set that the database is encrypted, all the data in the 
+     * transaction log  should be encrypted. 
+     */
+    public  void setDatabaseEncrypted() 
+    {
+        databaseEncrypted = true;
+    }
+
+    /*
+     * setup log for encryption. 
+     */
+    public  void setupLogEncryption() throws StandardException
+    {
+        // switch the database to a new log file, so that 
+        // new encrytion will start on new log file. 
+        switchLogFile();
+    }
+
+
 	/**
 		@see RawStoreFactory#encrypt
 		@exception StandardException Standard Cloudscape Error Policy
@@ -3967,7 +3983,8 @@
 						  byte[] ciphertext, int outputOffset)
 		 throws StandardException
 	{
-		return rawStoreFactory.encrypt(cleartext, offset, length, ciphertext, outputOffset);
+        return rawStoreFactory.encrypt(cleartext, offset, length, 
+                                       ciphertext, outputOffset, false);
 	}
 
 	/**

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/log/ReadOnly.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/log/ReadOnly.java?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/log/ReadOnly.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/store/raw/log/ReadOnly.java Wed May 17 13:17:45 2006
@@ -354,4 +354,21 @@
 	{
 		// nothing to do for read only databases.
 	}
+
+    /*
+     * Set that the database is encrypted. Read-only database can not 
+     * be reencrypted, nothing to do in this case. 
+     */
+    public void setDatabaseEncrypted() {
+
+        // nothing to do for a read-only database.
+    }
+
+    /*
+     * setup log for encryption. Read-only database can not 
+     * be reencrypted, nothing to do in this case. 
+     */
+    public void setupLogEncryption() throws StandardException {
+        // nothing to do for a read-only database. 
+    }
 }

Added: db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/encryptDatabaseTest1.out
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/encryptDatabaseTest1.out?rev=407366&view=auto
==============================================================================
--- db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/encryptDatabaseTest1.out (added)
+++ db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/encryptDatabaseTest1.out Wed May 17 13:17:45 2006
@@ -0,0 +1,96 @@
+ij> -- This script tests configuring an un-enctypted database for encryption. 
+disconnect;
+ij> ---test configure the database for encrypion with encryption key.
+connect 'wombat_key;create=true';
+ij> create table t1(a int ) ;
+0 rows inserted/updated/deleted
+ij> insert into t1 values(1) ;
+1 row inserted/updated/deleted
+ij> insert into t1 values(2) ;
+1 row inserted/updated/deleted
+ij> insert into t1 values(3) ;
+1 row inserted/updated/deleted
+ij> insert into t1 values(4) ;
+1 row inserted/updated/deleted
+ij> insert into t1 values(5) ;
+1 row inserted/updated/deleted
+ij> disconnect;
+ij> connect 'wombat_key;shutdown=true';
+ERROR 08006: Database 'wombat_key' shutdown.
+ij> -- configure the database for encrypion with external encryption key.
+connect 'jdbc:derby:wombat_key;dataEncryption=true;encryptionKey=61626364656667686961626364656568';
+ij> select * from t1;
+A          
+-----------
+1          
+2          
+3          
+4          
+5          
+ij> insert into t1 values(6);
+1 row inserted/updated/deleted
+ij> insert into t1 values(7);
+1 row inserted/updated/deleted
+ij> disconnect;
+ij> connect 'wombat_key;shutdown=true';
+ERROR 08006: Database 'wombat_key' shutdown.
+ij> connect 'jdbc:derby:wombat_key;encryptionKey=61626364656667686961626364656568';
+ij> select * from t1 ;
+A          
+-----------
+1          
+2          
+3          
+4          
+5          
+6          
+7          
+ij> disconnect;
+ij> connect 'wombat_key;shutdown=true';
+ERROR 08006: Database 'wombat_key' shutdown.
+ij> -- test confugring the database for encrypion with a boot password. 
+connect 'wombat_pwd;create=true';
+ij> create table t2(a int ) ;
+0 rows inserted/updated/deleted
+ij> insert into t2 values(1) ;
+1 row inserted/updated/deleted
+ij> insert into t2 values(2) ;
+1 row inserted/updated/deleted
+ij> insert into t2 values(3) ;
+1 row inserted/updated/deleted
+ij> insert into t2 values(4) ;
+1 row inserted/updated/deleted
+ij> insert into t2 values(5) ;
+1 row inserted/updated/deleted
+ij> disconnect;
+ij> connect 'wombat_pwd;shutdown=true';
+ERROR 08006: Database 'wombat_pwd' shutdown.
+ij> ---configure the database for encrypion with a boot password.
+connect 'jdbc:derby:wombat_pwd;dataEncryption=true;bootPassword=xyz1234abc';
+ij> select * from t2;
+A          
+-----------
+1          
+2          
+3          
+4          
+5          
+ij> insert into t2 values(6);
+1 row inserted/updated/deleted
+ij> insert into t2 values(7);
+1 row inserted/updated/deleted
+ij> disconnect;
+ij> connect 'wombat_pwd;shutdown=true';
+ERROR 08006: Database 'wombat_pwd' shutdown.
+ij> connect 'jdbc:derby:wombat_pwd;bootPassword=xyz1234abc';
+ij> select * from t2 ;
+A          
+-----------
+1          
+2          
+3          
+4          
+5          
+6          
+7          
+ij> 

Propchange: db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/encryptDatabaseTest1.out
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/suites/encryptionAll.runall
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/suites/encryptionAll.runall?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/suites/encryptionAll.runall (original)
+++ db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/suites/encryptionAll.runall Wed May 17 13:17:45 2006
@@ -1,3 +1,4 @@
 store/aes.sql
 store/encryptParams.sql
 store/encryptionKey.sql
+store/encryptDatabaseTest1.sql

Modified: db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/copyfiles.ant
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/copyfiles.ant?rev=407366&r1=407365&r2=407366&view=diff
==============================================================================
--- db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/copyfiles.ant (original)
+++ db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/copyfiles.ant Wed May 17 13:17:45 2006
@@ -56,6 +56,8 @@
 default_derby.properties
 encryptDatabase.sql
 encryptDatabase_app.properties
+encryptDatabaseTest1.sql
+encryptDatabaseTest1_app.properties
 encryptParams.sql
 encryptParams_app.properties
 encryptionKey.sql

Added: db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/encryptDatabaseTest1.sql
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/encryptDatabaseTest1.sql?rev=407366&view=auto
==============================================================================
--- db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/encryptDatabaseTest1.sql (added)
+++ db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/encryptDatabaseTest1.sql Wed May 17 13:17:45 2006
@@ -0,0 +1,46 @@
+-- This script tests configuring an un-enctypted database for encryption. 
+
+disconnect;
+---test configure the database for encrypion with encryption key.
+connect 'wombat_key;create=true';
+create table t1(a int ) ;
+insert into t1 values(1) ;
+insert into t1 values(2) ;
+insert into t1 values(3) ;
+insert into t1 values(4) ;
+insert into t1 values(5) ;
+disconnect;
+connect 'wombat_key;shutdown=true';
+
+-- configure the database for encrypion with external encryption key.
+connect 'jdbc:derby:wombat_key;dataEncryption=true;encryptionKey=61626364656667686961626364656568';
+select * from t1;
+insert into t1 values(6);
+insert into t1 values(7);
+disconnect;
+connect 'wombat_key;shutdown=true';
+connect 'jdbc:derby:wombat_key;encryptionKey=61626364656667686961626364656568';
+select * from t1 ;
+disconnect;
+connect 'wombat_key;shutdown=true';
+
+-- test confugring the database for encrypion with a boot password. 
+connect 'wombat_pwd;create=true';
+create table t2(a int ) ;
+insert into t2 values(1) ;
+insert into t2 values(2) ;
+insert into t2 values(3) ;
+insert into t2 values(4) ;
+insert into t2 values(5) ;
+disconnect;
+connect 'wombat_pwd;shutdown=true';
+
+---configure the database for encrypion with a boot password.
+connect 'jdbc:derby:wombat_pwd;dataEncryption=true;bootPassword=xyz1234abc';
+select * from t2;
+insert into t2 values(6);
+insert into t2 values(7);
+disconnect;
+connect 'wombat_pwd;shutdown=true';
+connect 'jdbc:derby:wombat_pwd;bootPassword=xyz1234abc';
+select * from t2 ;

Propchange: db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/encryptDatabaseTest1.sql
------------------------------------------------------------------------------
    svn:eol-style = native

Added: db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/encryptDatabaseTest1_app.properties
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/encryptDatabaseTest1_app.properties?rev=407366&view=auto
==============================================================================
--- db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/encryptDatabaseTest1_app.properties (added)
+++ db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/encryptDatabaseTest1_app.properties Wed May 17 13:17:45 2006
@@ -0,0 +1,4 @@
+usedefaults=true
+# Temporarily disabling the securiy manager for  this  new test
+# related to DERBY-1156 (reencrypt database ) work in progress. 
+noSecurityManager=true

Propchange: db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/encryptDatabaseTest1_app.properties
------------------------------------------------------------------------------
    svn:eol-style = native



Mime
View raw message