Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Encrypt and Decrypt a file in android using AES?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.18k
    Comment on it

    Encryption is the process of encoding plain text data(plaintext) using an encryption algorithm and generating some random and meaningless data (ciphertext) which can only be read after decryption. Decryption is the process of converting ciphertext back to plaintext.

     

    In this blog, we have a simple example showing how to encrypt and decrypt a file in android.

     

    What we are going to do in this blog:

     

    1. Generate a secret key for encrypting data.
    2. Create a file and save data using ENCRYPTION with our generated secret key to the SDCARD.
    3. With the help of the secret key DECRYPT the File and show the contents.

    1.Create a class SecurityUtil.java, where we have defined three methods generateKey(), encodeFile() and decodeFile().

    package com.realmdemo.utility;
    
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    
    /**
     * Created by anita on 10/3/17.
     */
    
    public class SecurityUtil {
        private static String algorithm = "AES";
    
        public static SecretKey generateKey() throws NoSuchAlgorithmException {
            // Generate a 256-bit key
            final int outputKeyLength = 256;
            SecureRandom secureRandom = new SecureRandom();
            // Do *not* seed secureRandom! Automatically seeded from system entropy.
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(outputKeyLength, secureRandom);
            SecretKey yourKey = keyGenerator.generateKey();
            return yourKey;
        }
        public static byte[] encodeFile(SecretKey yourKey, byte[] fileData)
                throws Exception {
            byte[] encrypted = null;
            byte[] data = yourKey.getEncoded();
            SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length,
                    algorithm);
            Cipher cipher = Cipher.getInstance(algorithm);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(
                    new byte[cipher.getBlockSize()]));
            encrypted = cipher.doFinal(fileData);
            return encrypted;
        }
    
        public static byte[] decodeFile(SecretKey yourKey, byte[] fileData)
                throws Exception {
            byte[] decrypted = null;
            Cipher cipher = Cipher.getInstance(algorithm);
            cipher.init(Cipher.DECRYPT_MODE, yourKey, new IvParameterSpec(
                    new byte[cipher.getBlockSize()]));
            decrypted = cipher.doFinal(fileData);
            return decrypted;
        }
        
    }
    

    2. Below is our activity class.

    package com.realmdemo.activity;
    
    
    import android.os.Environment;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    
    import com.realmdemo.R;
    import com.realmdemo.utility.SecurityUtil;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.security.NoSuchAlgorithmException;
    
    import javax.crypto.SecretKey;
    
    
    public class EncryptionActivity extends AppCompatActivity {
    
        private String encryptedFileName = "Encrypted_File.txt";
        static SecretKey yourKey = null;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_encryption);
            try {
                yourKey = SecurityUtil.generateKey();
            }catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            saveFile("Simple Test! of encryption and decryption");
            decodeFile();
    
            }
    
          void saveFile(String stringToSave) {
            try {
                File file = new File(Environment.getExternalStorageDirectory()
                        + File.separator, encryptedFileName);
                BufferedOutputStream bos = new BufferedOutputStream(
                        new FileOutputStream(file));
    
                byte[] filesBytes = SecurityUtil.encodeFile(yourKey, stringToSave.getBytes());
                bos.write(filesBytes);
                bos.flush();
                bos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        void decodeFile() {
    
            try {
                byte[] decodedData = SecurityUtil.decodeFile(yourKey, readFile());
                String decodedString = new String(decodedData);
                System.out.println("DECODED FILE CONTENTS : " + decodedString);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public byte[] readFile() {
            byte[] contents = null;
    
            File file = new File(Environment.getExternalStorageDirectory()
                    + File.separator, encryptedFileName);
            int size = (int) file.length();
            contents = new byte[size];
            try {
                BufferedInputStream buf = new BufferedInputStream(
                        new FileInputStream(file));
                try {
                    buf.read(contents);
                    buf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            return contents;
        }
    
    }
    

    Thanks :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: