How to send aes 256 encrypted data to a web server? - android

I successfully encrypted an audio file on my sd card and placed that encrypted file again in my sd card. I used the below code to save my file in sd card.
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, sks);
CipherOutputStream cos = new CipherOutputStream(outputStream, cipher);
int b;
byte[] d = new byte[8];
while((b = inputStream.read(d)) != -1){
cos.write(d, 0, b);
But now i want to encrypt and send that file to a web server without saving it in sd card. I tried using the above code, but it says
The constructor CipherOutputStream(HttpPost, Cipher) is undefined. Change type of httpPost to OutputStream.
How can i send it. Please help.
This is the method i use to send the original file to server:
public void uploadFile(String outfile) {
int count;
try{
// the URL where the file will be posted
String postReceiverUrl = "The url where i want to send";
// new HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
//outfile is the original file in sd card.
File file = new File(outfile);
FileBody fileBody = new FileBody(file);
String file_name_de = "MA_"+u_name.subSequence(0, 3)+u_id;
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("frm_file", fileBody);
reqEntity.addPart("frm_user_id", new StringBody(String.valueOf(u_id), Charset.forName("UTF-8")));
reqEntity.addPart("frm_token", new StringBody(u_token));
reqEntity.addPart("frm_file_name", new StringBody(file_name_de, Charset.forName("UTF-8")));
httpPost.setEntity(reqEntity);
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
//get the InputStream
InputStream is=fileBody.getInputStream();
byte[] data = baos.toByteArray();
//create a buffer
byte data[] = new byte[1024];//1024
//this updates the progress bar
long total=0;
while((count=is.read(d))!=-1){
total+=count;
publishProgress((int)(total*100/file.length()));
}
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
#SuppressWarnings("unused")
String responseStr = EntityUtils.toString(resEntity).trim();
//Log.d("Response: ", responseStr);
}
file.delete();
} catch (NullPointerException e) {
//e.printStackTrace();
} catch (Exception e) {
//e.printStackTrace();
}
}

You probably want to wrap the CipherOutputStream in a ByteArrayOutputStream like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CipherOutputStream cos = new CipherOutputStream(baos, cipher);
int b;
byte[] d = new byte[BUFFER_SIZE];
while((b = inputStream.read(d)) != -1){
cos.write(d, 0, b);
}
byte[] data = baos.toByteArray();
// now send data to server
This way you have the encrypted data packaged in a byte[], ready for you to shoot off to the server.

Related

How to encrypt and decrypt a pdf/doc file in Android

I am new to Android, and I am trying to encrypt and decrypt a file and want to display in Android device after decrypt.
Here I am downloading the file from the URL and storing in SD card and I don't now how to encrypt the file and then store in SD card and file size may be more then 20MB.
Code:
File downloadFile(String dwnload_file_path) {
File file = null;
try {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "SampleFolder");
folder.mkdir();
file = new File(folder, dest_file_path);
try{
file.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(file);
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();
//ToastManager.toast(this, "Download Complete. Open PDF Application installed in the device.");
} catch (final MalformedURLException e) {
//ToastManager.toast(this, "Some error occured. Press try again.");
} catch (final IOException e) {
//ToastManager.toast(this, "Some error occured. Press try again.");
} catch (final Exception e) {
//ToastManager.toast(this, "Failed to download image. Please check your internet connection.");
}
return file;
}
Here I am displaying the file in Android device but after decrypting the file, how can I display it?
Code:
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/SampleFolder/" + "Sample."pref.getString(Constants.PrefConstants.PATH_NAME));
File f = new File(pdfFile.toString());
if(f.exists()) {
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, pref.getString(Constants.PrefConstants.PATH_NAME_APP));
//pdfIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP);
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(pdfIntent);
} else {
//uiManager.execute(Constants.Commands.REQGET_INSTRUCTIONS_SCREEN,null);
ToastManager.toast(getApplicationContext(), "No data available...");
}
How can I resolve this issue?
You need to use the SecretKeySpec library .
Example of encrypt method
static void encrypt() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
// Here you read the cleartext.
FileInputStream fis = new FileInputStream("SampleFolder/yourfilename");
// This stream write the encrypted text. This stream will be wrapped by another stream.
FileOutputStream fos = new FileOutputStream("SampleFolder/yourencryptedfilename");
// 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();
}
For decrypt method see the link below.
More details : How to encrypt file from SD card using AES in Android?

Pdf download using HttpPost in Android shows incorrect PDF format

