Доброго времени суток, я пытаюсь написать программу которая будет зашифровывать и расшифровывать изображения. С таким исходником:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="ryvkin.com.scrambler.MainActivity">
<Button
android:text="@string/choose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true"
android:layout_marginTop="34dp"
android:id="@+id/btnChoose" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@android:drawable/checkbox_off_background"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:text="@string/path"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tvPath"
android:layout_below="@+id/btnChoose"
android:layout_centerHorizontal="true" />
<Button
android:text="@string/decrypt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnDecrypt"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:text="@string/encrypt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnEncrypt"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="@+id/btnDecrypt" />
</RelativeLayout>
MainActivity.java:
package ryvkin.com.scrambler;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;
public class MainActivity extends Activity implements OnClickListener {
Button btnChoose, btnEncrypt, btnDecrypt;
private static TextView tvPath;
private ImageView imageView;
private final int Pick_image = 1;
String filePath;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView)findViewById(R.id.imageView);
tvPath=(TextView)findViewById(R.id.tvPath);
btnChoose=(Button)findViewById(R.id.btnChoose);
btnEncrypt=(Button)findViewById(R.id.btnEncrypt);
btnDecrypt=(Button)findViewById(R.id.btnDecrypt);
btnChoose.setOnClickListener(this);
btnEncrypt.setOnClickListener(this);
btnDecrypt.setOnClickListener(this);
}
//Обрабатываем результат выбора в галерее:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case Pick_image:
if(resultCode == RESULT_OK){
try {
//Получаем URI изображения, преобразуем его в Bitmap
//объект и отображаем в элементе ImageView нашего интерфейса:
final Uri imageUri = imageReturnedIntent.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imageView.setImageBitmap(selectedImage);
tvPath.setText(getRealPathFromURI(imageUri));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}}
//Получаю адрес файла
private String getRealPathFromURI(Uri contentURI) {//http://ru.stackoverflow.com/questions/602034/%D0%92%D1%8B%D0%B2%D0%BE%D0%B4-%D0%BF%D1%83%D1%82%D0%B8-%D1%84%D0%B0%D0%B9%D0%BB%D0%B0
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Источником является Dropbox или другой локальный путь к файлу
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
private void chooseFile() {
//Вызываем стандартную галерею для выбора изображения с помощью Intent.ACTION_PICK:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
//Тип получаемых объектов - image:
photoPickerIntent.setType("image/*");
//Запускаем переход с ожиданием обратного результата в виде информации об изображении:
startActivityForResult(photoPickerIntent, Pick_image);
}
private void encryptFile() {
try{
filePath=this.getFilesDir().getPath().toString()+"/myDirectory/Encrypt.jpg";
FileInputStream file = new FileInputStream((String) tvPath.getText());
FileOutputStream outStream = new FileOutputStream(filePath);
byte k[]="CooL2116NiTh5252".getBytes();
SecretKeySpec key = new SecretKeySpec(k, "AES");
Cipher enc = Cipher.getInstance("AES");
enc.init(Cipher.ENCRYPT_MODE, key);
CipherOutputStream cos = new CipherOutputStream(outStream, enc);
byte[] buf = new byte[1024];
int read;
while((read=file.read(buf))!=-1){
cos.write(buf,0,read);
}
file.close();
outStream.flush();
cos.close();
Toast.makeText(getBaseContext(),"The file encrypted Successfully", Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(getBaseContext(), (CharSequence) e, Toast.LENGTH_LONG).show();
}
}
private void decryptFile() {
try{
filePath=this.getFilesDir().getPath().toString()+"/myDirectory/Decrypt.jpg";
FileInputStream file = new FileInputStream((String) tvPath.getText());
FileOutputStream outStream = new FileOutputStream(filePath);
byte k[]="CooL2116NiTh5252".getBytes();
SecretKeySpec key = new SecretKeySpec(k, "AES");
Cipher enc = Cipher.getInstance("AES");
enc.init(Cipher.DECRYPT_MODE, key);
CipherOutputStream cos = new CipherOutputStream(outStream, enc);
byte[] buf = new byte[1024];
int read;
while((read=file.read(buf))!=-1){
cos.write(buf,0,read);
}
file.close();
outStream.flush();
cos.close();
Toast.makeText(getBaseContext(),"The image was decrypted successfully", Toast.LENGTH_LONG).show();
Runtime.getRuntime().exec("rundll32 url.dll, FileProtocolHandler "+"Decrypt.jpg");
}catch(Exception e){
Toast.makeText(getBaseContext(), (CharSequence) e, Toast.LENGTH_LONG).show();
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnChoose:
chooseFile();
break;
case R.id.btnEncrypt:
encryptFile();
break;
case R.id.btnDecrypt:
decryptFile();
break;
}
}
}
Но по непонятным причинам при нажатии кнопки Encrypt прога вылетает.