Encrypting your data


SDK Version: 
M3

Sometimes you don't want to store any data on the sd card, but you have to, because your apps resources would take up too much space int the internal memory.
Here is a method on how to store your data securely.

Java has very easy to use built in encrypting methods, but they take up precious time.
For example a 188Kb jpg on a Nexus one would take:
Encode: 750ms
Decode 550ms
So I don't recommend using encryption on large files,

  1. public byte[] keyGen() throws NoSuchAlgorithmException {
  2.         KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
  3.         keyGenerator.init(192);
  4.         return keyGenerator.generateKey().getEncoded();
  5. }

You need to store the key in your app.
  1. public byte[] encript(byte[] dataToEncrypt, byte[] key)
  2.                 throws NoSuchAlgorithmException, NoSuchPaddingException,
  3.                 InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
  4.         //I'm using AES encription
  5.         Cipher c = Cipher.getInstance("AES");
  6.         SecretKeySpec k = new SecretKeySpec(key, "AES");
  7.         c.init(Cipher.ENCRYPT_MODE, k);
  8.         return c.doFinal(dataToEncrypt);
  9. }
  10.  
  11. public byte[] decript(byte[] encryptedData, byte[] key)
  12.                 throws NoSuchAlgorithmException, NoSuchPaddingException,
  13.                 InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
  14.         Cipher c = Cipher.getInstance("AES");
  15.         SecretKeySpec k = new SecretKeySpec(key, "AES");
  16.         c.init(Cipher.DECRYPT_MODE, k);
  17.         return c.doFinal(encryptedData);
  18. }