title: Cannot generate key in Android keystore
body: <p>We are currently experiencing an issue where sometimes when a user installes our app, the app tries to access and generate a key in the keystore but the keystore throws this exception:</p>
  
  <pre><code>Caused by: java.lang.IllegalStateException: could not generate key in keystore
          at android.security.AndroidKeyPairGenerator.generateKeyPair(AndroidKeyPairGenerator.java:100)
          at java.security.KeyPairGenerator$KeyPairGeneratorImpl.generateKeyPair(KeyPairGenerator.java:275)
  </code></pre>
  
  <p>We think it has to do with the unlock pattern off the phone does not unlock the keystore, and/or a device administrator locks the keystore. </p>
  
  <p>This is how the keystore is created and how the keys are generated:</p>
  
  <pre><code>public SecretKeyWrapper(Context context, String alias) throws GeneralSecurityException, IOException {
      mCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
      final KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
      keyStore.load(null);
  
      if (!keyStore.containsAlias(alias)) {
          generateKeyPair(context, alias);
      }
  
      final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null);
      mPair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey());
  }
  
  private static void generateKeyPair(Context context, String alias) throws GeneralSecurityException {
      final Calendar start = new GregorianCalendar();
      final Calendar end = new GregorianCalendar();
      end.add(Calendar.YEAR, 100);
  
      final KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
              .setAlias(alias)
              .setSubject(new X500Principal("CN=" + alias))
              .setSerialNumber(BigInteger.ONE)
              .setStartDate(start.getTime())
              .setEndDate(end.getTime())
              .build();
  
      final KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
      gen.initialize(spec);
      gen.generateKeyPair();
  }
  </code></pre>
  
  <p>Does anyone know how to:</p>
  
  <ul>
  <li>Lock the keystore as an device administrator?</li>
  <li>Unlock the keystore when it has been locked by a device administrator?</li>
  <li>Or reproduce this issue in another way?</li>
  </ul>