How to Encrypt File from Sd Card Using Aes in Android

How to encrypt file from SD card using AES in Android?

If you take user input for the password make sure to read this answer.

You should take a look at:
CipherInputStream and CipherOutputStream. They are used to encrypt and decrypt byte streams.

I have a file named cleartext. The file contains:

Hi, I'm a clear text.
How are you?
That's awesome!

Now, you have an encrypt() function:

static void encrypt() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
// Here you read the cleartext.
FileInputStream fis = new FileInputStream("data/cleartext");
// This stream write the encrypted text. This stream will be wrapped by another stream.
FileOutputStream fos = new FileOutputStream("data/encrypted");

// Length is 16 byte
// Careful when taking user input!!! https://stackoverflow.com/a/3452620/1188357
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES");
// Create cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sks);
// Wrap the output stream
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
// Write bytes
int b;
byte[] d = new byte[8];
while((b = fis.read(d)) != -1) {
cos.write(d, 0, b);
}
// Flush and close streams.
cos.flush();
cos.close();
fis.close();
}

After you execute this function, there should be a file names encrypted. The file contains the encrypted characters.

For decryption you have the decrypt function:

static void decrypt() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
FileInputStream fis = new FileInputStream("data/encrypted");

FileOutputStream fos = new FileOutputStream("data/decrypted");
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, cipher);
int b;
byte[] d = new byte[8];
while((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
fos.flush();
fos.close();
cis.close();
}

After the execution of decrypt, there should be a file named decrypted. This file contains the free text.

You write you're a "noob" but depending on the use-case of encryption you could do a lot of harm if you're not doing it the right way. Know your tools!

Usage of CipherOutputStream Oracle documentation:

SecretKeySpec skeySpec = new SecretKeySpec(y.getBytes(), "AES");

FileInputStream fis;
FileOutputStream fos;
CipherOutputStream cos;
// File you are reading from
fis = new FileInputStream("/tmp/a.txt");
// File output
fos = new FileOutputStream("/tmp/b.txt");

// Here the file is encrypted. The cipher1 has to be created.
// Key Length should be 128, 192 or 256 bit => i.e. 16 byte
SecretKeySpec skeySpec = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES");
Cipher cipher1 = Cipher.getInstance("AES");
cipher1.init(Cipher.ENCRYPT_MODE, skeySpec);
cos = new CipherOutputStream(fos, cipher1);
// Here you read from the file in fis and write to cos.
byte[] b = new byte[8];
int i = fis.read(b);
while (i != -1) {
cos.write(b, 0, i);
i = fis.read(b);
}
cos.flush();

Thus, the encryption should work. When you reverse the process, you should be able to read the decrypted bytes.

Secure a SD-CARD and access it through app

Packages used are rn-fetch-blob & simple-crypto-js

Stream-by-Stream Encryption and writing in memory:

RNFetchBlob.fs
.readStream(res.uri, "base64", 4194304, 4000)
.then(stream => {
let data = "";
stream.open();
stream.onData(chunk => {
data += chunk;
var cipherText = simpleCrypto.encrypt(chunk);
RNFetchBlob.fs
.appendFile(
RNFetchBlob.fs.dirs.DCIMDir + "/encryptfile1.dat",
cipherText,
"base64"
)
.then(data => {
console.log("file written", data); // gives buffer size use it for reading while decrypting
})
.catch(error => {
console.log("file writing error", error);
});
});
stream.onEnd(() => {
console.log(data.length);
});
});

Stream-by-Stream Decryption:

RNFetchBlob.fs
.readStream(
RNFetchBlob.fs.dirs.DCIMDir + "/encryptfile1.dat",
"base64",
5592464,
4000
)
.then(stream => {
let data = "";
stream.open();
stream.onData(chunk => {
data += chunk;
var decipherText = simpleCrypto.decrypt(chunk.toString());
this.writeOriginal(decipherText);
});
stream.onEnd(() => {
this.setState({ playvideo: !this.state.playvideo });
console.log("file decrypted");
});
});

Function to append decrypted base64 and generate .mp4 file:

writeOriginal(decipherText) {
RNFetchBlob.fs
.appendFile(
RNFetchBlob.fs.dirs.DCIMDir + "/encryptfile2.mp4",
decipherText,
"base64"
)
.then(() => {
console.log("File Written");
})
.catch(error => {
console.log("file writing error", error);
});
}

Secure downloaded Files in android applications with internal storage and encrypting usage?

You can use the download manager to download files using async task.
After that encrypt and decrypt that files.
please refer How to encrypt file from SD card using AES in Android?

SD card files encryption API

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

you need to store key in your app

     public byte[] encript(byte[] dataToEncrypt, byte[] key)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
//I'm using AES encription
Cipher c = Cipher.getInstance("AES");
SecretKeySpec k = new SecretKeySpec(key, "AES");
c.init(Cipher.ENCRYPT_MODE, k);
return c.doFinal(dataToEncrypt);
}

public byte[] decript(byte[] encryptedData, byte[] key)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher c = Cipher.getInstance("AES");
SecretKeySpec k = new SecretKeySpec(key, "AES");
c.init(Cipher.DECRYPT_MODE, k);
return c.doFinal(encryptedData);
}

How do i decrypt a file in Android with AES?

Here is the code:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button encryptButton = (Button) findViewById(R.id.button1);
Button DecryptButton = (Button) findViewById(R.id.button2);
encryptButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
encrypt();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

DecryptButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
decrypt();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

}

/**
* Here is Both function for encrypt and decrypt file in Sdcard folder. we
* can not lock folder but we can encrypt file using AES in Android, it may
* help you.
*
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
*/

static void encrypt() throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
// Here you read the cleartext.
File extStore = Environment.getExternalStorageDirectory();
FileInputStream fis = new FileInputStream(extStore + "/sampleFile");
// This stream write the encrypted text. This stream will be wrapped by
// another stream.
FileOutputStream fos = new FileOutputStream(extStore + "/encrypted");

// Length is 16 byte
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),
"AES");
// Create cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sks);
// Wrap the output stream
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
// Write bytes
int b;
byte[] d = new byte[8];
while ((b = fis.read(d)) != -1) {
cos.write(d, 0, b);
}
// Flush and close streams.
cos.flush();
cos.close();
fis.close();
}

static void decrypt() throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {

File extStore = Environment.getExternalStorageDirectory();
FileInputStream fis = new FileInputStream(extStore + "/encrypted");

FileOutputStream fos = new FileOutputStream(extStore + "/decrypted");
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),
"AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, cipher);
int b;
byte[] d = new byte[8];
while ((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
fos.flush();
fos.close();
cis.close();
}

}


Related Topics



Leave a reply



Submit