how to decrypt(AES) locally stored encrypted file in storage - java

i am new to android ,i building activity clicking submit button get data from five edittext as json and covert to AES encryption and store it on local when i refresh or else restart the activity i want fetch the file decrypt and auto populated to 5 edit text ... encryption works fine for me but decryption wont... help me
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText)findViewById(R.id.editText1);
e2 = (EditText)findViewById(R.id.editText2);
e3 = (EditText)findViewById(R.id.editText3);
e4 = (EditText)findViewById(R.id.editText4);
e5 = (EditText)findViewById(R.id.editText5);
final JSONObject obj = new JSONObject();
sub = (Button)findViewById(R.id.button);
final File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "Outer_Folder");
file.mkdir(); // store and fetch file from storage...
f1 = new File(file,"null"+".txt");
f2 = new File(fileD,"null"+".txt");
try {
SecureRandom srm = SecureRandom.getInstance("SHA1PRNG");
srm.setSeed("no one can read".getBytes());
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128,srm);
sec = kg.generateKey();
bb1 = sec.getEncoded();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
if (f1.exists()){
File file3 = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "Outer_Folder");
f4 = new File(file3,"null"+".txt");
int size = (int)f4.length();
contents = new byte[size];
try {
bufferedInputStream = new BufferedInputStream(new FileInputStream(f4));
try {
bufferedInputStream.read(contents);
bufferedInputStream.close();
String dd = new String(contents);
SecretKeySpec sdf = new SecretKeySpec(bb1,"AES");
Cipher cv = Cipher.getInstance("AES");
cv.init(Cipher.DECRYPT_MODE,sdf);
decodefile = cv.doFinal(dd.getBytes()); // aes decryption not working
String ggg = new String(decodefile);
Toast.makeText(getApplicationContext(),ggg,Toast.LENGTH_SHORT).show();
JSONObject jsonObj = new JSONObject(ggg);
v1=jsonObj.getString("one");
v2=jsonObj.getString("two"); // when enter the activity json filled by decryped file
v3=jsonObj.getString("three");
v4=jsonObj.getString("four");
v5=jsonObj.getString("five");
e1.setText(v1);
e2.setText(v2);
e3.setText(v3);
e4.setText(v4);
e5.setText(v5);
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} }else {
Toast.makeText(getApplicationContext(),"con't read",Toast.LENGTH_LONG).show();
} sub.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View v) {
s1=e1.getText().toString();
s2=e2.getText().toString();
s3=e3.getText().toString();
s4=e4.getText().toString();
s5=e5.getText().toString();
try {
obj.put("one", s1);
obj.put("two", s2);
obj.put("three", s3); //converting json
obj.put("four", s4);
obj.put("five", s5);
if (f1.exists()){ //
f1.delete();
}
vv = obj.toString();
new execute();
try {
SecretKeySpec sksep = new SecretKeySpec(bb1,"AES");
Cipher cp = Cipher.getInstance("AES");
cp.init(Cipher.ENCRYPT_MODE,sksep);
encobyte = cp.doFinal(vv.getBytes()); // aes encryption - working
FileOutputStream uu = null;
uu = new FileOutputStream(f1);
uu.write(encobyte);
oo = new String(encobyte);
Toast.makeText(getApplicationContext(),oo,Toast.LENGTH_LONG).show();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) { //
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace(); //
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

This is probably a serialization/deserialization error, although it is difficult to know without any errors or other information.
Try using hexadecimal or Base64 encoding on the encobyte array before serializing that data to persistent storage. Perform the corresponding decoding operation on the retrieved data dd before decrypting it.

Related

How to get client ip which is connected to android mobile hotspot in java scoket?

Is there any way to get client ip which is connected to android hotspot in java scoket, i have to send input values to client ip on submit
Here what i tried :
private class AttemptSubmit {
public ArrayList<String> getClientList1() {
ArrayList<String> clientList = new ArrayList<>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
String[] clientInfo = line.split(" +");
String mac = clientInfo[3];
if (mac.matches("..:..:..:..:..:..")) {
clientList.add(clientInfo[0]);
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket(clientInfo[0], 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(editUsername.getText().toString());
dataOutputStream.writeUTF(editPassword.getText().toString());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
} catch (java.io.IOException aE) {
aE.printStackTrace();
return null;
}
return getClientList1();
}
Submit action :
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AttemptSubmit attemptSubmit= new AttemptSubmit();
attemptSubmit.getClientList1();
}
});
The problem is, when i click on submit button i'm getting this error "Unfortunately,Aqua has stooped."

Android - saving Int on Internal Storage error

I am trying to save an int (score) on the Internal storage of a real device, and for some reason, when I load it, it makes score equals to 0.
Code:
public int score;
String scoreString = Integer.toString(score);
FileOutputStream fileOutputStream = null;
FileInputStream fileInputStream = null;
final TextView best = (TextView) findViewById(R.id.best);
// Save
try {
file = getFilesDir();
fileOutputStream = openFileOutput("record.txt", Context.MODE_PRIVATE);
fileOutputStream.write(scoreString.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(MainActivity.this, "Save() works fine " + scoreString + file, Toast.LENGTH_SHORT).show();
// load
try {
FileInputStream fileInputStream = openFileInput("record.txt");
int read = -1;
StringBuffer buffer = new StringBuffer();
while ((read = fileInputStream.read()) != -1){
buffer.append((char)read);
}
Log.i("ELY", buffer.toString());
String record = buffer.substring(0);
best.setText("Best: " + record);
Toast.makeText(MainActivity.this, "Load() OK " + record , Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can somebody help me? Thanks
UPDATED Well If you just want to save score you can use SharedPrefernces
To get Score:
public int getScore() {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MY_PREFS", context.MODE_PRIVATE);
return pref.getInt("SCORE", 0);
}
To store Score:
public void setScore(int score) {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MY_PREFS", context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("SCORE", score);
editor.commit();
}

No audio in MP4 file - Android

I am using the MP4ParserMergeAudioVideo to add a new audio to an MP4 file. The library had said to use .wav file, if i keep a .wav file in the directory and give the name of the audiofile as example.m4a, I get a file not found exception. So I changed the file to a .m4a audio file. The code is given below.
findViewById(R.id.append).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String root = Environment.getExternalStorageDirectory().toString();
Log.e("",""+root);
String audio = root + "/download/"+"mymovieaudio.m4a";
String video = root + "/download/"+"My_Movie.mp4";
String output = root + "/download/ouput.mp4";
mux(video, audio, output);
}
});
The mux function is like this
public boolean mux(String videoFile, String audioFile, String outputFile) {
Movie video;
try {
video = new MovieCreator().build(videoFile);
} catch (RuntimeException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
Movie audio;
try {
audio = new MovieCreator().build(audioFile);
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
Track audioTrack = audio.getTracks().get(0);
video.addTrack(audioTrack);
Container out = new DefaultMp4Builder().build(video);
FileOutputStream fos;
try {
fos = new FileOutputStream(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
BufferedWritableFileByteChannel byteBufferByteChannel = new BufferedWritableFileByteChannel(fos);
try {
out.writeContainer(byteBufferByteChannel);
byteBufferByteChannel.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
I successfully get the output.mp4 file in my download directory of my device. The problem is that it does not have any audio. Please help. Thanks in advance.

post image with text to linkedIn from android app

I want to post image from SD Card with text to linkedIn from my android app.
I could share text but image is not sharing.
I tried with following code:
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String share = et.getText().toString();
if (null != share && !share.equalsIgnoreCase("")) {
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Config.LINKEDIN_CONSUMER_KEY, Config.LINKEDIN_CONSUMER_SECRET);
consumer.setTokenWithSecret(accessToken.getToken(), accessToken.getTokenSecret());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://api.linkedin.com/v1/people/~/shares");
try {
consumer.sign(post);
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
} // here need the consumer for sign in for post the share
post.setHeader("content-type", "text/XML");
byte[] data = null;
try {
ileInputStream fis = new FileInputStream(imgUrl1);
Bitmap bi = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream()
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
Log.d("onCreate", "debug error e = " + e.toString());
}
String myEntity = "<share><comment>"+ text +"</comment> <content><submitted-image-url>data</submitted-image-url></content><visibility><code>anyone</code></visibility></share>";
try {
post.setEntity(new StringEntity(myEntity));
org.apache.http.HttpResponse response = httpclient.execute(post);
Toast.makeText(LinkedInSampleActivity.this,
"Shared sucessfully", Toast.LENGTH_SHORT).show();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else {
Toast.makeText(LinkedInSampleActivity.this,
"Please enter the text to share",
Toast.LENGTH_SHORT).show();
}
}
});
}
In linkedIn you can't share the local images.
For that you need to store the images in server and get the url of that image, now you can post the image to linkedIn...
This may help you...

How to change the background color for layouts using configuration file in android

I want to change the background color for layouts dynamically for the first time only, using configuration file in android that file should be in assets folder,it can be xml file or anything.
please help me.
If you set an ID to your layout as follows :
<LinearLayout android:id="#+id/myLayout">
<LinearLayout/>
Then you can set your backGround in onCreate like this:
myLayout= findViewById(R.id.myLayout);
myLayout.setBackgroundColor(Color.BLUE);
1.use color for int value.
in the assets file config.txt, you can input color for int value like this. for example this value is Color.RED
4294901760
2.use this code in your appliaction
String config = "config.txt";
InputStream is = null;
try {
is = getAssets().open(config);
DataInputStream dis = new DataInputStream(is);
String color = dis.readUTF();
ColorDrawable drawable = new ColorDrawable(Integer.parseInt(color));
//use drawable
//for example
new TextView(this).setBackgroundColor(Integer.parseInt(color));
new TextView(this).setBackgroundDrawable(drawable);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(is != null)
{
try {
is.close();
} catch (IOException e) {
}
}
}
3.you can use reflect, but in the config file, write the color name from values/colors.xml.
String config = "config.txt";
InputStream is = null;
try {
is = getAssets().open(config);
DataInputStream dis = new DataInputStream(is);
String color = dis.readUTF();
try {
Field field = R.color.class.getDeclaredField(color);
field.setAccessible(true);
Integer id = (Integer) field.get(null);
ColorDrawable drawable = new ColorDrawable(getResources().getColor(id));
// use drawable
// for example
new TextView(this).setBackgroundColor(getResources().getColor(id));
new TextView(this).setBackgroundDrawable(drawable);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
}

Categories

Resources