Merge change 26396 into eclair

* changes:
  b/2126036 Improve remote device capability identification by switching to use UUIDs instead of class bits.
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 908c955..367aa9c 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -303,7 +303,8 @@
                 <action android:name="android.intent.action.MAIN" />
                 <action android:name="android.settings.SECURITY_SETTINGS" />
                 <action android:name="android.settings.LOCATION_SOURCE_SETTINGS" />
-                <action android:name="android.security.UNLOCK_CREDENTIAL_STORAGE" />
+                <action android:name="android.credentials.UNLOCK" />
+                <action android:name="android.credentials.SYSTEM_INSTALL" />
                 <category android:name="android.intent.category.DEFAULT" />
                 <category android:name="android.intent.category.VOICE_LAUNCH" />
                 <category android:name="com.android.settings.SHORTCUT" />
diff --git a/res/layout/installed_app_details.xml b/res/layout/installed_app_details.xml
index 13d3b10..2810604 100644
--- a/res/layout/installed_app_details.xml
+++ b/res/layout/installed_app_details.xml
@@ -304,7 +304,7 @@
                 android:layout_centerHorizontal="true"
                 android:layout_width="150dip"
                 android:text="@string/clear_activities"
-                 android:layout_height="wrap_content" />
+                android:layout_height="wrap_content" />
         </RelativeLayout>
 
         <!-- Other controls section -->
@@ -320,6 +320,7 @@
                 android:layout_alignParentRight="true"
                 android:layout_alignParentTop="true"
                 android:layout_centerHorizontal="true"
+                android:paddingTop="6dip"
                 android:layout_width="150dip"
                 android:text="@string/force_stop"
                 android:layout_height="wrap_content" />
diff --git a/res/values/arrays.xml b/res/values/arrays.xml
index 5ffba79..5191d83 100644
--- a/res/values/arrays.xml
+++ b/res/values/arrays.xml
@@ -53,7 +53,6 @@
         <item>No animations</item>
         <item>Some animations</item>
         <item>All animations</item>
-        <item>Slower all animations</item>
     </string-array>
 
     <!-- Display settings.  Summary for each type of animation. -->
@@ -61,7 +60,6 @@
         <item>No window animations are shown</item>
         <item>Some window animations are shown</item>
         <item>All window animations are shown</item>
-        <item>Slower window animations are shown</item>
     </string-array>
 
     <!-- Do not translate. -->
@@ -72,8 +70,6 @@
         <item>01</item>
         <!-- Do not translate. -->
         <item>11</item>
-        <!-- Do not translate. -->
-        <item>22</item>
     </string-array>
 
     <!-- Display settings.  The delay in inactivity before the screen is turned off. These are shown ain a list dialog. -->
@@ -265,7 +261,7 @@
         <item>None</item>
         <item>PAP</item>
         <item>MSCHAP</item>
-        <item>MSCHAP2</item>
+        <item>MSCHAPV2</item>
         <item>GTC</item>
     </string-array>
 
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 6cdbc33..88163bd 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -1371,7 +1371,7 @@
     <string name="filter_apps_all">All</string>
     <!-- Text for filter option in ManageApps screen to display third party 
     applications only -->
-    <string name="filter_apps_third_party">Third-party</string>
+    <string name="filter_apps_third_party">Downloaded</string>
     <!-- Text for filter option in ManageApps screen to display list of running
     packages only. -->
     <string name="filter_apps_running">Running</string>
@@ -1381,7 +1381,7 @@
     <!-- Manage applications, individual application screen, confirmation dialog title. Displays when user selects to "Clear data". -->
     <string name="clear_data_dlg_title">Delete</string>
     <!-- Manage applications, individual application screen, confirmation dialog message. Displays when user selects to "Clear data". It warns the user of the consequences of clearing the data for an app. -->
-    <string name="clear_data_dlg_text">All information you\'ve saved in this application will be deleted permanently.</string>
+    <string name="clear_data_dlg_text">All of this application\'s data will be deleted permanently. This includes all files, settings, accounts, databases and so on.</string>
     <!-- Manage applications, individual application screen, confirmation dialog button. Displays when user selects to "Clear data". Goes through with the clearing of the data. -->
     <string name="dlg_ok">OK</string>
     <!-- Manage applications, individual application screen, confirmation dialog button. Displays when user selects to "Clear data". -->
@@ -1422,8 +1422,9 @@
     <string name="confirm_stop_service">Stop service?</string>
     <!-- Running services, message of dialog to stop a service -->
     <string name="confirm_stop_service_msg">The service will no longer run until
-            started again by its application.  This may have undesireable
-            consequences.</string>
+            started again.  This may have undesireable
+            consequences on the applicaton
+            <xliff:g id="application">%1$s</xliff:g>.</string>
     <!-- Running services, button to stop a service -->
     <string name="confirm_stop_stop">Stop</string>
     <!-- Running services, button to cancel stopping of a service -->
@@ -1433,9 +1434,11 @@
     <!-- Running services, description for a service in the started state -->
     <string name="service_client_name"><xliff:g id="client_name">%1$s</xliff:g>: select to manage</string>
     <!-- Running services, summary of background processes -->
-    <string name="service_background_processes">Bg: <xliff:g id="memory">%2$s</xliff:g> (<xliff:g id="count">%1$d</xliff:g> procs)</string>
+    <string name="service_background_processes">Avail: <xliff:g id="memory">%2$s</xliff:g> (<xliff:g id="count">%1$d</xliff:g> procs)</string>
     <!-- Running services, summary of foreground processes -->
-    <string name="service_foreground_processes">Fg: <xliff:g id="memory">%2$s</xliff:g> (<xliff:g id="count">%1$d</xliff:g> procs)</string>
+    <string name="service_foreground_processes">Other: <xliff:g id="memory">%2$s</xliff:g> (<xliff:g id="count">%1$d</xliff:g> procs)</string>
+    <!-- Text to label a process entry with the process name. -->
+    <string name="service_process_name">Process: <xliff:g id="process">%1$s</xliff:g></string>
     
     <!-- Language Settings --> <skip />
     <!-- Title of setting on main settings screen.  This item will take the user to the screen to tweak settings realted to locale and text -->
diff --git a/res/xml/appwidget_info.xml b/res/xml/appwidget_info.xml
index 22fb98a..2186dab 100644
--- a/res/xml/appwidget_info.xml
+++ b/res/xml/appwidget_info.xml
@@ -15,7 +15,7 @@
 -->
 
 <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
-    android:minWidth="311dip"
+    android:minWidth="294dip"
     android:minHeight="72dip"
     android:initialLayout="@layout/widget"
     >
diff --git a/src/com/android/settings/ManageApplications.java b/src/com/android/settings/ManageApplications.java
index 34a1e43..3d03666 100644
--- a/src/com/android/settings/ManageApplications.java
+++ b/src/com/android/settings/ManageApplications.java
@@ -142,11 +142,11 @@
     public static final int FILTER_APPS_RUNNING = MENU_OPTIONS_BASE + 4;
     public static final int FILTER_OPTIONS = MENU_OPTIONS_BASE + 5;
     // Alert Dialog presented to user to find out the filter option
-    AlertDialog mAlertDlg;
+    private AlertDialog mAlertDlg;
     // sort order
     private int mSortOrder = SORT_ORDER_ALPHA;
     // Filter value
-    int mFilterApps = FILTER_APPS_ALL;
+    private int mFilterApps = FILTER_APPS_THIRD_PARTY;
     
     // Custom Adapter used for managing items in the list
     private AppInfoAdapter mAppInfoAdapter;
@@ -1577,6 +1577,7 @@
         String action = intent.getAction();
         if (action.equals(Intent.ACTION_MANAGE_PACKAGE_STORAGE)) {
             mSortOrder = SORT_ORDER_SIZE;
+            mFilterApps = FILTER_APPS_ALL;
             mSizesFirst = true;
         }
         mPm = getPackageManager();
