title: How Can I Use the Android KeyStore to securely store arbitrary strings?
body: <p>I would like to be able securely store some sensitive strings in the Android KeyStore. I get the strings from the server but I have a use case which requires me to persist them. KeyStore will only allow access from the same UID as that assigned to my app, and it will encrypt the data with the device master password, so it's my understanding that I don't have to do any additional encryption to protect my data. My trouble is, I'm missing something about how to write the data. The code I have below works perfectly, as long as the call to KeyStore.store(null) is omitted. That code fails, and as long as I can't store the data after putting it to the KeyStore, then I can't persist it.</p>
  
  <p>I think I'm missing something about the KeyStore API, but I don't know what. Any help appreciated!</p>
  
  <pre><code>String metaKey = "ourSecretKey";
  String encodedKey = "this is supposed to be a secret";
  byte[] encodedKeyBytes = new byte[(int)encodedKey.length()];
  encodedKeyBytes = encodedKey.getBytes("UTF-8");
  KeyStoreParameter ksp = null;
  
  //String algorithm = "DES";
  String algorithm = "DESede";
  SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
  SecretKeySpec secretKeySpec = new SecretKeySpec(encodedKeyBytes, algorithm);
  SecretKey secretKey = secretKeyFactory.generateSecret(secretKeySpec);
  
  KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
  
  keyStore.load(null);
  
  KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(secretKey);
  keyStore.setEntry(metaKey, secretKeyEntry, ksp);
  
  keyStore.store(null);
  
  String recoveredSecret = "";
  if (keyStore.containsAlias(metaKey)) {
      KeyStore.SecretKeyEntry recoveredEntry = (KeyStore.SecretKeyEntry)keyStore.getEntry(metaKey, ksp);
      byte[] bytes = recoveredEntry.getSecretKey().getEncoded();
      for (byte b : bytes) {
          recoveredSecret += (char)b;
       }
  }
  Log.v(TAG, "recovered " + recoveredSecret);
  </code></pre>