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();
}
Related
I am creating a custom print service in Android. When PDF is share to print service, it prints correctly but when image is shared it does not print as expected since it is corrupted. Below is method in my custom printservice. It saves PDF and image file. PDF file is fine and readable but image is corrupted after saved
private void handleHandleQueuedPrintJob(final PrintJob printJob) {
if (printJob.isQueued()) {
printJob.start();
}
int printType = printJob.getDocument().getInfo().getContentType();
if (printType == CONTENT_TYPE_DOCUMENT) {
String fName = MyHelper.getRandomString(8) + ".pdf";
File destFile = new File(getExternalFilesDir(MyConstants.FolderTemp), fName);
try {
InputStream in = new FileInputStream(printJob.getDocument().getData().getFileDescriptor());
FileOutputStream out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} else if (printType == CONTENT_TYPE_PHOTO) {
String fName = MyHelper.getRandomString(8) + ".jpg";
File destFile = new File(getExternalFilesDir(MyConstants.FolderTemp), fName);
InputStream in = new FileInputStream(printJob.getDocument().getData().getFileDescriptor());
FileOutputStream out = null;
try {
out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else
MyHelper.showLongToast(this, getString(R.string.invalidfiletype));
printJob.complete();
}
Can anybody help me why image is corrupted?
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.
I want to copy zip file that includes images from asset to internal storage,And then unzip it.
This is my code :
protected void copyFromAssetsToInternalStorage(String filename){
AssetManager assetManager = getAssets();
try {
InputStream input = assetManager.open(filename);
OutputStream output = openFileOutput(filename, Context.MODE_PRIVATE);
copyFile(input, output);
} catch (IOException e) {
e.printStackTrace();
}
}
private void unZipFile(String filename){
try {
ZipInputStream zipInputStream = new ZipInputStream(openFileInput(filename));
ZipEntry zipEntry;
while((zipEntry = zipInputStream.getNextEntry()) != null){
FileOutputStream zipOutputStream = openFileOutput(zipEntry.getName(), MODE_PRIVATE);
int length;
byte[] buffer = new byte[1024];
while((length = zipInputStream.read(buffer)) > 0){
zipOutputStream.write(buffer, 0, length);
}
zipOutputStream.close();
zipInputStream.closeEntry();
}
zipInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
And i have this error :
java.lang.IllegalArgumentException: File filename/ contains a path separator
What should i do?
From openFileOutput documentation:
name The name of the file to open; can not contain path separators.
Hope this helps
Yaron
I have .3gp audio file which is stored in SD Card.I want to copy that file into another folder of sd card.I have googled a lot about it but didn't get any working idea.Please help me if anyone knows.The code I have tried till now is given below:
private void save(File file_save) {
String file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/RecordedAudio";
File file_dir = new File(file_path);
if (file_dir.exists()) {
file_dir.delete();
}
file_dir.mkdirs();
File file_audio = new File(file_dir, "audio"
+ System.currentTimeMillis() + ".3gp");
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(file_save);
out.close();
FileOutputStream fos = new FileOutputStream(file_audio);
byte[] buffer = bos.toByteArray();
fos.write(buffer);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is always create a new file with the size of 100.Thanks in advance...
The code when i call this save() method is:
mFileFirst = new File(mFileName);//mFileName is the path of sd card where .3gp file is located
save(mFileFirst);
Try this
private void save(File file_save) {
String file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/RecordedAudio";
File file_dir = new File(file_path);
if (file_dir.exists()) {
file_dir.delete();
}
file_dir.mkdirs();
File file_audio = new File(file_dir, "audio"
+ System.currentTimeMillis() + ".3gp");
try {
FileInputStream fis = new FileInputStream(file_save);
FileOutputStream fos = new FileOutputStream(file_audio);
byte[] buf = new byte[1024];
int len;
int total = 0;
while ((len = fis.read(buf)) > 0) {
total += len;
fos.write(buf, 0, len);
// Flush the stream once every so often
if (total > (20 * 1024)) {
fos.flush();
}
}
fos.flush();
fis.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Ive seen a few posts on how to import and export a database in android and i found these code, but i cant seem to make it work. I get the error java.io.filenotfoundexception /storage/sdcard0/BackupFolder/DatabaseName:open failed ENOENT (no such file or directory). Ive changed a few things but i still get no file found exception
here is my export:
private void exportDB() {
try {
db.open();
File newFile = new File("/sdcard/myexport");
InputStream input = new FileInputStream(
"/data/data/com.example.mycarfuel/data
bases/MyDatabase");
OutputStream output = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
db.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and my import:
private void importDB() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//" + "PackageName"
+ "//databases//" + "DatabaseName";
String backupDBPath = "/BackupFolder/DatabaseName
";
File backupDB = new File(data, currentDBPath);
File currentDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(),
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
}
SQlite database to our local file system-
Function declaration-
try {
backupDatabase();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Function defined-
public static void backupDatabase() throws IOException {
//Open your local db as the input stream
String inFileName = "/data/data/com.myapp.main/databases/MYDB";
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+"/MYDB";
//Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer))>0){
output.write(buffer, 0, length);
}
//Close the streams
output.flush();
output.close();
fis.close();
}
Above accepted answer will not work for Android version on or above 6 because database path is different.
please check below code . It will work on all devices.
public static boolean exportDB(Context context) {
String DATABASE_NAME = "my.db";
String databasePath = context.getDatabasePath(DATABASE_NAME).getPath();
String inFileName = databasePath;
try {
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory() + "/" + DATABASE_NAME;
OutputStream output = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
//Close the streams
output.flush();
output.close();
fis.close();
return true;
} catch (Exception e) {
return false;
}
}