Commits

Stephen Smalley committed 26b25f2 Merge

Merge branch 'master' into seandroid

Comments (0)

Files changed (38)

 			$(framework_res_source_path)/com/android/internal/R.java
 
 LOCAL_NO_STANDARD_LIBRARIES := true
-LOCAL_JAVA_LIBRARIES := bouncycastle core core-junit ext okhttp
+LOCAL_JAVA_LIBRARIES := bouncycastle conscrypt core core-junit ext okhttp
 
 LOCAL_MODULE := framework
 LOCAL_MODULE_CLASS := JAVA_LIBRARIES
 
 framework_docs_LOCAL_JAVA_LIBRARIES := \
 			bouncycastle \
+			conscrypt \
 			core \
 			okhttp \
 			ext \
     method public static void startMethodTracing(java.lang.String, int);
     method public static void startMethodTracing(java.lang.String, int, int);
     method public static void startNativeTracing();
-    method public static void stopAllocCounting();
+    method public static deprecated void stopAllocCounting();
     method public static void stopMethodTracing();
     method public static void stopNativeTracing();
     method public static long threadCpuTimeNanos();

cmds/app_process/app_main.cpp

 
 #define LOG_TAG "appproc"
 
+#include <cutils/properties.h>
 #include <binder/IPCThreadState.h>
 #include <binder/ProcessState.h>
 #include <utils/Log.h>
      * This breaks some programs which improperly embed
      * an out of date copy of Android's linker.
      */
