title: Android: Store SecretKey in KeyStore
body: <p>I use a <a href="http://developer.android.com/reference/javax/crypto/SecretKey.html" rel="noreferrer">SecretKey</a> to encrypt sensitive data in my application. Currently I am storing my SecretKey in Base64 encoded format in DB or SharedPrefs which is not a safe place to store Secret on a rooted phone. Hence, I want to move my SecretKey to <a href="http://developer.android.com/training/articles/keystore.html" rel="noreferrer">Android KeyStore</a>. The problem I am facing is when I try <a href="http://developer.android.com/training/articles/keystore.html#UsingAndroidKeyStore" rel="noreferrer">this sample code</a> from Google, it expects a PrivateKey instead of SecretKey. I couldn't figure out a way to store my SecretKey in KeyStore and fetch it for later use. I tried this:</p>
  
  <pre><code>private static void writeSecretKeyToKeystore(SecretKey secretKey, Context context) {
  KeyStore keyStore = null;
  try {
    keyStore = KeyStore.getInstance("AndroidKeyStore");
    keyStore.load(null);
    KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(secretKey);
    keyStore.setKeyEntry("Key", secretKeyEntry.getSecretKey().getEncoded(), null);
  } catch (KeyStoreException e) {
    e.printStackTrace();
  } catch (CertificateException e) {
    e.printStackTrace();
  } catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
  </code></pre>
  
  <p>When I try above code, it throws an exception <code>Operation not supported because encoding is unknown</code>.</p>
  
  <p>Any sample code would be of great help.</p>