Android encrypt and decrypt a file


Files in your Android devices can be encrypted to prevent them from being read or viewed by unauthorized users. There are many encryption algorithms (e.g. AES, Blowfisth, DES, RC4) that can be used to encrypt the files. In this Android tip, I am going to show you how to encrypt a file and decrypt it using the AES that is a fast and secure algorithm.
To encrypt a file, first, you need to read data of the file and store it in a byte array. Then you create an instance of Cipher class using its getInstance() method with passing the name of the transformation to create a cipher for. For the AES algorithm, the name is "AES/CBC/PKCS5Padding". Then you call the init() method to Initialize this cipher instance with the specified key and algorithm parameter. The specified key is a secret key that is 128, 192, or 256 bits long. The size of the secret key demines the strength of the encryption. You can be a byte array or a SecretKey object. The preferred way to generate a secret key is using KeyGenerator. The algorithm parameter can be an algorithm parameter specification for an initialization vector created from an unpredictable 128-bit byte array using IvParameterSpec.
After the cipher instance is initialized, you call the doFinal() method to encrypt the byte data. The doFinal() method returns an encrypted array of bytes that later can be decrypted or saved to a file.

To decrypt the encrypted file, you read the file data into a FileInputStream object. Then, you create a cipher instance and initialize it as you did with the encryption. Finally, you create an instance of CipherInputStream for the FileInputStream and the cipher. It reads the data and decrypts it. The decrypted data can be written into a byte array that later can be saved on the disc.


Here is the example code to encrypt an image file called img.png. The encrypted image is saved in another file called enimg.png. The enimg.png is decrypted and saved in a file called deimg.png.



public class MainActivity extends Activity{
byte[] key, iv;
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     // Get key
     key=getKey();
     // Get IV
     iv=getIV();       
   }  
   public void encryptFile(View view){
   Bitmap bitmap=BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/img.png");
     // Write image data to ByteArrayOutputStream
     ByteArrayOutputStream baos=new ByteArrayOutputStream();
     bitmap.compress(CompressFormat.PNG, 100,baos);
     // Encrypt and save the image       
     saveFile(encrypt(key,baos.toByteArray()),"enimg.png");
   }
   public void decryptFile(View view){
   try {
   // Create FileInputStream to read from the encrypted image file
FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory()+"/enimg.png");
// Save the decrypted image
saveFile(decrypt(key, fis),"deimg.png");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}    }   
   public void saveFile(byte[] data, String outFileName){
   FileOutputStream fos=null;
   try {
   fos=new FileOutputStream(Environment.getExternalStorageDirectory()+File.separator+outFileName);
fos.write(data);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
   finally{
   try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}    }
   }   
   private byte[] encrypt(byte[] skey, byte[] data){
     SecretKeySpec skeySpec = new SecretKeySpec(skey, "AES");
     Cipher cipher;
     byte[] encrypted=null;
try {
// Get Cipher instance for AES algorithm
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// Initialize cipher
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv));
// Encrypt the image byte data
encrypted = cipher.doFinal(data);
}catch(Exception e){
e.printStackTrace();
}
     return encrypted;
   }   
   private byte[] decrypt(byte[] skey, FileInputStream fis){
   SecretKeySpec skeySpec = new SecretKeySpec(skey, "AES");
     Cipher cipher;
     byte[] decryptedData=null;
     CipherInputStream cis=null;
try {
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(iv));
// Create CipherInputStream to read and decrypt the image data
cis = new CipherInputStream(fis, cipher);
// Write encrypted image data to ByteArrayOutputStream
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] data = new byte[2048];
while ((cis.read(data)) != -1) {
buffer.write(data);
}
buffer.flush();
decryptedData=buffer.toByteArray();

}catch(Exception e){
e.printStackTrace();
}
finally{
try {
fis.close();
cis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}    
     return decryptedData;
   }  
   private static byte[] getKey(){
   KeyGenerator keyGen;
   byte[] dataKey=null;
try {
// Generate 256-bit key
keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
   SecretKey secretKey = keyGen.generateKey();
   dataKey=secretKey.getEncoded();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace(); }
   return dataKey;  
   }   
   private static byte[] getIV(){
   SecureRandom random = new SecureRandom();
   byte[] iv = random.generateSeed(16);
   return iv;
   }
}


Android-encrypt-and-decrypt-a-file

Posted by: Dara | post date: 12-17-2014 | Subject: Android Apps Development

write programming tip




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.