]> hydra-www.ietfng.org Git - android-vcpass-oisafe/commitdiff
Major refactoring; sorry for the mess main
authorNathaniel Wesley Filardo <nwf@pf.priv.oc.ietfng.org>
Fri, 23 Jul 2010 06:22:36 +0000 (02:22 -0400)
committerNathaniel Wesley Filardo <nwf@pf.priv.oc.ietfng.org>
Fri, 23 Jul 2010 06:22:36 +0000 (02:22 -0400)
26 files changed:
build.properties
res/layout-land/front_door.xml
res/layout/chg_pass.xml
res/layout/front_door.xml
res/values/strings.xml
src/org/openintents/safe/AskPassword.java
src/org/openintents/safe/Backup.java
src/org/openintents/safe/CategoryList.java
src/org/openintents/safe/ChangePass.java
src/org/openintents/safe/CryptoContentProvider.java
src/org/openintents/safe/DBHelper.java
src/org/openintents/safe/IntentHandler.java
src/org/openintents/safe/LogOffActivity.java
src/org/openintents/safe/PassList.java
src/org/openintents/safe/Passwords.java
src/org/openintents/safe/Preferences.java
src/org/openintents/safe/Restore.java
src/org/openintents/safe/RestoreDataSet.java
src/org/openintents/safe/RestoreHandler.java
src/org/openintents/safe/RuntimeSecrets.java [deleted file]
src/org/openintents/safe/service/ServiceDispatch.aidl
src/org/openintents/safe/service/ServiceDispatchImpl.java
src/org/openintents/util/Base64.java [new file with mode: 0644]
src/org/openintents/util/FrontDooringActivity.java
src/org/openintents/util/FrontDooringListActivity.java
src/org/openintents/util/VCPassUtils.java [new file with mode: 0644]

index 3fb0478a78c8f7b809449e92d449c074deab1e06..45e4b69eed4e578cda2d1cd4d73517f36a53e3e3 100644 (file)
@@ -52,8 +52,8 @@ android.dx=dx.bat
 android.jar=android.jar\r
 \r
 ### Linux\r
-# android.sdk=/opt/tools/javame/android-sdk_m5-rc15_linux-x86\r
-android.aapt=aapt\r
-android.aidl=aidl\r
-android.dx=dx\r
-android.jar=android.jar\r
+android.sdk=/home/nwf/src/android-sdk-linux_86\r
+android.aapt=aapt\r
+android.aidl=aidl\r
+android.dx=dx\r
+android.jar=android.jar\r
index e8204fe30858b95aac8f6bc098a4492c469c7fe4..efa2c6414651da0aec6be8ef3a9fb37542673b3a 100644 (file)
                android:layout_width="wrap_content"\r
                android:layout_height="wrap_content" /> \r
 \r
+       <Button android:id="@+id/vcpass_button" \r
+               android:visibility="gone" \r
+               android:text="@string/vcpass_ask"\r
+        android:layout_below="@id/pass_confirm"\r
+        android:layout_alignParentRight="true"\r
+               android:layout_width="wrap_content"\r
+               android:layout_height="wrap_content" /> \r
+\r
        <Button android:id="@+id/restore_button" \r
                android:visibility="gone" \r
                android:text="@string/restore"\r
@@ -75,4 +83,4 @@
                android:layout_height="wrap_content" /> \r
 </LinearLayout>\r
 </ScrollView>\r
-       
\ No newline at end of file
+       \r
index 2823562d33ce1cb54720131072c8bcf5711dc4e4..2f2bfa7a91b76e0eae32070217ac79064fc6aa35 100644 (file)
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
 
+       <!-- Will be populated programmatically -->
+       <RadioGroup android:id="@+id/change_vc_mode"
+               android:layout_width="wrap_content"
+               android:layout_height="wrap_content"/>
+
        <Button android:id="@+id/change_password_button" 
                android:text="@string/change_password"
                android:layout_width="wrap_content"
index 6c3ec4572326095290718eac92b4e7b682451705..176ccad89e340d091ffbcad02b755717b51f26f7 100644 (file)
     android:layout_height="wrap_content"\r
     android:scrollbars="vertical">\r
 \r
-<LinearLayout\r
+<RelativeLayout\r
        android:orientation="vertical" android:layout_width="fill_parent"\r
        android:layout_height="fill_parent">\r
-        <LinearLayout android:layout_width="wrap_content" \r
+        <LinearLayout \r
+        android:id="@+id/ask_header"\r
+        android:layout_width="wrap_content" \r
                android:layout_height="wrap_content"\r
                android:orientation="horizontal"\r
                android:layout_gravity="center"\r
        </LinearLayout>\r
        <TextView android:id="@+id/first_time"\r
                android:text="@string/first_time" \r
+        android:layout_below="@id/ask_header"\r
                android:paddingBottom="10px"\r
                android:visibility="gone" \r
                android:layout_width="fill_parent"\r
                android:layout_height="wrap_content" /> \r
     <TextView android:id="@+id/remote"\r
                android:text="@string/remote_ask" \r
+        android:layout_below="@id/first_time"\r
                android:paddingBottom="10px"\r
                android:visibility="gone" \r
                android:layout_width="fill_parent"\r
                android:layout_height="wrap_content" />\r
 \r
        <EditText android:id="@+id/password" \r
+        android:layout_below="@id/remote"\r
                android:inputType="textPassword"\r
                android:hint="@string/master_password"\r
                android:layout_width="fill_parent"\r
                android:layout_height="wrap_content" />\r
 \r
        <EditText android:id="@+id/pass_confirm"\r
+        android:layout_below="@id/password"\r
                android:visibility="gone" \r
                android:inputType="textPassword"\r
                android:hint="@string/confirm"\r
        <Button android:id="@+id/continue_button" \r
                android:text="@string/continue_text"\r
                android:layout_width="wrap_content"\r
+        android:layout_below="@id/pass_confirm"\r
+        android:layout_alignParentLeft="true"\r
+               android:layout_height="wrap_content" /> \r
+       <Button android:id="@+id/vcpass_button" \r
+               android:visibility="gone" \r
+               android:text="@string/vcpass_ask"\r
+        android:layout_below="@id/pass_confirm"\r
+        android:layout_alignParentRight="true"\r
+               android:layout_width="wrap_content"\r
                android:layout_height="wrap_content" /> \r
        <Button android:id="@+id/restore_button" \r
                android:visibility="gone" \r
                android:text="@string/restore"\r
+        android:layout_below="@id/continue_button"\r
                android:layout_width="wrap_content"\r
                android:layout_height="wrap_content" /> \r
-</LinearLayout>\r
+</RelativeLayout>\r
 </ScrollView>\r
index 3c6362a313d6feff37f0400dca500b15854465c1..1237823ed499b0f4c96494bec0550f7f80f6f71f 100644 (file)
@@ -266,4 +266,11 @@ Current version: %s
     </string-array>\r
 \r
         \r
+    <string name="vcpass_ask">Continue with Visual Challenge</string>\r
+    <string name="vcpass_fail">Visual Challenge Error</string>\r
+    <!-- <string name="vcpass_ena">Use Visual Challenges</string> -->
+       <string name="change_vc_disable">Don't Use Visual Challenges</string>
+       <string name="change_vc_nochange">Continue Using Visual Challenges</string>
+       <string name="change_vc_newseeds">Import New Visual Seeds</string>
+       <string name="change_vc_startseeds">Begin Using Visual Challenges</string>
 </resources>
index dce59375a0eeb19d774bf7e255f0f8918be575ec..6126cb67ca67f0e15355a5a096702604ddb3a4e3 100644 (file)
@@ -20,6 +20,10 @@ import java.io.File;
 import java.security.NoSuchAlgorithmException;
 
 import org.openintents.distribution.EulaActivity;
+import org.openintents.util.Base64;
+import org.openintents.util.FrontDooringActivity;
+import org.openintents.util.IntentUtils;
+import org.openintents.util.VCPassUtils;
 import org.openintents.util.VersionUtils;
 
 import android.app.Activity;
@@ -28,8 +32,11 @@ import android.app.Dialog;
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.content.SharedPreferences;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
 import android.media.MediaPlayer;
 import android.os.Bundle;
+import android.os.Parcelable;
 import android.preference.PreferenceManager;
 import android.util.Log;
 import android.view.Menu;