Iam trying to download a file using HttpPost. But after downloading using the below code, it shows me invalid pdf format. Please help me rectify this issue?
private void downLoadFile(String Filename) throws ClientProtocolException, IOException{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
Log.i(TAG, "Filename: " + Filename);
pairs.add(new BasicNameValuePair("Filename:", Filename));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
InputStream is = response.getEntity().getContent();
FileOutputStream fos = new FileOutputStream(new File( Environment.getExternalStorageDirectory().getAbsolutePath() +"/omniware/retail/"+Filename));
int read = 0;
byte[] buffer = new byte[1048576];
while((read = is.read(buffer)) > 0){
fos.write(buffer, 0, read);
}
fos.flush();
fos.close();
is.close();
showPdf(Filename);
Log.i(TAG, "Response Code: " + Integer.toString(response.getStatusLine().getStatusCode()));
}
public void showPdf(String Filename){
File file2 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/omniware/retail/"+Filename);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file2);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}

File not saved using FileOutputStream and InputStream

I'm getting data from an api and I want to write/save some file with that data. This is my code
try
{
HttpResponse response = httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/incubate_files");
if (!myDir.exists()) myDir.mkdirs();
File file = new File(Environment.getExternalStorageDirectory().getPath()+File.separator+"/incubate_files/", "messageId_"+messageId+"."+ext);
FileOutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int bufferLength = 0;
while((bufferLength = content.read(buffer)) != -1)
output.write(buffer, 0, bufferLength);
output.close();
output.flush();
content.close();
}
catch (Exception e)
{
e.printStackTrace();
}
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
There is no exception, only a empty file
Thanks!
UPDATE
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
Log.d(app.TAG,"Cadena: "+builder.toString());
InputStream is = new ByteArrayInputStream(builder.toString().getBytes());
I change my InputStream white the content of the api. The api returns a lot of characters. The image actually exists in the server and I can see it.
Now the file is with some bytes but I cant see in my phone
The api reponse is in binary
You need to make use of getInputStream method from connection object and save the data into a File. For example:
InputStream input = connection.getInputStream();
File file = new File("download_directory_path", "file_name");
FileOutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int bufferLength = 0;
while((bufferLength = input.read(buffer)) != -1)
output.write(buffer, 0, bufferLength);
and then finally close() your output and input streams.
Once, writing is complete, the file points to the downloaded file.

Convert files xls to pdf with Android and http apache mime

That such a good night, I write to ask if I could help and to coregir the following code, which right through a listView and presslong, took the path of the file, to try and turn the service:
of:
http://www.convertapi.com/excel-pdf-api
I have not to use a webview, or could use a hidden way
thank
code is:
mPrefs = getSharedPreferences("RutaPath", Context.MODE_PRIVATE);
String rutasave = mPrefs.getString("Externa", "");
String resultcode = "0";
HttpPost httppost = new HttpPost("http://do.convertapi.com/Excel2Pdf/json");
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
// For File parameters
file=new File(rutasave+"prueba.xls");
//Toast.makeText(this,"cargando: " +rutasave+"prueba.xls",Toast.LENGTH_SHORT).show();
outputDir=rutasave;
entity.addPart("file", new FileBody(file, "binary/octet-stream"));//"file"
httppost.setEntity( entity );
HttpClient httpclient = new DefaultHttpClient();
// return new Boolean(true);//eliminar despues
try {
HttpResponse response = httpclient.execute(httppost);
Header rcHeader = response.getFirstHeader("result");
if(rcHeader != null){
resultcode = rcHeader.getValue();
if("True".equals(resultcode)){
filesize = response.getFirstHeader("filesize").getValue();
filename = response.getFirstHeader("OutputFileName").getValue();
//Toast.makeText(this,"Archivo: " +filename,Toast.LENGTH_SHORT).show();
HttpEntity hentity = response.getEntity();
if(hentity != null){
InputStream istream = hentity.getContent();
File file = new File(outputDir+filename+".pdf");//outputDir File.separator
FileOutputStream ostream = new FileOutputStream(file);
byte[] b = new byte[1024];
int num = 0;
while( (num = istream.read(b, 0, b.length)) > 0)
ostream.write(b, 0, num);
istream.close();
ostream.flush();
ostream.close();
return new Boolean(true);
}
}
}
} catch (ClientProtocolException e) {

Android getting pictures from webservice, how to?

I have an android application that needs to receive several pictures from the webservice.
But how to do this?
In my webservice i'm currently sending only 1 image as a byte[].
public static byte[] GetMapPicture(string SeqIndex)
{
try
{
byte[] maps;
InterventionEntity interventie = new InterventionEntity(long.Parse(SeqIndex));
MyDocumentsCollection files = interventie.Location.MyDocuments;
maps = null;
foreach (MyDocumentsEntity file in files)
{
if (file.SeqDocumentType == (int)LocationDocumentType.GroundPlanDocument && file.File.Filename.EndsWith(".jpg"))
maps = (file.File.File);
}
return maps;
} catch (Exception e) {
Log.Error(String.Format("Map not send, {0}", e));
return null;
}
}
The byte[] is returned from my webservice.
But in my android project the bitmap is not decoded and therefor null.
public Bitmap getPicture(String message, String url, Context context) throws IOException{
HttpClient hc = MySSLSocketFactory.getNewHttpClient();
Log.d(MobileConnectorApplication.APPLICATION_TAG, "NETWORK - Message to send: "+ message);
HttpPost p = new HttpPost(url);
Bitmap picture;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(httpParams, threeMinutes );
p.setParams(httpParams);
try{
if (message != null)
p.setEntity(new StringEntity(message, "UTF8"));
}catch(Exception e){
e.printStackTrace();
}
p.setHeader("Content-type", "application/json");
HttpContext httpcontext = new BasicHttpContext();
httpcontext.setAttribute(ClientContext.COOKIE_STORE, MobileConnectorApplication.COOKIE_STORE);
try{
HttpResponse resp = hc.execute(p,httpcontext);
InputStream is = resp.getEntity().getContent();
picture = BitmapFactory.decodeStream(is); //here is goes wrong
int httpResponsecode = resp.getStatusLine().getStatusCode() ;
checkResponse(url, message, "s", httpResponsecode);
Log.d(MobileConnectorApplication.APPLICATION_TAG, String.format("NETWORK - Response %s", httpResponsecode));
} finally{
}
return picture;
}
Can anyone help me on this?
assuming incomingbytearray is a byte array,
Bitmap bitmapimage = BitmapFactory.decodeByteArray(incomingbytearray, 0, incomingbytearray.length);
String filepath = "/sdcard/xyz.png";
File imagefile = new File(filepath);
FileOutputStream fos = new FileOutputStream(imagefile);
bitmapimage.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
This should be fine.
EDIT: input stream to bytearray,
InputStream in = new BufferedInputStream(url.openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
conversion code from Android: BitmapFactory.decodeByteArray gives pixelated bitmap

Categories

Resources