title: AndroidKeyStore KeyStoreException: Uninitialized keystore
body: <pre><code>java.security.KeyStoreException: Uninitialized keystore
      at java.security.KeyStore.entryInstanceOf(KeyStore.java:1690)
      at com.my.package.MyKeyManager.getSecretKey(MyKeyManager.java:137)
  </code></pre>
  <p>Why am I getting the above uninitialized keystore exception when executing the following code (Samsung S9 running Android 9):</p>
  <pre><code>import java.security.KeyStore;
  
  ...
  
  SecretKey getSecretKey(String alias) {
      mKeyStore = KeyStore.getInstance(&quot;AndroidKeyStore&quot;);
      mKeyStore.load(null);
      if (mKeyStore.containsAlias(alias) 
          &amp;&amp; mKeyStore.entryInstanceOf(alias, KeyStore.SecretKeyEntry.class)) {
      }
  }
  </code></pre>
  <p>Here's the really weird part - If you look at the Android source code for <a href="https://cs.android.com/android/platform/superproject/+/master:libcore/ojluni/src/main/java/java/security/KeyStore.java;l=1287?q=keystore.java&amp;ss=android%2Fplatform%2Fsuperproject" rel="nofollow noreferrer">containsAlias</a> which I call <em>right before</em> <a href="https://cs.android.com/android/platform/superproject/+/master:libcore/ojluni/src/main/java/java/security/KeyStore.java;l=1620" rel="nofollow noreferrer">entryInstanceOf</a>, it also has the same check for <code>!initialized</code>. Yet somehow the check in <code>containsAlias</code> passes and the check in <code>entryInstanceOf</code> fails.</p>
  <p>Also note that the exception is being thrown on line 1690 of the <code>java.security.KeyStore</code> file, but that line has never thrown that exception in the entire history of the AOSP (I checked the commit file history for that file). This leads me to believe that Samsung must be modifying this file for their flavor of Android.</p>
  <p><strong>Does anyone know what's going on here or if there is a way to view the Samsung Android java source files?</strong> I found <a href="https://opensource.samsung.com/uploadSearch?searchValue=SM-G960F" rel="nofollow noreferrer">opensource.samsung.com</a>, but none of the source downloads include any java files (only c files).</p>