diff --git a/src/com/android/settings/RunningServices.java b/src/com/android/settings/RunningServices.java
index a82292a..b7e2a50 100644
--- a/src/com/android/settings/RunningServices.java
+++ b/src/com/android/settings/RunningServices.java
@@ -169,9 +169,10 @@
         int mRunningSeq;
         ActivityManager.RunningAppProcessInfo mRunningProcessInfo;
         
-        public ProcessItem(int uid, String processName) {
+        public ProcessItem(Context context, int uid, String processName) {
             super(true);
-            mDescription = processName;
+            mDescription = context.getResources().getString(
+                    R.string.service_process_name, processName);
             mUid = uid;
             mProcessName = processName;
         }
@@ -274,7 +275,7 @@
                     }
                     si.mDisplayLabel = si.mLabel;
                 }
-                si.mPackageInfo = si.mServiceInfo;
+                si.mPackageInfo = si.mServiceInfo.applicationInfo;
                 mServices.put(service.service, si);
             }
             si.mCurSeq = mCurSeq;
@@ -312,7 +313,7 @@
         boolean updateSize(Context context, Debug.MemoryInfo mem, int curSeq) {
             mSize = ((long)mem.getTotalPss()) * 1024;
             if (mCurSeq == curSeq) {
-                String sizeStr = Formatter.formatFileSize(
+                String sizeStr = Formatter.formatShortFileSize(
                         context, mSize);
                 if (!sizeStr.equals(mSizeStr)){
                     mSizeStr = sizeStr;
@@ -415,7 +416,7 @@
                 ProcessItem proc = procs.get(si.process);
                 if (proc == null) {
                     changed = true;
-                    proc = new ProcessItem(si.uid, si.process);
+                    proc = new ProcessItem(context, si.uid, si.process);
                     procs.put(si.process, proc);
                 }
                 
@@ -453,7 +454,7 @@
                     // running list.
                     proc = mRunningProcesses.get(pi.pid);
                     if (proc == null) {
-                        proc = new ProcessItem(pi.uid, pi.processName);
+                        proc = new ProcessItem(context, pi.uid, pi.processName);
                         proc.mPid = pi.pid;
                         mRunningProcesses.put(pi.pid, proc);
                     }
@@ -698,12 +699,14 @@
             vh.description.setText(item.mDescription);
             if (item.mIsProcess) {
                 view.setBackgroundColor(mProcessBgColor);
-                vh.icon.setImageDrawable(item.mPackageInfo.loadIcon(getPackageManager()));
+                vh.icon.setImageDrawable(null);
+                vh.icon.setVisibility(View.GONE);
                 vh.description.setText(item.mDescription);
                 item.mCurSizeStr = null;
             } else {
                 view.setBackgroundDrawable(null);
-                vh.icon.setImageDrawable(null);
+                vh.icon.setImageDrawable(item.mPackageInfo.loadIcon(getPackageManager()));
+                vh.icon.setVisibility(View.VISIBLE);
                 vh.description.setText(item.mDescription);
                 ai.mFirstRunTime = item.mActiveSince;
             }
@@ -765,7 +768,7 @@
                 || mLastBackgroundProcessMemory != mState.mBackgroundProcessMemory) {
             mLastNumBackgroundProcesses = mState.mNumBackgroundProcesses;
             mLastBackgroundProcessMemory = mState.mBackgroundProcessMemory;
-            String sizeStr = Formatter.formatFileSize(this, mLastBackgroundProcessMemory);
+            String sizeStr = Formatter.formatShortFileSize(this, mLastBackgroundProcessMemory);
             mBackgroundProcessText.setText(getResources().getString(
                     R.string.service_background_processes, mLastNumBackgroundProcesses, sizeStr));
         }
@@ -773,7 +776,7 @@
                 || mLastForegroundProcessMemory != mState.mForegroundProcessMemory) {
             mLastNumForegroundProcesses = mState.mNumForegroundProcesses;
             mLastForegroundProcessMemory = mState.mForegroundProcessMemory;
-            String sizeStr = Formatter.formatFileSize(this, mLastForegroundProcessMemory);
+            String sizeStr = Formatter.formatShortFileSize(this, mLastForegroundProcessMemory);
             mForegroundProcessText.setText(getResources().getString(
                     R.string.service_foreground_processes, mLastNumForegroundProcesses, sizeStr));
         }
@@ -806,7 +809,10 @@
                 mCurSelected = bi;
                 AlertDialog.Builder builder = new AlertDialog.Builder(this);
                 builder.setTitle(R.string.confirm_stop_service);
-                builder.setMessage(R.string.confirm_stop_service_msg);
+                String msg = getResources().getString(
+                        R.string.confirm_stop_service_msg,
+                        si.mPackageInfo.loadLabel(getPackageManager()));
+                builder.setMessage(msg);
                 builder.setPositiveButton(R.string.confirm_stop_stop, this);
                 builder.setNegativeButton(R.string.confirm_stop_cancel, null);
                 builder.setCancelable(true);
diff --git a/src/com/android/settings/SecuritySettings.java b/src/com/android/settings/SecuritySettings.java
index 24b89b1..3d7a765 100644
--- a/src/com/android/settings/SecuritySettings.java
+++ b/src/com/android/settings/SecuritySettings.java
@@ -38,8 +38,8 @@
 import android.preference.PreferenceGroup;
 import android.preference.PreferenceScreen;
 import android.provider.Settings;
-import android.security.CertTool;
-import android.security.Keystore;
+import android.security.Credentials;
+import android.security.KeyStore;
 import android.text.Html;
 import android.text.TextUtils;
 import android.text.method.LinkMovementMethod;
@@ -87,17 +87,12 @@
     private static final String ASSISTED_GPS = "assisted_gps";
 
     // Credential storage
-    private static final String KEY_CSTOR_TYPE_NAME = "typeName";
-    private static final String KEY_CSTOR_ITEM = "item";
-    private static final String KEY_CSTOR_NAMESPACE = "namespace";
-    private static final String KEY_CSTOR_DESCRIPTION = "description";
     private static final int CSTOR_MIN_PASSWORD_LENGTH = 8;
 
     private static final int CSTOR_INIT_DIALOG = 1;
     private static final int CSTOR_CHANGE_PASSWORD_DIALOG = 2;
     private static final int CSTOR_UNLOCK_DIALOG = 3;
     private static final int CSTOR_RESET_DIALOG = 4;
-    private static final int CSTOR_NAME_CREDENTIAL_DIALOG = 5;
 
     private CstorHelper mCstorHelper = new CstorHelper();
 
@@ -162,7 +157,7 @@
             showUseLocationDialog(true);
         }
 
-        mCstorHelper.handleCstorIntents(getIntent());
+        mCstorHelper.handleIntent(getIntent());
     }
 
     private PreferenceScreen createPreferenceHierarchy() {
@@ -236,10 +231,7 @@
         PreferenceCategory credStoreCat = new PreferenceCategory(this);
         credStoreCat.setTitle(R.string.cstor_settings_category);
         root.addPreference(credStoreCat);
-        credStoreCat.addPreference(mCstorHelper.createAccessCheckBox());
-        credStoreCat.addPreference(mCstorHelper.createCertInstallPreference());
-        credStoreCat.addPreference(mCstorHelper.createSetPasswordPreference());
-        credStoreCat.addPreference(mCstorHelper.createResetPreference());
+        mCstorHelper.createPreferences(credStoreCat);
 
         return root;
     }
@@ -262,11 +254,8 @@
                 R.string.lockpattern_settings_choose_lock_pattern;
         mChoosePattern.setTitle(chooseStringRes);
 
