Decrypt AES256 encrypted file and save it in the phone - java

I'm downloading a file that is stored on a remote server, I try to decrypt it using JNCryptor, and all goes well except that the file I have downloaded and store in the phone external storage is corrupted and I cannot open it. Can anyone tell me where im going wrong?
Im trying to get the InputStream from the file, decrypt it, and save the file on external storage.
Thanks
Here is my code:
private void downloadFile() {
final String FILE_URL = "https://www.google.com";
final String PASS = "password";
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
Log.d(TAG, "starting");
JNCryptor cryptor = new AES256JNCryptor();
int count;
try {
URL url = new URL(FILE_URL);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
//decrypt istream
byte[] b = null;
byte[] data = null;
try {
b = new byte[input.available()];
input.read(b);
} catch (IOException e) {
Log.i("decrypt error", e.toString());
}
AES256JNCryptorOutputStream cryptorStream = null;
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
try {
cryptorStream = new AES256JNCryptorOutputStream(byteStream,
PASS.toCharArray());
} catch (CryptorException e) {
e.printStackTrace();
}
try {
cryptorStream.write(b);
cryptorStream.flush();
cryptorStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
byte[] encrypted = byteStream.toByteArray();
try {
data = cryptor.decryptData(encrypted, PASS.toCharArray());
Log.d(TAG, "decrypted");
} catch (InvalidHMACException e) {
e.printStackTrace();
} catch (CryptorException e) {
e.printStackTrace();
}
if (data != null) {
Log.d(TAG, "data is ok");
}
//end decryption
// Output stream
//test
FileOutputStream fos = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/temp.zip");
fos.write(data);
fos.close();
Log.d(TAG, "file saved ");
input.close();
Log.d(TAG, "done");
} catch (Exception e) {
Log.d(TAG, "Error: " + e.getMessage());
}
return null;
}
}.execute();
}
P.S. Im not getting any error or warning in logCat.

Related

Can't open file received from socket android java [duplicate]