-    if (getenv("NO_ADDR_COMPAT_LAYOUT_FIXUP") == NULL) {
+    char value[PROPERTY_VALUE_MAX];
+    property_get("ro.kernel.qemu", value, "");
+    bool is_qemu = (strcmp(value, "1") == 0);
+    if ((getenv("NO_ADDR_COMPAT_LAYOUT_FIXUP") == NULL) && !is_qemu) {
         int current = personality(0xFFFFFFFF);
         if ((current & ADDR_COMPAT_LAYOUT) == 0) {
             personality(current | ADDR_COMPAT_LAYOUT);

cmds/input/src/com/android/commands/input/Input.java

                     return;
                 }
             } else if (command.equals("keyevent")) {
-                if (args.length == 2) {
-                    int keyCode = KeyEvent.keyCodeFromString(args[1]);
-                    if (keyCode == KeyEvent.KEYCODE_UNKNOWN) {
-                        keyCode = KeyEvent.keyCodeFromString("KEYCODE_" + args[1]);
+                if (args.length >= 2) {
+                    for (int i=1; i < args.length; i++) {
+                        int keyCode = KeyEvent.keyCodeFromString(args[i]);
+                        if (keyCode == KeyEvent.KEYCODE_UNKNOWN) {
+                            keyCode = KeyEvent.keyCodeFromString("KEYCODE_" + args[i]);
+                        }
+                        sendKeyEvent(keyCode);
                     }
-                    sendKeyEvent(keyCode);
                     return;
                 }
             } else if (command.equals("tap")) {
                 DEFAULT_META_STATE, DEFAULT_PRECISION_X, DEFAULT_PRECISION_Y, DEFAULT_DEVICE_ID,
                 DEFAULT_EDGE_FLAGS);
         event.setSource(inputSource);
-        Log.i("Input", "injectMotionEvent: " + event);
+        Log.i(TAG, "injectMotionEvent: " + event);
         InputManager.getInstance().injectInputEvent(event,
                 InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH);
     }
     private void showUsage() {
         System.err.println("usage: input ...");
         System.err.println("       input text <string>");
-        System.err.println("       input keyevent <key code number or name>");
+        System.err.println("       input keyevent <key code number or name> ...");
         System.err.println("       input [touchscreen|touchpad] tap <x> <y>");
         System.err.println("       input [touchscreen|touchpad] swipe <x1> <y1> <x2> <y2>");
         System.err.println("       input trackball press");

core/java/android/app/ActivityThread.java

 import com.android.internal.os.RuntimeInit;
 import com.android.internal.os.SamplingProfilerIntegration;
 import com.android.internal.util.Objects;
-
-import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
+import com.android.org.conscrypt.OpenSSLSocketImpl;
 
 import java.io.File;
 import java.io.FileDescriptor;

core/java/android/inputmethodservice/InputMethodService.java

                 showWindow(true);
             }
             // If user uses hard keyboard, IME button should always be shown.
-            boolean showing = onEvaluateInputViewShown();
+            boolean showing = isInputViewShown();
             mImm.setImeWindowStatus(mToken, IME_ACTIVE | (showing ? IME_VISIBLE : 0),
                     mBackDisposition);
             if (resultReceiver != null) {

core/java/android/net/SSLCertificateSocketFactory.java

 
 import android.os.SystemProperties;
 import android.util.Log;
+import com.android.org.conscrypt.OpenSSLContextImpl;
+import com.android.org.conscrypt.OpenSSLSocketImpl;
+import com.android.org.conscrypt.SSLClientSessionCache;
 import java.io.IOException;
 import java.net.InetAddress;
 import java.net.Socket;
 import javax.net.ssl.SSLSocketFactory;
 import javax.net.ssl.TrustManager;
 import javax.net.ssl.X509TrustManager;
-import org.apache.harmony.xnet.provider.jsse.OpenSSLContextImpl;
-import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
-import org.apache.harmony.xnet.provider.jsse.SSLClientSessionCache;
 
 /**
  * SSLSocketFactory implementation with several extra features:

core/java/android/net/SSLSessionCache.java

 
 package android.net;
 
-import org.apache.harmony.xnet.provider.jsse.FileClientSessionCache;
-import org.apache.harmony.xnet.provider.jsse.SSLClientSessionCache;
-
 import android.content.Context;
 import android.util.Log;
 
+import com.android.org.conscrypt.FileClientSessionCache;
+import com.android.org.conscrypt.SSLClientSessionCache;
+
 import java.io.File;
 import java.io.IOException;
 

core/java/android/net/http/CertificateChainValidator.java

 
 package android.net.http;
 
+import com.android.org.conscrypt.SSLParametersImpl;
+import com.android.org.conscrypt.TrustManagerImpl;
 
+import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.security.GeneralSecurityException;
 import java.security.KeyManagementException;
 import java.security.cert.Certificate;
 import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
 import javax.net.ssl.DefaultHostnameVerifier;
 import javax.net.ssl.SSLHandshakeException;
 import javax.net.ssl.SSLSession;
 import javax.net.ssl.SSLSocket;
 import javax.net.ssl.X509TrustManager;
-import org.apache.harmony.security.provider.cert.X509CertImpl;
-import org.apache.harmony.xnet.provider.jsse.SSLParametersImpl;
-import org.apache.harmony.xnet.provider.jsse.TrustManagerImpl;
 
 /**
  * Class responsible for all server certificate validation functionality
 
         X509Certificate[] serverCertificates = new X509Certificate[certChain.length];
 
-        for (int i = 0; i < certChain.length; ++i) {
-            serverCertificates[i] = new X509CertImpl(certChain[i]);
+        try {
+            CertificateFactory cf = CertificateFactory.getInstance("X.509");
+            for (int i = 0; i < certChain.length; ++i) {
+                serverCertificates[i] = (X509Certificate) cf.generateCertificate(
+                        new ByteArrayInputStream(certChain[i]));
+            }
+        } catch (CertificateException e) {
+            throw new IOException("can't read certificate", e);
         }
 
         return verifyServerDomainAndCertificates(serverCertificates, domain, authType);

core/java/android/net/http/HttpsConnection.java

 
 import android.content.Context;
 import android.util.Log;
-import org.apache.harmony.xnet.provider.jsse.FileClientSessionCache;
-import org.apache.harmony.xnet.provider.jsse.OpenSSLContextImpl;
-import org.apache.harmony.xnet.provider.jsse.SSLClientSessionCache;
+import com.android.org.conscrypt.FileClientSessionCache;
+import com.android.org.conscrypt.OpenSSLContextImpl;
+import com.android.org.conscrypt.SSLClientSessionCache;
 import org.apache.http.Header;
 import org.apache.http.HttpException;
 import org.apache.http.HttpHost;

core/java/android/net/http/X509TrustManagerExtensions.java

 
 package android.net.http;
 
-import org.apache.harmony.xnet.provider.jsse.TrustManagerImpl;
+import com.android.org.conscrypt.TrustManagerImpl;
 
 import java.security.cert.CertificateException;
 import java.security.cert.X509Certificate;

core/java/android/os/Debug.java

      *
      * @see #startAllocCounting()
      */
+    @Deprecated
     public static void stopAllocCounting() {
         VMDebug.stopAllocCounting();
     }

core/java/android/security/IKeystoreService.java

                 return _result;
             }
 
-            public int insert(String name, byte[] item, int uid) throws RemoteException {
+            public int insert(String name, byte[] item, int uid, int flags) throws RemoteException {
                 Parcel _data = Parcel.obtain();
                 Parcel _reply = Parcel.obtain();
                 int _result;
                     _data.writeString(name);
                     _data.writeByteArray(item);
                     _data.writeInt(uid);
+                    _data.writeInt(flags);
                     mRemote.transact(Stub.TRANSACTION_insert, _data, _reply, 0);
                     _reply.readException();
                     _result = _reply.readInt();
                 return _result;
             }
 
-            public int generate(String name, int uid) throws RemoteException {
+            public int generate(String name, int uid, int flags) throws RemoteException {
                 Parcel _data = Parcel.obtain();
                 Parcel _reply = Parcel.obtain();
                 int _result;
                     _data.writeInterfaceToken(DESCRIPTOR);
                     _data.writeString(name);
                     _data.writeInt(uid);
+                    _data.writeInt(flags);
                     mRemote.transact(Stub.TRANSACTION_generate, _data, _reply, 0);
                     _reply.readException();
                     _result = _reply.readInt();
                 return _result;
             }
 
-            public int import_key(String name, byte[] data, int uid) throws RemoteException {
+            public int import_key(String name, byte[] data, int uid, int flags)
+                    throws RemoteException {
                 Parcel _data = Parcel.obtain();
                 Parcel _reply = Parcel.obtain();
                 int _result;
                     _data.writeString(name);
                     _data.writeByteArray(data);
                     _data.writeInt(uid);
+                    _data.writeInt(flags);
                     mRemote.transact(Stub.TRANSACTION_import, _data, _reply, 0);
                     _reply.readException();
                     _result = _reply.readInt();
 
     public byte[] get(String name) throws RemoteException;
 
-    public int insert(String name, byte[] item, int uid) throws RemoteException;
+    public int insert(String name, byte[] item, int uid, int flags) throws RemoteException;
 
     public int del(String name, int uid) throws RemoteException;
 
 
     public int zero() throws RemoteException;
 
-    public int generate(String name, int uid) throws RemoteException;
+    public int generate(String name, int uid, int flags) throws RemoteException;
 
-    public int import_key(String name, byte[] data, int uid) throws RemoteException;
+    public int import_key(String name, byte[] data, int uid, int flags) throws RemoteException;
 
     public byte[] sign(String name, byte[] data) throws RemoteException;
 

core/java/android/util/TimeUtils.java

      * during the lifetime of an activity.
      */
     public static String getTimeZoneDatabaseVersion() {
-        return ZoneInfoDB.getVersion();
+        return ZoneInfoDB.getInstance().getVersion();
     }
 
     /** @hide Field length that can hold 999 days of time */

core/java/android/view/KeyEvent.java

 
     // NOTE: If you add a new keycode here you must also add it to:
     //  isSystem()
-    //  native/include/android/keycodes.h
-    //  frameworks/base/include/ui/KeycodeLabels.h
+    //  frameworks/native/include/android/keycodes.h
+    //  frameworks/base/include/androidfw/KeycodeLabels.h
     //  external/webkit/WebKit/android/plugins/ANPKeyCodes.h
     //  frameworks/base/core/res/res/values/attrs.xml
     //  emulator?

core/java/android/webkit/BrowserFrame.java

 
 import junit.framework.Assert;
 
+import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.lang.ref.WeakReference;
 import java.net.URLEncoder;
-import java.nio.charset.Charsets;
 import java.security.PrivateKey;
-import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Set;
 
-import org.apache.harmony.security.provider.cert.X509CertImpl;
-import org.apache.harmony.xnet.provider.jsse.OpenSSLKey;
-import org.apache.harmony.xnet.provider.jsse.OpenSSLKeyHolder;
+import com.android.org.conscrypt.OpenSSLKey;
+import com.android.org.conscrypt.OpenSSLKeyHolder;
 
 class BrowserFrame extends Handler {
 
             String url) {
         final SslError sslError;
         try {
-            X509Certificate cert = new X509CertImpl(certDER);
+            CertificateFactory cf = CertificateFactory.getInstance("X.509");
+            X509Certificate cert = (X509Certificate) cf.generateCertificate(
+                    new ByteArrayInputStream(certDER));
             SslCertificate sslCert = new SslCertificate(cert);
             sslError = SslError.SslErrorFromChromiumErrorCode(certError, sslCert, url);
-        } catch (IOException e) {
+        } catch (Exception e) {
             // Can't get the certificate, not much to do.
             Log.e(LOGTAG, "Can't get the certificate from WebKit, canceling");
             nativeSslCertErrorCancel(handle, certError);
      */
     private void setCertificate(byte cert_der[]) {
         try {
-            X509Certificate cert = new X509CertImpl(cert_der);
+            CertificateFactory cf = CertificateFactory.getInstance("X.509");
+            X509Certificate cert = (X509Certificate) cf.generateCertificate(
+                    new ByteArrayInputStream(cert_der));
             mCallbackProxy.onReceivedCertificate(new SslCertificate(cert));
-        } catch (IOException e) {
+        } catch (Exception e) {
             // Can't get the certificate, not much to do.
             Log.e(LOGTAG, "Can't get the certificate from WebKit, canceling");
             return;

core/java/android/webkit/ClientCertRequestHandler.java

 import java.security.PrivateKey;
 import java.security.cert.CertificateEncodingException;
 import java.security.cert.X509Certificate;
-import org.apache.harmony.xnet.provider.jsse.NativeCrypto;
-import org.apache.harmony.xnet.provider.jsse.OpenSSLKey;
-import org.apache.harmony.xnet.provider.jsse.OpenSSLKeyHolder;
+import com.android.org.conscrypt.NativeCrypto;
+import com.android.org.conscrypt.OpenSSLKey;
+import com.android.org.conscrypt.OpenSSLKeyHolder;
 
 /**
  * ClientCertRequestHandler: class responsible for handling client

core/java/com/android/internal/os/ZygoteInit.java

 
 import libcore.io.IoUtils;
 import libcore.io.Libcore;
+import libcore.io.OsConstants;
 
 import java.io.BufferedReader;
 import java.io.FileDescriptor;
      */
     private static boolean startSystemServer()
             throws MethodAndArgsCaller, RuntimeException {
+        long capabilities = posixCapabilitiesAsBits(
+            OsConstants.CAP_KILL,
+            OsConstants.CAP_NET_ADMIN,
+            OsConstants.CAP_NET_BIND_SERVICE,
+            OsConstants.CAP_NET_BROADCAST,
+            OsConstants.CAP_NET_RAW,
+            OsConstants.CAP_SYS_BOOT,
+            OsConstants.CAP_SYS_MODULE,
+            OsConstants.CAP_SYS_NICE,
+            OsConstants.CAP_SYS_RESOURCE,
+            OsConstants.CAP_SYS_TIME,
+            OsConstants.CAP_SYS_TTY_CONFIG
+        );
         /* Hardcoded command line to start the system server */
         String args[] = {
             "--setuid=1000",
             "--setgid=1000",
             "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003,3006,3007",
-            "--capabilities=130104352,130104352",
+            "--capabilities=" + capabilities + "," + capabilities,
             "--runtime-init",
             "--nice-name=system_server",
             "com.android.server.SystemServer",
         return true;
     }
 
+    /**
+     * Gets the bit array representation of the provided list of POSIX capabilities.
+     */
+    private static long posixCapabilitiesAsBits(int... capabilities) {
+        long result = 0;
+        for (int capability : capabilities) {
+            if ((capability < 0) || (capability > OsConstants.CAP_LAST_CAP)) {
+                throw new IllegalArgumentException(String.valueOf(capability));
+            }
+            result |= (1L << capability);
+        }
+        return result;
+    }
+
     public static void main(String argv[]) {
         try {
             // Start profiling the zygote initialization.

core/tests/coretests/Android.mk

 
 LOCAL_DX_FLAGS := --core-library
 LOCAL_STATIC_JAVA_LIBRARIES := core-tests android-common frameworks-core-util-lib mockwebserver guava littlemock
-LOCAL_JAVA_LIBRARIES := android.test.runner telephony-common
+LOCAL_JAVA_LIBRARIES := android.test.runner conscrypt telephony-common
 LOCAL_PACKAGE_NAME := FrameworksCoreTests
 
 LOCAL_CERTIFICATE := platform

core/tests/coretests/src/android/net/http/X509TrustManagerExtensionsTest.java

 
 import junit.framework.TestCase;
 
-import org.apache.harmony.xnet.provider.jsse.TrustManagerImpl;
+import com.android.org.conscrypt.TrustManagerImpl;
 
 public class X509TrustManagerExtensionsTest extends TestCase {
 

docs/html/guide/topics/data/backup.jd

 
 <pre>
 public class MyFileBackupAgent extends BackupAgentHelper {
-    // The name of the SharedPreferences file
+    // The name of the file
     static final String TOP_SCORES = "scores";
     static final String PLAYER_STATS = "stats";
 

keystore/java/android/security/AndroidKeyPairGenerator.java

 
 import com.android.org.bouncycastle.x509.X509V3CertificateGenerator;
 
-import org.apache.harmony.xnet.provider.jsse.OpenSSLEngine;
+import com.android.org.conscrypt.OpenSSLEngine;
 
 import java.security.InvalidAlgorithmParameterException;
 import java.security.InvalidKeyException;
  *
  * {@hide}
  */
-@SuppressWarnings("deprecation")
 public class AndroidKeyPairGenerator extends KeyPairGeneratorSpi {
-    public static final String NAME = "AndroidKeyPairGenerator";
-
     private android.security.KeyStore mKeyStore;
 
     private AndroidKeyPairGeneratorSpec mSpec;
                     "Must call initialize with an AndroidKeyPairGeneratorSpec first");
         }
 
+        if (((mSpec.getFlags() & KeyStore.FLAG_ENCRYPTED) != 0)
+                && (mKeyStore.state() != KeyStore.State.UNLOCKED)) {
+            throw new IllegalStateException(
+                    "Android keystore must be in initialized and unlocked state "
+                            + "if encryption is required");
+        }
+
         final String alias = mSpec.getKeystoreAlias();
 
         Credentials.deleteAllTypesForAlias(mKeyStore, alias);
 
         final String privateKeyAlias = Credentials.USER_PRIVATE_KEY + alias;
-        mKeyStore.generate(privateKeyAlias);
+        if (!mKeyStore.generate(privateKeyAlias, KeyStore.UID_SELF, mSpec.getFlags())) {
+            throw new IllegalStateException("could not generate key in keystore");
+        }
 
         final PrivateKey privKey;
         final OpenSSLEngine engine = OpenSSLEngine.getInstance("keystore");
             throw new IllegalStateException("Can't get encoding of certificate", e);
         }
 
-        if (!mKeyStore.put(Credentials.USER_CERTIFICATE + alias, certBytes)) {
+        if (!mKeyStore.put(Credentials.USER_CERTIFICATE + alias, certBytes, KeyStore.UID_SELF,
+                mSpec.getFlags())) {
             Credentials.deleteAllTypesForAlias(mKeyStore, alias);
             throw new IllegalStateException("Can't store certificate in AndroidKeyStore");
         }

keystore/java/android/security/AndroidKeyPairGeneratorSpec.java

  * {@code KeyPairGenerator} that works with <a href="{@docRoot}
  * guide/topics/security/keystore.html">Android KeyStore facility</a>. The
  * Android KeyStore facility is accessed through a
- * {@link java.security.KeyPairGenerator} API using the
- * {@code AndroidKeyPairGenerator} provider. The {@code context} passed in may
- * be used to pop up some UI to ask the user to unlock or initialize the Android
- * keystore facility.
+ * {@link java.security.KeyPairGenerator} API using the {@code AndroidKeyStore}
+ * provider. The {@code context} passed in may be used to pop up some UI to ask
+ * the user to unlock or initialize the Android KeyStore facility.
  * <p>
  * After generation, the {@code keyStoreAlias} is used with the
  * {@link java.security.KeyStore#getEntry(String, java.security.KeyStore.ProtectionParameter)}
  * Distinguished Name along with the other parameters specified with the
  * {@link Builder}.
  * <p>
- * The self-signed certificate may be replaced at a later time by a certificate
- * signed by a real Certificate Authority.
+ * The self-signed X.509 certificate may be replaced at a later time by a
+ * certificate signed by a real Certificate Authority.
  *
  * @hide
  */
-public class AndroidKeyPairGeneratorSpec implements AlgorithmParameterSpec {
+public final class AndroidKeyPairGeneratorSpec implements AlgorithmParameterSpec {
     private final String mKeystoreAlias;
 
     private final Context mContext;
 
     private final Date mEndDate;
 
+    private final int mFlags;
+
     /**
      * Parameter specification for the "{@code AndroidKeyPairGenerator}"
      * instance of the {@link java.security.KeyPairGenerator} API. The
      * @hide should be built with AndroidKeyPairGeneratorSpecBuilder
      */
     public AndroidKeyPairGeneratorSpec(Context context, String keyStoreAlias,
-            X500Principal subjectDN, BigInteger serialNumber, Date startDate, Date endDate) {
+            X500Principal subjectDN, BigInteger serialNumber, Date startDate, Date endDate,
+            int flags) {
         if (context == null) {
             throw new IllegalArgumentException("context == null");
         } else if (TextUtils.isEmpty(keyStoreAlias)) {
         mSerialNumber = serialNumber;
         mStartDate = startDate;
         mEndDate = endDate;
+        mFlags = flags;
     }
 
     /**
-     * @hide
+     * Returns the alias that will be used in the {@code java.security.KeyStore}
+     * in conjunction with the {@code AndroidKeyStore}.
      */
-    String getKeystoreAlias() {
+    public String getKeystoreAlias() {
         return mKeystoreAlias;
     }
 
     /**
-     * @hide
+     * Gets the Android context used for operations with this instance.
      */
-    Context getContext() {
+    public Context getContext() {
         return mContext;
     }
 
     /**
-     * @hide
+     * Gets the subject distinguished name to be used on the X.509 certificate
+     * that will be put in the {@link java.security.KeyStore}.
      */
-    X500Principal getSubjectDN() {
+    public X500Principal getSubjectDN() {
         return mSubjectDN;
     }
 
     /**
-     * @hide
+     * Gets the serial number to be used on the X.509 certificate that will be
+     * put in the {@link java.security.KeyStore}.
      */
-    BigInteger getSerialNumber() {
+    public BigInteger getSerialNumber() {
         return mSerialNumber;
     }
 
     /**
-     * @hide
+     * Gets the start date to be used on the X.509 certificate that will be put
+     * in the {@link java.security.KeyStore}.
      */
-    Date getStartDate() {
+    public Date getStartDate() {
         return mStartDate;
     }
 
     /**
-     * @hide
+     * Gets the end date to be used on the X.509 certificate that will be put in
+     * the {@link java.security.KeyStore}.
      */
-    Date getEndDate() {
+    public Date getEndDate() {
         return mEndDate;
     }
 
     /**
+     * @hide
+     */
+    int getFlags() {
+        return mFlags;
+    }
+
+    /**
+     * Returns {@code true} if this parameter will require generated keys to be
+     * encrypted in the {@link java.security.KeyStore}.
+     */
+    public boolean isEncryptionRequired() {
+        return (mFlags & KeyStore.FLAG_ENCRYPTED) != 0;
+    }
+
+    /**
      * Builder class for {@link AndroidKeyPairGeneratorSpec} objects.
      * <p>
      * This will build a parameter spec for use with the <a href="{@docRoot}
      * Calendar end = new Calendar();
      * end.add(1, Calendar.YEAR);
      *
-     * AndroidKeyPairGeneratorSpec spec = new AndroidKeyPairGeneratorSpec.Builder(mContext)
-     *         .setAlias("myKey")
-     *         .setSubject(new X500Principal("CN=myKey"))
-     *         .setSerial(BigInteger.valueOf(1337))
-     *         .setStartDate(start.getTime())
-     *         .setEndDate(end.getTime())
-     *         .build();
+     * AndroidKeyPairGeneratorSpec spec =
+     *         new AndroidKeyPairGeneratorSpec.Builder(mContext)
+     *                 .setAlias(&quot;myKey&quot;)
+     *                 .setSubject(new X500Principal(&quot;CN=myKey&quot;))
+     *                 .setSerial(BigInteger.valueOf(1337))
+     *                 .setStartDate(start.getTime())
+     *                 .setEndDate(end.getTime())
+     *                 .build();
      * </pre>
      */
-    public static class Builder {
+    public final static class Builder {
         private final Context mContext;
 
         private String mKeystoreAlias;
 
         private Date mEndDate;
 
+        private int mFlags;
+
+        /**
+         * Creates a new instance of the {@code Builder} with the given
+         * {@code context}. The {@code context} passed in may be used to pop up
+         * some UI to ask the user to unlock or initialize the Android KeyStore
+         * facility.
+         */
         public Builder(Context context) {
             if (context == null) {
                 throw new NullPointerException("context == null");
         }
 
         /**
+         * Indicates that this key must be encrypted at rest on storage. Note
+         * that enabling this will require that the user enable a strong lock
+         * screen (e.g., PIN, password) before creating or using the generated
+         * key is successful.
+         */
+        public Builder setEncryptionRequired() {
+            mFlags |= KeyStore.FLAG_ENCRYPTED;
+            return this;
+        }
+
+        /**
          * Builds the instance of the {@code AndroidKeyPairGeneratorSpec}.
          *
          * @throws IllegalArgumentException if a required field is missing
          */
         public AndroidKeyPairGeneratorSpec build() {
             return new AndroidKeyPairGeneratorSpec(mContext, mKeystoreAlias, mSubjectDN,
-                    mSerialNumber, mStartDate, mEndDate);
+                    mSerialNumber, mStartDate, mEndDate, mFlags);
         }
     }
 }

keystore/java/android/security/AndroidKeyStore.java

 
 package android.security;
 
-import org.apache.harmony.xnet.provider.jsse.OpenSSLEngine;
-import org.apache.harmony.xnet.provider.jsse.OpenSSLKeyHolder;
+import com.android.org.conscrypt.OpenSSLEngine;
+import com.android.org.conscrypt.OpenSSLKeyHolder;
 
 import android.util.Log;
 
 import java.io.OutputStream;
 import java.security.InvalidKeyException;
 import java.security.Key;
+import java.security.KeyStore.Entry;
+import java.security.KeyStore.PrivateKeyEntry;
+import java.security.KeyStore.ProtectionParameter;
+import java.security.KeyStore;
 import java.security.KeyStoreException;
 import java.security.KeyStoreSpi;
 import java.security.NoSuchAlgorithmException;
         }
 
         if (key instanceof PrivateKey) {
-            setPrivateKeyEntry(alias, (PrivateKey) key, chain);
+            setPrivateKeyEntry(alias, (PrivateKey) key, chain, null);
         } else {
             throw new KeyStoreException("Only PrivateKeys are supported");
         }
     }
 
-    private void setPrivateKeyEntry(String alias, PrivateKey key, Certificate[] chain)
-            throws KeyStoreException {
+    private void setPrivateKeyEntry(String alias, PrivateKey key, Certificate[] chain,
+            AndroidKeyStoreParameter params) throws KeyStoreException {
         byte[] keyBytes = null;
 
         final String pkeyAlias;
             Credentials.deleteCertificateTypesForAlias(mKeyStore, alias);
         }
 
+        final int flags = (params == null) ? 0 : params.getFlags();
+
         if (shouldReplacePrivateKey
-                && !mKeyStore.importKey(Credentials.USER_PRIVATE_KEY + alias, keyBytes)) {
+                && !mKeyStore.importKey(Credentials.USER_PRIVATE_KEY + alias, keyBytes,
+                        android.security.KeyStore.UID_SELF, flags)) {
             Credentials.deleteAllTypesForAlias(mKeyStore, alias);
             throw new KeyStoreException("Couldn't put private key in keystore");
-        } else if (!mKeyStore.put(Credentials.USER_CERTIFICATE + alias, userCertBytes)) {
+        } else if (!mKeyStore.put(Credentials.USER_CERTIFICATE + alias, userCertBytes,
+                android.security.KeyStore.UID_SELF, flags)) {
             Credentials.deleteAllTypesForAlias(mKeyStore, alias);
             throw new KeyStoreException("Couldn't put certificate #1 in keystore");
         } else if (chainBytes != null
-                && !mKeyStore.put(Credentials.CA_CERTIFICATE + alias, chainBytes)) {
+                && !mKeyStore.put(Credentials.CA_CERTIFICATE + alias, chainBytes,
+                        android.security.KeyStore.UID_SELF, flags)) {
             Credentials.deleteAllTypesForAlias(mKeyStore, alias);
             throw new KeyStoreException("Couldn't put certificate chain in keystore");
         }
             throw new KeyStoreException(e);
         }
 
-        if (!mKeyStore.put(Credentials.CA_CERTIFICATE + alias, encoded)) {
+        if (!mKeyStore.put(Credentials.CA_CERTIFICATE + alias, encoded,
+                android.security.KeyStore.UID_SELF, android.security.KeyStore.FLAG_NONE)) {
             throw new KeyStoreException("Couldn't insert certificate; is KeyStore initialized?");
         }
     }
         mKeyStore = android.security.KeyStore.getInstance();
     }
 
+    @Override
+    public void engineSetEntry(String alias, Entry entry, ProtectionParameter param)
+            throws KeyStoreException {
+        if (entry == null) {
+            throw new KeyStoreException("entry == null");
+        }
+
+        if (engineContainsAlias(alias)) {
+            engineDeleteEntry(alias);
+        }
+
+        if (entry instanceof KeyStore.TrustedCertificateEntry) {
+            KeyStore.TrustedCertificateEntry trE = (KeyStore.TrustedCertificateEntry) entry;
+            engineSetCertificateEntry(alias, trE.getTrustedCertificate());
+            return;
+        }
+
+        if (param != null && !(param instanceof AndroidKeyStoreParameter)) {
+            throw new KeyStoreException("protParam should be AndroidKeyStoreParameter; was: "
+                    + param.getClass().getName());
+        }
+
+        if (entry instanceof PrivateKeyEntry) {
+            PrivateKeyEntry prE = (PrivateKeyEntry) entry;
+            setPrivateKeyEntry(alias, prE.getPrivateKey(), prE.getCertificateChain(),
+                    (AndroidKeyStoreParameter) param);
+            return;
+        }
+
+        throw new KeyStoreException(
+                "Entry must be a PrivateKeyEntry or TrustedCertificateEntry; was " + entry);
+    }
+
 }

keystore/java/android/security/AndroidKeyStoreParameter.java

+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.security;
+
+import android.content.Context;
+import android.security.AndroidKeyPairGeneratorSpec.Builder;
+
+import java.security.KeyPairGenerator;
+import java.security.PrivateKey;
+import java.security.KeyStore.ProtectionParameter;
+import java.security.cert.Certificate;
+
+/**
+ * This provides the optional parameters that can be specified for
+ * {@code KeyStore} entries that work with <a href="{@docRoot}
+ * guide/topics/security/keystore.html">Android KeyStore facility</a>. The
+ * Android KeyStore facility is accessed through a
+ * {@link java.security.KeyStore} API using the {@code AndroidKeyStore}
+ * provider. The {@code context} passed in may be used to pop up some UI to ask
+ * the user to unlock or initialize the Android KeyStore facility.
+ * <p>
+ * Any entries placed in the {@code KeyStore} may be retrieved later. Note that
+ * there is only one logical instance of the {@code KeyStore} per application
+ * UID so apps using the {@code sharedUid} facility will also share a
+ * {@code KeyStore}.
+ * <p>
+ * Keys may be generated using the {@link KeyPairGenerator} facility with a
+ * {@link AndroidKeyPairGeneratorSpec} to specify the entry's {@code alias}. A
+ * self-signed X.509 certificate will be attached to generated entries, but that
+ * may be replaced at a later time by a certificate signed by a real Certificate
+ * Authority.
+ *
+ * @hide
+ */
+public final class AndroidKeyStoreParameter implements ProtectionParameter {
+    private int mFlags;
+
+    private AndroidKeyStoreParameter(int flags) {
+        mFlags = flags;
+    }
+
+    /**
+     * @hide
+     */
+    public int getFlags() {
+        return mFlags;
+    }
+
+    /**
+     * Returns {@code true} if this parameter requires entries to be encrypted
+     * on the disk.
+     */
+    public boolean isEncryptionRequired() {
+        return (mFlags & KeyStore.FLAG_ENCRYPTED) != 0;
+    }
+
+    /**
+     * Builder class for {@link AndroidKeyStoreParameter} objects.
+     * <p>
+     * This will build protection parameters for use with the <a
+     * href="{@docRoot} guide/topics/security/keystore.html">Android KeyStore
+     * facility</a>.
+     * <p>
+     * This can be used to require that KeyStore entries be stored encrypted.
+     * <p>
+     * Example:
+     *
+     * <pre class="prettyprint">
+     * AndroidKeyStoreParameter params =
+     *         new AndroidKeyStoreParameter.Builder(mContext).setEncryptionRequired().build();
+     * </pre>
+     */
+    public final static class Builder {
+        private int mFlags;
+
+        /**
+         * Creates a new instance of the {@code Builder} with the given
+         * {@code context}. The {@code context} passed in may be used to pop up
+         * some UI to ask the user to unlock or initialize the Android KeyStore
+         * facility.
+         */
+        public Builder(Context context) {
+            if (context == null) {
+                throw new NullPointerException("context == null");
+            }
+
+            // Context is currently not used, but will be in the future.
+        }
+
+        /**
+         * Indicates that this key must be encrypted at rest on storage. Note
+         * that enabling this will require that the user enable a strong lock
+         * screen (e.g., PIN, password) before creating or using the generated
+         * key is successful.
+         */
+        public Builder setEncryptionRequired() {
+            mFlags |= KeyStore.FLAG_ENCRYPTED;
+            return this;
+        }
+
+        /**
+         * Builds the instance of the {@code AndroidKeyPairGeneratorSpec}.
+         *
+         * @throws IllegalArgumentException if a required field is missing
+         * @return built instance of {@code AndroidKeyPairGeneratorSpec}
+         */
+        public AndroidKeyStoreParameter build() {
+            return new AndroidKeyStoreParameter(mFlags);
+        }
+    }
+}

keystore/java/android/security/AndroidKeyStoreProvider.java

         put("KeyStore." + AndroidKeyStore.NAME, AndroidKeyStore.class.getName());
 
         // java.security.KeyPairGenerator
-        put("KeyPairGenerator." + AndroidKeyPairGenerator.NAME,
-                AndroidKeyPairGenerator.class.getName());
+        put("KeyPairGenerator." + AndroidKeyStore.NAME, AndroidKeyPairGenerator.class.getName());
     }
 }

keystore/java/android/security/KeyChain.java

 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.LinkedBlockingQueue;
 
-import org.apache.harmony.xnet.provider.jsse.OpenSSLEngine;
-import org.apache.harmony.xnet.provider.jsse.TrustedCertificateStore;
+import com.android.org.conscrypt.OpenSSLEngine;
+import com.android.org.conscrypt.TrustedCertificateStore;
 
 /**
  * The {@code KeyChain} class provides access to private keys and

keystore/java/android/security/KeyStore.java

     public static final int UNDEFINED_ACTION = 9;
     public static final int WRONG_PASSWORD = 10;
 
+    // Used for UID field to indicate the calling UID.
+    public static final int UID_SELF = -1;
+
+    // Flags for "put" "import" and "generate"
+    public static final int FLAG_NONE = 0;
+    public static final int FLAG_ENCRYPTED = 1;
+
     // States
     public enum State { UNLOCKED, LOCKED, UNINITIALIZED };
 
         }
     }
 
-    public boolean put(String key, byte[] value, int uid) {
+    public boolean put(String key, byte[] value, int uid, int flags) {
         try {
-            return mBinder.insert(key, value, uid) == NO_ERROR;
+            return mBinder.insert(key, value, uid, flags) == NO_ERROR;
         } catch (RemoteException e) {
             Log.w(TAG, "Cannot connect to keystore", e);
             return false;
         }
     }
 
+    public boolean put(String key, byte[] value, int uid) {
+        return put(key, value, uid, FLAG_ENCRYPTED);
+    }
+
     public boolean put(String key, byte[] value) {
-        return put(key, value, -1);
+        return put(key, value, UID_SELF);
     }
 
     public boolean delete(String key, int uid) {
     }
 
     public boolean delete(String key) {
-        return delete(key, -1);
+        return delete(key, UID_SELF);
     }
 
     public boolean contains(String key, int uid) {
     }
 
     public boolean contains(String key) {
-        return contains(key, -1);
+        return contains(key, UID_SELF);
     }
 
     public String[] saw(String prefix, int uid) {
     }
 
     public String[] saw(String prefix) {
-        return saw(prefix, -1);
+        return saw(prefix, UID_SELF);
     }
 
     public boolean reset() {
         }
     }
 
-    public boolean generate(String key, int uid) {
+    public boolean generate(String key, int uid, int flags) {
         try {
-            return mBinder.generate(key, uid) == NO_ERROR;
+            return mBinder.generate(key, uid, flags) == NO_ERROR;
         } catch (RemoteException e) {
             Log.w(TAG, "Cannot connect to keystore", e);
             return false;
         }
     }
 
+    public boolean generate(String key, int uid) {
+        return generate(key, uid, FLAG_ENCRYPTED);
+    }
+
     public boolean generate(String key) {
-        return generate(key, -1);
+        return generate(key, UID_SELF);
     }
 
-    public boolean importKey(String keyName, byte[] key, int uid) {
+    public boolean importKey(String keyName, byte[] key, int uid, int flags) {
         try {
-            return mBinder.import_key(keyName, key, uid) == NO_ERROR;
+            return mBinder.import_key(keyName, key, uid, flags) == NO_ERROR;
         } catch (RemoteException e) {
             Log.w(TAG, "Cannot connect to keystore", e);
             return false;
         }
     }
 
+    public boolean importKey(String keyName, byte[] key, int uid) {
+        return importKey(keyName, key, uid, FLAG_ENCRYPTED);
+    }
+
     public boolean importKey(String keyName, byte[] key) {
-        return importKey(keyName, key, -1);
+        return importKey(keyName, key, UID_SELF);
     }
 
     public byte[] getPubkey(String key) {
     }
 
     public boolean delKey(String key) {
-        return delKey(key, -1);
+        return delKey(key, UID_SELF);
     }
 
     public byte[] sign(String key, byte[] data) {

keystore/tests/Android.mk

 LOCAL_MODULE_TAGS := tests
 LOCAL_CERTIFICATE := platform
 
-LOCAL_JAVA_LIBRARIES := android.test.runner bouncycastle
+LOCAL_JAVA_LIBRARIES := android.test.runner bouncycastle conscrypt
 
 # Include all test java files.
 LOCAL_SRC_FILES := $(call all-java-files-under, src)

keystore/tests/src/android/security/AndroidKeyPairGeneratorSpecTest.java

     private static final Date NOW_PLUS_10_YEARS = new Date(NOW.getYear() + 10, 0, 1);
 
     public void testConstructor_Success() throws Exception {
-        AndroidKeyPairGeneratorSpec spec = new AndroidKeyPairGeneratorSpec(getContext(),
-                TEST_ALIAS_1, TEST_DN_1, SERIAL_1, NOW, NOW_PLUS_10_YEARS);
+        AndroidKeyPairGeneratorSpec spec =
+                new AndroidKeyPairGeneratorSpec(getContext(), TEST_ALIAS_1, TEST_DN_1, SERIAL_1,
+                        NOW, NOW_PLUS_10_YEARS, 0);
 
         assertEquals("Context should be the one specified", getContext(), spec.getContext());
 
                 .setSerialNumber(SERIAL_1)
                 .setStartDate(NOW)
                 .setEndDate(NOW_PLUS_10_YEARS)
+                .setEncryptionRequired()
                 .build();
 
         assertEquals("Context should be the one specified", getContext(), spec.getContext());
         assertEquals("startDate should be the one specified", NOW, spec.getStartDate());
 
         assertEquals("endDate should be the one specified", NOW_PLUS_10_YEARS, spec.getEndDate());
+
+        assertEquals("encryption flag should be on", KeyStore.FLAG_ENCRYPTED, spec.getFlags());
     }
 
     public void testConstructor_NullContext_Failure() throws Exception {
         try {
             new AndroidKeyPairGeneratorSpec(null, TEST_ALIAS_1, TEST_DN_1, SERIAL_1, NOW,
-                    NOW_PLUS_10_YEARS);
+                    NOW_PLUS_10_YEARS, 0);
             fail("Should throw IllegalArgumentException when context is null");
         } catch (IllegalArgumentException success) {
         }
     public void testConstructor_NullKeystoreAlias_Failure() throws Exception {
         try {
             new AndroidKeyPairGeneratorSpec(getContext(), null, TEST_DN_1, SERIAL_1, NOW,
-                    NOW_PLUS_10_YEARS);
+                    NOW_PLUS_10_YEARS, 0);
             fail("Should throw IllegalArgumentException when keystoreAlias is null");
         } catch (IllegalArgumentException success) {
         }
     public void testConstructor_NullSubjectDN_Failure() throws Exception {
         try {
             new AndroidKeyPairGeneratorSpec(getContext(), TEST_ALIAS_1, null, SERIAL_1, NOW,
-                    NOW_PLUS_10_YEARS);
+                    NOW_PLUS_10_YEARS, 0);
             fail("Should throw IllegalArgumentException when subjectDN is null");
         } catch (IllegalArgumentException success) {
         }
     public void testConstructor_NullSerial_Failure() throws Exception {
         try {
             new AndroidKeyPairGeneratorSpec(getContext(), TEST_ALIAS_1, TEST_DN_1, null, NOW,
-                    NOW_PLUS_10_YEARS);
+                    NOW_PLUS_10_YEARS, 0);
             fail("Should throw IllegalArgumentException when startDate is null");
         } catch (IllegalArgumentException success) {
         }
     public void testConstructor_NullStartDate_Failure() throws Exception {
         try {
             new AndroidKeyPairGeneratorSpec(getContext(), TEST_ALIAS_1, TEST_DN_1, SERIAL_1, null,
-                    NOW_PLUS_10_YEARS);
+                    NOW_PLUS_10_YEARS, 0);
             fail("Should throw IllegalArgumentException when startDate is null");
         } catch (IllegalArgumentException success) {
         }
     public void testConstructor_NullEndDate_Failure() throws Exception {
         try {
             new AndroidKeyPairGeneratorSpec(getContext(), TEST_ALIAS_1, TEST_DN_1, SERIAL_1, NOW,
-                    null);
+                    null, 0);
             fail("Should throw IllegalArgumentException when keystoreAlias is null");
         } catch (IllegalArgumentException success) {
         }
     public void testConstructor_EndBeforeStart_Failure() throws Exception {
         try {
             new AndroidKeyPairGeneratorSpec(getContext(), TEST_ALIAS_1, TEST_DN_1, SERIAL_1,
-                    NOW_PLUS_10_YEARS, NOW);
+                    NOW_PLUS_10_YEARS, NOW, 0);
             fail("Should throw IllegalArgumentException when end is before start");
         } catch (IllegalArgumentException success) {
         }

keystore/tests/src/android/security/AndroidKeyPairGeneratorTest.java

 import java.security.cert.Certificate;
 import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
+import java.text.SimpleDateFormat;
 import java.util.Date;
 
 import javax.security.auth.x500.X500Principal;
 
         assertFalse(mAndroidKeyStore.isUnlocked());
 
+        mGenerator = java.security.KeyPairGenerator.getInstance("AndroidKeyStore");
+    }
+
+    private void setupPassword() {
         assertTrue(mAndroidKeyStore.password("1111"));
         assertTrue(mAndroidKeyStore.isUnlocked());
 
         String[] aliases = mAndroidKeyStore.saw("");
         assertNotNull(aliases);
         assertEquals(0, aliases.length);
-
-        mGenerator = java.security.KeyPairGenerator.getInstance(AndroidKeyPairGenerator.NAME);
     }
 
-    public void testKeyPairGenerator_Initialize_Params_Success() throws Exception {
-        mGenerator.initialize(new AndroidKeyPairGeneratorSpec(getContext(), TEST_ALIAS_1,
-                TEST_DN_1, TEST_SERIAL_1, NOW, NOW_PLUS_10_YEARS));
+    public void testKeyPairGenerator_Initialize_Params_Encrypted_Success() throws Exception {
+        setupPassword();
+
+        mGenerator.initialize(new AndroidKeyPairGeneratorSpec.Builder(getContext())
+                .setAlias(TEST_ALIAS_1)
+                .setSubject(TEST_DN_1)
+                .setSerialNumber(TEST_SERIAL_1)
+                .setStartDate(NOW)
+                .setEndDate(NOW_PLUS_10_YEARS)
+                .setEncryptionRequired()
+                .build());
     }
 
-    public void testKeyPairGenerator_Initialize_KeySize_Failure() throws Exception {
+    public void testKeyPairGenerator_Initialize_KeySize_Encrypted_Failure() throws Exception {
+        setupPassword();
+
         try {
             mGenerator.initialize(1024);
             fail("KeyPairGenerator should not support setting the key size");
         }
     }
 
-    public void testKeyPairGenerator_Initialize_KeySizeAndSecureRandom_Failure() throws Exception {
+    public void testKeyPairGenerator_Initialize_KeySizeAndSecureRandom_Encrypted_Failure()
+            throws Exception {
+        setupPassword();
+
         try {
             mGenerator.initialize(1024, new SecureRandom());
             fail("KeyPairGenerator should not support setting the key size");
         }
     }
 
-    public void testKeyPairGenerator_Initialize_ParamsAndSecureRandom_Failure() throws Exception {
-        mGenerator.initialize(new AndroidKeyPairGeneratorSpec(getContext(), TEST_ALIAS_1,
-                TEST_DN_1, TEST_SERIAL_1, NOW, NOW_PLUS_10_YEARS), new SecureRandom());
+    public void testKeyPairGenerator_Initialize_ParamsAndSecureRandom_Encrypted_Failure()
+            throws Exception {
+        setupPassword();
+
+        mGenerator.initialize(
+                new AndroidKeyPairGeneratorSpec.Builder(getContext())
+                        .setAlias(TEST_ALIAS_1)
+                        .setSubject(TEST_DN_1)
+                        .setSerialNumber(TEST_SERIAL_1)
+                        .setStartDate(NOW)
+                        .setEndDate(NOW_PLUS_10_YEARS)
+                        .setEncryptionRequired()
+                        .build(),
+                new SecureRandom());
     }
 
-    public void testKeyPairGenerator_GenerateKeyPair_Success() throws Exception {
-        mGenerator.initialize(new AndroidKeyPairGeneratorSpec(getContext(), TEST_ALIAS_1,
-                TEST_DN_1, TEST_SERIAL_1, NOW, NOW_PLUS_10_YEARS));
+    public void testKeyPairGenerator_GenerateKeyPair_Encrypted_Success() throws Exception {
+        setupPassword();
+
+        mGenerator.initialize(new AndroidKeyPairGeneratorSpec.Builder(getContext())
+                .setAlias(TEST_ALIAS_1)
+                .setSubject(TEST_DN_1)
+                .setSerialNumber(TEST_SERIAL_1)
+                .setStartDate(NOW)
+                .setEndDate(NOW_PLUS_10_YEARS)
+                .setEncryptionRequired()
+                .build());
+
+        final KeyPair pair = mGenerator.generateKeyPair();
+        assertNotNull("The KeyPair returned should not be null", pair);
+
+        assertKeyPairCorrect(pair, TEST_ALIAS_1, TEST_DN_1, TEST_SERIAL_1, NOW, NOW_PLUS_10_YEARS);
+    }
+
+    public void testKeyPairGenerator_GenerateKeyPair_Unencrypted_Success() throws Exception {
+        mGenerator.initialize(new AndroidKeyPairGeneratorSpec.Builder(getContext())
+                .setAlias(TEST_ALIAS_1)
+                .setSubject(TEST_DN_1)
+                .setSerialNumber(TEST_SERIAL_1)
+                .setStartDate(NOW)
+                .setEndDate(NOW_PLUS_10_YEARS)
+                .build());
 
         final KeyPair pair = mGenerator.generateKeyPair();
         assertNotNull("The KeyPair returned should not be null", pair);
     public void testKeyPairGenerator_GenerateKeyPair_Replaced_Success() throws Exception {
         // Generate the first key
         {
-            mGenerator.initialize(new AndroidKeyPairGeneratorSpec(getContext(), TEST_ALIAS_1,
-                    TEST_DN_1, TEST_SERIAL_1, NOW, NOW_PLUS_10_YEARS));
+            mGenerator.initialize(new AndroidKeyPairGeneratorSpec.Builder(getContext())
+                    .setAlias(TEST_ALIAS_1)
+                    .setSubject(TEST_DN_1)
+                    .setSerialNumber(TEST_SERIAL_1)
+                    .setStartDate(NOW)
+                    .setEndDate(NOW_PLUS_10_YEARS)
+                    .build());
             final KeyPair pair1 = mGenerator.generateKeyPair();
             assertNotNull("The KeyPair returned should not be null", pair1);
             assertKeyPairCorrect(pair1, TEST_ALIAS_1, TEST_DN_1, TEST_SERIAL_1, NOW,
 
         // Replace the original key
         {
-            mGenerator.initialize(new AndroidKeyPairGeneratorSpec(getContext(), TEST_ALIAS_2,
-                    TEST_DN_2, TEST_SERIAL_2, NOW, NOW_PLUS_10_YEARS));
+            mGenerator.initialize(new AndroidKeyPairGeneratorSpec.Builder(getContext())
+                    .setAlias(TEST_ALIAS_2)
+                    .setSubject(TEST_DN_2)
+                    .setSerialNumber(TEST_SERIAL_2)
+                    .setStartDate(NOW)
+                    .setEndDate(NOW_PLUS_10_YEARS)
+                    .build());
             final KeyPair pair2 = mGenerator.generateKeyPair();
             assertNotNull("The KeyPair returned should not be null", pair2);
             assertKeyPairCorrect(pair2, TEST_ALIAS_2, TEST_DN_2, TEST_SERIAL_2, NOW,
         }
     }
 
+    public void testKeyPairGenerator_GenerateKeyPair_Replaced_UnencryptedToEncrypted_Success()
+            throws Exception {
+        // Generate the first key
+        {
+            mGenerator.initialize(new AndroidKeyPairGeneratorSpec.Builder(getContext())
+                    .setAlias(TEST_ALIAS_1)
+                    .setSubject(TEST_DN_1)
+                    .setSerialNumber(TEST_SERIAL_1)
+                    .setStartDate(NOW)
+                    .setEndDate(NOW_PLUS_10_YEARS)
+                    .build());
+            final KeyPair pair1 = mGenerator.generateKeyPair();
+            assertNotNull("The KeyPair returned should not be null", pair1);
+            assertKeyPairCorrect(pair1, TEST_ALIAS_1, TEST_DN_1, TEST_SERIAL_1, NOW,
+                    NOW_PLUS_10_YEARS);
+        }
+
+        // Attempt to replace previous key
+        {
+            mGenerator.initialize(new AndroidKeyPairGeneratorSpec.Builder(getContext())
+                    .setAlias(TEST_ALIAS_1)
+                    .setSubject(TEST_DN_2)
+                    .setSerialNumber(TEST_SERIAL_2)
+                    .setStartDate(NOW)
+                    .setEndDate(NOW_PLUS_10_YEARS)
+                    .setEncryptionRequired()
+                    .build());
+            try {
+                mGenerator.generateKeyPair();
+                fail("Should not be able to generate encrypted key while not initialized");
+            } catch (IllegalStateException expected) {
+            }
+
+            assertTrue(mAndroidKeyStore.password("1111"));
+            assertTrue(mAndroidKeyStore.isUnlocked());
+
+            final KeyPair pair2 = mGenerator.generateKeyPair();
+            assertNotNull("The KeyPair returned should not be null", pair2);
+            assertKeyPairCorrect(pair2, TEST_ALIAS_1, TEST_DN_2, TEST_SERIAL_2, NOW,
+                    NOW_PLUS_10_YEARS);
+        }
+    }
+
     private void assertKeyPairCorrect(KeyPair pair, String alias, X500Principal dn,
             BigInteger serial, Date start, Date end) throws Exception {
         final PublicKey pubKey = pair.getPublic();
         assertEquals("The Serial should be the one passed into the params", serial,
                 x509userCert.getSerialNumber());
 
-        assertEquals("The notBefore date should be the one passed into the params", start,
+        assertDateEquals("The notBefore date should be the one passed into the params", start,
                 x509userCert.getNotBefore());
 
-        assertEquals("The notAfter date should be the one passed into the params", end,
+        assertDateEquals("The notAfter date should be the one passed into the params", end,
                 x509userCert.getNotAfter());
 
         x509userCert.verify(pubKey);
         assertNotNull("The keystore should return the public key for the generated key",
                 pubKeyBytes);
     }
+
+    private static void assertDateEquals(String message, Date date1, Date date2) throws Exception {
+        SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
+
+        String result1 = formatter.format(date1);
+        String result2 = formatter.format(date2);
+
+        assertEquals(message, result1, result2);
+    }
 }

keystore/tests/src/android/security/AndroidKeyStoreTest.java

 
 import com.android.org.bouncycastle.x509.X509V3CertificateGenerator;
 
-import org.apache.harmony.xnet.provider.jsse.OpenSSLEngine;
+import com.android.org.conscrypt.OpenSSLEngine;
 
 import android.test.AndroidTestCase;
 
         assertTrue(mAndroidKeyStore.reset());
         assertFalse(mAndroidKeyStore.isUnlocked());
 
+        mKeyStore = java.security.KeyStore.getInstance("AndroidKeyStore");
+    }
+
+    private void setupPassword() {
         assertTrue(mAndroidKeyStore.password("1111"));
         assertTrue(mAndroidKeyStore.isUnlocked());
 
         assertEquals(0, mAndroidKeyStore.saw("").length);
-
-        mKeyStore = java.security.KeyStore.getInstance(AndroidKeyStore.NAME);
     }
 
     private void assertAliases(final String[] expectedAliases) throws KeyStoreException {
                 expectedAliases.length, count);
     }
 
-    public void testKeyStore_Aliases_Success() throws Exception {
+    public void testKeyStore_Aliases_Encrypted_Success() throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         assertAliases(new String[] {});
         assertAliases(new String[] { TEST_ALIAS_1, TEST_ALIAS_2 });
     }
 
-    public void testKeyStore_Aliases_NotInitialized_Failure() throws Exception {
+    public void testKeyStore_Aliases_NotInitialized_Encrypted_Failure() throws Exception {
+        setupPassword();
+
         try {
             mKeyStore.aliases();
             fail("KeyStore should throw exception when not initialized");
         }
     }
 
-    public void testKeyStore_ContainsAliases_PrivateAndCA_Success() throws Exception {
+    public void testKeyStore_ContainsAliases_PrivateAndCA_Encrypted_Success() throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         assertAliases(new String[] {});
                 mKeyStore.containsAlias(TEST_ALIAS_3));
     }
 
-    public void testKeyStore_ContainsAliases_CAOnly_Success() throws Exception {
+    public void testKeyStore_ContainsAliases_CAOnly_Encrypted_Success() throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         assertTrue(mAndroidKeyStore.put(Credentials.CA_CERTIFICATE + TEST_ALIAS_2, FAKE_CA_1));
         assertTrue("Should contain added CA certificate", mKeyStore.containsAlias(TEST_ALIAS_2));
     }
 
-    public void testKeyStore_ContainsAliases_NonExistent_Failure() throws Exception {
+    public void testKeyStore_ContainsAliases_NonExistent_Encrypted_Failure() throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         assertFalse("Should contain added CA certificate", mKeyStore.containsAlias(TEST_ALIAS_1));
     }
 
-    public void testKeyStore_DeleteEntry_Success() throws Exception {
+    public void testKeyStore_DeleteEntry_Encrypted_Success() throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         // TEST_ALIAS_1
         assertAliases(new String[] { });
     }
 
-    public void testKeyStore_DeleteEntry_EmptyStore_Success() throws Exception {
+    public void testKeyStore_DeleteEntry_EmptyStore_Encrypted_Success() throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         // Should not throw when a non-existent entry is requested for delete.
         mKeyStore.deleteEntry(TEST_ALIAS_1);
     }
 
-    public void testKeyStore_DeleteEntry_NonExistent_Success() throws Exception {
+    public void testKeyStore_DeleteEntry_NonExistent_Encrypted_Success() throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         // TEST_ALIAS_1
         mKeyStore.deleteEntry(TEST_ALIAS_2);
     }
 
-    public void testKeyStore_GetCertificate_Single_Success() throws Exception {
+    public void testKeyStore_GetCertificate_Single_Encrypted_Success() throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         assertTrue(mAndroidKeyStore.put(Credentials.CA_CERTIFICATE + TEST_ALIAS_1, FAKE_CA_1));
         assertEquals("Actual and retrieved certificates should be the same", actual, retrieved);
     }
 
-    public void testKeyStore_GetCertificate_NonExist_Failure() throws Exception {
+    public void testKeyStore_GetCertificate_NonExist_Encrypted_Failure() throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         assertNull("Certificate should not exist in keystore",
                 mKeyStore.getCertificate(TEST_ALIAS_1));
     }
 
-    public void testKeyStore_GetCertificateAlias_CAEntry_Success() throws Exception {
+    public void testKeyStore_GetCertificateAlias_CAEntry_Encrypted_Success() throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         assertTrue(mAndroidKeyStore.put(Credentials.CA_CERTIFICATE + TEST_ALIAS_1, FAKE_CA_1));
                 mKeyStore.getCertificateAlias(actual));
     }
 
-    public void testKeyStore_GetCertificateAlias_PrivateKeyEntry_Success() throws Exception {
+    public void testKeyStore_GetCertificateAlias_PrivateKeyEntry_Encrypted_Success()
+            throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         assertTrue(mAndroidKeyStore.importKey(Credentials.USER_PRIVATE_KEY + TEST_ALIAS_1,
                 mKeyStore.getCertificateAlias(actual));
     }
 
-    public void testKeyStore_GetCertificateAlias_CAEntry_WithPrivateKeyUsingCA_Success()
+    public void testKeyStore_GetCertificateAlias_CAEntry_WithPrivateKeyUsingCA_Encrypted_Success()
             throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         // Insert TrustedCertificateEntry with CA name
                 mKeyStore.getCertificateAlias(actual));
     }
 
-    public void testKeyStore_GetCertificateAlias_NonExist_Empty_Failure() throws Exception {
+    public void testKeyStore_GetCertificateAlias_NonExist_Empty_Encrypted_Failure()
+            throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         CertificateFactory f = CertificateFactory.getInstance("X.509");
                 mKeyStore.getCertificateAlias(actual));
     }
 
-    public void testKeyStore_GetCertificateAlias_NonExist_Failure() throws Exception {
+    public void testKeyStore_GetCertificateAlias_NonExist_Encrypted_Failure() throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         assertTrue(mAndroidKeyStore.put(Credentials.CA_CERTIFICATE + TEST_ALIAS_1, FAKE_CA_1));
                 mKeyStore.getCertificateAlias(userCert));
     }
 
-    public void testKeyStore_GetCertificateChain_SingleLength_Success() throws Exception {
+    public void testKeyStore_GetCertificateChain_SingleLength_Encrypted_Success() throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         assertTrue(mAndroidKeyStore.importKey(Credentials.USER_PRIVATE_KEY + TEST_ALIAS_1,
                 mKeyStore.getCertificateChain(TEST_ALIAS_2));
     }
 
-    public void testKeyStore_GetCertificateChain_NonExist_Failure() throws Exception {
+    public void testKeyStore_GetCertificateChain_NonExist_Encrypted_Failure() throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         assertNull("Stored certificate alias should not be found",
                 mKeyStore.getCertificateChain(TEST_ALIAS_1));
     }
 
-    public void testKeyStore_GetCreationDate_PrivateKeyEntry_Success() throws Exception {
+    public void testKeyStore_GetCreationDate_PrivateKeyEntry_Encrypted_Success() throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         assertTrue(mAndroidKeyStore.importKey(Credentials.USER_PRIVATE_KEY + TEST_ALIAS_1,
         assertTrue("Time should be close to current time", actual.after(expectedAfter));
     }
 
-    public void testKeyStore_GetCreationDate_CAEntry_Success() throws Exception {
+    public void testKeyStore_GetCreationDate_PrivateKeyEntry_Unencrypted_Success() throws Exception {
+        mKeyStore.load(null, null);
+
+        assertTrue(mAndroidKeyStore.importKey(Credentials.USER_PRIVATE_KEY + TEST_ALIAS_1,
+                FAKE_KEY_1, KeyStore.UID_SELF, KeyStore.FLAG_NONE));
+        assertTrue(mAndroidKeyStore.put(Credentials.USER_CERTIFICATE + TEST_ALIAS_1, FAKE_USER_1,
+                KeyStore.UID_SELF, KeyStore.FLAG_NONE));
+        assertTrue(mAndroidKeyStore.put(Credentials.CA_CERTIFICATE + TEST_ALIAS_1, FAKE_CA_1,
+                KeyStore.UID_SELF, KeyStore.FLAG_NONE));
+
+        Date now = new Date();
+        Date actual = mKeyStore.getCreationDate(TEST_ALIAS_1);
+
+        Date expectedAfter = new Date(now.getTime() - SLOP_TIME_MILLIS);
+        Date expectedBefore = new Date(now.getTime() + SLOP_TIME_MILLIS);
+
+        assertTrue("Time should be close to current time", actual.before(expectedBefore));
+        assertTrue("Time should be close to current time", actual.after(expectedAfter));
+    }
+
+    public void testKeyStore_GetCreationDate_CAEntry_Encrypted_Success() throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         assertTrue(mAndroidKeyStore.put(Credentials.CA_CERTIFICATE + TEST_ALIAS_1, FAKE_CA_1));
         assertTrue("Time should be close to current time", actual.after(expectedAfter));
     }
 
-    public void testKeyStore_GetEntry_NullParams_Success() throws Exception {
+    public void testKeyStore_GetEntry_NullParams_Encrypted_Success() throws Exception {
+        setupPassword();
+
         mKeyStore.load(null, null);
 
         assertTrue(mAndroidKeyStore.importKey(Credentials.USER_PRIVATE_KEY + TEST_ALIAS_1,
         assertPrivateKeyEntryEquals(keyEntry, FAKE_KEY_1, FAKE_USER_1, FAKE_CA_1);
     }
 
+    public void testKeyStore_GetEntry_NullParams_Unencrypted_Success() throws Exception {
+        mKeyStore.load(null, null);
+
+        assertTrue(mAndroidKeyStore.importKey(Credentials.USER_PRIVATE_KEY + TEST_ALIAS_1,
+                FAKE_KEY_1, KeyStore.UID_SELF, KeyStore.FLAG_NONE));
+        assertTrue(mAndroidKeyStore.put(Credentials.USER_CERTIFICATE + TEST_ALIAS_1, FAKE_USER_1,
+                KeyStore.UID_SELF, KeyStore.FLAG_NONE));
+        assertTrue(mAndroidKeyStore.put(Credentials.CA_CERTIFICATE + TEST_ALIAS_1, FAKE_CA_1,
+                KeyStore.UID_SELF, KeyStore.FLAG_NONE));
+
+        Entry entry = mKeyStore.getEntry(TEST_ALIAS_1, null);
+        assertNotNull("Entry should exist", entry);
+
+        assertTrue("Should be a PrivateKeyEntry", entry instanceof PrivateKeyEntry);
+
+        PrivateKeyEntry keyEntry = (PrivateKeyEntry) entry;
+
+        assertPrivateKeyEntryEquals(keyEntry, FAKE_KEY_1, FAKE_USER_1, FAKE_CA_1);
+    }
+
     @SuppressWarnings("unchecked")
     private void assertPrivateKeyEntryEquals(PrivateKeyEntry keyEntry, byte[] key, byte[] cert,
             byte[] ca) throws Exception {