-        mShowPassword
-                .setChecked(Settings.System.getInt(getContentResolver(),
+        mShowPassword.setChecked(Settings.System.getInt(getContentResolver(),
                 Settings.System.TEXT_SHOW_PASSWORD, 1) != 0);
-
-        mCstorHelper.resumeStates();
     }
 
     @Override
@@ -380,7 +369,6 @@
                 Settings.Secure.USE_LOCATION_FOR_SERVICES, use ? 1 : 0);
     }
 
-
     /**
      * For the user to disable keyguard, we first make them verify their
      * existing pattern.
@@ -447,7 +435,7 @@
     }
 
     @Override
-    protected Dialog onCreateDialog (int id) {
+    protected Dialog onCreateDialog(int id) {
         switch (id) {
             case CSTOR_INIT_DIALOG:
             case CSTOR_CHANGE_PASSWORD_DIALOG:
@@ -459,9 +447,6 @@
             case CSTOR_RESET_DIALOG:
                 return mCstorHelper.createResetDialog();
 
-            case CSTOR_NAME_CREDENTIAL_DIALOG:
-                return mCstorHelper.createNameCredentialDialog();
-
             default:
                 return null;
         }
@@ -485,270 +470,151 @@
     }
 
     private class CstorHelper implements DialogInterface.OnClickListener,
-            DialogInterface.OnDismissListener,
-            DialogInterface.OnCancelListener {
-        private Keystore mKeystore = Keystore.getInstance();
+            DialogInterface.OnDismissListener {
+        private KeyStore mKeyStore = KeyStore.getInstance();
+        private int mState;
+
         private View mView;
         private int mDialogId;
-        private boolean mConfirm = true;
-
+        private boolean mRetry = false;
         private CheckBoxPreference mAccessCheckBox;
         private Preference mResetButton;
 
-        private Intent mSpecialIntent;
-        private CstorAddCredentialHelper mCstorAddCredentialHelper;
+        private Intent mExternalIntent;
 
-        void handleCstorIntents(Intent intent) {
+        CstorHelper() {
+            mState = mKeyStore.test();
+        }
+
+        void handleIntent(Intent intent) {
             if (intent == null) return;
             String action = intent.getAction();
 
-            if (CertTool.ACTION_ADD_CREDENTIAL.equals(action)) {
-                mCstorAddCredentialHelper =
-                        new CstorAddCredentialHelper(intent);
-                showCstorDialog(CSTOR_NAME_CREDENTIAL_DIALOG);
-            } else if (Keystore.ACTION_UNLOCK_CREDENTIAL_STORAGE.equals(
-                    action)) {
-                mSpecialIntent = intent;
-                showCstorDialog(mCstorHelper.isCstorInitialized()
-                        ? CSTOR_UNLOCK_DIALOG
-                        : CSTOR_INIT_DIALOG);
+            if (Credentials.UNLOCK_ACTION.equals(action)) {
+                mExternalIntent = intent;
+                showCstorDialog(mState == KeyStore.UNINITIALIZED
+                        ? CSTOR_INIT_DIALOG : CSTOR_UNLOCK_DIALOG);
+            } else if (Credentials.SYSTEM_INSTALL_ACTION.equals(action)) {
+                mExternalIntent = intent;
+                // TODO: unlock and install.
             }
         }
 
-        void resumeStates() {
-            int state = mCstorHelper.getCstorState();
-            mAccessCheckBox.setEnabled(state != Keystore.UNINITIALIZED);
-            mAccessCheckBox.setChecked(state == Keystore.UNLOCKED);
-            mResetButton.setEnabled(state != Keystore.UNINITIALIZED);
+        private void updatePreferences(int state) {
+            mAccessCheckBox.setEnabled(state != KeyStore.UNINITIALIZED);
+            mAccessCheckBox.setChecked(state == KeyStore.NO_ERROR);
+            mResetButton.setEnabled(state != KeyStore.UNINITIALIZED);
+
+            // Show a toast message if the state is changed.
+            if (mState == state) return;
+            if (state == KeyStore.NO_ERROR) {
+                Toast.makeText(SecuritySettings.this, R.string.cstor_is_enabled,
+                        Toast.LENGTH_SHORT).show();
+            } else if (state == KeyStore.UNINITIALIZED) {
+                Toast.makeText(SecuritySettings.this, R.string.cstor_is_reset,
+                        Toast.LENGTH_LONG).show();
+            }
+            // TODO: disabled?
+            mState = state;
+        }
+
+        private void lockCstor() {
+            mKeyStore.lock();
+            updatePreferences(KeyStore.LOCKED);
+        }
+
+        private int unlockCstor(String passwd) {
+            mKeyStore.unlock(passwd);
+            return mKeyStore.getLastError();
+        }
+
+        private int changeCstorPassword(String oldPasswd, String newPasswd) {
+            mKeyStore.password(oldPasswd, newPasswd);
+            return mKeyStore.getLastError();
+        }
+
+        private void initCstor(String passwd) {
+            mKeyStore.password(passwd);
+            updatePreferences(KeyStore.NO_ERROR);
+        }
+
+        private void resetCstor() {
+            mKeyStore.reset();
+            updatePreferences(KeyStore.UNINITIALIZED);
         }
 
         private void showCstorDialog(int dialogId) {
             mDialogId = dialogId;
             showDialog(dialogId);
-
-            if (dialogId == CSTOR_NAME_CREDENTIAL_DIALOG) {
-                // set mView back as mView may be replaced by CSTOR_INIT_DIALOG
-                // or CSTOR_UNLOCK_DIALOG
-                mView = mCstorAddCredentialHelper.mView;
-            }
-        }
-
-        private int getCstorState() {
-            return mKeystore.getState();
-        }
-
-        private boolean isCstorUnlocked() {
-            return (mKeystore.getState() == Keystore.UNLOCKED);
-        }
-
-        private boolean isCstorInitialized() {
-            return (mKeystore.getState() != Keystore.UNINITIALIZED);
-        }
-
-        private void lockCstor() {
-            mKeystore.lock();
-            mAccessCheckBox.setChecked(false);
-        }
-
-        private int unlockCstor(String passwd) {
-            int ret = mKeystore.unlock(passwd);
-            if (ret == -1) resetCstor();
-            if (ret == 0) {
-                Toast.makeText(SecuritySettings.this, R.string.cstor_is_enabled,
-                        Toast.LENGTH_SHORT).show();
-            }
-            return ret;
-        }
-
-        private int changeCstorPassword(String oldPasswd, String newPasswd) {
-            int ret = mKeystore.changePassword(oldPasswd, newPasswd);
-            if (ret == -1) resetCstor();
-            return ret;
-        }
-
-        private void initCstor(String passwd) {
-            mKeystore.setPassword(passwd);
-            enablePreferences(true);
-            mAccessCheckBox.setChecked(true);
-            Toast.makeText(SecuritySettings.this, R.string.cstor_is_enabled,
-                    Toast.LENGTH_SHORT).show();
-        }
-
-        private void resetCstor() {
-            mKeystore.reset();
-            enablePreferences(false);
-            mAccessCheckBox.setChecked(false);
-            Toast.makeText(SecuritySettings.this, R.string.cstor_is_reset,
-                    Toast.LENGTH_LONG).show();
-        }
-
-        private boolean addCredential() {
-            if (mCstorAddCredentialHelper.saveToStorage() != 0) {
-                // set mView back as mView may be replaced by CSTOR_INIT_DIALOG
-                // or CSTOR_UNLOCK_DIALOG
-                mView = mCstorAddCredentialHelper.mView;
-                if (mCstorAddCredentialHelper.isPkcs12Keystore()) {
-                    showError(R.string.cstor_password_error);
-                } else {
-                    showError(R.string.cstor_storage_error);
-                }
-                Log.d("CSTOR", "failed to add credential");
-                return false;
-            }
-            Log.d("CSTOR", "credential is added: "
-                    + mCstorAddCredentialHelper.getName());
-            String formatString =
-                    getString(R.string.cstor_is_added);
-            String message = String.format(formatString,
-                    mCstorAddCredentialHelper.getName());
-            Toast.makeText(SecuritySettings.this, message,
-                    Toast.LENGTH_LONG).show();
-            return true;
-        }
-
-        public void onCancel(DialogInterface dialog) {
-            if (mCstorAddCredentialHelper == null) return;
-
-            switch (mDialogId) {
-                case CSTOR_INIT_DIALOG:
-                case CSTOR_UNLOCK_DIALOG:
-                    Toast.makeText(SecuritySettings.this,
-                            R.string.cstor_unable_to_save_cert,
-                            Toast.LENGTH_LONG).show();
-                    break;
-
-                case CSTOR_NAME_CREDENTIAL_DIALOG:
-                    Toast.makeText(SecuritySettings.this,
-                            R.string.cstor_cert_not_saved,
-                            Toast.LENGTH_LONG).show();
-                    break;
-            }
-            mCstorAddCredentialHelper = null;
-            finish();
         }
 
         public void onClick(DialogInterface dialog, int which) {
-            if (which == DialogInterface.BUTTON_NEGATIVE) {
-                onCancel(dialog);
-                return;
-            }
+            if (which == DialogInterface.BUTTON_NEGATIVE) return;
 
             switch (mDialogId) {
                 case CSTOR_INIT_DIALOG:
                 case CSTOR_CHANGE_PASSWORD_DIALOG:
-                    mConfirm = checkPasswords((Dialog) dialog);
+                    mRetry = !checkPasswords((Dialog) dialog);
                     break;
 
                 case CSTOR_UNLOCK_DIALOG:
-                    mConfirm = checkUnlockPassword((Dialog) dialog);
+                    mRetry = !checkPassword((Dialog) dialog);
                     break;
 
                 case CSTOR_RESET_DIALOG:
                     resetCstor();
                     break;
-
-                case CSTOR_NAME_CREDENTIAL_DIALOG:
-                    mConfirm = checkAddCredential();
-                    break;
             }
         }
 
         public void onDismiss(DialogInterface dialog) {
-            if (!mConfirm) {
-                mConfirm = true;
+            if (mRetry) {
                 showCstorDialog(mDialogId);
             } else {
-                if (mDialogId == CSTOR_UNLOCK_DIALOG) {
-                    mAccessCheckBox.setChecked(isCstorUnlocked());
-                }
-
-                if (mCstorAddCredentialHelper != null) {
-                    if (!isCstorInitialized()) {
-                        showCstorDialog(CSTOR_INIT_DIALOG);
-                    } else if (!isCstorUnlocked()) {
-                        showCstorDialog(CSTOR_UNLOCK_DIALOG);
-                    } else {
-                        if (addCredential()) {
-                            // succeeded
-                            finish();
-                        } else {
-                            // failed
-                            if (mDialogId != CSTOR_NAME_CREDENTIAL_DIALOG) {
-                                removeDialog(mDialogId);
-                            }
-                            showCstorDialog(CSTOR_NAME_CREDENTIAL_DIALOG);
-                        }
-                    }
-                    return;
-                } else if (mSpecialIntent != null) {
-                    finish();
-                }
                 removeDialog(mDialogId);
-            }
-        }
 
-        private void showResetWarning(int count) {
-            TextView v = showError(count <= 3
-                    ? R.string.cstor_password_error_reset_warning
-                    : R.string.cstor_password_error);
-            if (count <= 3) {
-                if (count == 1) {
-                    v.setText(R.string.cstor_password_error_reset_warning);
-                } else {
-                    String format = getString(
-                            R.string.cstor_password_error_reset_warning_plural);
-                    v.setText(String.format(format, count));
+                if (mExternalIntent != null) {
+                    if (Credentials.SYSTEM_INSTALL_ACTION.equals(
+                                    mExternalIntent.getAction())) {
+                        // TODO: install if unlocked.
+                    } else {
+                        finish();
+                    }
                 }
             }
         }
 
-        private boolean checkAddCredential() {
-            hideError();
-
-            String name = getText(R.id.cstor_credential_name);
-            if (TextUtils.isEmpty(name)) {
-                showError(R.string.cstor_name_empty_error);
+        // returns false if there is no error.
+        private boolean checkError(int error) {
+            if (error == KeyStore.NO_ERROR) {
+                updatePreferences(KeyStore.NO_ERROR);
                 return false;
             }
-
-            for (int i = 0, len = name.length(); i < len; i++) {
-                if (!Character.isLetterOrDigit(name.charAt(i))) {
-                    showError(R.string.cstor_name_char_error);
-                    return false;
-                }
+            if (error == KeyStore.UNINITIALIZED) {
+                updatePreferences(KeyStore.UNINITIALIZED);
+                return false;
             }
-
-            mCstorAddCredentialHelper.setName(name);
-
-            if (mCstorAddCredentialHelper.isPkcs12Keystore()) {
-                String password = getText(R.id.cstor_credential_password);
-                if (TextUtils.isEmpty(password)) {
-                    showError(R.string.cstor_password_empty_error);
-                    return false;
-                }
-
-                mCstorAddCredentialHelper.setPassword(password);
+            if (error < KeyStore.WRONG_PASSWORD) {
+                return false;
             }
-
+            int count = error - KeyStore.WRONG_PASSWORD + 1;
+            if (count > 3) {
+                showError(R.string.cstor_password_error);
+                return true;
+            }
+            TextView v = showError(R.string.cstor_password_error_reset_warning);
+            if (count == 1) {
+                v.setText(R.string.cstor_password_error_reset_warning);
+            } else {
+                String format = getString(
+                        R.string.cstor_password_error_reset_warning_plural);
+                v.setText(String.format(format, count));
+            }
             return true;
         }
 
-        // returns true if the password is long enough and does not contain
-        // characters that we don't like
-        private boolean verifyPassword(String passwd) {
-            if (passwd == null) {
-                showError(R.string.cstor_passwords_empty_error);
-                return false;
-            } else if (passwd.length() < CSTOR_MIN_PASSWORD_LENGTH) {
-                showError(R.string.cstor_password_verification_error);
-                return false;
-            } else {
-                return true;
-            }
-        }
-
-        // returns true if the password is ok
-        private boolean checkUnlockPassword(Dialog d) {
+        // returns true if the password is correct
+        private boolean checkPassword(Dialog d) {
             hideError();
 
             String passwd = getText(R.id.cstor_password);
@@ -757,17 +623,10 @@
                 return false;
             }
 
-            int count = unlockCstor(passwd);
-            if (count > 0) {
-                showResetWarning(count);
-                return false;
-            } else {
-                // done or reset
-                return true;
-            }
+            return !checkError(unlockCstor(passwd));
         }
 
-        // returns true if the passwords are ok
+        // returns true if the passwords are correct
         private boolean checkPasswords(Dialog d) {
             hideError();
 
@@ -778,39 +637,22 @@
             if ((mDialogId == CSTOR_CHANGE_PASSWORD_DIALOG)
                     && TextUtils.isEmpty(oldPasswd)) {
                 showError(R.string.cstor_password_empty_error);
-                return false;
-            }
-
-            if (TextUtils.isEmpty(newPasswd)
-                    && TextUtils.isEmpty(confirmPasswd)) {
+            } else if (TextUtils.isEmpty(newPasswd)
+                    || TextUtils.isEmpty(confirmPasswd)) {
                 showError(R.string.cstor_passwords_empty_error);
-                return false;
-            }
-
-            if (!verifyPassword(newPasswd)) {
-                return false;
+            } else if (newPasswd.length() < CSTOR_MIN_PASSWORD_LENGTH) {
+                showError(R.string.cstor_password_verification_error);
             } else if (!newPasswd.equals(confirmPasswd)) {
                 showError(R.string.cstor_passwords_error);
-                return false;
-            }
-
-            if (mDialogId == CSTOR_CHANGE_PASSWORD_DIALOG) {
-                int count = changeCstorPassword(oldPasswd, newPasswd);
-                if (count > 0) {
-                    showResetWarning(count);
-                    return false;
+            } else {
+                if (mDialogId == CSTOR_CHANGE_PASSWORD_DIALOG) {
+                    return !checkError(changeCstorPassword(oldPasswd, newPasswd));
                 } else {
-                    // done or reset
+                    initCstor(newPasswd);
                     return true;
                 }
-            } else {
-                initCstor(newPasswd);
-                return true;
             }
-        }
-
-        private void installCertFromSdCard() {
-            startActivity(new Intent(CertTool.ACTION_INSTALL_CERT_FROM_SDCARD));
+            return false;
         }
 
         private TextView showError(int messageId) {
@@ -820,40 +662,24 @@
             return v;
         }
 
+        private void hideError() {
+            hide(R.id.cstor_error);
+        }
+
         private void hide(int viewId) {
             View v = mView.findViewById(viewId);
             if (v != null) v.setVisibility(View.GONE);
         }
 
-        private void hideError() {
-            hide(R.id.cstor_error);
-        }
-
         private String getText(int viewId) {
             return ((TextView) mView.findViewById(viewId)).getText().toString();
         }
 
-        private void setText(int viewId, String text) {
-            TextView v = (TextView) mView.findViewById(viewId);
-            if (v != null) v.setText(text);
-        }
-
-        private void setText(int viewId, int textId) {
-            TextView v = (TextView) mView.findViewById(viewId);
-            if (v != null) v.setText(textId);
-        }
-
-        private void enablePreferences(boolean enabled) {
-            mAccessCheckBox.setEnabled(enabled);
-            mResetButton.setEnabled(enabled);
-        }
-
-        private Preference createAccessCheckBox() {
-            CheckBoxPreference pref = new CheckBoxPreference(
-                    SecuritySettings.this);
-            pref.setTitle(R.string.cstor_access_title);
-            pref.setSummary(R.string.cstor_access_summary);
-            pref.setOnPreferenceChangeListener(
+        private void createPreferences(PreferenceCategory category) {
+            mAccessCheckBox = new CheckBoxPreference(SecuritySettings.this);
+            mAccessCheckBox.setTitle(R.string.cstor_access_title);
+            mAccessCheckBox.setSummary(R.string.cstor_access_summary);
+            mAccessCheckBox.setOnPreferenceChangeListener(
                     new Preference.OnPreferenceChangeListener() {
                         public boolean onPreferenceChange(
                                 Preference pref, Object value) {
@@ -865,53 +691,48 @@
                             return true;
                         }
                     });
-            mAccessCheckBox = pref;
-            return pref;
-        }
+            category.addPreference(mAccessCheckBox);
 
-        private Preference createCertInstallPreference() {
-            Preference pref = new Preference(SecuritySettings.this);
-            pref.setTitle(R.string.cstor_cert_install_title);
-            pref.setSummary(R.string.cstor_cert_install_summary);
-            pref.setOnPreferenceClickListener(
+            Preference install = new Preference(SecuritySettings.this);
+            install.setTitle(R.string.cstor_cert_install_title);
+            install.setSummary(R.string.cstor_cert_install_summary);
+            install.setOnPreferenceClickListener(
                     new Preference.OnPreferenceClickListener() {
                         public boolean onPreferenceClick(Preference pref) {
-                            installCertFromSdCard();
+                            Credentials.getInstance().installFromSdCard(
+                                            SecuritySettings.this);
                             return true;
                         }
                     });
-            return pref;
-        }
+            category.addPreference(install);
 
-        private Preference createSetPasswordPreference() {
-            Preference pref = new Preference(SecuritySettings.this);
-            pref.setTitle(R.string.cstor_set_passwd_title);
-            pref.setSummary(R.string.cstor_set_passwd_summary);
-            pref.setOnPreferenceClickListener(
+            Preference password = new Preference(SecuritySettings.this);
+            password.setTitle(R.string.cstor_set_passwd_title);
+            password.setSummary(R.string.cstor_set_passwd_summary);
+            password.setOnPreferenceClickListener(
                     new Preference.OnPreferenceClickListener() {
                         public boolean onPreferenceClick(Preference pref) {
-                            showCstorDialog(isCstorInitialized()
-                                    ? CSTOR_CHANGE_PASSWORD_DIALOG
-                                    : CSTOR_INIT_DIALOG);
+                            showCstorDialog(mState == KeyStore.UNINITIALIZED
+                                    ? CSTOR_INIT_DIALOG
+                                    : CSTOR_CHANGE_PASSWORD_DIALOG);
                             return true;
                         }
                     });
-            return pref;
-        }
+            category.addPreference(password);
 
-        private Preference createResetPreference() {
-            Preference pref = new Preference(SecuritySettings.this);
-            pref.setTitle(R.string.cstor_reset_title);
-            pref.setSummary(R.string.cstor_reset_summary);
-            pref.setOnPreferenceClickListener(
+            mResetButton = new Preference(SecuritySettings.this);
+            mResetButton.setTitle(R.string.cstor_reset_title);
+            mResetButton.setSummary(R.string.cstor_reset_summary);
+            mResetButton.setOnPreferenceClickListener(
                     new Preference.OnPreferenceClickListener() {
                         public boolean onPreferenceClick(Preference pref) {
                             showCstorDialog(CSTOR_RESET_DIALOG);
                             return true;
                         }
                     });
-            mResetButton = pref;
-            return pref;
+            category.addPreference(mResetButton);
+
+            updatePreferences(mState);
         }
 
         private Dialog createUnlockDialog() {
@@ -920,8 +741,7 @@
             hideError();
 
             // show extra hint only when the action comes from outside
-            if ((mSpecialIntent == null)
-                    && (mCstorAddCredentialHelper == null)) {
+            if (mExternalIntent == null) {
                 hide(R.id.cstor_access_dialog_hint_from_action);
             }
 
@@ -930,7 +750,6 @@
                     .setTitle(R.string.cstor_access_dialog_title)
                     .setPositiveButton(android.R.string.ok, this)
                     .setNegativeButton(android.R.string.cancel, this)
-                    .setOnCancelListener(this)
                     .create();
             d.setOnDismissListener(this);
             return d;
@@ -941,13 +760,6 @@
                     R.layout.cstor_set_password_dialog_view, null);
             hideError();
 
-            // show extra hint only when the action comes from outside
-            if ((mSpecialIntent != null)
-                    || (mCstorAddCredentialHelper != null)) {
-                setText(R.id.cstor_first_time_hint,
-                        R.string.cstor_first_time_hint_from_action);
-            }
-
             switch (id) {
                 case CSTOR_INIT_DIALOG:
                     mView.findViewById(R.id.cstor_old_password_block)
@@ -969,7 +781,6 @@
                     .setTitle(R.string.cstor_set_passwd_dialog_title)
                     .setPositiveButton(android.R.string.ok, this)
                     .setNegativeButton(android.R.string.cancel, this)
-                    .setOnCancelListener(this)
                     .create();
             d.setOnDismissListener(this);
             return d;
@@ -984,115 +795,5 @@
                     .setNegativeButton(getString(android.R.string.cancel), this)
                     .create();
         }
-
-        private Dialog createNameCredentialDialog() {
-            mView = View.inflate(SecuritySettings.this,
-                    R.layout.cstor_name_credential_dialog_view, null);
-            if (mCstorAddCredentialHelper != null) {
-                mCstorAddCredentialHelper.mView = mView;
-            }
-
-            hideError();
-            if (!mCstorAddCredentialHelper.isPkcs12Keystore()) {
-                hide(R.id.cstor_credential_password_container);
-            }
-
-            setText(R.id.cstor_credential_name_title,
-                    R.string.cstor_credential_name);
-            setText(R.id.cstor_credential_info_title,
-                    R.string.cstor_credential_info);
-            setText(R.id.cstor_credential_info,
-                    mCstorAddCredentialHelper.getDescription().toString());
-
-            Dialog d = new AlertDialog.Builder(SecuritySettings.this)
-                    .setView(mView)
-                    .setTitle(R.string.cstor_name_credential_dialog_title)
-                    .setPositiveButton(android.R.string.ok, this)
-                    .setNegativeButton(android.R.string.cancel, this)
-                    .setOnCancelListener(this)
-                    .create();
-            d.setOnDismissListener(this);
-            return d;
-        }
-    }
-
-    private class CstorAddCredentialHelper {
-        private String mTypeName;
-        private List<byte[]> mItemList;
-        private List<String> mNamespaceList;
-        private String mDescription;
-        private String mName;
-        private String mPassword;
-        private View mView;
-
-        CstorAddCredentialHelper(Intent intent) {
-            parse(intent);
-        }
-
-        String getTypeName() {
-            return mTypeName;
-        }
-
-        boolean isPkcs12Keystore() {
-            return CertTool.TITLE_PKCS12_KEYSTORE.equals(mTypeName);
-        }
-
-        CharSequence getDescription() {
-            return Html.fromHtml(mDescription);
-        }
-
-        void setName(String name) {
-            mName = name;
-        }
-
-        String getName() {
-            return mName;
-        }
-
-        void setPassword(String password) {
-            mPassword = password;
-        }
-
-        String getPassword() {
-            return mPassword;
-        }
-
-        int saveToStorage() {
-            if (isPkcs12Keystore()) {
-                return CertTool.getInstance().addPkcs12Keystore(
-                        mItemList.get(0), mPassword, mName);
-            } else {
-                Keystore ks = Keystore.getInstance();
-                for (int i = 0, count = mItemList.size(); i < count; i++) {
-                    byte[] blob = mItemList.get(i);
-                    int ret = ks.put(mNamespaceList.get(i), mName,
-                            new String(blob));
-                    if (ret != 0) return ret;
-                }
-            }
-            return 0;
-        }
-
-        private void parse(Intent intent) {
-            mTypeName = intent.getStringExtra(KEY_CSTOR_TYPE_NAME);
-            mItemList = new ArrayList<byte[]>();
-            mNamespaceList = new ArrayList<String>();
-            for (int i = 0; ; i++) {
-                byte[] blob = intent.getByteArrayExtra(KEY_CSTOR_ITEM + i);
-                if (blob == null) break;
-                mItemList.add(blob);
-                mNamespaceList.add(intent.getStringExtra(
-                        KEY_CSTOR_NAMESPACE + i));
-            }
-
-            // build description string
-            StringBuilder sb = new StringBuilder();
-            for (int i = 0; ; i++) {
-                String s = intent.getStringExtra(KEY_CSTOR_DESCRIPTION + i);
-                if (s == null) break;
-                sb.append(s).append("<br>");
-            }
-            mDescription = sb.toString();
-        }
     }
 }
diff --git a/src/com/android/settings/vpn/L2tpIpsecEditor.java b/src/com/android/settings/vpn/L2tpIpsecEditor.java
index b14feb3..276ee2f 100644
--- a/src/com/android/settings/vpn/L2tpIpsecEditor.java
+++ b/src/com/android/settings/vpn/L2tpIpsecEditor.java
@@ -24,7 +24,8 @@
 import android.preference.ListPreference;
 import android.preference.Preference;
 import android.preference.PreferenceGroup;
-import android.security.CertTool;
+import android.security.Credentials;
+import android.security.KeyStore;
 import android.text.TextUtils;
 
 /**
@@ -33,6 +34,8 @@
 class L2tpIpsecEditor extends L2tpEditor {
     private static final String TAG = L2tpIpsecEditor.class.getSimpleName();
 
+    private KeyStore mKeyStore = KeyStore.getInstance();
+
     private ListPreference mUserCertificate;
     private ListPreference mCaCertificate;
 
@@ -67,7 +70,7 @@
         mUserCertificate = createListPreference(c,
                 R.string.vpn_user_certificate_title,
                 mProfile.getUserCertificate(),
-                CertTool.getInstance().getAllUserCertificateKeys(),
+                mKeyStore.saw(Credentials.USER_CERTIFICATE),
                 new Preference.OnPreferenceChangeListener() {
                     public boolean onPreferenceChange(
                             Preference pref, Object newValue) {
@@ -86,7 +89,7 @@
         mCaCertificate = createListPreference(c,
                 R.string.vpn_ca_certificate_title,
                 mProfile.getCaCertificate(),
-                CertTool.getInstance().getAllCaCertificateKeys(),
+                mKeyStore.saw(Credentials.CA_CERTIFICATE),
                 new Preference.OnPreferenceChangeListener() {
                     public boolean onPreferenceChange(
                             Preference pref, Object newValue) {
diff --git a/src/com/android/settings/vpn/VpnSettings.java b/src/com/android/settings/vpn/VpnSettings.java
index eea0aca..d0c6a89 100644
--- a/src/com/android/settings/vpn/VpnSettings.java
+++ b/src/com/android/settings/vpn/VpnSettings.java
@@ -47,8 +47,8 @@
 import android.preference.PreferenceManager;
 import android.preference.PreferenceScreen;
 import android.preference.Preference.OnPreferenceClickListener;
-import android.security.CertTool;
-import android.security.Keystore;
+import android.security.Credentials;
+import android.security.KeyStore;
 import android.text.TextUtils;
 import android.util.Log;
 import android.view.ContextMenu;
@@ -109,9 +109,8 @@
 
     private static final int NO_ERROR = VpnManager.VPN_ERROR_NO_ERROR;
 
-    private static final String NAMESPACE_VPN = "vpn";
-    private static final String KEY_PREFIX_IPSEC_PSK = "ipsk000";
-    private static final String KEY_PREFIX_L2TP_SECRET = "lscrt000";
+    private static final String KEY_PREFIX_IPSEC_PSK = Credentials.VPN + 'i';
+    private static final String KEY_PREFIX_L2TP_SECRET = Credentials.VPN + 'l';
 
     private PreferenceScreen mAddVpn;
     private PreferenceCategory mVpnListContainer;
@@ -129,6 +128,8 @@
     // states saved for unlocking keystore
     private Runnable mUnlockAction;
 
+    private KeyStore mKeyStore = KeyStore.getInstance();
+
     private VpnManager mVpnManager = new VpnManager(this);
 
     private ConnectivityReceiver mConnectivityReceiver =
@@ -172,7 +173,7 @@
     public void onResume() {
         super.onResume();
 
-        if ((mUnlockAction != null) && isKeystoreUnlocked()) {
+        if ((mUnlockAction != null) && isKeyStoreUnlocked()) {
             Runnable action = mUnlockAction;
             mUnlockAction = null;
             runOnUiThread(action);
@@ -402,13 +403,13 @@
                 return;
             }
 
-            if (needKeystoreToSave(p)) {
+            if (needKeyStoreToSave(p)) {
                 Runnable action = new Runnable() {
                     public void run() {
                         onActivityResult(requestCode, resultCode, data);
                     }
                 };
-                if (!unlockKeystore(p, action)) return;
+                if (!unlockKeyStore(p, action)) return;
             }
 
             try {
@@ -610,22 +611,26 @@
         startActivityForResult(intent, REQUEST_SELECT_VPN_TYPE);
     }
 
-    private boolean isKeystoreUnlocked() {
-        return (Keystore.getInstance().getState() == Keystore.UNLOCKED);
-    }
-
-
-    // Returns true if the profile needs to access keystore
-    private boolean needKeystoreToSave(VpnProfile p) {
-        return needKeystoreToConnect(p);
+    private boolean isKeyStoreUnlocked() {
+        return mKeyStore.test() == KeyStore.NO_ERROR;
     }
 
     // Returns true if the profile needs to access keystore
-    private boolean needKeystoreToEdit(VpnProfile p) {
+    private boolean needKeyStoreToSave(VpnProfile p) {
         switch (p.getType()) {
-            case L2TP_IPSEC:
             case L2TP_IPSEC_PSK:
-                return true;
+                L2tpIpsecPskProfile pskProfile = (L2tpIpsecPskProfile) p;
+                String presharedKey = pskProfile.getPresharedKey();
+                if (!TextUtils.isEmpty(presharedKey)) return true;
+                // pass through
+
+            case L2TP:
+                L2tpProfile l2tpProfile = (L2tpProfile) p;
+                if (l2tpProfile.isSecretEnabled() &&
+                        !TextUtils.isEmpty(l2tpProfile.getSecretString())) {
+                    return true;
+                }
+                // pass through
 
             default:
                 return false;
@@ -633,7 +638,7 @@
     }
 
     // Returns true if the profile needs to access keystore
-    private boolean needKeystoreToConnect(VpnProfile p) {
+    private boolean needKeyStoreToConnect(VpnProfile p) {
         switch (p.getType()) {
             case L2TP_IPSEC:
             case L2TP_IPSEC_PSK:
@@ -648,37 +653,27 @@
     }
 
     // Returns true if keystore is unlocked or keystore is not a concern
-    private boolean unlockKeystore(VpnProfile p, Runnable action) {
-        if (isKeystoreUnlocked()) return true;
+    private boolean unlockKeyStore(VpnProfile p, Runnable action) {
+        if (isKeyStoreUnlocked()) return true;
         mUnlockAction = action;
-        startActivity(
-                new Intent(Keystore.ACTION_UNLOCK_CREDENTIAL_STORAGE));
+        Credentials.getInstance().unlock(this);
         return false;
     }
 
     private void startVpnEditor(final VpnProfile profile) {
-        if (needKeystoreToEdit(profile)) {
-            Runnable action = new Runnable() {
-                public void run() {
-                    startVpnEditor(profile);
-                }
-            };
-            if (!unlockKeystore(profile, action)) return;
-        }
-
         Intent intent = new Intent(this, VpnEditor.class);
         intent.putExtra(KEY_VPN_PROFILE, (Parcelable) profile);
         startActivityForResult(intent, REQUEST_ADD_OR_EDIT_PROFILE);
     }
 
     private synchronized void connect(final VpnProfile p) {
-        if (needKeystoreToConnect(p)) {
+        if (needKeyStoreToConnect(p)) {
             Runnable action = new Runnable() {
                 public void run() {
                     connect(p);
                 }
             };
-            if (!unlockKeystore(p, action)) return;
+            if (!unlockKeyStore(p, action)) return;
         }
 
         if (!checkSecrets(p)) return;
@@ -888,43 +883,32 @@
         return mVpnManager.createVpnProfile(Enum.valueOf(VpnType.class, type));
     }
 
-    private String keyNameForDaemon(String keyName) {
-        return NAMESPACE_VPN + "_" + keyName;
-    }
-
     private boolean checkSecrets(VpnProfile p) {
-        Keystore ks = Keystore.getInstance();
-        HashSet<String> secretSet = new HashSet<String>();
         boolean secretMissing = false;
 
         if (p instanceof L2tpIpsecProfile) {
             L2tpIpsecProfile certProfile = (L2tpIpsecProfile) p;
-            CertTool certTool = CertTool.getInstance();
-            Collections.addAll(secretSet, certTool.getAllCaCertificateKeys());
+
             String cert = certProfile.getCaCertificate();
-            if (TextUtils.isEmpty(cert) || !secretSet.contains(cert)) {
+            if (TextUtils.isEmpty(cert) ||
+                    !mKeyStore.contains(Credentials.CA_CERTIFICATE + cert)) {
                 certProfile.setCaCertificate(null);
                 secretMissing = true;
             }
 
-            secretSet.clear();
-            Collections.addAll(secretSet, certTool.getAllUserCertificateKeys());
             cert = certProfile.getUserCertificate();
-            if (TextUtils.isEmpty(cert) || !secretSet.contains(cert)) {
+            if (TextUtils.isEmpty(cert) ||
+                    !mKeyStore.contains(Credentials.USER_CERTIFICATE + cert)) {
                 certProfile.setUserCertificate(null);
                 secretMissing = true;
             }
         }
 
-        secretSet.clear();
-        Collections.addAll(secretSet, ks.listKeys(NAMESPACE_VPN));
-
         if (p instanceof L2tpIpsecPskProfile) {
             L2tpIpsecPskProfile pskProfile = (L2tpIpsecPskProfile) p;
             String presharedKey = pskProfile.getPresharedKey();
-            String keyName = KEY_PREFIX_IPSEC_PSK + p.getId();
-            if (TextUtils.isEmpty(presharedKey)
-                    || !secretSet.contains(keyName)) {
+            String key = KEY_PREFIX_IPSEC_PSK + p.getId();
+            if (TextUtils.isEmpty(presharedKey) || !mKeyStore.contains(key)) {
                 pskProfile.setPresharedKey(null);
                 secretMissing = true;
             }
@@ -934,9 +918,8 @@
             L2tpProfile l2tpProfile = (L2tpProfile) p;
             if (l2tpProfile.isSecretEnabled()) {
                 String secret = l2tpProfile.getSecretString();
-                String keyName = KEY_PREFIX_L2TP_SECRET + p.getId();
-                if (TextUtils.isEmpty(secret)
-                        || !secretSet.contains(keyName)) {
+                String key = KEY_PREFIX_L2TP_SECRET + p.getId();
+                if (TextUtils.isEmpty(secret) || !mKeyStore.contains(key)) {
                     l2tpProfile.setSecretString(null);
                     secretMissing = true;
                 }
@@ -953,35 +936,30 @@
     }
 
     private void processSecrets(VpnProfile p) {
-        Keystore ks = Keystore.getInstance();
         switch (p.getType()) {
             case L2TP_IPSEC_PSK:
                 L2tpIpsecPskProfile pskProfile = (L2tpIpsecPskProfile) p;
                 String presharedKey = pskProfile.getPresharedKey();
-                String keyName = KEY_PREFIX_IPSEC_PSK + p.getId();
-                if (!TextUtils.isEmpty(presharedKey)) {
-                    int ret = ks.put(NAMESPACE_VPN, keyName, presharedKey);
-                    if (ret != 0) {
-                        Log.e(TAG, "keystore write failed: key=" + keyName);
-                    }
+                String key = KEY_PREFIX_IPSEC_PSK + p.getId();
+                if (!TextUtils.isEmpty(presharedKey) &&
+                        !mKeyStore.put(key, presharedKey)) {
+                    Log.e(TAG, "keystore write failed: key=" + key);
                 }
-                pskProfile.setPresharedKey(keyNameForDaemon(keyName));
+                pskProfile.setPresharedKey(key);
                 // pass through
 
             case L2TP:
                 L2tpProfile l2tpProfile = (L2tpProfile) p;
-                keyName = KEY_PREFIX_L2TP_SECRET + p.getId();
+                key = KEY_PREFIX_L2TP_SECRET + p.getId();
                 if (l2tpProfile.isSecretEnabled()) {
                     String secret = l2tpProfile.getSecretString();
-                    if (!TextUtils.isEmpty(secret)) {
-                        int ret = ks.put(NAMESPACE_VPN, keyName, secret);
-                        if (ret != 0) {
-                            Log.e(TAG, "keystore write failed: key=" + keyName);
-                        }
+                    if (!TextUtils.isEmpty(secret) &&
+                            !mKeyStore.put(key, secret)) {
+                        Log.e(TAG, "keystore write failed: key=" + key);
                     }
-                    l2tpProfile.setSecretString(keyNameForDaemon(keyName));
+                    l2tpProfile.setSecretString(key);
                 } else {
-                    ks.remove(NAMESPACE_VPN, keyName);
+                    mKeyStore.delete(key);
                 }
                 break;
         }
diff --git a/src/com/android/settings/wifi/AccessPointDialog.java b/src/com/android/settings/wifi/AccessPointDialog.java
index f244366..bb5ee6f 100644
--- a/src/com/android/settings/wifi/AccessPointDialog.java
+++ b/src/com/android/settings/wifi/AccessPointDialog.java
@@ -23,8 +23,8 @@
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.content.res.Resources;
-import android.security.CertTool;
-import android.security.Keystore;
+import android.security.Credentials;
+import android.security.KeyStore;
 import android.net.wifi.WifiInfo;
 import android.net.wifi.WifiManager;
 import android.os.Bundle;
@@ -128,13 +128,13 @@
     private TextView mSecurityText;
     private Spinner mSecuritySpinner;
     private Spinner mWepTypeSpinner;
-    private CertTool mCertTool;
+    private KeyStore mKeyStore;
 
     public AccessPointDialog(Context context, WifiLayer wifiLayer) {
         super(context);
 
         mWifiLayer = wifiLayer;
-        mCertTool = CertTool.getInstance();
+        mKeyStore = KeyStore.getInstance();
     }
 
     @Override
@@ -342,18 +342,22 @@
     }
 
     private String[] getAllCaCertificateKeys() {
-        return appendEmptyInSelection(mCertTool.getAllCaCertificateKeys());
+        return appendEmptyInSelection(mKeyStore.saw(Credentials.CA_CERTIFICATE));
     }
 
     private String[] getAllUserCertificateKeys() {
-        return appendEmptyInSelection(mCertTool.getAllUserCertificateKeys());
+        return appendEmptyInSelection(mKeyStore.saw(Credentials.USER_CERTIFICATE));
     }
 
     private String[] appendEmptyInSelection(String[] keys) {
-      String[] selections = new String[keys.length + 1];
-      System.arraycopy(keys, 0, selections, 0, keys.length);
-      selections[keys.length] = NOT_APPLICABLE;
-      return selections;
+        if (keys == null) {
+            return new String[] {NOT_APPLICABLE};
+        } else {
+            String[] selections = new String[keys.length + 1];
+            System.arraycopy(keys, 0, selections, 0, keys.length);
+            selections[keys.length] = NOT_APPLICABLE;
+            return selections;
+        }
     }
 
     private void setEnterpriseFields(View view) {
@@ -635,31 +639,22 @@
         Spinner spinner = mClientCertSpinner;
         int index = spinner.getSelectedItemPosition();
         if (index != (spinner.getCount() - 1)) {
-            String key = (String)spinner.getSelectedItem();
-            value = mCertTool.getUserCertificate(key);
-            if (!TextUtils.isEmpty(value)) {
-                mState.setEnterpriseField(AccessPointState.CLIENT_CERT,
-                        BLOB_HEADER + value);
-            }
-            value = mCertTool.getUserPrivateKey(key);
-            if (!TextUtils.isEmpty(value)) {
-                mState.setEnterpriseField(AccessPointState.PRIVATE_KEY,
-                        BLOB_HEADER + value);
-            }
+            String key = (String) spinner.getSelectedItem();
+            mState.setEnterpriseField(AccessPointState.CLIENT_CERT,
+                    BLOB_HEADER + Credentials.USER_CERTIFICATE + key);
+            mState.setEnterpriseField(AccessPointState.PRIVATE_KEY,
+                    BLOB_HEADER + Credentials.USER_PRIVATE_KEY + key);
         }
         spinner = mCaCertSpinner;
         index = spinner.getSelectedItemPosition();
         if (index != (spinner.getCount() - 1)) {
-            String key = (String)spinner.getSelectedItem();
-            value = mCertTool.getCaCertificate(key);
-            if (!TextUtils.isEmpty(value)) {
-                mState.setEnterpriseField(AccessPointState.CA_CERT,
-                        BLOB_HEADER + value);
-            }
+            String key = (String) spinner.getSelectedItem();
+            mState.setEnterpriseField(AccessPointState.CA_CERT,
+                    BLOB_HEADER + Credentials.CA_CERTIFICATE + key);
         }
         mState.setSecurity(AccessPointState.EAP);
         mState.setEap(mEapSpinner.getSelectedItemPosition());
-        mState.setPhase2((String)mPhase2Spinner.getSelectedItem());
+        mState.setPhase2((String) mPhase2Spinner.getSelectedItem());
     }
 
     /**
@@ -765,9 +760,8 @@
             }
             case SECURITY_EAP: {
                 // Unlock the keystore if it is not unlocked yet.
-                if (Keystore.getInstance().getState() != Keystore.UNLOCKED) {
-                    getContext().startActivity(new Intent(
-                            Keystore.ACTION_UNLOCK_CREDENTIAL_STORAGE));
+                if (mKeyStore.test() != KeyStore.NO_ERROR) {
+                    Credentials.getInstance().unlock(getContext());
                     return;
                 }
                 enableEnterpriseFields();
diff --git a/src/com/android/settings/wifi/WifiSettings.java b/src/com/android/settings/wifi/WifiSettings.java
index 4aa5dc3..361f159 100644
--- a/src/com/android/settings/wifi/WifiSettings.java
+++ b/src/com/android/settings/wifi/WifiSettings.java
@@ -29,7 +29,8 @@
 import android.preference.PreferenceScreen;
 import android.preference.CheckBoxPreference;
 import android.provider.Settings;
-import android.security.Keystore;
+import android.security.Credentials;
+import android.security.KeyStore;
 import android.util.Log;
 import android.view.ContextMenu;
 import android.view.Menu;
@@ -86,6 +87,7 @@
     
     private WeakHashMap<AccessPointState, AccessPointPreference> mAps;
 
+    private KeyStore mKeyStore = KeyStore.getInstance();
     private AccessPointState mResumeState = null;
     private int mResumeMode;
     
@@ -156,14 +158,14 @@
         mWifiEnabler.resume();
         // do what we should have after keystore is unlocked.
         if (mResumeState != null) {
-            if (Keystore.getInstance().getState() == Keystore.UNLOCKED) {
+            if (mKeyStore.test() == KeyStore.NO_ERROR) {
                 showAccessPointDialog(mResumeState, mResumeMode);
             }
             mResumeMode = -1;
             mResumeState = null;
         } else {
             if (mResumeMode == AccessPointDialog.MODE_CONFIGURE) {
-                if (Keystore.getInstance().getState() == Keystore.UNLOCKED) {
+                if (mKeyStore.test() == KeyStore.NO_ERROR) {
                     ((AccessPointDialog) mDialog).enableEnterpriseFields();
                 }
             }
@@ -372,10 +374,8 @@
     }
     
     public void showAccessPointDialog(AccessPointState state, int mode) {
-        if (state.isEnterprise() &&
-                Keystore.getInstance().getState() != Keystore.UNLOCKED) {
-            startActivity(new Intent(
-                    Keystore.ACTION_UNLOCK_CREDENTIAL_STORAGE));
+        if (state.isEnterprise() && mKeyStore.test() != KeyStore.NO_ERROR) {
+            Credentials.getInstance().unlock(this);
             mResumeState = state;
             mResumeMode = mode;
             return;