This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 2 years ago.
I am making an app with socket in which i want to share data from two devices in the same wifi. With my code i can share the file successfully between two devices with the exact size of the file and saves into the device storage with a specific name but when i try to open it fails to open in the file manager. I have tried this with mp4 file and apk files
Here is the sender's code
#Override
public void run() {
//File file = new File(src);
File file = new File(Environment.getExternalStorageDirectory() + "/c.mp4");
byte[] bytes = new byte[(int) file.length()];
BufferedInputStream bis;
try {
bis = new BufferedInputStream(new FileInputStream(file));
DataInputStream dis = new DataInputStream(bis);
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("anything");
dos.writeLong(bytes.length);
int read;
while ((read = dis.read(bytes)) != -1){
dos.write(bytes,0,read);
}
//os.write(bytes, 0, bytes.length); //commented
//os.flush(); //commented
socket.close();
final String sentMsg = "File sent to: " + socket.getInetAddress();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, sentMsg, Toast.LENGTH_LONG).show();
}});
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And here is the receiver
#Override
public void run() {
Socket socket = null;
int bytesRead;
InputStream in; //changed
int bufferSize=0;
try {
socket = new Socket(dstAddress, dstPort);
bufferSize = socket.getReceiveBufferSize();
in = socket.getInputStream();
DataInputStream clientData = new DataInputStream(in);
File file = new File(Environment.getExternalStorageDirectory(), "c.mp4");
OutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[bufferSize];
int read;
while ((read = clientData.read(buffer)) != -1){
output.write(buffer, 0 , read);
}
//bos.close(); //commented
socket.close();
MainActivity2.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity2.this, "Finished", Toast.LENGTH_LONG).show();
}});
} catch (IOException e) {
e.printStackTrace();
final String eMsg = "Something wrong: " + e.getMessage();
MainActivity2.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity2.this,
eMsg,
Toast.LENGTH_LONG).show();
}});
} finally {
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You need to read the clientData (DataInputStream) in the same way you write it to the output stream of the socket.
uft-8 string,
long value,
seq. of bytes
Your mp4 file content will prefixed with "anything" and length. so it will be considered as corrupted file.
save the file without ("anything" and length)

Download a image from server to android and show in imageview

I have an server (i use GlassFish). I am able to send Json or XML etc. with http to my android device. I saw an example to upload a picture from my android device to the server. That converts my picked image to byte, converts to String and back at my server. So i can put it on my PC (server).
Now i just want the opposite: get a picture from my PC and with the URL get the image (bitmap here) to imageview. but with debugging bmp seems to be "null". google says its because my image is not a valid bitmap (so maybe something is wrong at my server encoding?).
What does i need to change to this code to get it working?
Server code:
public class getImage{
String imageDataString = null;
#GET
#Path("imageid/{id}")
public String findImageById(#PathParam("id") Integer id) {
//todo: schrijf een query voor het juiste pad te krijgen!
System.out.println("in findImageById");
File file = new File("C:\\Users\\vulst\\Desktop\\MatchIDImages\\Results\\R\\Tensile_Hole_2177N.tif_r.bmp");
try{
// Reading a Image file from file system
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
imageDataString = Base64.encodeBase64URLSafeString(imageData);
imageInFile.close();
System.out.println("Image Successfully Manipulated!");
} catch (FileNotFoundException e) {
System.out.println("Image not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading the Image " + ioe);
}
return imageDataString;
}
}
and this is the android side (android studio):
public class XMLTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
java.net.URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String line) {
super.onPostExecute(line);
byte[] imageByteArray = Base64.decode(line , Base64.DEFAULT);
try {
Bitmap bmp = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
ivFoto.setImageBitmap(bmp);
}catch (Exception e){
Log.d("tag" , e.toString());
}
}
}
Have you tried HttpURlConnection?
Here's a sample code:
private class SendHttpRequestTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL("http://xxx.xxx.xxx/image.jpg");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
}catch (Exception e){
Log.d(TAG,e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
ImageView imageView = (ImageView) findViewById(ID OF YOUR IMAGE VIEW);
imageView.setImageBitmap(result);
}
}
I hope i could help
You can use Glide it is simplest way to load image
This is how you can save image
Glide.with(context)
.load(image)
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
String name = new Date().toString() + ".jpg";
imageName = imageName + name.replaceAll("\\s+", "");
Log.d(TAG, "onResourceReady: imageName = " + imageName);
ContextWrapper contextWrapper = new ContextWrapper(mContext);
File directory = contextWrapper.getDir("imageDir", Context.MODE_PRIVATE);
File myPath = new File(directory, imageName);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(myPath);
resource.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
and this is how you can read the image
ContextWrapper contextWrapper = new ContextWrapper(mContext);
File directory = contextWrapper.getDir("imageDir", Context.MODE_PRIVATE);
String path = directory.getAbsolutePath();
path = path + "/" + imageName;
Glide.with(mContext).load(path).into(your imageview);
Why don't you use Glide?
For build.gradle in your app module:
dependencies {
compile 'com.github.bumptech.glide:glide:3.7.0'
...
}
Then:
Glide
.with(context) // replace with 'this' if it's in activity
.load("http://www.google.com/.../image.gif")
.into(R.id.imageView);
Try using Base64.encodeBase64String(imageData) with out using the URLSafeString.
If there are people who are also trying to do it my way, this is working:
public class XMLTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
java.net.URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String line) {
super.onPostExecute(line);
byte[] imageByteArray = Base64.decode(line , Base64.DEFAULT);
try {
Bitmap bmp = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
ivFoto.setImageBitmap(bmp);
}catch (Exception e){
Log.d("tag" , e.toString());
}
}
}
#Stateless
#Path("getImage")
public class getImage {
//todo: capture error inandroid + take just path!
String imageDataString = null;
#GET
#Path("imageid/{id}")
public String findImageById(#PathParam("id") Integer id) {
//todo: schrijf een query voor het juiste pad te krijgen!
System.out.println("in findImageById");
File file = new File("C:\\Users\\vulst\\Desktop\\MatchIDImages\\Results\\R\\Tensile_Hole_2177N.tif_r.bmp");
try{
// Reading a Image file from file system
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
imageDataString = Base64.encodeBase64String(imageData);
imageInFile.close();
System.out.println("Image Successfully Manipulated!");
} catch (FileNotFoundException e) {
System.out.println("Image not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading the Image " + ioe);
}
return imageDataString;
}
}
I hope this code is useful.
go to your MainActivity.java and try this code:
public class MainActivity extends AppCompatActivity {
ImageView imageView;
public void downloadImage(View view)
{
Log.i("Button","Tapped");
DownloadImage task = new DownloadImage();
Bitmap result = null;
try {
result = task.execute("https://vignette.wikia.nocookie.net/disney/images/0/0a/ElsaPose.png/revision/latest?cb=20170221004839").get();
}
catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
imageView.setImageBitmap(result);
}
public class DownloadImage extends AsyncTask<String, Void, Bitmap>
{
#Override
protected Bitmap doInBackground(String... imageurls) {
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(imageurls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream in =httpURLConnection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(in);
return myBitmap;
}
catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.imageView);
}
}
Don't forget to add this piece of code in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>

Uploading files to Parse database

