title: How to store secretKey in KeyStore and retrieve it
body: <p>I'm currently developing an Android application but I'm expecting some issues due to storage and retrieving of a <code>SecretKey</code> into the <code>Keystore</code></p>
  <p>This is my code:
  Here I generate the <code>SecretKey</code> then save it into <code>KeyStore</code>, and use it to encrypt my data</p>
  <pre><code>try {
      KeyStore keyStore = null;
      keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
      char[] passwordKS = &quot;network&quot;.toCharArray();
  
      SecureRandom sr = SecureRandom.getInstance(&quot;SHA1PRNG&quot;);
      sr.setSeed(&quot;any data used as random seed&quot;.getBytes());
      KeyGenerator kg = KeyGenerator.getInstance(&quot;AES&quot;);
      kg.init(128, sr);
      key = kg.generateKey();
      keyToSave = key.getEncoded();
      sks = new SecretKeySpec(keyToSave, &quot;AES&quot;);
  
      try {
          keyStore.load(null, null);
          keyStore.setKeyEntry(&quot;aliasKey&quot;, key, passwordKS, null);
      } catch (Exception ex) {
      }
      FileOutputStream ksout = openFileOutput(&quot;keyStoreName&quot;, Context.MODE_PRIVATE);
      keyStore.store(ksout, passwordKS);
      ksout.close();
  } catch (Exception e) {
  }
  byte[] userLongENC = null;
  byte[] userLatENC = null;
  try {
      Cipher c = Cipher.getInstance(&quot;AES&quot;);
      c.init(Cipher.ENCRYPT_MODE, sks);
      userLatENC = c.doFinal(userLat.getBytes());
      userLongENC = c.doFinal(userLong.getBytes());
  } catch (Exception e) {
  }
  </code></pre>
  <p>In another activity, I try to get back my key from the <code>Keystore</code> and use it to decrypt my data
  Unfortunately I get this exception back:</p>
  <blockquote>
  <p>javax.crypto.IllegalBlockSizeException: last block incomplete in
  decryption</p>
  </blockquote>
  <pre><code>SecretKeySpec sks = null; // Or, equivalently SecretKey sk = null;
  SecretKey sk =null;
  try {
      KeyStore keyStore= KeyStore.getInstance(KeyStore.getDefaultType());
      char[] passwordKS=&quot;network&quot;.toCharArray();
      FileInputStream fis =null;
      try {
          fis = openFileInput(&quot;keyStoreName&quot;);
      }catch (Exception ex) {
      }
      keyStore.load(fis,passwordKS);
      //sk=(SecretKey) keyStore.getKey(&quot;aliasKey&quot;, passwordKS);
      sk=(SecretKey) keyStore.getKey(&quot;aliasKey&quot;, passwordKS);
      sks=new SecretKeySpec((keyStore.getKey(&quot;aliasKey&quot;, passwordKS)).getEncoded(), &quot;AES&quot;);
  } catch (Exception e) {
  }
  byte[] latDEC=null;
  byte[] longDEC=null;
  try {
      Cipher c = Cipher.getInstance(&quot;AES&quot;);
      c.init(Cipher.DECRYPT_MODE, sks);
      latDEC = c.doFinal(lat.getBytes());
      longDEC = c.doFinal(longit.getBytes());
  } catch (Exception e) {
  }
  </code></pre>