title: Keys lost from BKS file without deleteKey command
body: <p>I use a keystore (BKS format) in my android app to store public private keypairs. The app was used over a long time and had 10+ public private key pairs. All of a sudden, one of the app's major functionality stopped working. Root cause was found out to be the following:</p>
  
  <p>Only one public private keypair is remaining in the BKS file. All other keypairs are lost. I verified in the code that 
  KeyStore.deleteEntry(alias) is not called anywhere in the app. The only place where I could find if something would have gone wrong is  following:</p>
  
  <p>We create a keypair and set it using: </p>
  
  <pre><code>KeyStore.setKeyEntry(keyId, keyPair.getPrivate(), getKeyStorePassword(), certChain);
  </code></pre>
  
  <p>The javadoc of above method states the following:
  If the given alias already exists, the keystore information associated with it is overridden by the given key (and possibly certificate chain).</p>
  
  <p>Normally, a string obtained from server which is a UUID is used as alias to set a new KeyPair in KeyStore. So, the possibility of new alias being same as one which is already present in keystore is very unlikely. Even if that's the case, it would have just overridden one key pair. But, in this case, around 10+ key pairs are lost.</p>
  
  <p>Does anyone know of any known issues which result in this kind of key-pair loss?</p>
  
  <p><strong>Additional info:</strong></p>
  
  <ol>
  <li><p>I found that the certificate associated with public key for every key pair is valid only for 1 year. I thought the key pairs for which certificate is expired may be deleted when a new key pair is being set in the keystore. But, when I executed the test case by changing the validity as 30 days, and changing the device time ahead by more than 30 days, the issue could not be reproduced. </p></li>
  <li><p>One more thing which I am not sure if it is relevant for this issue is: Currently the serial number for the all the certificates being generated is BigInteger.ONE:</p>
  
  <p>X509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder(
                  subject, BigInteger.ONE, notBefore, notAfter, subject,
                  keyPair.getPublic());</p></li>
  </ol>
  
  <p>I think this is wrong, but, I am not sure if this may lead to the issue which I have.</p>
  
  <ol start="3">
  <li><p>Following is the list of security providers (<code>Security.getProviders()</code>) in the device in which this issue was seen:</p>
  
  <ul>
  <li>AndroidKeyStoreBCWorkaround version 1.0 </li>
  <li>AndroidOpenSSL version 1.0 </li>
  <li>BC version 1.52 </li>
  <li>Crypto version 1.0 </li>
  <li>HarmonyJSSE version 1.0</li>
  <li>AndroidKeyStore version 1.0</li>
  </ul></li>
  </ol>
  
  <p>So, all Java crypto operations are done using AndroidKeyStoreBCWorkaround version 1.0. The device is Nexus 5, Android 6.0.1.</p>