I want to add a feature to my app in which the users can upload files (PDF files) from their mobile to the database, then download this file back to the app and display it.
I have no idea how to start doing this and what is the right code to use.
I tried using this code,
ParseObject pObject = new ParseObject("ExampleObject");
pObject.put("myNumber", number);
pObject.put("myString", name);
pObject.saveInBackground(); // asynchronous, no callback
- EDIT -
I tried this code but the app crashes when I click the button:
public class Test extends Activity {
Button btn;
File PDFFile;
ParseObject po;
String userPDFFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
po = new ParseObject("pdfFilesUser");
btn = (Button) findViewById(R.id.button);
PDFFile = new File("res/raw/test.pdf");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadPDFToParse(PDFFile, po, userPDFFile);
}
});
}
private ParseObject uploadPDFToParse(File PDFFile, ParseObject po, String columnName){
if(PDFFile != null){
Log.d("EB", "PDFFile is not NULL: " + PDFFile.toString());
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(PDFFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int read;
byte[] buff = new byte[1024];
try {
while ((read = in.read(buff)) > 0)
{
out.write(buff, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
byte[] pdfBytes = out.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile(PDFFile.getName() , pdfBytes);
po.put(columnName, file);
// Upload the file into Parse Cloud
file.saveInBackground();
po.saveInBackground();
}
return po;
}
}
You can upload a file manually via REST API. Take a look at this docs here
Can try this code:
private ParseObject uploadPDFToParse(File PDFFile, ParseObject po, String columnName){
if(PDFFile != null){
Log.d("EB", "PDFFile is not NULL: " + PDFFile.toString());
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(PDFFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int read;
byte[] buff = new byte[1024];
try {
while ((read = in.read(buff)) > 0)
{
out.write(buff, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
byte[] pdfBytes = out.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile(PDFFile.getName() , pdfBytes);
po.put(columnName, file);
// Upload the file into Parse Cloud
file.saveInBackground();
po.saveInBackground();
}
return po;
}
For more details check this
I would strongly suggest you quickly get up to speed with the Parse Java development wiki.
To answer your question. You want to be using:
byte[] data = "Working at Parse is great!".getBytes();
ParseFile file = new ParseFile("resume.txt", data);
file.saveInBackground();
First declare your file etc then save it using that. But once again, first read the guidelines to better understand the framework you working with.
https://parseplatform.github.io/docs/android/guide/

Android Activity Restarts When Turning Back To App From Adobe Reader

My app downloads a PDF file from webserver and opens it with Adobe Reader. But when I click back button on Adobe Reader, my app restarts. I don't want my app to restart when closing Adobe Reader. Note: My app has a file browser dialog, I choose a PDF and display it.
How can I prevent restarting the acitivity when turn back from Adobe Reader?
My code ...
private class DownloadFile extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0]; // -> http://maven.apache.org/maven-1.x/dokuman.pdf
String fileName = strings[1]; // -> dokuman.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "dokuman");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
Downloader.downloadFile(fileUrl, pdfFile);
return null;
}
}
...
public class Downloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
...
new DownloadFile().execute(host+"dene.pdf", "dokuman.pdf");
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/dokuman/" + "dokuman.pdf"); // -> filename = dokuman.pdf
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(MainActivity.this, "No PDF Viewer App!", Toast.LENGTH_SHORT).show();
...

Unable to download complete file in android app

following is my code,
From Activity class
Intent intent = new Intent(this, DownloadService.class);
// Create a new Messenger for the communication back
Messenger messenger = new Messenger(handler);
intent.putExtra("MESSENGER", messenger);
intent.setData(Uri.parse("http://www.abc.ezy.asia/E-MobApps/op.apk"));
intent.putExtra("urlpath", "http://www.abc.ezy.asia/E-MobApps/op.apk");
startService(intent);
I have overrided Service Class method onHandle Event
// DownloadService Class
#Override
protected void onHandleIntent(Intent intent) {
Uri data = intent.getData();
String urlPath = intent.getStringExtra("urlpath");
String fileName = data.getLastPathSegment();
File output = new File(Environment.getExternalStorageDirectory(),fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
fos = new FileOutputStream(output.getPath());
byte dataB[] = new byte[1024];
InputStreamReader reader = new InputStreamReader(stream);
int next = -1;
while ((next = reader.read()) != -1) {
fos.write(next);
}
fos.flush();
result = Activity.RESULT_OK;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Bundle extras = intent.getExtras();
if (extras != null) {
Messenger messenger = (Messenger) extras.get("MESSENGER");
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = output.getAbsolutePath();
try {
messenger.send(msg);
} catch (android.os.RemoteException e1) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
}
}
In above code I used File Streams & Input stream reader for downloading
when tried to download html file then complete file was downloaded to my sdcard.But when I tried for APK. The File downloaded of 2.2 mb instead of 2.4 mb Parsing problem is there. Kindly help me to resolve the issue.
try this piece of code :
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(output.getPath());
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
input.close();
result = Activity.RESULT_OK;

Categories