@@ -53,11 +60,15 @@ import android.widget.Toast;
  */
 public class AskPassword extends Activity {
 
-       private boolean debug = false;
+       private boolean debug = true;
        private static String TAG = "AskPassword";
        public static String EXTRA_IS_LOCAL = "org.openintents.safe.bundle.EXTRA_IS_REMOTE";
 
-    public static final int REQUEST_RESTORE = 0;
+    private static final int REQUEST_RESTORE = 0;
+       // Steady state presentation of stored challenges
+    private static final int REQUEST_VCPASS_CHALLENGE = 1;
+       // First time import -- provides both a challenge and a the seed keys
+    private static final int REQUEST_VCPASS_IMPORT = 2;
 
     // Menu Item order
     public static final int SWITCH_MODE_INDEX = Menu.FIRST;
@@ -76,9 +87,12 @@ public class AskPassword extends Activity {
        private String PBEKey;
        private String salt;
        private String masterKey;
-       private CryptoHelper ch;
        private boolean firstTime = false;
 
+       // VCPass state control
+       private String vc_seeds;                // used only on firstTime paths
+       private String vc_secret;               // used only on not-first-time paths
+
        // Keypad variables
        private String keypadPassword="";
        
@@ -100,7 +114,6 @@ public class AskPassword extends Activity {
 
                dbHelper = new DBHelper(this);
                        
-               ch = new CryptoHelper();
                if (dbHelper.needsUpgrade()) {
                        switch (dbHelper.fetchVersion()) {
                        case 2:
@@ -160,10 +173,57 @@ public class AskPassword extends Activity {
                                remoteAsk.setVisibility(View.VISIBLE);
                        }
                }
+               Button vcpassButton = (Button) findViewById(R.id.vcpass_button);
                Button continueButton = (Button) findViewById(R.id.continue_button);
+               if(firstTime) {
+                       final Intent i = new Intent(VCPassUtils.ACT_SEED_IMPORT);
+                       if (IntentUtils.isIntentAvailable(this, i)) {
+                               vcpassButton.setVisibility(View.VISIBLE);
+                               vcpassButton.setOnClickListener(new View.OnClickListener() {
+                                       public void onClick(View arg0) {
+                                               // Make sure password and confirm fields match before
+                                               // we import and initialize the VCPass system
+                                               if (pbeKey.getText().toString().compareTo(
+                                                       confirmPass.getText().toString()) != 0) {
+                                                       Toast.makeText(AskPassword.this,
+                                                                       R.string.confirm_pass_fail, Toast.LENGTH_SHORT)
+                                                                       .show();
+                                                       return;
+                                               }
+                                               startActivityForResult(i, REQUEST_VCPASS_IMPORT);
+                                       }
+                               });
+                       }
+               } else {
+                       final Intent i = new Intent(VCPassUtils.ACT_CHAL_PRESENT);
+                       String vc_chal_m64 = dbHelper.fetchVCChal();
+                       if (IntentUtils.isIntentAvailable(this, i)) {
+                               if(vc_chal_m64 != null && !"".equals(vc_chal_m64)) {
+                                       try{ 
+                                       byte[] vc_chal_m = Base64.decode(vc_chal_m64, Base64.URL_SAFE);
+                                       Bitmap vc_chal = BitmapFactory.decodeByteArray(
+                                                                                       vc_chal_m, 0, vc_chal_m.length);
+                                       i.putExtra("CHAL", vc_chal);
+                                       continueButton.setVisibility(View.INVISIBLE);
+                                       vcpassButton.setVisibility(View.VISIBLE);
+                                       vcpassButton.setOnClickListener(new View.OnClickListener() {
+                                               public void onClick(View arg0) {
+                                                       startActivityForResult(i, REQUEST_VCPASS_CHALLENGE);
+                                               }
+                                       });
+                                       } catch (java.io.IOException ioe) {
+                                               throw new RuntimeException(ioe);
+                                       }
+                               }
+                       } else if (vc_chal_m64 != null) {
+                               Toast.makeText(AskPassword.this,
+                                               R.string.vcpass_fail, Toast.LENGTH_SHORT)
+                                               .show();
+                               return;
+                       }
+               }
 
                continueButton.setOnClickListener(new View.OnClickListener() {
-
                        public void onClick(View arg0) {
                                PBEKey = pbeKey.getText().toString();
                                // For this version of CryptoHelper, we use the user-entered password.
@@ -175,74 +235,74 @@ public class AskPassword extends Activity {
                                        Toast.makeText(AskPassword.this, R.string.notify_blank_pass,
                                                        Toast.LENGTH_SHORT).show();
                                    Animation shake = AnimationUtils
-                               .loadAnimation(AskPassword.this, R.anim.shake);
-                               
+                           .loadAnimation(AskPassword.this, R.anim.shake);
+               
                                findViewById(R.id.password).startAnimation(shake);
                                        return;
                                }
 
-                               // If it's the user's first time to enter a password,
-                               // we have to store it in the database. We are going to
-                               // store an encrypted hash of the password.
-                               // Generate a master key, encrypt that with the pbekey
-                               // and store the encrypted master key in database.
-                               if (firstTime) {
-
-                                       // Make sure password and confirm fields match
-                                       if (pbeKey.getText().toString().compareTo(
-                                                       confirmPass.getText().toString()) != 0) {
-                                               Toast.makeText(AskPassword.this,
-                                                               R.string.confirm_pass_fail, Toast.LENGTH_SHORT)
-                                                               .show();
-                                               return;
-                                       }
-                                       try {
-                                               salt = CryptoHelper.generateSalt();
-                                               masterKey = CryptoHelper.generateMasterKey();
-                                       } catch (NoSuchAlgorithmException e1) {
-                                               e1.printStackTrace();
-                                               Toast.makeText(AskPassword.this,getString(R.string.crypto_error)
-                                                       + e1.getMessage(), Toast.LENGTH_SHORT).show();
-                                               return;
-                                       }
-                                       if (debug) Log.i(TAG, "Saving Password: " + masterKey);
-                                       try {
-                                               ch.init(CryptoHelper.EncryptionStrong,salt);
-                                               ch.setPassword(PBEKey);
-                                               String encryptedMasterKey = ch.encrypt(masterKey);
-                                               dbHelper.storeSalt(salt);
-                                               dbHelper.storeMasterKey(encryptedMasterKey);
-                                       } catch (CryptoHelperException e) {
-                                               Log.e(TAG, e.toString());
-                                               Toast.makeText(AskPassword.this,getString(R.string.crypto_error)
-                                                       + e.getMessage(), Toast.LENGTH_SHORT).show();
-                                               return;
-                                       }
-                               } else if (!checkUserPassword(PBEKey)) {
-                                       // Check the user's password and display a
-                                       // message if it's wrong
-                                       Toast.makeText(AskPassword.this, R.string.invalid_password,
-                                                       Toast.LENGTH_SHORT).show();
-                               Animation shake = AnimationUtils
-                               .loadAnimation(AskPassword.this, R.anim.shake);
-                               
-                               findViewById(R.id.password).startAnimation(shake);
+                               // Make sure password and confirm fields match
+                               if (firstTime && pbeKey.getText().toString().compareTo(
+                                               confirmPass.getText().toString()) != 0) {
+                                       Toast.makeText(AskPassword.this,
+                                                       R.string.confirm_pass_fail, Toast.LENGTH_SHORT)
+                                                       .show();
                                        return;
                                }
-                               gotPassword();
+
+                               normalTryPassword();
                        }
                });
        }
+
+       private void normalTryPassword() {
+               String fullpw = PBEKey;
+               if(vc_secret != null)
+                       fullpw += vc_secret;
+
+               // If it's the user's first time to enter a password,
+               // generate a master key, encrypt that with the pbekey
+               // and store the encrypted master key in database.
+               if (firstTime) {
+                       try {
+                               salt = CryptoHelper.generateSalt();
+                               masterKey = CryptoHelper.generateMasterKey();
+                       } catch (NoSuchAlgorithmException e1) {
+                               e1.printStackTrace();
+                               Toast.makeText(AskPassword.this,getString(R.string.crypto_error)
+                                       + e1.getMessage(), Toast.LENGTH_SHORT).show();
+                               return;
+                       }
+               } else if (!checkUserPassword(fullpw)) {
+                       // Check the user's password and display a
+                       // message if it's wrong
+                       Toast.makeText(AskPassword.this, R.string.invalid_password,
+                                       Toast.LENGTH_SHORT).show();
+               Animation shake = AnimationUtils
+               .loadAnimation(AskPassword.this, R.anim.shake);
+               
+               findViewById(R.id.password).startAnimation(shake);
+                       return;
+               }
+        
+               gotPassword(PBEKey, vc_secret);
+       }
+
        
-       private void gotPassword() {
+       private void gotPassword(String password, String vc_secret) {
                Intent callbackIntent = new Intent();
-               
-               // Return the master key to our caller.  We no longer need the
-               // user-entered PBEKey. The master key is used for everything
-               // from here on out.
+
+               // Return the master key to our caller.
                if (debug) Log.d(TAG,"calbackintent: masterKey="+masterKey+" salt="+salt);
                callbackIntent.putExtra("masterKey", masterKey);
                callbackIntent.putExtra("salt", salt);
+               callbackIntent.putExtra("pw", password);
+               if((vc_seeds != null) && (vc_secret == null))
+                       callbackIntent.putExtra("vcseeds", vc_seeds);
+               else if((vc_secret != null) && (vc_seeds == null))
+                       callbackIntent.putExtra("vcsecret", vc_secret);
+               else if((vc_secret != null) && (vc_seeds != null))
+                       throw new RuntimeException("AskPassword state machine violation: both vc");
                setResult(RESULT_OK, callbackIntent);
                
                finish();
@@ -264,27 +324,30 @@ public class AskPassword extends Activity {
 
                        public void onClick(View arg0) {
                                Intent restore = new Intent(AskPassword.this, Restore.class);
-                               restore.putExtra(Restore.KEY_FIRST_TIME, true);
+                               restore.putExtra(FrontDooringActivity.KEY_NO_IMMEDIATE, true);
                                startActivityForResult(restore,REQUEST_RESTORE);                
                        }
                });
        }
 
+/*
        @Override
        protected void onPause() {
                super.onPause();
 
                if (debug) Log.d(TAG, "onPause()");
 
-               if (dbHelper!=null) {
-                       dbHelper.close();
-                       dbHelper = null;
-               }
        }
+*/
 
        @Override
        public void onDestroy() {
                super.onDestroy();
+
+               if (dbHelper!=null) {
+                       dbHelper.close();
+                       dbHelper = null;
+               }
                
                if (debug) Log.d(TAG,"onDestroy()");
                keypadOnDestroy();
@@ -295,12 +358,9 @@ public class AskPassword extends Activity {
                super.onPause();
 
                if (debug) Log.d(TAG, "onResume()");
-               if (RuntimeSecrets.isSignedIn()) {
-                       if (debug) Log.d(TAG,"already signed in");
-                       Intent callbackIntent = new Intent();
-                       callbackIntent.putExtra("salt", RuntimeSecrets.getSalt());
-                       callbackIntent.putExtra("masterKey", RuntimeSecrets.getMasterKey());
-                       setResult(RESULT_OK, callbackIntent);
+               if (IntentHandler.isSignedIn()) {
+                       Log.w(TAG, "ALREADY SIGNED IN!?!");
+                       setResult(RESULT_OK, null);
                        finish();
                        return;
                }
@@ -388,6 +448,7 @@ public class AskPassword extends Activity {
                String encryptedMasterKey = dbHelper.fetchMasterKey();
                String decryptedMasterKey = "";
                if (debug) Log.d(TAG,"checkUserPassword: encryptedMasterKey="+encryptedMasterKey);
+               CryptoHelper ch = new CryptoHelper();
                try {
                        ch.init(CryptoHelper.EncryptionStrong,salt);
                        ch.setPassword(password);
@@ -407,12 +468,30 @@ public class AskPassword extends Activity {
     protected void onActivityResult(int requestCode, int resultCode, Intent i) {
        super.onActivityResult(requestCode, resultCode, i);
 
-       if ((requestCode== REQUEST_RESTORE) && (resultCode == RESULT_OK)) {
-               Log.d(TAG,"returning masterkey: "+RuntimeSecrets.getMasterKey());
-                       Intent callbackIntent = new Intent();
-                       callbackIntent.putExtra("salt", RuntimeSecrets.getSalt());
-                       callbackIntent.putExtra("masterKey", RuntimeSecrets.getMasterKey());
-                       setResult(RESULT_OK, callbackIntent);
+       if (((requestCode == REQUEST_VCPASS_IMPORT)
+                       || (requestCode == REQUEST_VCPASS_CHALLENGE))
+               && (resultCode == RESULT_OK)) {
+                       String error    = i.getStringExtra    ("ERR"  );
+                       char[] useed    = i.getCharArrayExtra ("USEED");
+                       char[] vseed    = i.getCharArrayExtra ("VSEED");
+                       if(error != null) {
+                               Log.e(TAG, error);
+                               Toast.makeText(AskPassword.this,
+                                               R.string.vcpass_fail, Toast.LENGTH_SHORT)
+                                    .show();
+                               return;
+                       }
+                       if(requestCode == REQUEST_VCPASS_IMPORT) {
+                               vc_seeds = VCPassUtils.encode_seeds(useed, vseed);
+                       } else {
+                               vc_secret = i.getStringExtra("SEQ");
+                       }
+           
+                       PBEKey = pbeKey.getText().toString();
+                       normalTryPassword();
+       } else if ((requestCode== REQUEST_RESTORE) && (resultCode == RESULT_OK)) {
+               if(debug) Log.d(TAG,"returning masterkey: "+i.getStringExtra("masterKey"));
+                       setResult(RESULT_OK, i);
                finish();
        }
     }
@@ -545,7 +624,7 @@ public class AskPassword extends Activity {
                        if (!mute) {
                                mpSuccessBeep.start();
                        }
-                       gotPassword();
+                       gotPassword(password, null);    // XXX NWF VC no vc with keypad
                }else{
                        if (debug) Log.d(TAG,"bad password");
                        if (!mute) {
index c9d7d6b86737534778e54867b4f14200fb5bc329..46ddde4ee19770ebe417f708a2a72019b45daa1d 100644 (file)
@@ -65,17 +65,35 @@ public class Backup {
             dateOut = dateFormatter.format(today);
 
             serializer.attribute(null, "date", dateOut);
-            
-                       String masterKeyEncrypted = Passwords.fetchMasterKeyEncrypted();
+
+                       DBHelper dbh = new DBHelper(myCtx);
+
                        serializer.startTag(null, "MasterKey");
-                       serializer.text(masterKeyEncrypted);
+                       serializer.text(dbh.fetchMasterKey());  // Encrypted
                        serializer.endTag(null, "MasterKey");
 
-                       String salt = Passwords.fetchSalt();
                        serializer.startTag(null, "Salt");
-                       serializer.text(salt);
+                       serializer.text(dbh.fetchSalt());
                        serializer.endTag(null, "Salt");
 
+                       String cvcs = dbh.fetchCryptVCSeed();
+                       if(cvcs != null && !"".equals(cvcs)) {
+                               String cvcc = dbh.fetchVCChal();
+                               assert(cvcc != null && !"".equals(cvcc));
+
+                               serializer.startTag(null, "VCSeeds");
+                               serializer.text(cvcs);
+                               serializer.endTag(null, "VCSeeds");
+
+                               serializer.startTag(null, "VCChal");
+                               serializer.text(cvcc);
+                               serializer.endTag(null, "VCChal");
+
+                               IntentHandler.rotateVC();
+                       }
+
+                       dbh.close();
+
                        List<CategoryEntry> crows;
                        crows = Passwords.getCategoryEntries();
                        
index 6cd20006a26cda98734489f2a752def7bb7bdc70..6f1a76d14155568f3fb166a919b0d25e355e55c7 100644 (file)
@@ -525,10 +525,7 @@ public class CategoryList extends FrontDooringListActivity {
 
     
     private void lockAndShutFrontDoor () {
-       Intent serviceIntent = new Intent();
-               serviceIntent.setClass(this, ServiceDispatchImpl.class );
-           stopService(serviceIntent);
-               RuntimeSecrets.setSignedOut();
+               IntentHandler.signOut();
            Intent frontdoor = new Intent(this, Safe.class);
                frontdoor.setAction(CryptoIntents.ACTION_AUTOLOCK);
            startActivity(frontdoor);
index 87cb53674f413667ae35f209ef99babf2c35c6ef..f9f6bca6aed48255c793d31d305e611d8b87b3ca 100644 (file)
  */
 package org.openintents.safe;
 
+import java.io.File;
 import java.util.List;
 
 import org.openintents.intents.CryptoIntents;
 import org.openintents.util.FrontDooringActivity;
+import org.openintents.util.VCPassUtils;
 
 import android.app.Activity;
 import android.app.Dialog;
@@ -35,6 +37,8 @@ import android.util.Log;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;
+import android.widget.RadioButton;
+import android.widget.RadioGroup;
 import android.widget.Toast;
 
 /**
@@ -49,28 +53,22 @@ public class ChangePass extends FrontDooringActivity {
        private static final String TAG = "ChangePass";
        
        ProgressDialog mChangePassProgress;
-       
+
        private static final int CHANGE_PASS_PROGRESS_KEY = 0;
+
+    private static final int REQUEST_VCPASS_IMPORT = 0;
        
        protected static final int MSG_PASS_CHANGED = 0x101; 
        
-       Thread changePassThread = null;
-       String oldPassword;
-       String newPassword;
+       // Thread changePassThread = null;
+       // String oldPassword;
+       // String newPassword;
 
-    Handler myViewUpdateHandler = new Handler(){
-               // @Override
-               public void handleMessage(Message msg) {
-                       switch (msg.what) {
-                               case ChangePass.MSG_PASS_CHANGED:
-                                       Toast.makeText(ChangePass.this, R.string.password_changed,
-                                               Toast.LENGTH_LONG).show();
-                                       finish();
-                                       break;
-                       }
-                       super.handleMessage(msg);
-               }
-    }; 
+       RadioButton continuevcB;
+       RadioButton disablevcB;
+       RadioButton newseedsvcB;
+
+       DBHelper dbHelper = null;
 
     /** 
      * Called when the activity is first created. 
@@ -93,7 +91,39 @@ public class ChangePass extends FrontDooringActivity {
                        performChangePass();
                    }
                });
-               
+
+               if(dbHelper == null) {
+                       dbHelper = new DBHelper(this);
+               }
+
+               RadioGroup vcmoderg = (RadioGroup) findViewById(R.id.change_vc_mode);
+
+        RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(
+                RadioGroup.LayoutParams.WRAP_CONTENT,
+                RadioGroup.LayoutParams.WRAP_CONTENT);
+
+               disablevcB = new RadioButton(this);
+                       disablevcB.setText(getString(R.string.change_vc_disable));
+
+               newseedsvcB = new RadioButton(this);
+               int ix = 0;
+               int tocheck = 0;
+
+               String vcs = dbHelper.fetchCryptVCSeed();
+               if(vcs != null && !vcs.equals("")) {
+                       newseedsvcB.setText(getString(R.string.change_vc_newseeds));
+
+                       continuevcB = new RadioButton(this);
+                               continuevcB.setText(getString(R.string.change_vc_nochange));
+                       vcmoderg.addView(continuevcB,ix++,lp);
+                       tocheck = continuevcB.getId();
+               } else {
+                       newseedsvcB.setText(getString(R.string.change_vc_startseeds));
+                       tocheck = disablevcB.getId();
+               }
+               vcmoderg.addView(disablevcB,ix++,lp);
+               vcmoderg.addView(newseedsvcB,ix++,lp);
+               vcmoderg.check(tocheck);
     }
     
     @Override
@@ -101,7 +131,8 @@ public class ChangePass extends FrontDooringActivity {
                super.onPause();
                
                if (debug) Log.d(TAG,"onPause()");
-               
+       
+/*     
                if ((changePassThread != null) && (changePassThread.isAlive())) {
                        if (debug) Log.d(TAG,"wait for thread");
 //                     importThread.interrupt();
@@ -109,6 +140,11 @@ public class ChangePass extends FrontDooringActivity {
                        try { changePassThread.join(maxWaitToDie); } 
                        catch(InterruptedException e){} //  ignore 
                }
+*/
+
+               if(dbHelper != null) {
+                       dbHelper.close();
+               }
     }
 
     @Override
@@ -116,6 +152,10 @@ public class ChangePass extends FrontDooringActivity {
                super.onResume();
 
                if (debug) Log.d(TAG,"onResume()");
+
+               if(dbHelper == null) {
+                       dbHelper = new DBHelper(this);
+               }
         
         Passwords.Initialize(this);
     }
@@ -133,6 +173,31 @@ public class ChangePass extends FrontDooringActivity {
         }
         return null;
     }
+
+       @Override
+    protected void onActivityResult(int requestCode, int resultCode, Intent i) {
+               if(requestCode == REQUEST_VCPASS_IMPORT) {
+                       if(resultCode != RESULT_OK) { return; } 
+
+                       String error    = i.getStringExtra    ("ERR"  );
+                       char[] useed    = i.getCharArrayExtra ("USEED");
+                       char[] vseed    = i.getCharArrayExtra ("VSEED");
+
+                       if(error != null) {
+                               Log.e(TAG, error);
+                               Toast.makeText(this,
+                                               R.string.vcpass_fail, Toast.LENGTH_SHORT)
+                                    .show();
+                               return;
+                       }
+
+                       IntentHandler.changeVCSeedsAndPassword(
+                               VCPassUtils.encode_seeds(useed, vseed),
+                               ((EditText)findViewById(R.id.new_password)).getText().toString()
+                       );
+                       finishChange();
+               }
+       }
     
     /**
      * Check the old, new and verify fields then try to re-encrypt
@@ -159,14 +224,41 @@ public class ChangePass extends FrontDooringActivity {
                     Toast.LENGTH_SHORT).show();
             return;
                }
-               if (!checkUserPassword(oldPlain)) {
+               if (!oldPlain.equals(IntentHandler.getLastPassword())) {
             Toast.makeText(ChangePass.this, R.string.invalid_old_password,
                     Toast.LENGTH_SHORT).show();
             return;
                }
 //             changePassThreadStart(oldPlain, newPlain);
-               changeMasterPassword(oldPlain, newPlain);
+//             changeMasterPassword(oldPlain, newPlain);
+
+               String vcs = dbHelper.fetchCryptVCSeed();
+               if(continuevcB != null && continuevcB.isChecked()) {
+                       /* Don't have to do anything */
+               } else if(disablevcB.isChecked()
+                       && vcs != null && !vcs.equals("")) {
+                       // If VC is turned off, we don't have to do anything here either
+                       if(!IntentHandler.changeVCSeedsAndPassword(null, newPlain)) {
+               Toast.makeText(ChangePass.this, R.string.vcpass_fail,
+                           Toast.LENGTH_SHORT).show();
+               return;
+                       }
+               } else if(newseedsvcB.isChecked()) {
+                       final Intent i = new Intent(VCPassUtils.ACT_SEED_IMPORT);
+                       startActivityForResult(i, REQUEST_VCPASS_IMPORT);
+                       return;
+               }
+
+               IntentHandler.changePassword(newPlain);
+               finishChange();
     }
+
+       private void finishChange() {
+               Toast.makeText(ChangePass.this, R.string.password_changed,
+                                               Toast.LENGTH_LONG).show();
+               setResult(RESULT_OK);
+               finish();
+       }
     
        /**
         * Start a separate thread to import the database.   By running
@@ -197,7 +289,20 @@ public class ChangePass extends FrontDooringActivity {
                        });
                changePassThread.start();
        }
-       */
+
+    Handler myViewUpdateHandler = new Handler(){
+               // @Override
+               public void handleMessage(Message msg) {
+                       switch (msg.what) {
+                               case ChangePass.MSG_PASS_CHANGED:
+                                       Toast.makeText(ChangePass.this, R.string.password_changed,
+                                               Toast.LENGTH_LONG).show();
+                                       finish();
+                                       break;
+                       }
+                       super.handleMessage(msg);
+               }
+    }; 
 
     private boolean changeMasterPassword(String oldPass, String newPass) {
        
@@ -217,6 +322,7 @@ public class ChangePass extends FrontDooringActivity {
                                if (ch.getStatus()==true) { // successful encryption?
                                        dbHelper.storeMasterKey(encryptedMasterKey);
                                        dbHelper.close();
+
                                        Toast.makeText(ChangePass.this, R.string.password_changed,
                                                        Toast.LENGTH_LONG).show();
                                        setResult(RESULT_OK);
@@ -233,10 +339,12 @@ public class ChangePass extends FrontDooringActivity {
 
                dbHelper.close();
 
+
                Toast.makeText(ChangePass.this, R.string.error_changing_password,
                                Toast.LENGTH_LONG).show();
                return false;
     }
+       */
     
     /**
      * This is an older function.   We'll want to re-use this when we
@@ -245,6 +353,7 @@ public class ChangePass extends FrontDooringActivity {
      * @param oldPass
      * @param newPass
      */
+       /*
     public void changePassword(String oldPass, String newPass) {
        if (debug) Log.d(TAG,"changePassword(,)");
        
@@ -258,9 +367,7 @@ public class ChangePass extends FrontDooringActivity {
                List<PassEntry> passRows;
                passRows = dbHelper.fetchAllRows(new Long(0));
                
-               /**
-                * Decrypt everything using the old password.
-                */
+               // Decrypt everything using the old password.
                if (debug) Log.d(TAG,"decrypting");
                ch.setPassword(oldPass);
 
@@ -291,9 +398,7 @@ public class ChangePass extends FrontDooringActivity {
                    }
                }
 
-               /**
-                * Encrypt everything using the new password.
-                */
+               // Encrypt everything using the new password.
                if (debug) Log.d(TAG,"encrypting");
                ch.setPassword(newPass);
 
@@ -323,9 +428,7 @@ public class ChangePass extends FrontDooringActivity {
                    }
                }
 
-               /**
-                * Update the database with the newly encrypted data.
-                */
+               // Update the database with the newly encrypted data.
                if (debug) Log.d(TAG,"updating database");
                dbHelper.beginTransaction();
 
@@ -355,39 +458,9 @@ public class ChangePass extends FrontDooringActivity {
 
                dbHelper.commit();
                
-               RuntimeSecrets.setMasterKey(newPass);
+               IntentHandler.setMasterKey(newPass);
 
                dbHelper.close();
     }
-    
-    /**
-     * Check the provided clear text password with the one stored
-     * in the database.
-     * 
-     * @param pass = clear text password
-     * @return True if password is correct.
-     */
-    private boolean checkUserPassword(String pass) {
-       if (debug) Log.d(TAG,"checkUserPassword()");
-       
-               DBHelper dbHelper= new DBHelper(this);
-               String confirmKey = dbHelper.fetchMasterKey();
-
-               CryptoHelper ch = new CryptoHelper();
-
-               try {
-                       ch.init(CryptoHelper.EncryptionStrong, dbHelper.fetchSalt());
-                       ch.setPassword(pass);
-                       ch.decrypt(confirmKey);
-               } catch (CryptoHelperException e) {
-                       Log.e(TAG, e.toString());
-               }
-               dbHelper.close();
-
-               // was decryption of the master key successful?
-               if (ch.getStatus()==true) {
-                       return true;    // then we must have a good master password
-               }
-               return false;
-       }
+       */
 }
index 993f5edca9bf58091b5c1dbdedfce8f696c6d3a6..469abd5d45adefb5a8e0b451605b7178553b93a5 100644 (file)
@@ -149,7 +149,7 @@ public class CryptoContentProvider extends ContentProvider {
                                }\r
                                \r
                                if (debug) Log.d(TAG, "Original file path: " + originalFile);\r
-                                       if (RuntimeSecrets.isSignedIn()==false) {\r
+                                       if (IntentHandler.isSignedIn()==false) {\r
                                                Intent frontdoor = new Intent(getContext(), Safe.class);\r
                                                frontdoor.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\r
                                                getContext().startActivity(frontdoor);          \r
index 66570a99ee3196fc1a3915576df06acae9c71446..7188c16048715e17156abc42ef00acfa7ed056b3 100644 (file)
@@ -47,7 +47,13 @@ public class DBHelper {
     private static final String TABLE_SALT = "salt";
     private static final String TABLE_PACKAGE_ACCESS = "package_access";
     private static final String TABLE_CIPHER_ACCESS = "cipher_access";
-    private static final int DATABASE_VERSION = 4;
+
+       // VC seed encrypted as a sessioned packed using the master key
+    private static final String TABLE_VC_CRYPTEDSEED = "vcseedcrypt";
+       // VC challenge, plaintext base64-encoded serialized bitmap object
+    private static final String TABLE_VC_CHAL = "vcchal";
+
+    private static final int DATABASE_VERSION = 5;
     private static String TAG = "DBHelper";
 
     private static final String DBVERSION_CREATE = 
@@ -104,6 +110,19 @@ public class DBHelper {
 //    private static final String CIPHER_ACCESS_DROP =
 //     "drop table " + TABLE_CIPHER_ACCESS + ";";
 
+       // May be NULL to indicate that no VC is to happen.
+    private static final String VC_CRYPTEDSEED_CREATE =
+       "create table " + TABLE_VC_CRYPTEDSEED + " ( " + TABLE_VC_CRYPTEDSEED + " text ); ";
+
+    private static final String VC_CRYPTEDSEED_DROP =
+       "drop table " + TABLE_VC_CRYPTEDSEED + ";" ;
+
+    private static final String VC_CHAL_CREATE =
+       "create table " + TABLE_VC_CHAL + " ( " + TABLE_VC_CHAL + " text ); ";
+
+    private static final String VC_CHAL_DROP =
+       "drop table " + TABLE_VC_CHAL + ";" ;
+
     private SQLiteDatabase db;
     private boolean needsPrePopulation=false;
     private boolean needsUpgrade=false;
@@ -164,6 +183,8 @@ public class DBHelper {
                        db.execSQL(CIPHER_ACCESS_CREATE);
                        db.execSQL(MASTER_KEY_CREATE);
                        db.execSQL(SALT_CREATE);
+                       db.execSQL(VC_CRYPTEDSEED_CREATE);
+                       db.execSQL(VC_CHAL_CREATE);
                } catch (SQLException e)
                {
                        Log.d(TAG,"SQLite exception: " + e.getLocalizedMessage());
@@ -173,6 +194,12 @@ public class DBHelper {
     public void deleteDatabase()
     {
         try {
+                       db.execSQL(VC_CRYPTEDSEED_DROP);
+                       db.execSQL(VC_CRYPTEDSEED_CREATE);
+
+                       db.execSQL(VC_CHAL_DROP);
+                       db.execSQL(VC_CHAL_CREATE);
+
                        db.execSQL(PASSWORDS_DROP);
                        db.execSQL(PASSWORDS_CREATE);
 
@@ -300,6 +327,24 @@ public class DBHelper {
                storeSV(TABLE_MASTER_KEY, "encryptedkey", MasterKey);
     }
 
+////////// VC Functions ////////////////
+
+    public String fetchCryptVCSeed() {
+               return fetchSV(TABLE_VC_CRYPTEDSEED, TABLE_VC_CRYPTEDSEED);
+    }
+    
+    public void storeCryptVCSeed(String cs) {
+               storeSV(TABLE_VC_CRYPTEDSEED, TABLE_VC_CRYPTEDSEED, cs);
+    }
+
+    public String fetchVCChal() {
+               return fetchSV(TABLE_VC_CHAL, TABLE_VC_CHAL);
+    }
+    
+    public void storeVCChal(String cs) {
+               storeSV(TABLE_VC_CHAL, TABLE_VC_CHAL, cs);
+    }
+
 
 //////////Category Functions ////////////////
 
@@ -802,15 +847,8 @@ public class DBHelper {
         * 
         * @return true if successful
         */
-       public boolean beginTransaction() {
-        try {
-                       db.execSQL("begin transaction;");
-        } catch (SQLException e)
-               {
-                       Log.d(TAG,"SQLite exception: " + e.getLocalizedMessage());
-                       return false;
-               }
-        return true;
+       public void beginTransaction() {
+               db.beginTransaction();
        }
 
        /**
@@ -818,12 +856,8 @@ public class DBHelper {
         * open database.
         */
        public void commit() {
-        try {
-                       db.execSQL("commit;");
-        } catch (SQLException e)
-               {
-                       Log.d(TAG,"SQLite exception: " + e.getLocalizedMessage());
-               }
+               db.setTransactionSuccessful();
+               db.endTransaction();
        }
 
        /**
@@ -831,12 +865,7 @@ public class DBHelper {
         * open database.
         */
        public void rollback() {
-        try {
-                       db.execSQL("rollback;");
-        } catch (SQLException e)
-               {
-                       Log.d(TAG,"SQLite exception: " + e.getLocalizedMessage());
-               }
+               db.endTransaction();
        }
 }
 
index 6082fc43bc46cb7f34691076d341be6f37926e32..ad9389e9ff840864604b29021227fa9a850d1a03 100644 (file)
@@ -24,6 +24,7 @@ import org.openintents.intents.CryptoIntents;
 import org.openintents.safe.dialog.DialogHostingActivity;\r
 import org.openintents.safe.service.ServiceDispatch;\r
 import org.openintents.safe.service.ServiceDispatchImpl;\r
+import org.openintents.util.VCPassUtils;\r
 \r
 import android.app.Activity;\r
 import android.content.ComponentName;\r
@@ -31,6 +32,7 @@ import android.content.Context;
 import android.content.Intent;\r
 import android.content.ServiceConnection;\r
 import android.content.SharedPreferences;\r
+import android.graphics.Bitmap;\r
 import android.net.Uri;\r
 import android.os.Bundle;\r
 import android.os.IBinder;\r
@@ -50,20 +52,19 @@ import android.widget.Toast;
  */\r
 public class IntentHandler extends Activity {\r
 \r
-       private static final boolean debug = false;\r
+       private static final boolean debug = true;\r
        private static String TAG = "IntentHandler";\r
        \r
        private static final int REQUEST_CODE_ASK_PASSWORD = 1;\r
        private static final int REQUEST_CODE_ALLOW_EXTERNAL_ACCESS = 2;\r
        \r
-       private String salt;\r
-       private String masterKey;\r
-       private CryptoHelper ch;\r
+       private CryptoHelper ch;        \r
        \r
        // service elements\r
     private static ServiceDispatch service=null;\r
     private ServiceDispatchConnection conn=null;\r
        private Intent mServiceIntent;\r
+       private Intent saved_ask_data;\r
 \r
     SharedPreferences mPreferences;\r
        \r
@@ -88,19 +89,14 @@ public class IntentHandler extends Activity {
                case REQUEST_CODE_ASK_PASSWORD:\r
                        if (resultCode == RESULT_OK) {\r
                                if (debug) Log.d(TAG,"RESULT_OK");\r
-                               if (service == null) {\r
-                                       mServiceIntent = data;\r
-                                       // setServiceParametersFromExtrasAndDispatchAction() is called in onServiceConnected.\r
+                               if (data == null) {\r
+                                       /* Already signed in */\r
                                        return;\r
                                }\r
-                               \r
+\r
                                setServiceParametersFromExtrasAndDispatchAction(data);\r
-                               \r
                        } else { // resultCode == RESULT_CANCELED, which means the user hit Back at AskPassword\r
-                               if (debug) Log.d(TAG,"RESULT_CANCELED");\r
-                               moveTaskToBack(true);\r
-                               setResult(RESULT_CANCELED);\r
-                               finish();\r
+                               doCancel();\r
                        }\r
                        break;\r
                case REQUEST_CODE_ALLOW_EXTERNAL_ACCESS:\r
@@ -110,32 +106,31 @@ public class IntentHandler extends Activity {
                        if (service == null) {\r
                                if (debug) Log.i(TAG, "actionDispatch called later");\r
                                // actionDispatch() is called in onServiceConnected.\r
-                       } else if (salt == null) {\r
-                               try {\r
-                               salt = service.getSalt();\r
-                                       masterKey = service.getPassword();\r
-               if (debug) Log.d(TAG,"starting actiondispatch");\r
-                                       actionDispatch();\r
-                               } catch (RemoteException e) {\r
-                                       Log.d(TAG, e.toString());\r
-                                       // Not successful...\r
-                                       finish();\r
-                               }\r
                        } else {\r
-                               if (debug) Log.i(TAG, "actionDispatch called right now");\r
+                               if (debug) Log.d(TAG,"starting actiondispatch");\r
                                actionDispatch();\r
                        }\r
                        break;\r
                }\r
-                       \r
+       }\r
+\r
+       private void doCancel() {\r
+               if (debug) Log.d(TAG,"RESULT_CANCELED");\r
+               moveTaskToBack(true);\r
+               setResult(RESULT_CANCELED);\r
+               finish();\r
        }\r
 \r
        /**\r
         * @param data\r
         */\r
        private void setServiceParametersFromExtrasAndDispatchAction(Intent data) {\r
-               salt = data.getStringExtra("salt");\r
-               masterKey = data.getStringExtra("masterKey");\r
+               if (service == null) {\r
+                       assert(mServiceIntent == null);\r
+                       mServiceIntent = data;\r
+                       return;\r
+               }\r
+\r
                String timeout = mPreferences.getString(Preferences.PREFERENCE_LOCK_TIMEOUT, Preferences.PREFERENCE_LOCK_TIMEOUT_DEFAULT_VALUE);\r
                boolean lockOnScreenLock = mPreferences.getBoolean(Preferences.PREFERENCE_LOCK_ON_SCREEN_LOCK, true);\r
 \r
@@ -147,13 +142,17 @@ public class IntentHandler extends Activity {
                }\r
                \r
                try {\r
+                       // should already be connected.\r
                        service.setTimeoutMinutes(timeoutMinutes);\r
                        service.setLockOnScreenLock(lockOnScreenLock);\r
-                       service.setSalt(salt);\r
-                       service.setPassword(masterKey); // should already be connected.\r
+                       service.signIn(\r
+                               data.getStringExtra("pw"),\r
+                               data.getStringExtra("vcsecret"),\r
+                               data.getStringExtra("vcseeds"),\r
+                               data.getStringExtra("salt"),\r
+                               data.getStringExtra("masterKey"));\r
                } catch (RemoteException e1) {\r
-                       // TODO Auto-generated catch block\r
-                       e1.printStackTrace();\r
+                       throw new RuntimeException(e1);\r
                }\r
 \r
                boolean externalAccess = mPreferences.getBoolean(Preferences.PREFERENCE_ALLOW_EXTERNAL_ACCESS, false);\r
@@ -184,24 +183,18 @@ public class IntentHandler extends Activity {
         final String action = thisIntent.getAction();\r
        Intent callbackIntent = getIntent(); \r
        int callbackResult = RESULT_CANCELED;\r
-        RuntimeSecrets.setSalt(salt);\r
-        RuntimeSecrets.setMasterKey(masterKey);\r
         \r
         if (debug) Log.d(TAG,"actionDispatch()");\r
-        if ((salt==null) || (salt=="")) {\r
-               return;\r
-        }\r
         if (ch == null) {\r
                ch = new CryptoHelper();\r
         }\r
         try {\r
-                       ch.init(CryptoHelper.EncryptionMedium,salt);\r
-               ch.setPassword(masterKey);\r
-               } catch (CryptoHelperException e1) {\r
-                       e1.printStackTrace();\r
-                       Toast.makeText(this, getString(R.string.crypto_error)\r
-                               + e1.getMessage(), Toast.LENGTH_SHORT).show();\r
-                       return;\r
+                       ch.init(CryptoHelper.EncryptionMedium,service.getSalt());\r
+               ch.setPassword(service.getMasterKey());\r
+               } catch (CryptoHelperException e) {\r
+                       throw new RuntimeException(e);\r
+               } catch (RemoteException e) {\r
+                       throw new RuntimeException(e);\r
                }\r
 \r
         boolean externalAccess = mPreferences.getBoolean(Preferences.PREFERENCE_ALLOW_EXTERNAL_ACCESS, false);\r
@@ -364,8 +357,6 @@ public class IntentHandler extends Activity {
        \r
        private Intent getSetPassword (Intent thisIntent, Intent callbackIntent) throws CryptoHelperException, Exception {\r
                String action = thisIntent.getAction();\r
-        //TODO: Consider moving this elsewhere. Maybe DBHelper? Also move strings to resource.\r
-        //DBHelper dbHelper = new DBHelper(this);\r
         if (debug) Log.d(TAG, "GET_or_SET_PASSWORD");\r
         String username = null;\r
         String password = null;\r
@@ -466,20 +457,21 @@ public class IntentHandler extends Activity {
 \r
                if (debug)\r
                        Log.d(TAG, "onResume()");\r
-               \r
-               initService(); // start up the PWS service so other applications can query.\r
+       \r
+               if (saved_ask_data == null)     \r
+                       initService(); // start up the PWS service so other applications can query.\r
        }\r
        \r
        @Override\r
        protected void onDestroy() {\r
                super.onDestroy();\r
+\r
                releaseService();\r
        }\r
 \r
 \r
        //--------------------------- service stuff ------------\r
        private void initService() {\r
-\r
         boolean isLocal = isIntentLocal();\r
         if (conn==null) {\r
                        conn = new ServiceDispatchConnection(isLocal);\r
@@ -517,9 +509,12 @@ public class IntentHandler extends Activity {
                public void onServiceConnected(ComponentName className, \r
                                IBinder boundService )\r
                {\r
+\r
+                       if(debug) Log.d(TAG, "onServiceConnected");\r
                        service = ServiceDispatch.Stub.asInterface((IBinder)boundService);\r
-                       \r
+\r
                        if (mServiceIntent != null) {\r
+                               assert(service != null);\r
                                setServiceParametersFromExtrasAndDispatchAction(mServiceIntent);\r
                                mServiceIntent = null;\r
                                return;\r
@@ -533,7 +528,7 @@ public class IntentHandler extends Activity {
                                        askPassIsLocal=true;\r
                                }\r
 \r
-                               if (service.getPassword() == null) {\r
+                               if (service.getMasterKey() == null) {\r
                                        boolean promptforpassword = getIntent().getBooleanExtra(CryptoIntents.EXTRA_PROMPT, true);\r
                                        if (debug) Log.d(TAG, "Prompt for password: " + promptforpassword);\r
                                        if (promptforpassword) {\r
@@ -562,8 +557,6 @@ public class IntentHandler extends Activity {
                                boolean externalAccess = mPreferences.getBoolean(Preferences.PREFERENCE_ALLOW_EXTERNAL_ACCESS, false);\r
                                \r
                                if (askPassIsLocal || externalAccess) {\r
-                                       salt = service.getSalt();\r
-                                               masterKey = service.getPassword();\r
                                                if (debug) Log.d(TAG,"starting actiondispatch from service");\r
 \r
                                                actionDispatch();\r
@@ -598,4 +591,89 @@ public class IntentHandler extends Activity {
                }\r
        }\r
 \r
+       public static String getMasterKey() {\r
+               if(service != null) {\r
+                       try {\r
+                               return service.getMasterKey();\r
+                       } catch (RemoteException e) {\r
+                               Log.d(TAG, e.toString());\r
+                       }\r
+               }\r
+               return null;\r
+       }\r
+\r
+       public static String getSalt() {\r
+               if(service != null) {\r
+                       try {\r
+                               return service.getSalt();\r
+                       } catch (RemoteException e) {\r
+                               Log.d(TAG, e.toString());\r
+                       }\r
+               }\r
+               return null;\r
+       }\r
+\r
+       public static void changePassword(String s) {\r
+               if(service != null) {\r
+                       try {\r
+                               service.changePassword(s);\r
+                       } catch (RemoteException e) {\r
+                               Log.d(TAG, e.toString());\r
+                       }\r
+               }\r
+       }\r
+\r
+       public static String getLastPassword() {\r
+               if(service != null) {\r
+                       try {\r
+                               return service.getLastPassword();\r
+                       } catch (RemoteException e) {\r
+                               Log.d(TAG, e.toString());\r
+                       }\r
+               }\r
+               return null;\r
+       }\r
+\r
+       public static boolean changeVCSeedsAndPassword(String seed, String pw) {\r
+               if(service != null) {\r
+                       try {\r
+                               return service.changeVCSeedsAndPassword(seed, pw);\r
+                       } catch (RemoteException e) {\r
+                               Log.d(TAG, e.toString());\r
+                       }\r
+               }\r
+               return false;\r
+       }\r
+\r
+       public static boolean isSignedIn() {\r
+               if(service != null) {\r
+                       try {\r
+                               return service.isSignedIn();\r
+                       } catch (RemoteException e) {\r
+                               Log.d(TAG, e.toString());\r
+                               return false;\r
+                       }\r
+               }\r
+               return false;\r
+       }\r
+\r
+       public static void signOut() {\r
+        if (debug) Log.d(TAG,"signOut now");\r
+               if (service != null) {\r
+                       try { service.signOff(); }\r
+                       catch (RemoteException e) {\r
+                               Log.d(TAG, e.toString());\r
+                       }\r
+               }\r
+       }\r
+\r
+       public static void rotateVC() {\r
+               if (service != null) {\r
+                       try { service.rotateVC(); }\r
+                       catch (RemoteException e) {\r
+                               Log.d(TAG, e.toString());\r
+                       }\r
+               }\r
+       }\r
+\r
 }\r
index 39b3b9e9c1bacaeecedf2f7dee50a3d0e33657ac..c868524d9bc00fa3d232de47fee93e4e6b7d6c7e 100644 (file)
@@ -30,10 +30,7 @@ public class LogOffActivity extends Activity {
                
                logoffButton.setOnClickListener(new View.OnClickListener() {
                                public void onClick(View arg0) {
-                                       Intent serviceIntent = new Intent();
-                                       serviceIntent.setClass(LogOffActivity.this, ServiceDispatchImpl.class );
-                                       stopService(serviceIntent);
-                                       RuntimeSecrets.setSignedOut();
+                                       IntentHandler.signOut();
                                        
                                        /*
                                        Intent intent = new Intent(LogOffActivity.this, FrontDoor.class);
index 0fb3939beee673d273eb080df10a3f07793a3488..65cc9cf3f9cc5b5968c1e84b79c8fc35f8111775 100644 (file)
@@ -24,6 +24,7 @@ import java.util.List;
 import java.util.Set;
 
 import org.openintents.intents.CryptoIntents;
+import org.openintents.util.FrontDooringListActivity;
 
 import android.app.AlertDialog;
 import android.app.Dialog;
@@ -59,7 +60,7 @@ import android.widget.AdapterView.AdapterContextMenuInfo;
  * 
  * @author Steven Osborn - http://steven.bitsetters.com
  */
-public class PassList extends ListActivity {
+public class PassList extends FrontDooringListActivity {
 
        private static final boolean debug = false;
     private static final String TAG = "PassList";
@@ -85,9 +86,6 @@ public class PassList extends ListActivity {
 
     private Long CategoryId=null;
 
-    Intent frontdoor;
-    private Intent restartTimerIntent=null;
-
        private Thread fillerThread=null;
 
     private List<PassEntry> rows=null;
@@ -121,15 +119,6 @@ public class PassList extends ListActivity {
                }
        }; 
 
-    BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
-        public void onReceive(Context context, Intent intent) {
-            if (intent.getAction().equals(CryptoIntents.ACTION_CRYPTO_LOGGED_OUT)) {
-                if (debug) Log.d(TAG,"caught ACTION_CRYPTO_LOGGED_OUT");
-                startActivity(frontdoor);
-            }
-        }
-    };
-
     /** 
      * Called when the activity is first created. 
      */
@@ -150,18 +139,12 @@ public class PassList extends ListActivity {
                        return;
                }
 
-               frontdoor = new Intent(this, Safe.class);
-               frontdoor.setAction(CryptoIntents.ACTION_AUTOLOCK);
-               restartTimerIntent = new Intent (CryptoIntents.ACTION_RESTART_TIMER);
-
                setContentView(R.layout.pass_list);
 
                final ListView list = getListView();
                list.setFocusable(true);
                list.setOnCreateContextMenuListener(this);
                registerForContextMenu(list);
-               
-               sendBroadcast (restartTimerIntent);
     }
     
        @Override
@@ -188,11 +171,6 @@ public class PassList extends ListActivity {
                        try { fillerThread.join(maxWaitToDie); } 
                        catch(InterruptedException e){} //  ignore 
                }
-               try {
-                       unregisterReceiver(mIntentReceiver);
-               } catch (IllegalArgumentException e) {
-                       //if (debug) Log.d(TAG,"IllegalArgumentException");
-               }
                removeDialog(DECRYPT_PROGRESS_KEY);
     }
 
@@ -202,13 +180,6 @@ public class PassList extends ListActivity {
                
                if (debug) Log.d(TAG,"onResume()");
 
-               if (RuntimeSecrets.isSignedIn()==false) {
-                       startActivity(frontdoor);
-                       return;
-               }
-        IntentFilter filter = new IntentFilter(CryptoIntents.ACTION_CRYPTO_LOGGED_OUT);
-        registerReceiver(mIntentReceiver, filter);
-
                Passwords.Initialize(this);
 
                String categoryName=Passwords.getCategoryEntry(CategoryId).plainName;
@@ -491,17 +462,4 @@ public class PassList extends ListActivity {
                fillData();
        }
     }
-
-    @Override
-       public void onUserInteraction() {
-               super.onUserInteraction();
-
-               if (debug) Log.d(TAG,"onUserInteraction()");
-
-               if (RuntimeSecrets.isSignedIn()==false) {
-//                     startActivity(frontdoor);
-               }else{
-                       if (restartTimerIntent!=null) sendBroadcast (restartTimerIntent);
-               }
-       }
 }
index f53734747ddfba41ba09a559f4aed492fca7d4e9..f586f95f161fd0353d86eb3797725cf0e7e3c3cd 100644 (file)
@@ -62,12 +62,12 @@ public class Passwords {
                if (ch==null) {
                        ch = new CryptoHelper();
                }
-               if ((cryptoInitialized==false) && RuntimeSecrets.isSignedIn())
+               if ((cryptoInitialized==false) && IntentHandler.isSignedIn())
                {
                        try {
                                Passwords.InitCrypto(CryptoHelper.EncryptionMedium,
-                                               RuntimeSecrets.getSalt(),
-                                               RuntimeSecrets.getMasterKey());
+                                               IntentHandler.getSalt(),
+                                               IntentHandler.getMasterKey());
                                cryptoInitialized=true;
                        } catch (Exception e) {
                                e.printStackTrace();
@@ -134,13 +134,6 @@ public class Passwords {
                dbHelper.clearPrePopulate();
        }
        
-       public static String fetchSalt() {
-               return dbHelper.fetchSalt();
-       }
-       
-       public static String fetchMasterKeyEncrypted() {
-               return dbHelper.fetchMasterKey();
-       }
        ///////////////////////////////////////////////////
        ///////////// Category Functions //////////////////
        ///////////////////////////////////////////////////
index e5b901e0395341d19430eeac088626936410f484..4f4fac1f574e0ef7b4f952a7351b5a8e8ff55b5b 100644 (file)
@@ -53,7 +53,7 @@ public class Preferences extends PreferenceActivity {
        protected void onResume() {
                super.onResume();
 
-               if (RuntimeSecrets.isSignedIn()==false) {
+               if (IntentHandler.isSignedIn()==false) {
                        startActivity(frontdoor);
                        return;
                }
@@ -82,7 +82,7 @@ public class Preferences extends PreferenceActivity {
 
                if (debug) Log.d(TAG,"onUserInteraction()");
 
-               if (RuntimeSecrets.isSignedIn()==false) {
+               if (IntentHandler.isSignedIn()==false) {
 //                     startActivity(frontdoor);
                }else{
                        if (restartTimerIntent!=null) sendBroadcast (restartTimerIntent);
index f85d92a5e7493d471a4138eafbaf0a7e7267b9a4..dbcce1e2b77e25b35bc43767f76370b0cf4e329e 100644 (file)
@@ -22,6 +22,9 @@ import java.io.IOException;
 
 import org.openintents.intents.CryptoIntents;
 import org.openintents.util.FrontDooringActivity;
+import org.openintents.util.Base64;
+import org.openintents.util.IntentUtils;
+import org.openintents.util.VCPassUtils;
 
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.parsers.SAXParser;
@@ -40,6 +43,8 @@ import android.content.DialogInterface;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.SharedPreferences;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
 import android.os.Bundle;
 import android.preference.PreferenceManager;
 import android.util.Log;
@@ -53,16 +58,21 @@ import android.widget.Toast;
 
 public class Restore extends FrontDooringActivity {
        
-       private static boolean debug = false;
+       private static boolean debug = true;
        private static final String TAG = "Restore";
        
        private DBHelper dbHelper=null;
+       private String masterPassword=null;
+       private String vcsecret=null;
+       private String vcseedsenc;
+       private String vcseeds;
+       private String vcc;
        private String masterKey="";
        private String filename=null;
        private RestoreDataSet restoreDataSet=null;
        private boolean firstTime=false;
 
-    public static final String KEY_FIRST_TIME = "first_time";  // Intent keys
+    private static final int REQUEST_VCPASS_CHALLENGE = 1;
 
        @Override
        public void onCreate(Bundle icicle) {
@@ -70,19 +80,13 @@ public class Restore extends FrontDooringActivity {
 
                if (debug) Log.d(TAG,"onCreate()");
 
-               firstTime = icicle != null ? icicle.getBoolean(Restore.KEY_FIRST_TIME) : false;
-               if (firstTime == false) {
-                   Bundle extras = getIntent().getExtras();            
-                   firstTime = extras != null ? extras.getBoolean(Restore.KEY_FIRST_TIME) : false;
-               }
-
                Passwords.Initialize(this);
 
                setContentView(R.layout.restore);
                String title = getResources().getString(R.string.app_name) + " - " +
                        getResources().getString(R.string.restore);
                setTitle(title);
-               
+
                if (filename==null) {
                        filename=Constants.BACKUP_FILENAME;
                }
@@ -100,6 +104,7 @@ public class Restore extends FrontDooringActivity {
                restoreButton = (Button) findViewById(R.id.restore_button);
 
                if (!backupFileExists(filename)) {
+                       if(debug) Log.d(TAG, "!backupFileExists");
                        passwordText.setVisibility(0);
                        restoreButton.setVisibility(0);
                        restoreInfoText.setText(R.string.restore_no_file);
@@ -117,8 +122,8 @@ public class Restore extends FrontDooringActivity {
                                EditText passwordText;
                                passwordText = (EditText) findViewById(R.id.restore_password);
 
-                               String masterPassword = passwordText.getText().toString();
-                               read(filename, masterPassword);
+                               masterPassword = passwordText.getText().toString();
+                               read();
                        }
                });
     }
@@ -136,7 +141,7 @@ public class Restore extends FrontDooringActivity {
                return true;
     }
 
-    public boolean read(String filename, String masterPassword) {
+    private void read() {
                if (debug) Log.d(TAG,"read("+filename+",)");
        
                FileReader fr;
@@ -147,7 +152,7 @@ public class Restore extends FrontDooringActivity {
                        Toast.makeText(Restore.this, getString(R.string.restore_unable_to_open,
                                e1.getLocalizedMessage()),
                                Toast.LENGTH_LONG).show();
-                       return false;
+                       return;
                }
 
                SAXParserFactory spf = SAXParserFactory.newInstance();
@@ -168,36 +173,102 @@ public class Restore extends FrontDooringActivity {
                        Toast.makeText(Restore.this, getString(R.string.restore_unable_to_open,
                                e.getLocalizedMessage()),
                                Toast.LENGTH_LONG).show();
-                       return false;
+                       return;
                } catch (SAXException e) {
                        //e.printStackTrace();
                        Toast.makeText(Restore.this, getString(R.string.restore_unable_to_open,
                                e.getLocalizedMessage()),
                                Toast.LENGTH_LONG).show();
-                       return false;
+                       return;
                } catch (IOException e) {
                        //e.printStackTrace();
                        Toast.makeText(Restore.this, getString(R.string.restore_unable_to_open,
                                e.getLocalizedMessage()),
                                Toast.LENGTH_LONG).show();
-                       return false;
+                       return;
                } 
 
                if (restoreDataSet.getVersion() != Backup.CURRENT_VERSION) {
                        Toast.makeText(Restore.this, getString(R.string.restore_bad_version,
                                Integer.toString(restoreDataSet.getVersion())),
                                Toast.LENGTH_LONG).show();
-               return false;
+               return;
+               }
+
+               vcc = restoreDataSet.getVCChal();
+               vcseedsenc = restoreDataSet.getVCSeedsEncrypted();
+               if(vcc != null) {
+                       if(vcseedsenc == null) {
+                               Toast.makeText(Restore.this, getString(R.string.vcpass_fail),
+                                       Toast.LENGTH_SHORT).show();
+                               return;
+                       }
+                       final Intent i = new Intent(VCPassUtils.ACT_CHAL_PRESENT);
+                       if (!IntentUtils.isIntentAvailable(this, i)) {
+                               Toast.makeText(Restore.this, getString(R.string.vcpass_fail),
+                                       Toast.LENGTH_SHORT).show();
+                               return;
+                       }
+                       try{ 
+                       byte[] vc_chal_m = Base64.decode(vcc, Base64.URL_SAFE);
+                       assert(vc_chal_m != null);
+                       Log.d(TAG, Integer.toString(vc_chal_m.length));
+                       Bitmap vc_chal = BitmapFactory.decodeByteArray(
+                                                                       vc_chal_m, 0, vc_chal_m.length);
+                       if(vc_chal == null) {
+                               Toast.makeText(Restore.this, getString(R.string.vcpass_fail),
+                                       Toast.LENGTH_SHORT).show();
+                               return;
+                       }
+                       i.putExtra("CHAL", vc_chal);
+                       startActivityForResult(i, REQUEST_VCPASS_CHALLENGE);
+                       } catch (java.io.IOException ioe) {
+                               throw new RuntimeException(ioe);
+                       }
+               } else {
+                       finishRead();
+               }
+       }
+
+       @Override
+    protected void onActivityResult(int requestCode, int resultCode, Intent i) {
+       super.onActivityResult(requestCode, resultCode, i);
+
+               assert(requestCode == REQUEST_VCPASS_CHALLENGE);
+
+               if(resultCode == RESULT_CANCELED) {
+                       /* Don't cancel here in case the user just realized a typo */
+                       return;
+               }
+
+               String error     = i.getStringExtra("ERR");
+               if(error != null) {
+                       Log.e(TAG, error);
+                       Toast.makeText(this,
+                                       R.string.vcpass_fail, Toast.LENGTH_SHORT)
+                            .show();
+                       return;
                }
+
+               vcsecret = i.getStringExtra("SEQ");
+               finishRead();
+       }
+
+       private void finishRead() {
                CategoryEntry firstCatEntry= null;
                if (restoreDataSet.getCategories().size() > 0) {
                        firstCatEntry = restoreDataSet.getCategories().get(0);
                        if (firstCatEntry==null) {
                                Toast.makeText(Restore.this, getString(R.string.restore_error),
                                        Toast.LENGTH_LONG).show();
-                               return false;
+                               return;
                        }
                }
+
+               String fullpw = masterPassword;
+               if(vcsecret != null)
+                       fullpw += vcsecret;
+
                CryptoHelper ch=new CryptoHelper();
                
                String salt=restoreDataSet.getSalt();
@@ -205,13 +276,14 @@ public class Restore extends FrontDooringActivity {
                masterKey="";
                try {
                        ch.init(CryptoHelper.EncryptionStrong, salt);
-                       ch.setPassword(masterPassword);
+                       ch.setPassword(fullpw);
                        masterKey = ch.decrypt(masterKeyEncrypted);
+                       if(vcseedsenc != null) vcseeds = ch.decrypt(vcseedsenc);
                } catch (CryptoHelperException e) {
                        Log.e(TAG,e.toString());
                        Toast.makeText(this, getString(R.string.crypto_error)
                                + e.getMessage(), Toast.LENGTH_SHORT).show();
-                       return false;
+                       return;
                }
                if (ch.getStatus()==false) {
                        Toast.makeText(Restore.this, getString(R.string.restore_decrypt_error),
@@ -220,7 +292,7 @@ public class Restore extends FrontDooringActivity {
                        .loadAnimation(Restore.this, R.anim.shake);
                findViewById(R.id.restore_password).startAnimation(shake);
 
-                       return false;
+                       return;
                }
                ch=new CryptoHelper();
                try {
@@ -230,7 +302,7 @@ public class Restore extends FrontDooringActivity {
                        e1.printStackTrace();
                        Toast.makeText(this, getString(R.string.crypto_error)
                                + e1.getMessage(), Toast.LENGTH_SHORT).show();
-                       return false;
+                       return;
                }
                
                if (firstCatEntry != null) {
@@ -243,10 +315,11 @@ public class Restore extends FrontDooringActivity {
                        if (ch.getStatus() == false) {
                                Toast.makeText(Restore.this, getString(R.string.restore_decrypt_error),
                                        Toast.LENGTH_LONG).show();
-                               return false;
+                               return;
                        }
                        if (debug) Log.d(TAG,"firstCategory="+firstCategory);
                }
+
                
                dbHelper=new DBHelper(Restore.this);
 
@@ -272,17 +345,29 @@ public class Restore extends FrontDooringActivity {
                .create();
                confirm.show();
 
-               return true;
+               return;
        }
     
        private void restoreDatabase() {
+               Intent callbackIntent = new Intent();
+
+               /* set these as if we were AskPassword */
+               callbackIntent.putExtra("salt", restoreDataSet.getSalt());
+               callbackIntent.putExtra("masterKey", masterKey);
+               callbackIntent.putExtra("pw", masterPassword);
+               callbackIntent.putExtra("vcseeds", vcseeds);
+               callbackIntent.putExtra("vcsecret", vcsecret);
+
                dbHelper.beginTransaction();
                dbHelper.deleteDatabase();
 
                dbHelper.storeSalt(restoreDataSet.getSalt());
                dbHelper.storeMasterKey(restoreDataSet.getMasterKeyEncrypted());
-               RuntimeSecrets.setSalt(restoreDataSet.getSalt());
-               RuntimeSecrets.setMasterKey(masterKey);
+               assert((vcseedsenc == null && vcseeds == null && vcsecret == null)
+                       || (vcseedsenc != null && vcseeds != null && vcsecret != null));
+               if(vcseedsenc != null) {
+                       dbHelper.storeCryptVCSeed(vcseedsenc);
+               }
                for (CategoryEntry category : restoreDataSet.getCategories()) {
                        if (debug) Log.d(TAG,"category="+category.name);
                        dbHelper.addCategory(category);
@@ -314,7 +399,7 @@ public class Restore extends FrontDooringActivity {
         editor.putBoolean(Preferences.PREFERENCE_FIRST_TIME_WARNING, true);
         editor.commit();
 
-               setResult(RESULT_OK);
+               setResult(RESULT_OK, callbackIntent);
                finish();
        }
 }
index 67c749140388d880d09ec623a5dc64886c3adab3..ca80410d98aa81a48c41ecb43cc1444e510e1992 100644 (file)
@@ -38,6 +38,9 @@ public class RestoreDataSet {
        private String currentPackageAccess;
        private ArrayList<PassEntry> passEntries = new ArrayList<PassEntry>();
        private int totalEntries = 0;
+
+       private String vcSeedsEncrypted = null;
+       private StringBuilder vcChal = new StringBuilder();
        
        public int getVersion() {
                return version;
@@ -63,6 +66,18 @@ public class RestoreDataSet {
        public void setMasterKeyEncrypted(String extractedKey) {
                masterKeyEncrypted = extractedKey;
        }
+       public String getVCSeedsEncrypted() {
+               return vcSeedsEncrypted;
+       }
+       public void setVCSeedsEncrypted(String extractedSeeds) {
+               vcSeedsEncrypted = extractedSeeds;
+       }
+       public String getVCChal() {
+               return vcChal.toString();
+       }
+       public void appendVCChal(String extractedChal) {
+               vcChal.append(extractedChal);
+       }
        public ArrayList<CategoryEntry> getCategories() {
                return categoryEntries;
        }
index c31067dee7ebfa0a814355b9a837aa5f69bd6a9d..99c22bb9de84a7f0a3701509d5cb092189bddec9 100644 (file)
@@ -24,7 +24,7 @@ import android.util.Log;
 
 public class RestoreHandler extends DefaultHandler {
 
-       private static boolean debug = false;
+       private static boolean debug = true;
        private static final String TAG = "Restore";
 
     // ===========================================================
@@ -34,6 +34,8 @@ public class RestoreHandler extends DefaultHandler {
     private boolean in_oisafe = false;
     private boolean in_salt = false;
     private boolean in_masterkey = false;
+       private boolean in_vcseeds = false;
+       private boolean in_vcchal = false;
     private boolean in_category = false;
     private boolean in_entry = false;
     private boolean in_rowid = false;
@@ -98,7 +100,14 @@ public class RestoreHandler extends DefaultHandler {
                        in_masterkey = true;
 
                        if (debug) Log.d(TAG,"found MasterKey");
+               }else if (in_oisafe && localName.equals("VCSeeds")) {
+                       in_vcseeds = true;
 
+                       if (debug) Log.d(TAG,"found vcseeds");
+               }else if (in_oisafe && localName.equals("VCChal")) {
+                       in_vcchal = true;
+
+                       if (debug) Log.d(TAG,"found vcchal");
                }else if (in_oisafe && localName.equals("Category")) {
                        in_category = true;
 
@@ -146,6 +155,10 @@ public class RestoreHandler extends DefaultHandler {
                        in_salt = false;
                }else if (in_oisafe && localName.equals("MasterKey")) {
                        in_masterkey = false;
+               }else if (in_oisafe && localName.equals("VCSeeds")) {
+                       in_vcseeds = false;
+               }else if (in_oisafe && localName.equals("VCChal")) {
+                       in_vcchal = false;
                }else if (in_oisafe && localName.equals("Category")) {
                        in_category = false;
                        
@@ -183,6 +196,10 @@ public class RestoreHandler extends DefaultHandler {
                        myRestoreDataSet.setSalt(new String(ch, start, length));
                } else if (in_masterkey){
                        myRestoreDataSet.setMasterKeyEncrypted(new String(ch, start, length));
+               } else if (in_vcseeds){
+                       myRestoreDataSet.setVCSeedsEncrypted(new String(ch, start, length));
+               } else if (in_vcchal){
+                       myRestoreDataSet.appendVCChal(new String(ch, start, length));
                } else if (in_rowid){
                        myRestoreDataSet.setRowID(new String(ch, start, length));
                } else if (in_description){
diff --git a/src/org/openintents/safe/RuntimeSecrets.java b/src/org/openintents/safe/RuntimeSecrets.java
deleted file mode 100644 (file)
index f27fed4..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-/* A new central holding place for runtime secrets of the safe */
-
-package org.openintents.safe;
-
-import android.util.Log;
-
-public class RuntimeSecrets {
-
-       private static final boolean debug = false;
-       private static final String TAG = "RuntimeSecrets";
-
-       private static String salt;
-    static void setSalt(String saltIn) {
-               salt = saltIn;
-    }
-    static String getSalt() {
-               return salt;
-    }
-
-    private static String masterKey;                   
-    static void setMasterKey(String key) {
-               masterKey = key;
-    }
-
-    static String getMasterKey() {
-               return masterKey;
-    }
-
-    /**
-     * Returns the current status of signedIn. 
-     * 
-     * @return True if signed in
-     */
-    public static boolean isSignedIn() {
-       if ((salt != null) && (masterKey != null)) {
-               return true;
-       }
-       return false;
-    }
-    
-    /**
-     * Sets signedIn status to false.
-     * 
-     * @see org.openintents.safe.CategoryList#isSignedIn
-     */
-    public static void setSignedOut() {
-       if (debug) Log.d(TAG,"setSignedOut()");
-       masterKey=null;
-    }
-}
index cbf350f7a6f878601f635b962d09828ea30a4ad0..170f92a3a327a8f8f77babb0e3253b3c915aa174 100644 (file)
 package org.openintents.safe.service;\r
 \r
 interface ServiceDispatch {\r
-  void setSalt (String saltIn);\r
+  void signIn(String pw, String vcsec, String vcseed, String salt, String masterKey);\r
+  boolean isSignedIn();\r
+  void signOff();\r
+\r
   String getSalt ();\r
-  void setPassword (String masterPasswordIn);\r
-  String getPassword ();\r
-  String encrypt (String clearText);\r
-  String decrypt (String cryptoText);\r
+  String getMasterKey ();\r
+\r
+  String getLastPassword();\r
+  void changePassword(String pw);\r
+  void rotateVC();\r
+  boolean changeVCSeedsAndPassword(String seed, String pw);\r
+\r
   void setTimeoutMinutes(int timeoutMinutesIn);\r
   void setLockOnScreenLock (boolean lock);\r
+\r
+  String encrypt (String clearText);\r
+  String decrypt (String cryptoText);\r
 }\r
index 17a27c964219bf14b37f8f3a521fd17d68f3f493..da3e2d58defab5ee8d3a05a7c533eb5582810d33 100644 (file)
  * limitations under the License.
  */
 
+/*
+ * Ordinarily, we'd try to avoid recrypting the master key every time
+ * somebody sneezes, but unfortunately, the Android framework doesn't
+ * actually cleanly shut us down in some cases, including when we're being
+ * reinstalled.  We just croak.  Erk, thud, etc.  As a result, we were
+ * not getting a chance to write our finalized keys out to disk.  I'm
+ * pretty sure there's a race here how we were doing things before;
+ * hopefully the new design not so much.
+ */
+
 package org.openintents.safe.service;
 
 // TODO: Currently the timer MIGHT not actually de-activate the service
@@ -23,7 +33,7 @@ package org.openintents.safe.service;
 import org.openintents.intents.CryptoIntents;
 import org.openintents.safe.CryptoHelper;
 import org.openintents.safe.CryptoHelperException;
-import org.openintents.safe.RuntimeSecrets;
+import org.openintents.safe.DBHelper;
 
 
 import android.app.Service;
@@ -32,15 +42,41 @@ import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.os.IBinder;
+import android.os.RemoteException;
 import android.util.Log;
 import android.os.CountDownTimer;
 
+// VC imports
+import java.io.ByteArrayOutputStream;
+import java.lang.reflect.Field; 
+import java.lang.reflect.Method; 
+import android.content.pm.ActivityInfo;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.graphics.Bitmap;
+import dalvik.system.PathClassLoader;
+import org.openintents.util.Base64;
+import org.openintents.util.IntentUtils;
+import org.openintents.util.VCPassUtils;
+
+import java.util.Formatter;
+
 public class ServiceDispatchImpl extends Service {
-       private static boolean debug = false;
+       private static boolean debug = true;
        private static String TAG = "ServiceDispatchIMPL";
-       public static CryptoHelper ch;  // TODO Peli: Could clean this up by moving it into a singleton? Or at least a separate static class?
+       // XXX accessed by CryptoHelper for session key
+       public  static CryptoHelper ch;
+
        private String salt;
        private String masterKey;
+    private String lastpw;
+    private String lastvcsecret;
+       private char[] vc_useed;
+       private char[] vc_vseed;
+
+       private Thread vc_calc_thread;
+
     private CountDownTimer t;
     private int timeoutMinutes = 5;
        private long timeoutUntilStop = timeoutMinutes * 60000;
@@ -86,21 +122,33 @@ public class ServiceDispatchImpl extends Service {
          super.onDestroy();
 
          if (debug) Log.d( TAG,"onDestroy" );
-         unregisterReceiver(mIntentReceiver);
+
+         wait_vc_chal();
+
          if (masterKey!=null) {
                  lockOut();
          }
+
+         unregisterReceiver(mIntentReceiver);
          ServiceNotification.clearNotification(ServiceDispatchImpl.this);
     }
 
+//     @Override
+//    protected void onActivityResult(int requestCode, int resultCode, Intent i) {
+//     }
+
     private void lockOut() {
-         masterKey = null;
-         ch = null;
-         ServiceNotification.clearNotification(ServiceDispatchImpl.this);
-         
-         RuntimeSecrets.setSignedOut();
-         Intent intent = new Intent(CryptoIntents.ACTION_CRYPTO_LOGGED_OUT);
-         sendBroadcast(intent);
+               wait_vc_chal();
+
+               masterKey = null;
+               salt = null;
+               lastpw = null;
+               lastvcsecret = null;
+               ch = null;
+               ServiceNotification.clearNotification(ServiceDispatchImpl.this);
+               
+               Intent intent = new Intent(CryptoIntents.ACTION_CRYPTO_LOGGED_OUT);
+               sendBroadcast(intent);
     }
 
     private void startTimer () {
@@ -133,12 +181,161 @@ public class ServiceDispatchImpl extends Service {
        }
     }
 
+       private void __new_vc_chal()
+       {
+       Intent intent = new Intent(VCPassUtils.ACT_CHAL_CREATE);
+               assert(IntentUtils.isIntentAvailable(ServiceDispatchImpl.this, intent));
+
+               PackageManager pm = getPackageManager();
+               ResolveInfo ri = pm.resolveActivity(intent, 0);
+               PathClassLoader pcl = new PathClassLoader
+                       (ri.activityInfo.applicationInfo.publicSourceDir
+                       ,getClassLoader()
+               );
+
+               try{    
+                       Class c = pcl.loadClass(ri.activityInfo.name);
+                       Log.i("VCPass:CREATE:c", c.toString());
+
+                       /* This loop is dumb because Java clearly knows better than we do
+                        * but specifying the parameter types is a pain.  If something goes
+                        * wrong, it'll get caught by reflection later.
+                        */
+                       Method m = null;
+                       for(Method mc : c.getMethods()) {
+                               if(mc.getName().equals("do_createChallenge")) { m = mc; break; }
+                       }
+                       if(m == null) {
+                               throw new RuntimeException("No do_createChallenge routine!");
+                       } else {
+                               Log.i("VCPass:CREATE:m", m.toString());
+                       }
+
+                       Object r = m.invoke(null, vc_useed, vc_vseed, new Integer(0), null);
+                       Log.i("VCPass:CREATE:r", r.toString());
+               
+                       Field fe = r.getClass().getField("error");
+                       String e = (String) fe.get(r);
+                       Field fp = r.getClass().getField("plain");
+                       String p = (String) fp.get(r);
+                       Field fb = r.getClass().getField("bm");
+                       Bitmap b = (Bitmap) fb.get(r);
+
+                       if(e != null)
+                               Log.i("VCPass:CREATE:e", e);
+                       else {
+                               Log.i("VCPass:CREATE:b", b.toString());
+                               Log.i("VCPass:CREATE:p", p);
+                       }
+
+                       lastvcsecret = p;
+
+                       DBHelper dbh = new DBHelper(ServiceDispatchImpl.this);
+                       dbh.beginTransaction();
+                               /* Store masterKey, salt, vcseeds */
+                       _writeToDB(dbh);
+                               /* Store new challenge */
+                       ByteArrayOutputStream baos = new ByteArrayOutputStream();
+                       b.compress(Bitmap.CompressFormat.PNG, 0, baos);
+                       baos.close();
+                       dbh.storeVCChal(Base64.encodeBytes(baos.toByteArray(), Base64.URL_SAFE));
+                       dbh.commit();
+                       dbh.close();
+
+                       synchronized(this) {
+                               vc_calc_thread = null;
+                       }
+               } catch (CryptoHelperException che) {
+                       throw new RuntimeException(che);
+               } catch (ClassNotFoundException cnfe) {
+                       throw new RuntimeException(cnfe);
+               } catch (IllegalAccessException iae) {
+                       throw new RuntimeException(iae);
+               } catch (NoSuchFieldException nsfe) {
+                       throw new RuntimeException(nsfe);
+               } catch (java.lang.reflect.InvocationTargetException ite) {
+                       throw new RuntimeException(ite);
+               } catch (java.io.IOException ioe) {
+                       throw new RuntimeException(ioe);
+               }
+       }
+
+       private void new_vc_chal() {
+               synchronized(this) {
+                       vc_calc_thread = new Thread(new Runnable(){
+                               public void run() { __new_vc_chal(); }
+                       });
+                       vc_calc_thread.start();
+               }
+       }
+
+       private void wait_vc_chal() {
+               Thread local_vc_calc_thread;
+               synchronized(this) {
+                 local_vc_calc_thread = vc_calc_thread;
+               }
+               if(local_vc_calc_thread != null) {
+                       try { 
+                       local_vc_calc_thread.join();
+                       } catch (InterruptedException ie) {
+                               ; /* Do nothing */
+                       }
+               }
+       }
+
+       private void _initMasterCH(CryptoHelper wch)
+       throws CryptoHelperException {
+               wch.init(CryptoHelper.EncryptionStrong,salt);
+               if(lastvcsecret == null)
+                       wch.setPassword(lastpw);
+               else
+                       wch.setPassword(lastpw + lastvcsecret);
+       }
+
+
+       private void _writeToDB(DBHelper dbh)
+       throws CryptoHelperException {
+               assert((masterKey != null) && (salt != null));
+               if (debug) {
+                       Log.d(TAG,"writeToDB");
+                       if(lastvcsecret == null)
+                               Log.d(TAG, lastpw);
+                       else
+                               Log.d(TAG, lastpw + lastvcsecret);
+               }
+
+               // if (debug) Log.i(TAG, "Saving Password: " + masterKey);
+               CryptoHelper wch = new CryptoHelper();
+               _initMasterCH(wch);
+
+               dbh.storeSalt(salt);
+               dbh.storeMasterKey(wch.encrypt(masterKey));
+               if(vc_useed != null) {
+                       dbh.storeCryptVCSeed(
+                               wch.encrypt(
+                                       VCPassUtils.encode_seeds(vc_useed,vc_vseed)
+                       ));
+               }
+       }
+
+       private void writeToDB(DBHelper dbh) {
+               try {
+                       dbh.beginTransaction();
+                       _writeToDB(dbh);
+                       dbh.commit();
+               } catch (CryptoHelperException che) {
+                       throw new RuntimeException(che);
+               }
+       }
+
     /**
      * The ServiceDispatch is defined through IDL
      */
     private final ServiceDispatch.Stub mBinder = new ServiceDispatch.Stub() {
        private String TAG = "SERVICEDISPATCH";
 
+
+               @Override
        public String encrypt (String clearText)  {
                restartTimer();
                String cryptoText = null;
@@ -150,6 +347,73 @@ public class ServiceDispatchImpl extends Service {
                return (cryptoText);
        }
 
+               @Override
+               public void signIn(
+                       String pw,
+                       String vcsec,
+                       String vcseed,
+                       String salt,
+                       String masterKey
+               ) {
+               startTimer(); //should be initial timer start
+                       ServiceDispatchImpl.this.salt = salt;
+                       ServiceDispatchImpl.this.masterKey = masterKey;
+                       ServiceDispatchImpl.this.lastvcsecret = vcsec;
+                       ServiceDispatchImpl.this.lastpw = pw;
+
+                       final DBHelper dbh = new DBHelper(ServiceDispatchImpl.this);
+                       String cvcs = dbh.fetchCryptVCSeed();
+
+                       CryptoHelper dch = new CryptoHelper();
+                       ch = new CryptoHelper();
+                       try {
+                               ch.init(CryptoHelper.EncryptionMedium, salt);
+                               ch.setPassword(masterKey);
+                               _initMasterCH(dch);
+                               if(cvcs != null && !"".equals(cvcs)) {
+                                       assert(vcseed == null);
+                                       vcseed = dch.decrypt(cvcs);
+                               }
+                       } catch (CryptoHelperException e) {
+                               e.printStackTrace();
+                               throw new RuntimeException(e);
+                       }
+
+                       if(debug) {
+               StringBuilder sb = new StringBuilder();
+                   Formatter f = new Formatter(sb);
+               f.format("SIGN ON '%s' '%s' '%s' '%s' '%s'",
+                                       salt, masterKey, vcsec, vcseed, pw);
+                   Log.d("OIS:SDI", sb.toString());
+                       }
+
+                       if (vcseed == null || "".equals(vcseed)) {
+                               assert(vcsec == null);
+                               vc_useed = null;
+                               vc_vseed = null;
+
+                               // XXX Is there any harm in doing this every time?
+                               writeToDB(dbh);
+                       } else { 
+                               try {
+                                       char[][] dec = VCPassUtils.decode_seeds(vcseed);
+                                       vc_useed = dec[0];
+                                       vc_vseed = dec[1];
+                               } catch (Exception e) {
+                                       throw new RuntimeException(e);
+                               }
+
+                               /* Cycle VC challenge */
+                               new_vc_chal();
+                       }
+                       dbh.close();
+                       
+                       ServiceNotification.setNotification(ServiceDispatchImpl.this);
+
+               }
+
+
+               @Override
        public String decrypt (String cryptoText)  {
                restartTimer();
                String clearText = null;
@@ -161,40 +425,96 @@ public class ServiceDispatchImpl extends Service {
                return (clearText);
        }
 
-       public void setSalt (String saltIn){
-                       salt = saltIn;
+               @Override
+       public String getSalt (){
+                       return salt;
+               }
+
+               @Override
+               public String getMasterKey() {
+               restartTimer();
+                       return masterKey;
+               }
+
+               @Override
+       public void changePassword (String s){
+               if (debug) { Log.d(TAG,"changePassword: "); Log.d(TAG, s); }
+
+                       wait_vc_chal();
+
+                       lastpw = s;
+
+                       DBHelper dbh = new DBHelper(ServiceDispatchImpl.this);
+                       writeToDB(dbh);
+                       dbh.close();
        }
 
-               public String getSalt() {
-                       return salt;
+               @Override
+       public String getLastPassword (){
+                       return lastpw;
                }
 
-       public void setPassword (String masterKeyIn){
-               startTimer(); //should be initial timer start
-                       ch = new CryptoHelper();
-                       try {
-                               ch.init(CryptoHelper.EncryptionMedium, salt);
-                               ch.setPassword(masterKeyIn);
-                       } catch (CryptoHelperException e) {
-                               e.printStackTrace();
-                               return;
+               @Override
+       public boolean changeVCSeedsAndPassword (String vcseed, String pw){
+               if (debug) {
+                               Log.d(TAG,"changeVCSeedsAndPassword: ");
+                               if(vcseed != null) { Log.d(TAG, vcseed); }
+                               Log.d(TAG, pw);
                        }
-                       masterKey = masterKeyIn;
-                       
-                       ServiceNotification.setNotification(ServiceDispatchImpl.this);
+
+                       wait_vc_chal();
+
+                       lastpw = pw;
+
+                       final DBHelper dbh = new DBHelper(ServiceDispatchImpl.this);
+                       if(vcseed == null) {
+                               lastvcsecret = null;
+                               vc_useed = null;
+                               vc_vseed = null;
+                               dbh.beginTransaction();
+                               dbh.storeVCChal(null);
+                               writeToDB(dbh);
+                               dbh.commit();
+                       } else {
+                               try {
+                                       char[][] dec = VCPassUtils.decode_seeds(vcseed);
+                                       vc_useed = dec[0];
+                                       vc_vseed = dec[1];
+                               } catch (Exception e) {
+                                       throw new RuntimeException(e);
+                               }
+                               new_vc_chal();
+                       }
+                       dbh.close();
+                       return true;
        }
 
-               public String getPassword() {
-               restartTimer();
-                       return masterKey;
+               @Override
+               public void rotateVC() {
+                       if(vc_useed != null) {
+                               wait_vc_chal();
+                               new_vc_chal();
+                       }
                }
-               
+
+               @Override
+               public boolean isSignedIn() {
+                       return (masterKey != null) && (salt != null);
+               }
+
+               @Override
+               public void signOff() {
+                       stopSelf();
+               }
+
+               @Override
                public void setTimeoutMinutes (int timeoutMinutesIn){
                        timeoutMinutes = timeoutMinutesIn;
                        timeoutUntilStop = timeoutMinutes * 60000;
                        Log.d(TAG,"set timeout to "+timeoutMinutes);
                }
 
+               @Override
                public void setLockOnScreenLock (boolean lock){
                        lockOnScreenLock = lock;
        }
diff --git a/src/org/openintents/util/Base64.java b/src/org/openintents/util/Base64.java
new file mode 100644 (file)
index 0000000..c5f2957
--- /dev/null
@@ -0,0 +1,2069 @@
+/*
+ * Imported into OI Safe since Android's framework didn't sprout base64
+ * facilities until version 2.2 (er, guys, it's a networked device.)
+ */
+package org.openintents.util;
+
+/**
+ * <p>Encodes and decodes to and from Base64 notation.</p>
+ * <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p>
+ * 
+ * <p>Example:</p>
+ * 
+ * <code>String encoded = Base64.encode( myByteArray );</code>
+ * <br />
+ * <code>byte[] myByteArray = Base64.decode( encoded );</code>
+ *
+ * <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass 
+ * several pieces of information to the encoder. In the "higher level" methods such as 
+ * encodeBytes( bytes, options ) the options parameter can be used to indicate such 
+ * things as first gzipping the bytes before encoding them, not inserting linefeeds,
+ * and encoding using the URL-safe and Ordered dialects.</p>
+ *
+ * <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>,
+ * Section 2.1, implementations should not add line feeds unless explicitly told
+ * to do so. I've got Base64 set to this behavior now, although earlier versions
+ * broke lines by default.</p>
+ *
+ * <p>The constants defined in Base64 can be OR-ed together to combine options, so you 
+ * might make a call like this:</p>
+ *
+ * <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code>
+ * <p>to compress the data before encoding it and then making the output have newline characters.</p>
+ * <p>Also...</p>
+ * <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code>
+ *
+ *
+ *
+ * <p>
+ * Change Log:
+ * </p>
+ * <ul>
+ *  <li>v2.3.7 - Fixed subtle bug when base 64 input stream contained the
+ *   value 01111111, which is an invalid base 64 character but should not
+ *   throw an ArrayIndexOutOfBoundsException either. Led to discovery of
+ *   mishandling (or potential for better handling) of other bad input
+ *   characters. You should now get an IOException if you try decoding
+ *   something that has bad characters in it.</li>
+ *  <li>v2.3.6 - Fixed bug when breaking lines and the final byte of the encoded
+ *   string ended in the last column; the buffer was not properly shrunk and
+ *   contained an extra (null) byte that made it into the string.</li>
+ *  <li>v2.3.5 - Fixed bug in {@link #encodeFromFile} where estimated buffer size
+ *   was wrong for files of size 31, 34, and 37 bytes.</li>
+ *  <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing
+ *   the Base64.OutputStream closed the Base64 encoding (by padding with equals
+ *   signs) too soon. Also added an option to suppress the automatic decoding
+ *   of gzipped streams. Also added experimental support for specifying a
+ *   class loader when using the
+ *   {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)}
+ *   method.</li>
+ *  <li>v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java
+ *   footprint with its CharEncoders and so forth. Fixed some javadocs that were
+ *   inconsistent. Removed imports and specified things like java.io.IOException
+ *   explicitly inline.</li>
+ *  <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the
+ *   final encoded data will be so that the code doesn't have to create two output
+ *   arrays: an oversized initial one and then a final, exact-sized one. Big win
+ *   when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not
+ *   using the gzip options which uses a different mechanism with streams and stuff).</li>
+ *  <li>v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some
+ *   similar helper methods to be more efficient with memory by not returning a
+ *   String but just a byte array.</li>
+ *  <li>v2.3 - <strong>This is not a drop-in replacement!</strong> This is two years of comments
+ *   and bug fixes queued up and finally executed. Thanks to everyone who sent
+ *   me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else.
+ *   Much bad coding was cleaned up including throwing exceptions where necessary 
+ *   instead of returning null values or something similar. Here are some changes
+ *   that may affect you:
+ *   <ul>
+ *    <li><em>Does not break lines, by default.</em> This is to keep in compliance with
+ *      <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li>
+ *    <li><em>Throws exceptions instead of returning null values.</em> Because some operations
+ *      (especially those that may permit the GZIP option) use IO streams, there
+ *      is a possiblity of an java.io.IOException being thrown. After some discussion and
+ *      thought, I've changed the behavior of the methods to throw java.io.IOExceptions
+ *      rather than return null if ever there's an error. I think this is more
+ *      appropriate, though it will require some changes to your code. Sorry,
+ *      it should have been done this way to begin with.</li>
+ *    <li><em>Removed all references to System.out, System.err, and the like.</em>
+ *      Shame on me. All I can say is sorry they were ever there.</li>
+ *    <li><em>Throws NullPointerExceptions and IllegalArgumentExceptions</em> as needed
+ *      such as when passed arrays are null or offsets are invalid.</li>
+ *    <li>Cleaned up as much javadoc as I could to avoid any javadoc warnings.
+ *      This was especially annoying before for people who were thorough in their
+ *      own projects and then had gobs of javadoc warnings on this file.</li>
+ *   </ul>
+ *  <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug
+ *   when using very small files (~&lt; 40 bytes).</li>
+ *  <li>v2.2 - Added some helper methods for encoding/decoding directly from
+ *   one file to the next. Also added a main() method to support command line
+ *   encoding/decoding from one file to the next. Also added these Base64 dialects:
+ *   <ol>
+ *   <li>The default is RFC3548 format.</li>
+ *   <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates
+ *   URL and file name friendly format as described in Section 4 of RFC3548.
+ *   http://www.faqs.org/rfcs/rfc3548.html</li>
+ *   <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates
+ *   URL and file name friendly format that preserves lexical ordering as described
+ *   in http://www.faqs.org/qa/rfcc-1940.html</li>
+ *   </ol>
+ *   Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a>
+ *   for contributing the new Base64 dialects.
+ *  </li>
+ * 
+ *  <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
+ *   some convenience methods for reading and writing to and from files.</li>
+ *  <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
+ *   with other encodings (like EBCDIC).</li>
+ *  <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
+ *   encoded data was a single byte.</li>
+ *  <li>v2.0 - I got rid of methods that used booleans to set options. 
+ *   Now everything is more consolidated and cleaner. The code now detects
+ *   when data that's being decoded is gzip-compressed and will decompress it
+ *   automatically. Generally things are cleaner. You'll probably have to
+ *   change some method calls that you were making to support the new
+ *   options format (<tt>int</tt>s that you "OR" together).</li>
+ *  <li>v1.5.1 - Fixed bug when decompressing and decoding to a             
+ *   byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.      
+ *   Added the ability to "suspend" encoding in the Output Stream so        
+ *   you can turn on and off the encoding if you need to embed base64       
+ *   data in an otherwise "normal" stream (like an XML file).</li>  
+ *  <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
+ *      This helps when using GZIP streams.
+ *      Added the ability to GZip-compress objects before encoding them.</li>
+ *  <li>v1.4 - Added helper methods to read/write files.</li>
+ *  <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
+ *  <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
+ *      where last buffer being read, if not completely full, was not returned.</li>
+ *  <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
+ *  <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
+ * </ul>
+ *
+ * <p>
+ * I am placing this code in the Public Domain. Do with it as you will.
+ * This software comes with no guarantees or warranties but with
+ * plenty of well-wishing instead!
+ * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
+ * periodically to check for updates or to contribute improvements.
+ * </p>
+ *
+ * @author Robert Harder
+ * @author rob@iharder.net
+ * @version 2.3.7
+ */
+public class Base64
+{
+    
+/* ********  P U B L I C   F I E L D S  ******** */   
+    
+    
+    /** No options specified. Value is zero. */
+    public final static int NO_OPTIONS = 0;
+    
+    /** Specify encoding in first bit. Value is one. */
+    public final static int ENCODE = 1;
+    
+    
+    /** Specify decoding in first bit. Value is zero. */
+    public final static int DECODE = 0;
+    
+
+    /** Specify that data should be gzip-compressed in second bit. Value is two. */
+    public final static int GZIP = 2;
+
+    /** Specify that gzipped data should <em>not</em> be automatically gunzipped. */
+    public final static int DONT_GUNZIP = 4;
+    
+    
+    /** Do break lines when encoding. Value is 8. */
+    public final static int DO_BREAK_LINES = 8;
+       
+    /** 
+     * Encode using Base64-like encoding that is URL- and Filename-safe as described
+     * in Section 4 of RFC3548: 
+     * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
+     * It is important to note that data encoded this way is <em>not</em> officially valid Base64, 
+     * or at the very least should not be called Base64 without also specifying that is
+     * was encoded using the URL- and Filename-safe dialect.
+     */
+     public final static int URL_SAFE = 16;
+
+
+     /**
+      * Encode using the special "ordered" dialect of Base64 described here:
+      * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
+      */
+     public final static int ORDERED = 32;
+    
+    
+/* ********  P R I V A T E   F I E L D S  ******** */  
+    
+    
+    /** Maximum line length (76) of Base64 output. */
+    private final static int MAX_LINE_LENGTH = 76;
+    
+    
+    /** The equals sign (=) as a byte. */
+    private final static byte EQUALS_SIGN = (byte)'=';
+    
+    
+    /** The new line character (\n) as a byte. */
+    private final static byte NEW_LINE = (byte)'\n';
+    
+    
+    /** Preferred encoding. */
+    private final static String PREFERRED_ENCODING = "US-ASCII";
+    
+       
+    private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
+    private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
+       
+       
+/* ********  S T A N D A R D   B A S E 6 4   A L P H A B E T  ******** */      
+    
+    /** The 64 valid Base64 values. */
+    /* Host platform me be something funny like EBCDIC, so we hardcode these values. */
+    private final static byte[] _STANDARD_ALPHABET = {
+        (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
+        (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
+        (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', 
+        (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
+        (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
+        (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
+        (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', 
+        (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
+        (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', 
+        (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
+    };
+       
+    
+    /** 
+     * Translates a Base64 value to either its 6-bit reconstruction value
+     * or a negative number indicating some other meaning.
+     **/
+    private final static byte[] _STANDARD_DECODABET = {
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,                 // Decimal  0 -  8
+        -5,-5,                                      // Whitespace: Tab and Linefeed
+        -9,-9,                                      // Decimal 11 - 12
+        -5,                                         // Whitespace: Carriage Return
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 14 - 26
+        -9,-9,-9,-9,-9,                             // Decimal 27 - 31
+        -5,                                         // Whitespace: Space
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,              // Decimal 33 - 42
+        62,                                         // Plus sign at decimal 43
+        -9,-9,-9,                                   // Decimal 44 - 46
+        63,                                         // Slash at decimal 47
+        52,53,54,55,56,57,58,59,60,61,              // Numbers zero through nine
+        -9,-9,-9,                                   // Decimal 58 - 60
+        -1,                                         // Equals sign at decimal 61
+        -9,-9,-9,                                      // Decimal 62 - 64
+        0,1,2,3,4,5,6,7,8,9,10,11,12,13,            // Letters 'A' through 'N'
+        14,15,16,17,18,19,20,21,22,23,24,25,        // Letters 'O' through 'Z'
+        -9,-9,-9,-9,-9,-9,                          // Decimal 91 - 96
+        26,27,28,29,30,31,32,33,34,35,36,37,38,     // Letters 'a' through 'm'
+        39,40,41,42,43,44,45,46,47,48,49,50,51,     // Letters 'n' through 'z'
+        -9,-9,-9,-9,-9                              // Decimal 123 - 127
+        ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,       // Decimal 128 - 139
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 140 - 152
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 153 - 165
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 166 - 178
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 179 - 191
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 192 - 204
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 205 - 217
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 218 - 230
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 231 - 243
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9         // Decimal 244 - 255 
+    };
+       
+       
+/* ********  U R L   S A F E   B A S E 6 4   A L P H A B E T  ******** */
+       
+    /**
+     * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: 
+     * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
+     * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."
+     */
+    private final static byte[] _URL_SAFE_ALPHABET = {
+      (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
+      (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
+      (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', 
+      (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
+      (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
+      (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
+      (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', 
+      (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
+      (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', 
+      (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_'
+    };
+       
+    /**
+     * Used in decoding URL- and Filename-safe dialects of Base64.
+     */
+    private final static byte[] _URL_SAFE_DECODABET = {
+      -9,-9,-9,-9,-9,-9,-9,-9,-9,                 // Decimal  0 -  8
+      -5,-5,                                      // Whitespace: Tab and Linefeed
+      -9,-9,                                      // Decimal 11 - 12
+      -5,                                         // Whitespace: Carriage Return
+      -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 14 - 26
+      -9,-9,-9,-9,-9,                             // Decimal 27 - 31
+      -5,                                         // Whitespace: Space
+      -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,              // Decimal 33 - 42
+      -9,                                         // Plus sign at decimal 43
+      -9,                                         // Decimal 44
+      62,                                         // Minus sign at decimal 45
+      -9,                                         // Decimal 46
+      -9,                                         // Slash at decimal 47
+      52,53,54,55,56,57,58,59,60,61,              // Numbers zero through nine
+      -9,-9,-9,                                   // Decimal 58 - 60
+      -1,                                         // Equals sign at decimal 61
+      -9,-9,-9,                                   // Decimal 62 - 64
+      0,1,2,3,4,5,6,7,8,9,10,11,12,13,            // Letters 'A' through 'N'
+      14,15,16,17,18,19,20,21,22,23,24,25,        // Letters 'O' through 'Z'
+      -9,-9,-9,-9,                                // Decimal 91 - 94
+      63,                                         // Underscore at decimal 95
+      -9,                                         // Decimal 96
+      26,27,28,29,30,31,32,33,34,35,36,37,38,     // Letters 'a' through 'm'
+      39,40,41,42,43,44,45,46,47,48,49,50,51,     // Letters 'n' through 'z'
+      -9,-9,-9,-9,-9                              // Decimal 123 - 127
+      ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 128 - 139
+      -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 140 - 152
+      -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 153 - 165
+      -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 166 - 178
+      -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 179 - 191
+      -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 192 - 204
+      -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 205 - 217
+      -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 218 - 230
+      -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 231 - 243
+      -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9         // Decimal 244 - 255 
+    };
+
+
+
+/* ********  O R D E R E D   B A S E 6 4   A L P H A B E T  ******** */
+
+    /**
+     * I don't get the point of this technique, but someone requested it,
+     * and it is described here:
+     * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
+     */
+    private final static byte[] _ORDERED_ALPHABET = {
+      (byte)'-',
+      (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4',
+      (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9',
+      (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
+      (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
+      (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
+      (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
+      (byte)'_',
+      (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
+      (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
+      (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
+      (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z'
+    };
+       
+    /**
+     * Used in decoding the "ordered" dialect of Base64.
+     */
+    private final static byte[] _ORDERED_DECODABET = {
+      -9,-9,-9,-9,-9,-9,-9,-9,-9,                 // Decimal  0 -  8
+      -5,-5,                                      // Whitespace: Tab and Linefeed
+      -9,-9,                                      // Decimal 11 - 12
+      -5,                                         // Whitespace: Carriage Return
+      -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 14 - 26
+      -9,-9,-9,-9,-9,                             // Decimal 27 - 31
+      -5,                                         // Whitespace: Space
+      -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,              // Decimal 33 - 42
+      -9,                                         // Plus sign at decimal 43
+      -9,                                         // Decimal 44
+      0,                                          // Minus sign at decimal 45
+      -9,                                         // Decimal 46
+      -9,                                         // Slash at decimal 47
+      1,2,3,4,5,6,7,8,9,10,                       // Numbers zero through nine
+      -9,-9,-9,                                   // Decimal 58 - 60
+      -1,                                         // Equals sign at decimal 61
+      -9,-9,-9,                                   // Decimal 62 - 64
+      11,12,13,14,15,16,17,18,19,20,21,22,23,     // Letters 'A' through 'M'
+      24,25,26,27,28,29,30,31,32,33,34,35,36,     // Letters 'N' through 'Z'
+      -9,-9,-9,-9,                                // Decimal 91 - 94
+      37,                                         // Underscore at decimal 95
+      -9,                                         // Decimal 96
+      38,39,40,41,42,43,44,45,46,47,48,49,50,     // Letters 'a' through 'm'
+      51,52,53,54,55,56,57,58,59,60,61,62,63,     // Letters 'n' through 'z'
+      -9,-9,-9,-9,-9                                 // Decimal 123 - 127
+       ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 128 - 139
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 140 - 152
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 153 - 165
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 166 - 178
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 179 - 191
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 192 - 204
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 205 - 217
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 218 - 230
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 231 - 243
+        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9         // Decimal 244 - 255 
+    };
+
+       
+/* ********  D E T E R M I N E   W H I C H   A L H A B E T  ******** */
+
+
+    /**
+     * Returns one of the _SOMETHING_ALPHABET byte arrays depending on
+     * the options specified.
+     * It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE
+     * in which case one of them will be picked, though there is
+     * no guarantee as to which one will be picked.
+     */
+    private final static byte[] getAlphabet( int options ) {
+        if ((options & URL_SAFE) == URL_SAFE) {
+            return _URL_SAFE_ALPHABET;
+        } else if ((options & ORDERED) == ORDERED) {
+            return _ORDERED_ALPHABET;
+        } else {
+            return _STANDARD_ALPHABET;
+        }
+    }  // end getAlphabet
+
+
+    /**
+     * Returns one of the _SOMETHING_DECODABET byte arrays depending on
+     * the options specified.
+     * It's possible, though silly, to specify ORDERED and URL_SAFE
+     * in which case one of them will be picked, though there is
+     * no guarantee as to which one will be picked.
+     */
+    private final static byte[] getDecodabet( int options ) {
+        if( (options & URL_SAFE) == URL_SAFE) {
+            return _URL_SAFE_DECODABET;
+        } else if ((options & ORDERED) == ORDERED) {
+            return _ORDERED_DECODABET;
+        } else {
+            return _STANDARD_DECODABET;
+        }
+    }  // end getAlphabet
+
+
+    
+    /** Defeats instantiation. */
+    private Base64(){}
+    
+
+    
+    
+/* ********  E N C O D I N G   M E T H O D S  ******** */    
+    
+    
+    /**
+     * Encodes up to the first three bytes of array <var>threeBytes</var>
+     * and returns a four-byte array in Base64 notation.
+     * The actual number of significant bytes in your array is
+     * given by <var>numSigBytes</var>.
+     * The array <var>threeBytes</var> needs only be as big as
+     * <var>numSigBytes</var>.
+     * Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
+     *
+     * @param b4 A reusable byte array to reduce array instantiation
+     * @param threeBytes the array to convert
+     * @param numSigBytes the number of significant bytes in your array
+     * @return four byte array in Base64 notation.
+     * @since 1.5.1
+     */
+    private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) {
+        encode3to4( threeBytes, 0, numSigBytes, b4, 0, options );
+        return b4;
+    }   // end encode3to4
+
+    
+    /**
+     * <p>Encodes up to three bytes of the array <var>source</var>
+     * and writes the resulting four Base64 bytes to <var>destination</var>.
+     * The source and destination arrays can be manipulated
+     * anywhere along their length by specifying 
+     * <var>srcOffset</var> and <var>destOffset</var>.
+     * This method does not check to make sure your arrays
+     * are large enough to accomodate <var>srcOffset</var> + 3 for
+     * the <var>source</var> array or <var>destOffset</var> + 4 for
+     * the <var>destination</var> array.
+     * The actual number of significant bytes in your array is
+     * given by <var>numSigBytes</var>.</p>
+        * <p>This is the lowest level of the encoding methods with
+        * all possible parameters.</p>
+     *
+     * @param source the array to convert
+     * @param srcOffset the index where conversion begins
+     * @param numSigBytes the number of significant bytes in your array
+     * @param destination the array to hold the conversion
+     * @param destOffset the index where output will be put
+     * @return the <var>destination</var> array
+     * @since 1.3
+     */
+    private static byte[] encode3to4( 
+    byte[] source, int srcOffset, int numSigBytes,
+    byte[] destination, int destOffset, int options ) {
+        
+       byte[] ALPHABET = getAlphabet( options ); 
+       
+        //           1         2         3  
+        // 01234567890123456789012345678901 Bit position
+        // --------000000001111111122222222 Array position from threeBytes
+        // --------|    ||    ||    ||    | Six bit groups to index ALPHABET
+        //          >>18  >>12  >> 6  >> 0  Right shift necessary
+        //                0x3f  0x3f  0x3f  Additional AND
+        
+        // Create buffer with zero-padding if there are only one or two
+        // significant bytes passed in the array.
+        // We have to shift left 24 in order to flush out the 1's that appear
+        // when Java treats a value as negative that is cast from a byte to an int.
+        int inBuff =   ( numSigBytes > 0 ? ((source[ srcOffset     ] << 24) >>>  8) : 0 )
+                     | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
+                     | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
+
+        switch( numSigBytes )
+        {
+            case 3:
+                destination[ destOffset     ] = ALPHABET[ (inBuff >>> 18)        ];
+                destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
+                destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>>  6) & 0x3f ];
+                destination[ destOffset + 3 ] = ALPHABET[ (inBuff       ) & 0x3f ];
+                return destination;
+                
+            case 2:
+                destination[ destOffset     ] = ALPHABET[ (inBuff >>> 18)        ];
+                destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
+                destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>>  6) & 0x3f ];
+                destination[ destOffset + 3 ] = EQUALS_SIGN;
+                return destination;
+                
+            case 1:
+                destination[ destOffset     ] = ALPHABET[ (inBuff >>> 18)        ];
+                destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
+                destination[ destOffset + 2 ] = EQUALS_SIGN;
+                destination[ destOffset + 3 ] = EQUALS_SIGN;
+                return destination;
+                
+            default:
+                return destination;
+        }   // end switch
+    }   // end encode3to4
+
+
+
+    /**
+     * Performs Base64 encoding on the <code>raw</code> ByteBuffer,
+     * writing it to the <code>encoded</code> ByteBuffer.
+     * This is an experimental feature. Currently it does not
+     * pass along any options (such as {@link #DO_BREAK_LINES}
+     * or {@link #GZIP}.
+     *
+     * @param raw input buffer
+     * @param encoded output buffer
+     * @since 2.3
+     */
+    public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){
+        byte[] raw3 = new byte[3];
+        byte[] enc4 = new byte[4];
+
+        while( raw.hasRemaining() ){
+            int rem = Math.min(3,raw.remaining());
+            raw.get(raw3,0,rem);
+            Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
+            encoded.put(enc4);
+        }   // end input remaining
+    }
+
+
+    /**
+     * Performs Base64 encoding on the <code>raw</code> ByteBuffer,
+     * writing it to the <code>encoded</code> CharBuffer.
+     * This is an experimental feature. Currently it does not
+     * pass along any options (such as {@link #DO_BREAK_LINES}
+     * or {@link #GZIP}.
+     *
+     * @param raw input buffer
+     * @param encoded output buffer
+     * @since 2.3
+     */
+    public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){
+        byte[] raw3 = new byte[3];
+        byte[] enc4 = new byte[4];
+
+        while( raw.hasRemaining() ){
+            int rem = Math.min(3,raw.remaining());
+            raw.get(raw3,0,rem);
+            Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
+            for( int i = 0; i < 4; i++ ){
+                encoded.put( (char)(enc4[i] & 0xFF) );
+            }
+        }   // end input remaining
+    }
+
+
+    
+    
+    /**
+     * Serializes an object and returns the Base64-encoded
+     * version of that serialized object.  
+     *  
+     * <p>As of v 2.3, if the object
+     * cannot be serialized or there is another error,
+     * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
+     * In earlier versions, it just returned a null value, but
+     * in retrospect that's a pretty poor way to handle it.</p>
+     * 
+     * The object is not GZip-compressed before being encoded.
+     *
+     * @param serializableObject The object to encode
+     * @return The Base64-encoded object
+     * @throws java.io.IOException if there is an error
+     * @throws NullPointerException if serializedObject is null
+     * @since 1.4
+     */
+    public static String encodeObject( java.io.Serializable serializableObject )
+    throws java.io.IOException {
+        return encodeObject( serializableObject, NO_OPTIONS );
+    }   // end encodeObject
+    
+
+
+    /**
+     * Serializes an object and returns the Base64-encoded
+     * version of that serialized object.
+     *  
+     * <p>As of v 2.3, if the object
+     * cannot be serialized or there is another error,
+     * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
+     * In earlier versions, it just returned a null value, but
+     * in retrospect that's a pretty poor way to handle it.</p>
+     * 
+     * The object is not GZip-compressed before being encoded.
+     * <p>
+     * Example options:<pre>
+     *   GZIP: gzip-compresses object before encoding it.
+     *   DO_BREAK_LINES: break lines at 76 characters
+     * </pre>
+     * <p>
+     * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
+     * <p>
+     * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
+     *
+     * @param serializableObject The object to encode
+     * @param options Specified options
+     * @return The Base64-encoded object
+     * @see Base64#GZIP
+     * @see Base64#DO_BREAK_LINES
+     * @throws java.io.IOException if there is an error
+     * @since 2.0
+     */
+    public static String encodeObject( java.io.Serializable serializableObject, int options )
+    throws java.io.IOException {
+
+        if( serializableObject == null ){
+            throw new NullPointerException( "Cannot serialize a null object." );
+        }   // end if: null
+        
+        // Streams
+        java.io.ByteArrayOutputStream  baos  = null; 
+        java.io.OutputStream           b64os = null;
+        java.util.zip.GZIPOutputStream gzos  = null;
+        java.io.ObjectOutputStream     oos   = null;
+        
+        
+        try {
+            // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
+            baos  = new java.io.ByteArrayOutputStream();
+            b64os = new Base64.OutputStream( baos, ENCODE | options );
+            if( (options & GZIP) != 0 ){
+                // Gzip
+                gzos = new java.util.zip.GZIPOutputStream(b64os);
+                oos = new java.io.ObjectOutputStream( gzos );
+            } else {
+                // Not gzipped
+                oos = new java.io.ObjectOutputStream( b64os );
+            }
+            oos.writeObject( serializableObject );
+        }   // end try
+        catch( java.io.IOException e ) {
+            // Catch it and then throw it immediately so that
+            // the finally{} block is called for cleanup.
+            throw e;
+        }   // end catch
+        finally {
+            try{ oos.close();   } catch( Exception e ){}
+            try{ gzos.close();  } catch( Exception e ){}
+            try{ b64os.close(); } catch( Exception e ){}
+            try{ baos.close();  } catch( Exception e ){}
+        }   // end finally
+        
+        // Return value according to relevant encoding.
+        try {
+            return new String( baos.toByteArray(), PREFERRED_ENCODING );
+        }   // end try
+        catch (java.io.UnsupportedEncodingException uue){
+            // Fall back to some Java default
+            return new String( baos.toByteArray() );
+        }   // end catch
+        
+    }   // end encode
+    
+    
+
+    /**
+     * Encodes a byte array into Base64 notation.
+     * Does not GZip-compress data.
+     *  
+     * @param source The data to convert
+     * @return The data in Base64-encoded form
+     * @throws NullPointerException if source array is null
+     * @since 1.4
+     */
+    public static String encodeBytes( byte[] source ) {
+        // Since we're not going to have the GZIP encoding turned on,
+        // we're not going to have an java.io.IOException thrown, so
+        // we should not force the user to have to catch it.
+        String encoded = null;
+        try {
+            encoded = encodeBytes(source, 0, source.length, NO_OPTIONS);
+        } catch (java.io.IOException ex) {
+            assert false : ex.getMessage();
+        }   // end catch
+        assert encoded != null;
+        return encoded;
+    }   // end encodeBytes
+    
+
+
+    /**
+     * Encodes a byte array into Base64 notation.
+     * <p>
+     * Example options:<pre>
+     *   GZIP: gzip-compresses object before encoding it.
+     *   DO_BREAK_LINES: break lines at 76 characters
+     *     <i>Note: Technically, this makes your encoding non-compliant.</i>
+     * </pre>
+     * <p>
+     * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
+     * <p>
+     * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
+     *
+     *  
+     * <p>As of v 2.3, if there is an error with the GZIP stream,
+     * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
+     * In earlier versions, it just returned a null value, but
+     * in retrospect that's a pretty poor way to handle it.</p>
+     * 
+     *
+     * @param source The data to convert
+     * @param options Specified options
+     * @return The Base64-encoded data as a String
+     * @see Base64#GZIP
+     * @see Base64#DO_BREAK_LINES
+     * @throws java.io.IOException if there is an error
+     * @throws NullPointerException if source array is null
+     * @since 2.0
+     */
+    public static String encodeBytes( byte[] source, int options ) throws java.io.IOException {
+        return encodeBytes( source, 0, source.length, options );
+    }   // end encodeBytes
+    
+    
+    /**
+     * Encodes a byte array into Base64 notation.
+     * Does not GZip-compress data.
+     *  
+     * <p>As of v 2.3, if there is an error,
+     * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
+     * In earlier versions, it just returned a null value, but
+     * in retrospect that's a pretty poor way to handle it.</p>
+     * 
+     *
+     * @param source The data to convert
+     * @param off Offset in array where conversion should begin
+     * @param len Length of data to convert
+     * @return The Base64-encoded data as a String
+     * @throws NullPointerException if source array is null
+     * @throws IllegalArgumentException if source array, offset, or length are invalid
+     * @since 1.4
+     */
+    public static String encodeBytes( byte[] source, int off, int len ) {
+        // Since we're not going to have the GZIP encoding turned on,
+        // we're not going to have an java.io.IOException thrown, so
+        // we should not force the user to have to catch it.
+        String encoded = null;
+        try {
+            encoded = encodeBytes( source, off, len, NO_OPTIONS );
+        } catch (java.io.IOException ex) {
+            assert false : ex.getMessage();
+        }   // end catch
+        assert encoded != null;
+        return encoded;
+    }   // end encodeBytes
+    
+    
+
+    /**
+     * Encodes a byte array into Base64 notation.
+     * <p>
+     * Example options:<pre>
+     *   GZIP: gzip-compresses object before encoding it.
+     *   DO_BREAK_LINES: break lines at 76 characters
+     *     <i>Note: Technically, this makes your encoding non-compliant.</i>
+     * </pre>
+     * <p>
+     * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
+     * <p>
+     * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
+     *
+     *  
+     * <p>As of v 2.3, if there is an error with the GZIP stream,
+     * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
+     * In earlier versions, it just returned a null value, but
+     * in retrospect that's a pretty poor way to handle it.</p>
+     * 
+     *
+     * @param source The data to convert
+     * @param off Offset in array where conversion should begin
+     * @param len Length of data to convert
+     * @param options Specified options
+     * @return The Base64-encoded data as a String
+     * @see Base64#GZIP
+     * @see Base64#DO_BREAK_LINES
+     * @throws java.io.IOException if there is an error
+     * @throws NullPointerException if source array is null
+     * @throws IllegalArgumentException if source array, offset, or length are invalid
+     * @since 2.0
+     */
+    public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {
+        byte[] encoded = encodeBytesToBytes( source, off, len, options );
+
+        // Return value according to relevant encoding.
+        try {
+            return new String( encoded, PREFERRED_ENCODING );
+        }   // end try
+        catch (java.io.UnsupportedEncodingException uue) {
+            return new String( encoded );
+        }   // end catch
+        
+    }   // end encodeBytes
+
+
+
+
+    /**
+     * Similar to {@link #encodeBytes(byte[])} but returns
+     * a byte array instead of instantiating a String. This is more efficient
+     * if you're working with I/O streams and have large data sets to encode.
+     *
+     *
+     * @param source The data to convert
+     * @return The Base64-encoded data as a byte[] (of ASCII characters)
+     * @throws NullPointerException if source array is null
+     * @since 2.3.1
+     */
+    public static byte[] encodeBytesToBytes( byte[] source ) {
+        byte[] encoded = null;
+        try {
+            encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS );
+        } catch( java.io.IOException ex ) {
+            assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
+        }
+        return encoded;
+    }
+
+
+    /**
+     * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns
+     * a byte array instead of instantiating a String. This is more efficient
+     * if you're working with I/O streams and have large data sets to encode.
+     *
+     *
+     * @param source The data to convert
+     * @param off Offset in array where conversion should begin
+     * @param len Length of data to convert
+     * @param options Specified options
+     * @return The Base64-encoded data as a String
+     * @see Base64#GZIP
+     * @see Base64#DO_BREAK_LINES
+     * @throws java.io.IOException if there is an error
+     * @throws NullPointerException if source array is null
+     * @throws IllegalArgumentException if source array, offset, or length are invalid
+     * @since 2.3.1
+     */
+    public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {
+
+        if( source == null ){
+            throw new NullPointerException( "Cannot serialize a null array." );
+        }   // end if: null
+
+        if( off < 0 ){
+            throw new IllegalArgumentException( "Cannot have negative offset: " + off );
+        }   // end if: off < 0
+
+        if( len < 0 ){
+            throw new IllegalArgumentException( "Cannot have length offset: " + len );
+        }   // end if: len < 0
+
+        if( off + len > source.length  ){
+            throw new IllegalArgumentException(
+            String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length));
+        }   // end if: off < 0
+
+
+
+        // Compress?
+        if( (options & GZIP) != 0 ) {
+            java.io.ByteArrayOutputStream  baos  = null;
+            java.util.zip.GZIPOutputStream gzos  = null;
+            Base64.OutputStream            b64os = null;
+
+            try {
+                // GZip -> Base64 -> ByteArray
+                baos = new java.io.ByteArrayOutputStream();
+                b64os = new Base64.OutputStream( baos, ENCODE | options );
+                gzos  = new java.util.zip.GZIPOutputStream( b64os );
+
+                gzos.write( source, off, len );
+                gzos.close();
+            }   // end try
+            catch( java.io.IOException e ) {
+                // Catch it and then throw it immediately so that
+                // the finally{} block is called for cleanup.
+                throw e;
+            }   // end catch
+            finally {
+                try{ gzos.close();  } catch( Exception e ){}
+                try{ b64os.close(); } catch( Exception e ){}
+                try{ baos.close();  } catch( Exception e ){}
+            }   // end finally
+
+            return baos.toByteArray();
+        }   // end if: compress
+
+        // Else, don't compress. Better not to use streams at all then.
+        else {
+            boolean breakLines = (options & DO_BREAK_LINES) != 0;
+
+            //int    len43   = len * 4 / 3;
+            //byte[] outBuff = new byte[   ( len43 )                      // Main 4:3
+            //                           + ( (len % 3) > 0 ? 4 : 0 )      // Account for padding
+            //                           + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
+            // Try to determine more precisely how big the array needs to be.
+            // If we get it right, we don't have to do an array copy, and
+            // we save a bunch of memory.
+            int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding
+            if( breakLines ){
+                encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters
+            }
+            byte[] outBuff = new byte[ encLen ];
+
+
+            int d = 0;
+            int e = 0;
+            int len2 = len - 2;
+            int lineLength = 0;
+            for( ; d < len2; d+=3, e+=4 ) {
+                encode3to4( source, d+off, 3, outBuff, e, options );
+
+                lineLength += 4;
+                if( breakLines && lineLength >= MAX_LINE_LENGTH )
+                {
+                    outBuff[e+4] = NEW_LINE;
+                    e++;
+                    lineLength = 0;
+                }   // end if: end of line
+            }   // en dfor: each piece of array
+
+            if( d < len ) {
+                encode3to4( source, d+off, len - d, outBuff, e, options );
+                e += 4;
+            }   // end if: some padding needed
+
+
+            // Only resize array if we didn't guess it right.
+            if( e <= outBuff.length - 1 ){
+                // If breaking lines and the last byte falls right at
+                // the line length (76 bytes per line), there will be
+                // one extra byte, and the array will need to be resized.
+                // Not too bad of an estimate on array size, I'd say.
+                byte[] finalOut = new byte[e];
+                System.arraycopy(outBuff,0, finalOut,0,e);
+                //System.err.println("Having to resize array from " + outBuff.length + " to " + e );
+                return finalOut;
+            } else {
+                //System.err.println("No need to resize array.");
+                return outBuff;
+            }
+        
+        }   // end else: don't compress
+
+    }   // end encodeBytesToBytes
+    
+
+    
+    
+    
+/* ********  D E C O D I N G   M E T H O D S  ******** */
+    
+    
+    /**
+     * Decodes four bytes from array <var>source</var>
+     * and writes the resulting bytes (up to three of them)
+     * to <var>destination</var>.
+     * The source and destination arrays can be manipulated
+     * anywhere along their length by specifying 
+     * <var>srcOffset</var> and <var>destOffset</var>.
+     * This method does not check to make sure your arrays
+     * are large enough to accomodate <var>srcOffset</var> + 4 for
+     * the <var>source</var> array or <var>destOffset</var> + 3 for
+     * the <var>destination</var> array.
+     * This method returns the actual number of bytes that 
+     * were converted from the Base64 encoding.
+        * <p>This is the lowest level of the decoding methods with
+        * all possible parameters.</p>
+     * 
+     *
+     * @param source the array to convert
+     * @param srcOffset the index where conversion begins
+     * @param destination the array to hold the conversion
+     * @param destOffset the index where output will be put
+        * @param options alphabet type is pulled from this (standard, url-safe, ordered)
+     * @return the number of decoded bytes converted
+     * @throws NullPointerException if source or destination arrays are null
+     * @throws IllegalArgumentException if srcOffset or destOffset are invalid
+     *         or there is not enough room in the array.
+     * @since 1.3
+     */
+    private static int decode4to3( 
+    byte[] source, int srcOffset, 
+    byte[] destination, int destOffset, int options ) {
+        
+        // Lots of error checking and exception throwing
+        if( source == null ){
+            throw new NullPointerException( "Source array was null." );
+        }   // end if
+        if( destination == null ){
+            throw new NullPointerException( "Destination array was null." );
+        }   // end if
+        if( srcOffset < 0 || srcOffset + 3 >= source.length ){
+            throw new IllegalArgumentException( String.format(
+            "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) );
+        }   // end if
+        if( destOffset < 0 || destOffset +2 >= destination.length ){
+            throw new IllegalArgumentException( String.format(
+            "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) );
+        }   // end if
+        
+        
+        byte[] DECODABET = getDecodabet( options ); 
+       
+        // Example: Dk==
+        if( source[ srcOffset + 2] == EQUALS_SIGN ) {
+            // Two ways to do the same thing. Don't know which way I like best.
+          //int outBuff =   ( ( DECODABET[ source[ srcOffset    ] ] << 24 ) >>>  6 )
+          //              | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
+            int outBuff =   ( ( DECODABET[ source[ srcOffset    ] ] & 0xFF ) << 18 )
+                          | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
+            
+            destination[ destOffset ] = (byte)( outBuff >>> 16 );
+            return 1;
+        }
+        
+        // Example: DkL=
+        else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
+            // Two ways to do the same thing. Don't know which way I like best.
+          //int outBuff =   ( ( DECODABET[ source[ srcOffset     ] ] << 24 ) >>>  6 )
+          //              | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
+          //              | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
+            int outBuff =   ( ( DECODABET[ source[ srcOffset     ] ] & 0xFF ) << 18 )
+                          | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
+                          | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) <<  6 );
+            
+            destination[ destOffset     ] = (byte)( outBuff >>> 16 );
+            destination[ destOffset + 1 ] = (byte)( outBuff >>>  8 );
+            return 2;
+        }
+        
+        // Example: DkLE
+        else {
+            // Two ways to do the same thing. Don't know which way I like best.
+          //int outBuff =   ( ( DECODABET[ source[ srcOffset     ] ] << 24 ) >>>  6 )
+          //              | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
+          //              | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
+          //              | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
+            int outBuff =   ( ( DECODABET[ source[ srcOffset     ] ] & 0xFF ) << 18 )
+                          | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
+                          | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) <<  6)
+                          | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF )      );
+
+            
+            destination[ destOffset     ] = (byte)( outBuff >> 16 );
+            destination[ destOffset + 1 ] = (byte)( outBuff >>  8 );
+            destination[ destOffset + 2 ] = (byte)( outBuff       );
+
+            return 3;
+        }
+    }   // end decodeToBytes
+    
+
+
+
+
+    /**
+     * Low-level access to decoding ASCII characters in
+     * the form of a byte array. <strong>Ignores GUNZIP option, if
+     * it's set.</strong> This is not generally a recommended method,
+     * although it is used internally as part of the decoding process.
+     * Special case: if len = 0, an empty array is returned. Still,
+     * if you need more speed and reduced memory footprint (and aren't
+     * gzipping), consider this method.
+     *
+     * @param source The Base64 encoded data
+     * @return decoded data
+     * @since 2.3.1
+     */
+    public static byte[] decode( byte[] source )
+    throws java.io.IOException {
+        byte[] decoded = null;
+//        try {
+            decoded = decode( source, 0, source.length, Base64.NO_OPTIONS );
+//        } catch( java.io.IOException ex ) {
+//            assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
+//        }
+        return decoded;
+    }
+
+    
+    
+    /**
+     * Low-level access to decoding ASCII characters in
+     * the form of a byte array. <strong>Ignores GUNZIP option, if
+     * it's set.</strong> This is not generally a recommended method,
+     * although it is used internally as part of the decoding process.
+     * Special case: if len = 0, an empty array is returned. Still,
+     * if you need more speed and reduced memory footprint (and aren't
+     * gzipping), consider this method.
+     *
+     * @param source The Base64 encoded data
+     * @param off    The offset of where to begin decoding
+     * @param len    The length of characters to decode
+     * @param options Can specify options such as alphabet type to use
+     * @return decoded data
+     * @throws java.io.IOException If bogus characters exist in source data
+     * @since 1.3
+     */
+    public static byte[] decode( byte[] source, int off, int len, int options )
+    throws java.io.IOException {
+        
+        // Lots of error checking and exception throwing
+        if( source == null ){
+            throw new NullPointerException( "Cannot decode null source array." );
+        }   // end if
+        if( off < 0 || off + len > source.length ){
+            throw new IllegalArgumentException( String.format(
+            "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) );
+        }   // end if
+        
+        if( len == 0 ){
+            return new byte[0];
+        }else if( len < 4 ){
+            throw new IllegalArgumentException( 
+            "Base64-encoded string must have at least four characters, but length specified was " + len );
+        }   // end if
+        
+        byte[] DECODABET = getDecodabet( options );
+       
+        int    len34   = len * 3 / 4;       // Estimate on array size
+        byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
+        int    outBuffPosn = 0;             // Keep track of where we're writing
+        
+        byte[] b4        = new byte[4];     // Four byte buffer from source, eliminating white space
+        int    b4Posn    = 0;               // Keep track of four byte input buffer
+        int    i         = 0;               // Source array counter
+        byte   sbiDecode = 0;               // Special value from DECODABET
+        
+        for( i = off; i < off+len; i++ ) {  // Loop through source
+            
+            sbiDecode = DECODABET[ source[i]&0xFF ];
+            
+            // White space, Equals sign, or legit Base64 character
+            // Note the values such as -5 and -9 in the
+            // DECODABETs at the top of the file.
+            if( sbiDecode >= WHITE_SPACE_ENC )  {
+                if( sbiDecode >= EQUALS_SIGN_ENC ) {
+                    b4[ b4Posn++ ] = source[i];         // Save non-whitespace
+                    if( b4Posn > 3 ) {                  // Time to decode?
+                        outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
+                        b4Posn = 0;
+                        
+                        // If that was the equals sign, break out of 'for' loop
+                        if( source[i] == EQUALS_SIGN ) {
+                            break;
+                        }   // end if: equals sign
+                    }   // end if: quartet built
+                }   // end if: equals sign or better
+            }   // end if: white space, equals sign or better
+            else {
+                // There's a bad input character in the Base64 stream.
+                throw new java.io.IOException( String.format(
+                "Bad Base64 input character decimal %d in array position %d", ((int)source[i])&0xFF, i ) );
+            }   // end else: 
+        }   // each input character
+                                   
+        byte[] out = new byte[ outBuffPosn ];
+        System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); 
+        return out;
+    }   // end decode
+    
+    
+       
+       
+    /**
+     * Decodes data from Base64 notation, automatically
+     * detecting gzip-compressed data and decompressing it.
+     *
+     * @param s the string to decode
+     * @return the decoded data
+     * @throws java.io.IOException If there is a problem
+     * @since 1.4
+     */
+    public static byte[] decode( String s ) throws java.io.IOException {
+        return decode( s, NO_OPTIONS );
+    }
+
+    
+    
+    /**
+     * Decodes data from Base64 notation, automatically
+     * detecting gzip-compressed data and decompressing it.
+     *
+     * @param s the string to decode
+     * @param options encode options such as URL_SAFE
+     * @return the decoded data
+     * @throws java.io.IOException if there is an error
+     * @throws NullPointerException if <tt>s</tt> is null
+     * @since 1.4
+     */
+    public static byte[] decode( String s, int options ) throws java.io.IOException {
+        
+        if( s == null ){
+            throw new NullPointerException( "Input string was null." );
+        }   // end if
+        
+        byte[] bytes;
+        try {
+            bytes = s.getBytes( PREFERRED_ENCODING );
+        }   // end try
+        catch( java.io.UnsupportedEncodingException uee ) {
+            bytes = s.getBytes();
+        }   // end catch
+               //</change>
+        
+        // Decode
+        bytes = decode( bytes, 0, bytes.length, options );
+        
+        // Check to see if it's gzip-compressed
+        // GZIP Magic Two-Byte Number: 0x8b1f (35615)
+        boolean dontGunzip = (options & DONT_GUNZIP) != 0;
+        if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) {
+            
+            int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
+            if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head )  {
+                java.io.ByteArrayInputStream  bais = null;
+                java.util.zip.GZIPInputStream gzis = null;
+                java.io.ByteArrayOutputStream baos = null;
+                byte[] buffer = new byte[2048];
+                int    length = 0;
+
+                try {
+                    baos = new java.io.ByteArrayOutputStream();
+                    bais = new java.io.ByteArrayInputStream( bytes );
+                    gzis = new java.util.zip.GZIPInputStream( bais );
+
+                    while( ( length = gzis.read( buffer ) ) >= 0 ) {
+                        baos.write(buffer,0,length);
+                    }   // end while: reading input
+
+                    // No error? Get new bytes.
+                    bytes = baos.toByteArray();
+
+                }   // end try
+                catch( java.io.IOException e ) {
+                    e.printStackTrace();
+                    // Just return originally-decoded bytes
+                }   // end catch
+                finally {
+                    try{ baos.close(); } catch( Exception e ){}
+                    try{ gzis.close(); } catch( Exception e ){}
+                    try{ bais.close(); } catch( Exception e ){}
+                }   // end finally
+
+            }   // end if: gzipped
+        }   // end if: bytes.length >= 2
+        
+        return bytes;
+    }   // end decode
+
+
+
+    /**
+     * Attempts to decode Base64 data and deserialize a Java
+     * Object within. Returns <tt>null</tt> if there was an error.
+     *
+     * @param encodedObject The Base64 data to decode
+     * @return The decoded and deserialized object
+     * @throws NullPointerException if encodedObject is null
+     * @throws java.io.IOException if there is a general error
+     * @throws ClassNotFoundException if the decoded object is of a
+     *         class that cannot be found by the JVM
+     * @since 1.5
+     */
+    public static Object decodeToObject( String encodedObject )
+    throws java.io.IOException, java.lang.ClassNotFoundException {
+        return decodeToObject(encodedObject,NO_OPTIONS,null);
+    }
+    
+
+    /**
+     * Attempts to decode Base64 data and deserialize a Java
+     * Object within. Returns <tt>null</tt> if there was an error.
+     * If <tt>loader</tt> is not null, it will be the class loader
+     * used when deserializing.
+     *
+     * @param encodedObject The Base64 data to decode
+     * @param options Various parameters related to decoding
+     * @param loader Optional class loader to use in deserializing classes.
+     * @return The decoded and deserialized object
+     * @throws NullPointerException if encodedObject is null
+     * @throws java.io.IOException if there is a general error
+     * @throws ClassNotFoundException if the decoded object is of a 
+     *         class that cannot be found by the JVM
+     * @since 2.3.4
+     */
+    public static Object decodeToObject( 
+    String encodedObject, int options, final ClassLoader loader )
+    throws java.io.IOException, java.lang.ClassNotFoundException {
+        
+        // Decode and gunzip if necessary
+        byte[] objBytes = decode( encodedObject, options );
+        
+        java.io.ByteArrayInputStream  bais = null;
+        java.io.ObjectInputStream     ois  = null;
+        Object obj = null;
+        
+        try {
+            bais = new java.io.ByteArrayInputStream( objBytes );
+
+            // If no custom class loader is provided, use Java's builtin OIS.
+            if( loader == null ){
+                ois  = new java.io.ObjectInputStream( bais );
+            }   // end if: no loader provided
+
+            // Else make a customized object input stream that uses
+            // the provided class loader.
+            else {
+                ois = new java.io.ObjectInputStream(bais){
+                    @Override
+                    public Class<?> resolveClass(java.io.ObjectStreamClass streamClass)
+                    throws java.io.IOException, ClassNotFoundException {
+                        Class c = Class.forName(streamClass.getName(), false, loader);
+                        if( c == null ){
+                            return super.resolveClass(streamClass);
+                        } else {
+                            return c;   // Class loader knows of this class.
+                        }   // end else: not null
+                    }   // end resolveClass
+                };  // end ois
+            }   // end else: no custom class loader
+        
+            obj = ois.readObject();
+        }   // end try
+        catch( java.io.IOException e ) {
+            throw e;    // Catch and throw in order to execute finally{}
+        }   // end catch
+        catch( java.lang.ClassNotFoundException e ) {
+            throw e;    // Catch and throw in order to execute finally{}
+        }   // end catch
+        finally {
+            try{ bais.close(); } catch( Exception e ){}
+            try{ ois.close();  } catch( Exception e ){}
+        }   // end finally
+        
+        return obj;
+    }   // end decodeObject
+    
+    
+    
+    /**
+     * Convenience method for encoding data to a file.
+     *
+     * <p>As of v 2.3, if there is a error,
+     * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
+     * In earlier versions, it just returned false, but
+     * in retrospect that's a pretty poor way to handle it.</p>
+     * 
+     * @param dataToEncode byte array of data to encode in base64 form
+     * @param filename Filename for saving encoded data
+     * @throws java.io.IOException if there is an error
+     * @throws NullPointerException if dataToEncode is null
+     * @since 2.1
+     */
+    public static void encodeToFile( byte[] dataToEncode, String filename )
+    throws java.io.IOException {
+        
+        if( dataToEncode == null ){
+            throw new NullPointerException( "Data to encode was null." );
+        }   // end iff
+        
+        Base64.OutputStream bos = null;
+        try {
+            bos = new Base64.OutputStream( 
+                  new java.io.FileOutputStream( filename ), Base64.ENCODE );
+            bos.write( dataToEncode );
+        }   // end try
+        catch( java.io.IOException e ) {
+            throw e; // Catch and throw to execute finally{} block
+        }   // end catch: java.io.IOException
+        finally {
+            try{ bos.close(); } catch( Exception e ){}
+        }   // end finally
+        
+    }   // end encodeToFile
+    
+    
+    /**
+     * Convenience method for decoding data to a file.
+     *
+     * <p>As of v 2.3, if there is a error,
+     * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
+     * In earlier versions, it just returned false, but
+     * in retrospect that's a pretty poor way to handle it.</p>
+     * 
+     * @param dataToDecode Base64-encoded data as a string
+     * @param filename Filename for saving decoded data
+     * @throws java.io.IOException if there is an error
+     * @since 2.1
+     */
+    public static void decodeToFile( String dataToDecode, String filename )
+    throws java.io.IOException {
+        
+        Base64.OutputStream bos = null;
+        try{
+            bos = new Base64.OutputStream( 
+                      new java.io.FileOutputStream( filename ), Base64.DECODE );
+            bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );
+        }   // end try
+        catch( java.io.IOException e ) {
+            throw e; // Catch and throw to execute finally{} block
+        }   // end catch: java.io.IOException
+        finally {
+                try{ bos.close(); } catch( Exception e ){}
+        }   // end finally
+        
+    }   // end decodeToFile
+    
+    
+    
+    
+    /**
+     * Convenience method for reading a base64-encoded
+     * file and decoding it.
+     *
+     * <p>As of v 2.3, if there is a error,
+     * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
+     * In earlier versions, it just returned false, but
+     * in retrospect that's a pretty poor way to handle it.</p>
+     * 
+     * @param filename Filename for reading encoded data
+     * @return decoded byte array
+     * @throws java.io.IOException if there is an error
+     * @since 2.1
+     */
+    public static byte[] decodeFromFile( String filename )
+    throws java.io.IOException {
+        
+        byte[] decodedData = null;
+        Base64.InputStream bis = null;
+        try
+        {
+            // Set up some useful variables
+            java.io.File file = new java.io.File( filename );
+            byte[] buffer = null;
+            int length   = 0;
+            int numBytes = 0;
+            
+            // Check for size of file
+            if( file.length() > Integer.MAX_VALUE )
+            {
+                throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." );
+            }   // end if: file too big for int index
+            buffer = new byte[ (int)file.length() ];
+            
+            // Open a stream
+            bis = new Base64.InputStream( 
+                      new java.io.BufferedInputStream( 
+                      new java.io.FileInputStream( file ) ), Base64.DECODE );
+            
+            // Read until done
+            while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {
+                length += numBytes;
+            }   // end while
+            
+            // Save in a variable to return
+            decodedData = new byte[ length ];
+            System.arraycopy( buffer, 0, decodedData, 0, length );
+            
+        }   // end try
+        catch( java.io.IOException e ) {
+            throw e; // Catch and release to execute finally{}
+        }   // end catch: java.io.IOException
+        finally {
+            try{ bis.close(); } catch( Exception e) {}
+        }   // end finally
+        
+        return decodedData;
+    }   // end decodeFromFile
+    
+    
+    
+    /**
+     * Convenience method for reading a binary file
+     * and base64-encoding it.
+     *
+     * <p>As of v 2.3, if there is a error,
+     * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
+     * In earlier versions, it just returned false, but
+     * in retrospect that's a pretty poor way to handle it.</p>
+     * 
+     * @param filename Filename for reading binary data
+     * @return base64-encoded string
+     * @throws java.io.IOException if there is an error
+     * @since 2.1
+     */
+    public static String encodeFromFile( String filename )
+    throws java.io.IOException {
+        
+        String encodedData = null;
+        Base64.InputStream bis = null;
+        try
+        {
+            // Set up some useful variables
+            java.io.File file = new java.io.File( filename );
+            byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4+1),40) ]; // Need max() for math on small files (v2.2.1); Need +1 for a few corner cases (v2.3.5)
+            int length   = 0;
+            int numBytes = 0;
+            
+            // Open a stream
+            bis = new Base64.InputStream( 
+                      new java.io.BufferedInputStream( 
+                      new java.io.FileInputStream( file ) ), Base64.ENCODE );
+            
+            // Read until done
+            while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {
+                length += numBytes;
+            }   // end while
+            
+            // Save in a variable to return
+            encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
+                
+        }   // end try
+        catch( java.io.IOException e ) {
+            throw e; // Catch and release to execute finally{}
+        }   // end catch: java.io.IOException
+        finally {
+            try{ bis.close(); } catch( Exception e) {}
+        }   // end finally
+        
+        return encodedData;
+        }   // end encodeFromFile
+    
+    /**
+     * Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
+     *
+     * @param infile Input file
+     * @param outfile Output file
+     * @throws java.io.IOException if there is an error
+     * @since 2.2
+     */
+    public static void encodeFileToFile( String infile, String outfile )
+    throws java.io.IOException {
+        
+        String encoded = Base64.encodeFromFile( infile );
+        java.io.OutputStream out = null;
+        try{
+            out = new java.io.BufferedOutputStream(
+                  new java.io.FileOutputStream( outfile ) );
+            out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output.
+        }   // end try
+        catch( java.io.IOException e ) {
+            throw e; // Catch and release to execute finally{}
+        }   // end catch
+        finally {
+            try { out.close(); }
+            catch( Exception ex ){}
+        }   // end finally    
+    }   // end encodeFileToFile
+
+
+    /**
+     * Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.
+     *
+     * @param infile Input file
+     * @param outfile Output file
+     * @throws java.io.IOException if there is an error
+     * @since 2.2
+     */
+    public static void decodeFileToFile( String infile, String outfile )
+    throws java.io.IOException {
+        
+        byte[] decoded = Base64.decodeFromFile( infile );
+        java.io.OutputStream out = null;
+        try{
+            out = new java.io.BufferedOutputStream(
+                  new java.io.FileOutputStream( outfile ) );
+            out.write( decoded );
+        }   // end try
+        catch( java.io.IOException e ) {
+            throw e; // Catch and release to execute finally{}
+        }   // end catch
+        finally {
+            try { out.close(); }
+            catch( Exception ex ){}
+        }   // end finally    
+    }   // end decodeFileToFile
+    
+    
+    /* ********  I N N E R   C L A S S   I N P U T S T R E A M  ******** */
+    
+    
+    
+    /**
+     * A {@link Base64.InputStream} will read data from another
+     * <tt>java.io.InputStream</tt>, given in the constructor,
+     * and encode/decode to/from Base64 notation on the fly.
+     *
+     * @see Base64
+     * @since 1.3
+     */
+    public static class InputStream extends java.io.FilterInputStream {
+        
+        private boolean encode;         // Encoding or decoding
+        private int     position;       // Current position in the buffer
+        private byte[]  buffer;         // Small buffer holding converted data
+        private int     bufferLength;   // Length of buffer (3 or 4)
+        private int     numSigBytes;    // Number of meaningful bytes in the buffer
+        private int     lineLength;
+        private boolean breakLines;     // Break lines at less than 80 characters
+        private int     options;        // Record options used to create the stream.
+        private byte[]  decodabet;      // Local copies to avoid extra method calls
+        
+        
+        /**
+         * Constructs a {@link Base64.InputStream} in DECODE mode.
+         *
+         * @param in the <tt>java.io.InputStream</tt> from which to read data.
+         * @since 1.3
+         */
+        public InputStream( java.io.InputStream in ) {
+            this( in, DECODE );
+        }   // end constructor
+        
+        
+        /**
+         * Constructs a {@link Base64.InputStream} in
+         * either ENCODE or DECODE mode.
+         * <p>
+         * Valid options:<pre>
+         *   ENCODE or DECODE: Encode or Decode as data is read.
+         *   DO_BREAK_LINES: break lines at 76 characters
+         *     (only meaningful when encoding)</i>
+         * </pre>
+         * <p>
+         * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
+         *
+         *
+         * @param in the <tt>java.io.InputStream</tt> from which to read data.
+         * @param options Specified options
+         * @see Base64#ENCODE
+         * @see Base64#DECODE
+         * @see Base64#DO_BREAK_LINES
+         * @since 2.0
+         */
+        public InputStream( java.io.InputStream in, int options ) {
+            
+            super( in );
+            this.options      = options; // Record for later
+            this.breakLines   = (options & DO_BREAK_LINES) > 0;
+            this.encode       = (options & ENCODE) > 0;
+            this.bufferLength = encode ? 4 : 3;
+            this.buffer       = new byte[ bufferLength ];
+            this.position     = -1;
+            this.lineLength   = 0;
+            this.decodabet    = getDecodabet(options);
+        }   // end constructor
+        
+        /**
+         * Reads enough of the input stream to convert
+         * to/from Base64 and returns the next byte.
+         *
+         * @return next byte
+         * @since 1.3
+         */
+        @Override
+        public int read() throws java.io.IOException  {
+            
+            // Do we need to get data?
+            if( position < 0 ) {
+                if( encode ) {
+                    byte[] b3 = new byte[3];
+                    int numBinaryBytes = 0;
+                    for( int i = 0; i < 3; i++ ) {
+                        int b = in.read();
+
+                        // If end of stream, b is -1.
+                        if( b >= 0 ) {
+                            b3[i] = (byte)b;
+                            numBinaryBytes++;
+                        } else {
+                            break; // out of for loop
+                        }   // end else: end of stream
+                            
+                    }   // end for: each needed input byte
+                    
+                    if( numBinaryBytes > 0 ) {
+                        encode3to4( b3, 0, numBinaryBytes, buffer, 0, options );
+                        position = 0;
+                        numSigBytes = 4;
+                    }   // end if: got data
+                    else {
+                        return -1;  // Must be end of stream
+                    }   // end else
+                }   // end if: encoding
+                
+                // Else decoding
+                else {
+                    byte[] b4 = new byte[4];
+                    int i = 0;
+                    for( i = 0; i < 4; i++ ) {
+                        // Read four "meaningful" bytes:
+                        int b = 0;
+                        do{ b = in.read(); }
+                        while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC );
+                        
+                        if( b < 0 ) {
+                            break; // Reads a -1 if end of stream
+                        }   // end if: end of stream
+                        
+                        b4[i] = (byte)b;
+                    }   // end for: each needed input byte
+                    
+                    if( i == 4 ) {
+                        numSigBytes = decode4to3( b4, 0, buffer, 0, options );
+                        position = 0;
+                    }   // end if: got four characters
+                    else if( i == 0 ){
+                        return -1;
+                    }   // end else if: also padded correctly
+                    else {
+                        // Must have broken out from above.
+                        throw new java.io.IOException( "Improperly padded Base64 input." );
+                    }   // end 
+                    
+                }   // end else: decode
+            }   // end else: get data
+            
+            // Got data?
+            if( position >= 0 ) {
+                // End of relevant data?
+                if( /*!encode &&*/ position >= numSigBytes ){
+                    return -1;
+                }   // end if: got data
+                
+                if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) {
+                    lineLength = 0;
+                    return '\n';
+                }   // end if
+                else {
+                    lineLength++;   // This isn't important when decoding
+                                    // but throwing an extra "if" seems
+                                    // just as wasteful.
+                    
+                    int b = buffer[ position++ ];
+
+                    if( position >= bufferLength ) {
+                        position = -1;
+                    }   // end if: end
+
+                    return b & 0xFF; // This is how you "cast" a byte that's
+                                     // intended to be unsigned.
+                }   // end else
+            }   // end if: position >= 0
+            
+            // Else error
+            else {
+                throw new java.io.IOException( "Error in Base64 code reading stream." );
+            }   // end else
+        }   // end read
+        
+        
+        /**
+         * Calls {@link #read()} repeatedly until the end of stream
+         * is reached or <var>len</var> bytes are read.
+         * Returns number of bytes read into array or -1 if
+         * end of stream is encountered.
+         *
+         * @param dest array to hold values
+         * @param off offset for array
+         * @param len max number of bytes to read into array
+         * @return bytes read into array or -1 if end of stream is encountered.
+         * @since 1.3
+         */
+        @Override
+        public int read( byte[] dest, int off, int len ) 
+        throws java.io.IOException {
+            int i;
+            int b;
+            for( i = 0; i < len; i++ ) {
+                b = read();
+                
+                if( b >= 0 ) {
+                    dest[off + i] = (byte) b;
+                }
+                else if( i == 0 ) {
+                    return -1;
+                }
+                else {
+                    break; // Out of 'for' loop
+                } // Out of 'for' loop
+            }   // end for: each byte read
+            return i;
+        }   // end read
+        
+    }   // end inner class InputStream
+    
+    
+    
+    
+    
+    
+    /* ********  I N N E R   C L A S S   O U T P U T S T R E A M  ******** */
+    
+    
+    
+    /**
+     * A {@link Base64.OutputStream} will write data to another
+     * <tt>java.io.OutputStream</tt>, given in the constructor,
+     * and encode/decode to/from Base64 notation on the fly.
+     *
+     * @see Base64
+     * @since 1.3
+     */
+    public static class OutputStream extends java.io.FilterOutputStream {
+        
+        private boolean encode;
+        private int     position;
+        private byte[]  buffer;
+        private int     bufferLength;
+        private int     lineLength;
+        private boolean breakLines;
+        private byte[]  b4;         // Scratch used in a few places
+        private boolean suspendEncoding;
+        private int     options;    // Record for later
+        private byte[]  decodabet;  // Local copies to avoid extra method calls
+        
+        /**
+         * Constructs a {@link Base64.OutputStream} in ENCODE mode.
+         *
+         * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
+         * @since 1.3
+         */
+        public OutputStream( java.io.OutputStream out ) {
+            this( out, ENCODE );
+        }   // end constructor
+        
+        
+        /**
+         * Constructs a {@link Base64.OutputStream} in
+         * either ENCODE or DECODE mode.
+         * <p>
+         * Valid options:<pre>
+         *   ENCODE or DECODE: Encode or Decode as data is read.
+         *   DO_BREAK_LINES: don't break lines at 76 characters
+         *     (only meaningful when encoding)</i>
+         * </pre>
+         * <p>
+         * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
+         *
+         * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
+         * @param options Specified options.
+         * @see Base64#ENCODE
+         * @see Base64#DECODE
+         * @see Base64#DO_BREAK_LINES
+         * @since 1.3
+         */
+        public OutputStream( java.io.OutputStream out, int options ) {
+            super( out );
+            this.breakLines   = (options & DO_BREAK_LINES) != 0;
+            this.encode       = (options & ENCODE) != 0;
+            this.bufferLength = encode ? 3 : 4;
+            this.buffer       = new byte[ bufferLength ];
+            this.position     = 0;
+            this.lineLength   = 0;
+            this.suspendEncoding = false;
+            this.b4           = new byte[4];
+            this.options      = options;
+            this.decodabet    = getDecodabet(options);
+        }   // end constructor
+        
+        
+        /**
+         * Writes the byte to the output stream after
+         * converting to/from Base64 notation.
+         * When encoding, bytes are buffered three
+         * at a time before the output stream actually
+         * gets a write() call.
+         * When decoding, bytes are buffered four
+         * at a time.
+         *
+         * @param theByte the byte to write
+         * @since 1.3
+         */
+        @Override
+        public void write(int theByte) 
+        throws java.io.IOException {
+            // Encoding suspended?
+            if( suspendEncoding ) {
+                this.out.write( theByte );
+                return;
+            }   // end if: supsended
+            
+            // Encode?
+            if( encode ) {
+                buffer[ position++ ] = (byte)theByte;
+                if( position >= bufferLength ) { // Enough to encode.
+                
+                    this.out.write( encode3to4( b4, buffer, bufferLength, options ) );
+
+                    lineLength += 4;
+                    if( breakLines && lineLength >= MAX_LINE_LENGTH ) {
+                        this.out.write( NEW_LINE );
+                        lineLength = 0;
+                    }   // end if: end of line
+
+                    position = 0;
+                }   // end if: enough to output
+            }   // end if: encoding
+
+            // Else, Decoding
+            else {
+                // Meaningful Base64 character?
+                if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) {
+                    buffer[ position++ ] = (byte)theByte;
+                    if( position >= bufferLength ) { // Enough to output.
+                    
+                        int len = Base64.decode4to3( buffer, 0, b4, 0, options );
+                        out.write( b4, 0, len );
+                        position = 0;
+                    }   // end if: enough to output
+                }   // end if: meaningful base64 character
+                else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) {
+                    throw new java.io.IOException( "Invalid character in Base64 data." );
+                }   // end else: not white space either
+            }   // end else: decoding
+        }   // end write
+        
+        
+        
+        /**
+         * Calls {@link #write(int)} repeatedly until <var>len</var> 
+         * bytes are written.
+         *
+         * @param theBytes array from which to read bytes
+         * @param off offset for array
+         * @param len max number of bytes to read into array
+         * @since 1.3
+         */
+        @Override
+        public void write( byte[] theBytes, int off, int len ) 
+        throws java.io.IOException {
+            // Encoding suspended?
+            if( suspendEncoding ) {
+                this.out.write( theBytes, off, len );
+                return;
+            }   // end if: supsended
+            
+            for( int i = 0; i < len; i++ ) {
+                write( theBytes[ off + i ] );
+            }   // end for: each byte written
+            
+        }   // end write
+        
+        
+        
+        /**
+         * Method added by PHIL. [Thanks, PHIL. -Rob]
+         * This pads the buffer without closing the stream.
+         * @throws java.io.IOException  if there's an error.
+         */
+        public void flushBase64() throws java.io.IOException  {
+            if( position > 0 ) {
+                if( encode ) {
+                    out.write( encode3to4( b4, buffer, position, options ) );
+                    position = 0;
+                }   // end if: encoding
+                else {
+                    throw new java.io.IOException( "Base64 input not properly padded." );
+                }   // end else: decoding
+            }   // end if: buffer partially full
+
+        }   // end flush
+
+        
+        /** 
+         * Flushes and closes (I think, in the superclass) the stream. 
+         *
+         * @since 1.3
+         */
+        @Override
+        public void close() throws java.io.IOException {
+            // 1. Ensure that pending characters are written
+            flushBase64();
+
+            // 2. Actually close the stream
+            // Base class both flushes and closes.
+            super.close();
+            
+            buffer = null;
+            out    = null;
+        }   // end close
+        
+        
+        
+        /**
+         * Suspends encoding of the stream.
+         * May be helpful if you need to embed a piece of
+         * base64-encoded data in a stream.
+         *
+         * @throws java.io.IOException  if there's an error flushing
+         * @since 1.5.1
+         */
+        public void suspendEncoding() throws java.io.IOException  {
+            flushBase64();
+            this.suspendEncoding = true;
+        }   // end suspendEncoding
+        
+        
+        /**
+         * Resumes encoding of the stream.
+         * May be helpful if you need to embed a piece of
+         * base64-encoded data in a stream.
+         *
+         * @since 1.5.1
+         */
+        public void resumeEncoding() {
+            this.suspendEncoding = false;
+        }   // end resumeEncoding
+        
+        
+        
+    }   // end inner class OutputStream
+    
+    
+}   // end class Base64
index 6375cb8cd0c40d554a576ae486756ae329869f6f..e00cf01973eeb0bfaad02d482fcffdfa5e582f95 100644 (file)
@@ -2,7 +2,7 @@
 package org.openintents.util;
 
 import org.openintents.intents.CryptoIntents;
-import org.openintents.safe.RuntimeSecrets;
+import org.openintents.safe.IntentHandler;
 import org.openintents.safe.Safe;
 
 import android.app.Activity;
@@ -21,6 +21,8 @@ public class FrontDooringActivity extends Activity {
        private Intent frontdoor;
     protected Intent restartTimerIntent=null;
 
+    public static final String KEY_NO_IMMEDIATE = "no_immediate";  // Intent keys
+
     protected BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
         public void onReceive(Context context, Intent intent) {
             if (intent.getAction().equals(CryptoIntents.ACTION_CRYPTO_LOGGED_OUT)) {
@@ -34,7 +36,8 @@ public class FrontDooringActivity extends Activity {
     protected void onResume() {
                super.onResume();
 
-               if (RuntimeSecrets.isSignedIn()==false) {
+               if (IntentHandler.isSignedIn()==false
+               && !getIntent().getBooleanExtra(KEY_NO_IMMEDIATE,false)) {
                        startActivity(frontdoor);
                        return;
                }
@@ -59,7 +62,7 @@ public class FrontDooringActivity extends Activity {
 
                if (debug) Log.d(TAG,"onUserInteraction()");
 
-               if (!RuntimeSecrets.isSignedIn()==false) {
+               if (!IntentHandler.isSignedIn()==false) {
                        if (restartTimerIntent!=null) sendBroadcast (restartTimerIntent);
                }
        }
index d544eda19c2a81657d0068808444db89eddb27e1..c5a7677224fd015469021be3518e4284cd0be748 100644 (file)
@@ -2,7 +2,7 @@
 package org.openintents.util;
 
 import org.openintents.intents.CryptoIntents;
-import org.openintents.safe.RuntimeSecrets;
+import org.openintents.safe.IntentHandler;
 import org.openintents.safe.Safe;
 
 import android.app.ListActivity;
@@ -34,7 +34,7 @@ public class FrontDooringListActivity extends ListActivity {
     protected void onResume() {
                super.onResume();
 
-               if (RuntimeSecrets.isSignedIn()==false) {
+               if (IntentHandler.isSignedIn()==false) {
                        startActivity(frontdoor);
                        return;
                }
@@ -59,7 +59,7 @@ public class FrontDooringListActivity extends ListActivity {
 
                if (debug) Log.d(TAG,"onUserInteraction()");
 
-               if (!RuntimeSecrets.isSignedIn()==false) {
+               if (!IntentHandler.isSignedIn()==false) {
                        if (restartTimerIntent!=null) sendBroadcast (restartTimerIntent);
                }
        }
diff --git a/src/org/openintents/util/VCPassUtils.java b/src/org/openintents/util/VCPassUtils.java
new file mode 100644 (file)
index 0000000..eec8d5a
--- /dev/null
@@ -0,0 +1,55 @@
+package org.openintents.util;                              
+
+import android.app.Activity;
+import android.content.Intent;
+
+public class VCPassUtils {
+       public static final String ACT_CHAL_CREATE  =
+               "org.ietfng.ns.android.vcpass.CHAL_CREATE";
+       public static final String ACT_CHAL_PRESENT =
+               "org.ietfng.ns.android.vcpass.CHAL_PRESENT";
+       public static final String ACT_SEED_IMPORT  =
+               "org.ietfng.ns.android.vcpass.SEED_IMPORT";
+
+       /*                
+        * DJB Netstrings-esque encoding functions for storing
+        * our two seeds in one string.                       
+        */                                                   
+       public final static String encode_seeds(char[] useed, char[] vseed) {
+               StringBuilder seed = new StringBuilder();              
+               seed.append(Integer.toString(useed.length));           
+               seed.append(':');                                      
+               seed.append(useed);                                    
+               seed.append(Integer.toString(vseed.length));           
+               seed.append(':');                                      
+               seed.append(vseed);                                    
+               return seed.toString();                                
+       }                                                              
+       public final static char[][] decode_seeds(String s) {                
+               StringBuilder sb = new StringBuilder(s);               
+               int ulenend = sb.indexOf(":");                         
+               int ulen = Integer.parseInt(sb.substring(0,ulenend));  
+               int vlenend = sb.indexOf(":",ulenend+ulen+1);          
+               int vlen = Integer.parseInt(sb.substring(ulenend+ulen+1,vlenend));
+               char[][] ret = new char[2][];                                     
+               ret[0] = sb.substring(ulenend+1,ulenend+ulen+1).toCharArray();    
+               ret[1] = sb.substring(vlenend+1).toCharArray();                   
+               return ret;                                                       
+       }
+
+/*     
+       public static boolean startCreateActivity(Activity a, int c, String s) {
+               try{
+                       Intent vcci = new Intent(
+                               "org.ietfng.ns.android.vcpass.CHAL_CREATE");
+                       char[][] seeds = decode_seeds(s);
+                       vcci.putExtra("USEED", seeds[0]);
+                       vcci.putExtra("VSEED", seeds[1]);
+                       a.startActivityForResult(vcci, c);
+                       return true;
+               } catch( Exception e ) {
+                       return false;
+               }
+       }
+*/
+}