Android Encrypt video file with Facebook conceal library - android

I want to encrypt video files stored in SD card
Environment.getExternalStorageDirectory()
I have found that Facebook conceal is good for encrypting large files. I have followed this tutorial Make fast cryptographic operations on Android with Conceal
Here is what i have done up to now.
Encryption method
public void encodeAndSaveFile(File videoFile, String path) {
try {
final byte[] encrypt = new byte[(int) videoFile.length()];
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir(path, Context.MODE_PRIVATE);
File mypath = new File(directory, "en1");
Crypto crypto = new Crypto(new SharedPrefsBackedKeyChain(this), new SystemNativeCryptoLibrary());
if (!crypto.isAvailable()) {
return;
}
OutputStream fileStream = new BufferedOutputStream(
new FileOutputStream(mypath));
OutputStream outputStream = crypto.getCipherOutputStream(
fileStream, new Entity("Passwordd"));
outputStream.write(encrypt);
outputStream.close();
} catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(WebViewActivity.this,"Encrypted",Toast.LENGTH_LONG).show();
}
Decryption method
private void decodeFile(String filename,String path) {
Crypto crypto = new Crypto(new SharedPrefsBackedKeyChain(this),
new SystemNativeCryptoLibrary());
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir(path, Context.MODE_PRIVATE);
File file = new File(directory, filename);
try {
FileInputStream fileStream = new FileInputStream(file);
InputStream inputStream = crypto.getCipherInputStream(fileStream,
new Entity("Password"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read;
byte[] buffer = new byte[1024];
while ((read = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(WebViewActivity.this,"Decrypted",Toast.LENGTH_LONG).show();
}
But this code throwing following error at the run time
java.lang.illegalArgumentException: File contains a path separator
Then i have changed "mypath: variable of encodeAndSaveFile to this
File mypath = new File(directory, "en1");
and "file" variable of decodeFile to this
File file = new File(directory, filename);
Then no errors but. Encryption is not happening. Please help to solve this or suggest correct method for video encryption with conceal lib.

Related

What is Entity in android?

I'm beginner in android.I'm using below code(Facebook Conceal Library) for encrypt and decrypt video but I dont't know what is Entity exactly?I searched many time on the net and also visited developer.android.com/reference/android/content/Entity but I don't know what should I use for Entity still?
public void testEncrypt()
{
File inputFile = new File("/storage/emulated/0/Download/video1.mp4");
try {
final byte[] encrypt = new byte[(int) inputFile.length()];
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("/storage/emulated/0/Download/", Context.MODE_PRIVATE);
File mypath = new File(directory, "encrypt.mp4");
Crypto crypto = new Crypto(new SharedPrefsBackedKeyChain(this), new SystemNativeCryptoLibrary());
if (!crypto.isAvailable()) {
return;
}
OutputStream fileStream = new BufferedOutputStream(
new FileOutputStream(mypath));
OutputStream outputStream = crypto.getCipherOutputStream(
fileStream, new **Entity()**);
outputStream.write(encrypt);
outputStream.close();
} catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this,"Encrypted",Toast.LENGTH_LONG).show();
}
public Void testDecrypt() {
Crypto crypto = new Crypto(new SharedPrefsBackedKeyChain(this),
new SystemNativeCryptoLibrary());
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("/storage/emulated/0/Download/", Context.MODE_PRIVATE);
File file = new File(directory, "decrypt.mp4");
try {
FileInputStream fileStream = new FileInputStream(file);
InputStream inputStream = crypto.getCipherInputStream(fileStream,
new **Entity()**);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read;
byte[] buffer = new byte[1024];
while ((read = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "Decrypted", Toast.LENGTH_LONG).show();
}

Save music file to internal storage from sdacard

I have been trying to save the file ( soundtrack ) from sdcard to the internal storage.
I have already done so with the image with this code
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/fairyTale/app_data/ImgMsc
File directory = cw.getDir("ImgMsc", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,Name+".png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
Now this works well, creates a directory and saves my bitmap, but i want to do the same thing for the music file.
Also i want to know how to read that file ( use it in the app ).
I have used this code to read the bitmap
File f=new File(path,name+".png");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
return b;
P.S. the code i have tried, but doesn't seem to be producing the right copy:
String filePath=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/"+name;
File music = new File(filePath);
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/fairyTale/app_data/ImgMsc
File directory = cw.getDir("ImgMsc", Context.MODE_PRIVATE);
File mypath=new File(directory,name+".mp3");
try {
InputStream is=new FileInputStream(music);
OutputStream os;
os = new FileOutputStream(mypath);
byte[] buff=new byte[1024];
int len;
while((len=is.read(buff))>0){
os.write(buff,0,len);
}
is.close();
os.close();
}
Here is the code that worked for me:
private void saveToInternalStorage(String name){
String filePath=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/"+name;
File music = new File(filePath);
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to your data
File directory = cw.getDir("ImgMsc", Context.MODE_PRIVATE);
File mypath=new File(directory,name+".mp3");
// Create imageDir
try {
InputStream is=new FileInputStream(music);
OutputStream os;
os = new FileOutputStream(mypath);
byte[] buff=new byte[1024];
int len;
while((len=is.read(buff))>0){
os.write(buff,0,len);
}
is.close();
os.close();
DeleteFile(filePath);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Hope it helps!

Android: Accessing File from Internal Storage Using RandomAccessFile

I am creating an app that needs to read data from a file. I was initially reading it from the assets folder using a BufferedReader and an InputStreamReader but I was running into memory issues (see Android: File Reading - OutOfMemory Issue). One suggestion was to copy the data from the assets folder to the internal storage (not the SD card) and then access it via RandomAccessFile. So I looked up how to copy files from the assets to internal storage and I found 2 sources:
https://groups.google.com/forum/?fromgroups=#!topic/android-developers/RpXiMYV48Ww
http://developergoodies.blogspot.com/2012/11/copy-android-asset-to-internal-storage.html
I decided to use the code from the second one and modified it for my file. So it looks like this:
public void copyFile() {
//Open your file in assets
Context context = getApplicationContext();
String destinationFile = context.getFilesDir().getPath() + File.separator + "text.txt";
if (!new File(destinationFile).exists()) {
try {
copyFromAssetsToStorage(context, "text.txt", destinationFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void copyStream(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int length = Input.read(buffer);
while (length > 0) {
output.write(buffer, 0, length);
length = input.read(buffer);
}
}
private void copyFromAssetsToStorage(Context context, String sourceFile, String destinationFile) throws IOException {
InputStream inputStream = context.getAssets().open(sourceFile);
OutputStream outputStream = new FileOutputStream(destinationFile);
copyStream(inputStream , outputStream );
outputStream.flush();
outputStream.close();
inputStream.close();
}
I am assuming that this copies the file into the app's data directory. I have not been able to test it because I would like to be able to access the file using RandomAccessFile. However, I have never done either one of these two (copying the file from assets and RandomAccessFile) so I am stuck. The work on this app has come to a standstill because this is the only thing that is preventing me from completing it.
Can anyone provide me with corrections, suggestions, and correct implementations of how to access the data using RandomAccessFile? (The data is a list of strings 4-15 characters in length on each line.)
EDIT*
private File createCacheFile(Context context, String filename){
File cacheFile = new File(context.getCacheDir(), filename);
if (cacheFile.exists()) {
return cacheFile ;
}
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
inputStream = context.getAssets().open(filename);
fileOutputStream = new FileOutputStream(cacheFile);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ( (length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer,0,length);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return cacheFile;
}
1- Copy the file from assets to the cache directory
This code just for illustration, you have to do appropriate exception handling and close resources
private File createCacheFile(Context context, String filename){
File cacheFile = new File(context.getCacheDir(), filename);
if (cacheFile.exists()) {
return cacheFile ;
}
InputStream inputStream = context.getAssets().open(filename);
FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ( (length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer,0,length);
}
fileOutputStream.close();
inputStream.close();
return cacheFile;
}
2- Open the file using RandomAccessFile
File cacheFile = createCacheFile(context, "text.txt");
RandomAccessFile randomAccessFile = new RandomAccessFile(cacheFile, "r");
// Process the file
randomAccessFile.close();
On a side note, you should follow Java naming conventions, e.g. your method and variable name should start with small letter such as copyFromAssetsToStorage and destinationFile
Edit:
You should make a separate try/catch for each close() operation, so if one fails the other still get executed and check that they are not null
finally {
try {
if(fileOutputStream!=null){
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(inputStream!=null){
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

File writing in external storage device is not working

I tried writing a file to my android phone using phonegap ui.
I have given the write permission and i tried by using getExternalStorageDirectory() and by giving the absolute path. But still not able to write it.
s1 is the name of the file that i am writing in the external storage
Environment.getExternalStorageState();
//File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"/Android/");
File file = new File("/mnt/sdcard"+ File.separator + "Android" + File.separator);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Folder");
}
}
Environment.getExternalStorageState();
File outputFile = new File(file, s1);
FileOutputStream fileoutputstream = new FileOutputStream(outputFile);
byte abyte0[] = new byte[1024];
for (int i = 0; (i = inputstream.read(abyte0)) > 0;)
fileoutputstream.write(abyte0, 0, i);
fileoutputstream.close();
inputstream.close();
I wrote a quick working demo of writing a file to the external storage.
If this still doesn't work maybe it is a phonegap specific issue.
Hope this helps:
InputStream is = null;
OutputStream os = null;
byte[] buffer = new byte[2048];
int bytes_read = 0;
File inputFile = new File("/init.rc");
File outputFile = new File(Environment.getExternalStorageDirectory() + "/testfile");
try
{
is = new FileInputStream(inputFile);
os = new FileOutputStream(outputFile);
while ((bytes_read = is.read(buffer)) != -1)
{
os.write(buffer, 0, bytes_read);
}
}
catch (Exception ignore) {}
finally
{
try
{
is.close();
}
catch (Exception ignore) {}
try
{
os.close();
}
catch (Exception ignore) {}
}
if (outputFile.exists())
{
Toast.makeText(this, "Success!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "Failure!", Toast.LENGTH_LONG).show();
}

save audio file in raw or assets folder to sdcard android

Hi guys i am having a audio file in assets folder and i need to save the same file onto sdcard .
How to acheive this.
Below is the code i am using to save file
String filename = "filename.txt";
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos;
byte[] data = new String("data to write to file").getBytes();
try {
fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
please help
try this
AssetManager mngr = getAssets();
InputStream path = mngr.open("music/music1.mp3");
BufferedInputStream bis = new BufferedInputStream(path,1024);
//get the bytes one by one
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
}
byte[] bitmapdata = baf.toByteArray();
After converting into byte array copy this into the sdcard as follows
File file = new File(Environment.getExternalStorageDirectory(), music1.mp3);
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
fos.write(bitmapdata );
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}

Categories

Resources