有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用AES加密Android/Java的FileNotFoundException

我正在尝试使用AES加密文件,方法是将文件转换为base64,然后应用AES,但是我的SD卡上从来没有任何输出,似乎我抛出了一个FileNotFoundException。我在该行设置了一个断点:

SecretKeySpec secretKey = new SecretKeySpec(Password.getBytes("ASCII"), "AES");

然而,我注意到只有当我选择了一个文件夹,而不是一个文件(无论哪种情况:都没有加密的文件输出)时,它才会被访问

还有——我不确定这行是否正确:boolean encryptedString = MySecurity.encryptFile(chosenFile);

我只需要弄清楚为什么我不能用这种方法加密文件

权限:

<uses-permission 安卓:name="安卓.permission.READ_EXTERNAL_STORAGE" />
<uses-permission 安卓:name="安卓.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission 安卓:name="安卓.permission.WRITE_INTERNAL_STORAGE" />
  <uses-permission 安卓:name="安卓.permission.READ_INTERNAL_STORAGE" />

LogCat:

01-16 19:54:50.551: I/System.out(18108): Sending WAIT chunk
01-16 19:54:50.556: I/dalvikvm(18108): Debugger is active
01-16 19:54:50.751: I/System.out(18108): Debugger has connected
01-16 19:54:50.751: I/System.out(18108): waiting for debugger to settle...
01-16 19:54:50.951: I/System.out(18108): waiting for debugger to settle...
01-16 19:54:51.151: I/System.out(18108): waiting for debugger to settle...
01-16 19:54:51.351: I/System.out(18108): waiting for debugger to settle...
01-16 19:54:51.551: I/System.out(18108): waiting for debugger to settle...
01-16 19:54:51.751: I/System.out(18108): waiting for debugger to settle...
01-16 19:54:51.956: I/System.out(18108): waiting for debugger to settle...
01-16 19:54:52.156: I/System.out(18108): debugger has settled (1454)
01-16 19:54:52.416: E/SensorManager(18108): thread start
01-16 19:54:52.426: D/SensorManager(18108): registerListener :: handle = 0  name= K3DH Acceleration Sensor delay= 200000 Trklfufi 9 budiwrd5mrfo5WirfulblrwuFmfulTrklfufi$KfukwiFmfulTrklfufiRvht@,*b-c)b8
01-16 19:54:52.476: D/SensorManager(18108): unregisterListener:: Trklfufi 9 budiwrd5mrfo5WirfulblrwuFmfulTrklfufi$KfukwiFmfulTrklfufiRvht@,*b-c)b8
01-16 19:54:52.476: D/Sensors(18108): Remain listener = Sending .. normal delay 200ms
01-16 19:54:52.476: I/Sensors(18108): sendDelay --- 200000000
01-16 19:54:52.476: D/SensorManager(18108): JNI - sendDelay
01-16 19:54:52.476: I/SensorManager(18108): Set normal delay = true
01-16 19:54:52.516: D/SensorManager(18108): registerListener :: handle = 0  name= K3DH Acceleration Sensor delay= 200000 Trklfufi 9 budiwrd5mrfo5WirfulblrwuFmfulTrklfufi$KfukwiFmfulTrklfufiRvht@,*b-c)b8
01-16 19:54:52.546: D/libEGL(18108): loaded /system/lib/egl/libEGL_mali.so
01-16 19:54:52.546: D/libEGL(18108): loaded /system/lib/egl/libGLESv1_CM_mali.so
01-16 19:54:52.551: D/libEGL(18108): loaded /system/lib/egl/libGLESv2_mali.so
01-16 19:54:52.556: D/(18108): Device driver API match
01-16 19:54:52.556: D/(18108): Device driver API version: 10
01-16 19:54:52.556: D/(18108): User space API version: 10 
01-16 19:54:52.556: D/(18108): mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Thu Oct 25 08:43:05 KST 2012 
01-16 19:54:52.576: D/OpenGLRenderer(18108): Enabling debug mode 0
01-16 19:54:55.901: D/SensorManager(18108): unregisterListener:: Trklfufi 9 budiwrd5mrfo5WirfulblrwuFmfulTrklfufi$KfukwiFmfulTrklfufiRvht@,*b-c)b8
01-16 19:54:55.901: D/Sensors(18108): Remain listener = Sending .. normal delay 200ms
01-16 19:54:55.901: I/Sensors(18108): sendDelay --- 200000000
01-16 19:54:55.901: D/SensorManager(18108): JNI - sendDelay
01-16 19:54:55.901: I/SensorManager(18108): Set normal delay = true
01-16 19:54:56.806: D/SensorManager(18108): registerListener :: handle = 0  name= K3DH Acceleration Sensor delay= 200000 Trklfufi 9 budiwrd5mrfo5WirfulblrwuFmfulTrklfufi$KfukwiFmfulTrklfufiRvht@,*b-c)b8
01-16 19:54:58.341: D/dalvikvm(18108): GC_CONCURRENT freed 121K, 13% free 9638K/11015K, paused 12ms+12ms, total 37ms
01-16 19:54:58.361: D/DIRECTORY(18108): LOST.DIR
01-16 19:54:58.361: D/DIRECTORY(18108): external_sd
01-16 19:54:58.361: D/DIRECTORY(18108): usbStorage
01-16 19:54:58.361: D/DIRECTORY(18108): DCIM
01-16 19:54:58.361: D/DIRECTORY(18108): Android
01-16 19:54:58.361: D/DIRECTORY(18108): ShareViaWifi
01-16 19:54:58.361: D/DIRECTORY(18108): Attachments
01-16 19:54:58.361: D/DIRECTORY(18108): LazyList
01-16 19:54:58.361: D/FILE(18108): syncast.3gp
01-16 19:54:58.366: D/DIRECTORY(18108): download
01-16 19:54:58.366: D/FILE(18108): test.mp3
01-16 19:54:58.366: D/DIRECTORY(18108): ScreenCapture
01-16 19:54:58.366: D/FILE(18108): mp3.sdp
01-16 19:54:58.366: D/DIRECTORY(18108): Videomaker
01-16 19:54:58.366: D/DIRECTORY(18108): bluetooth
01-16 19:54:58.366: D/DIRECTORY(18108): Notifications
01-16 19:54:58.366: D/DIRECTORY(18108): Music
01-16 19:54:58.366: D/DIRECTORY(18108): Podcasts
01-16 19:54:58.371: D/DIRECTORY(18108): Ringtones
01-16 19:54:58.371: D/DIRECTORY(18108): Alarms
01-16 19:54:58.371: D/DIRECTORY(18108): Pictures
01-16 19:54:58.371: D/DIRECTORY(18108): Movies
01-16 19:54:58.371: D/DIRECTORY(18108): EarthRot
01-16 19:54:58.371: D/DIRECTORY(18108): projectM
01-16 19:54:58.371: D/DIRECTORY(18108): jibbigo
01-16 19:54:58.371: D/FILE(18108): darkknight.mp4
01-16 19:54:58.371: D/FILE(18108): idg-wallpaper-signed.apk
01-16 19:54:58.371: D/FILE(18108): DiskCacheIndex-1154456374.tmp
01-16 19:54:58.376: D/DIRECTORY(18108): Photo Editor
01-16 19:54:58.376: D/DIRECTORY(18108): SC2
01-16 19:54:58.376: D/DIRECTORY(18108): data
01-16 19:54:58.376: D/DIRECTORY(18108): Galaxier
01-16 19:54:58.376: D/DIRECTORY(18108): samsungapps
01-16 19:54:58.376: D/FILE(18108): tmp.jpg
01-16 19:54:58.376: D/FILE(18108): syncasterstream9760825383gp
01-16 19:54:58.376: D/FILE(18108): syncasterstream9075633613gp
01-16 19:54:58.376: D/FILE(18108): syncasterstream14259657453gp
01-16 19:54:58.381: D/FILE(18108): syncasterstream5539679723gp
01-16 19:54:58.381: D/FILE(18108): syncasterstream20634352173gp
01-16 19:54:58.381: D/FILE(18108): syncasterstream-15179503023gp
01-16 19:54:58.381: D/FILE(18108): syncasterstream3522853173gp
01-16 19:54:58.381: D/FILE(18108): syncasterstream-18907628143gp
01-16 19:54:58.381: D/FILE(18108): syncasterstream-14453506253gp
01-16 19:54:58.381: D/FILE(18108): Img1361203892838.jpg
01-16 19:54:58.381: D/FILE(18108): DiskCacheIndex739049279.tmp
01-16 19:54:58.381: D/FILE(18108): DiskCacheIndex-2062736231.tmp
01-16 19:54:58.386: D/FILE(18108): DiskCacheIndex-1094825277.tmp
01-16 19:54:58.386: D/FILE(18108): DiskCacheIndex887219410.tmp
01-16 19:54:58.386: D/FILE(18108): DiskCacheIndex1525162948.tmp
01-16 19:54:58.386: D/DIRECTORY(18108): Playlists
01-16 19:54:58.386: D/FILE(18108): darkknight.mp4.SEMP
01-16 19:54:58.386: D/DIRECTORY(18108): log
01-16 19:54:58.386: D/DIRECTORY(18108): media
01-16 19:54:58.386: D/DIRECTORY(18108): urbanspoon
01-16 19:54:58.386: D/DIRECTORY(18108): Nearby
01-16 19:54:58.386: D/DIRECTORY(18108): Documents
01-16 19:54:58.436: D/AbsListView(18108): Get MotionRecognitionManager
01-16 19:54:58.531: W/ResourceType(18108): Failure getting entry for 0x010802c0 (t=7 e=704) in package 0 (error -75)
01-16 19:54:58.546: D/F_PATH(18108): /storage/sdcard0
01-16 19:54:58.611: D/SensorManager(18108): unregisterListener:: Trklfufi 9 budiwrd5mrfo5WirfulblrwuFmfulTrklfufi$KfukwiFmfulTrklfufiRvht@,*b-c)b8
01-16 19:54:58.611: D/Sensors(18108): Remain listener = Sending .. normal delay 200ms
01-16 19:54:58.611: I/Sensors(18108): sendDelay --- 200000000
01-16 19:54:58.611: D/SensorManager(18108): JNI - sendDelay
01-16 19:54:58.611: I/SensorManager(18108): Set normal delay = true
01-16 19:55:00.811: D/DIRECTORY(18108): Camera
01-16 19:55:00.811: D/DIRECTORY(18108): Facebook
01-16 19:55:00.851: D/AbsListView(18108): Get MotionRecognitionManager
01-16 19:55:00.971: W/ResourceType(18108): Failure getting entry for 0x010802c0 (t=7 e=704) in package 0 (error -75)
01-16 19:55:00.986: D/F_PATH(18108): /storage/sdcard0/DCIM
01-16 19:55:07.706: D/F_PATH(18108): DCIM
01-16 19:55:36.996: W/System.err(18108): java.io.FileNotFoundException: /DCIM: open failed: ENOENT (No such file or directory)
01-16 19:55:37.006: W/System.err(18108):    at libcore.io.IoBridge.open(IoBridge.java:416)
01-16 19:55:37.011: W/System.err(18108):    at java.io.FileInputStream.<init>(FileInputStream.java:78)
01-16 19:55:37.016: W/System.err(18108):    at java.io.FileInputStream.<init>(FileInputStream.java:105)
01-16 19:55:37.021: W/System.err(18108):    at com.encrpytion.idg.MySecurity.encryptFile(MySecurity.java:83)
01-16 19:55:37.026: W/System.err(18108):    at com.encrpytion.idg.FileExplore$3.onClick(FileExplore.java:175)
01-16 19:55:37.031: W/System.err(18108):    at com.安卓.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:934)
01-16 19:55:37.036: W/System.err(18108):    at 安卓.widget.AdapterView.performItemClick(AdapterView.java:301)
01-16 19:55:37.041: W/System.err(18108):    at 安卓.widget.AbsListView.performItemClick(AbsListView.java:1280)
01-16 19:55:37.046: W/System.err(18108):    at 安卓.widget.AbsListView$PerformClick.run(AbsListView.java:3071)
01-16 19:55:37.051: W/System.err(18108):    at 安卓.widget.AbsListView$1.run(AbsListView.java:3973)
01-16 19:55:37.056: W/System.err(18108):    at 安卓.os.Handler.handleCallback(Handler.java:615)
01-16 19:55:37.056: W/System.err(18108):    at 安卓.os.Handler.dispatchMessage(Handler.java:92)
01-16 19:55:37.056: W/System.err(18108):    at 安卓.os.Looper.loop(Looper.java:137)
01-16 19:55:37.061: W/System.err(18108):    at 安卓.app.ActivityThread.main(ActivityThread.java:4921)
01-16 19:55:37.061: W/System.err(18108):    at java.lang.reflect.Method.invokeNative(Native Method)
01-16 19:55:37.061: W/System.err(18108):    at java.lang.reflect.Method.invoke(Method.java:511)
01-16 19:55:37.061: W/System.err(18108):    at com.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
01-16 19:55:37.066: W/System.err(18108):    at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:794)
01-16 19:55:37.066: W/System.err(18108):    at dalvik.system.NativeStart.main(Native Method)
01-16 19:55:37.066: W/System.err(18108): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
01-16 19:55:37.071: W/System.err(18108):    at libcore.io.Posix.open(Native Method)
01-16 19:55:37.071: W/System.err(18108):    at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
01-16 19:55:37.076: W/System.err(18108):    at libcore.io.IoBridge.open(IoBridge.java:400)
01-16 19:55:37.076: W/System.err(18108):    ... 18 more

我的安全。爪哇

public class MySecurity
{
    private static Cipher ecipher;
    private Cipher dcipher;
    private static String Password = "$emP0sTM@rkT0P$3cu!ty12345678912";
    private static String InitialVector = "OFRna73m*aze01xY";

    // ENCRYPTION ******************************************************
    public String encryptText(String plainText)
    {
        String errorText = "Error";

        try {
            SecretKeySpec secretKey = new SecretKeySpec(Password.getBytes("ASCII"), "AES");
            ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            ecipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(InitialVector.getBytes("ASCII")));
             // Encode the string into bytes using utf-8
            byte[] utf8 = plainText.getBytes("UTF8");

            // Encrypt
            byte[] enc = ecipher.doFinal(utf8);
             // Encode bytes to base64 to get a string
            return Base64.encodeToString(enc, Base64.DEFAULT);  

        } catch (InvalidKeyException e) {
            e.printStackTrace();
            errorText = e.getMessage();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
            errorText = e.getMessage();
        }catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            errorText = e.getMessage();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            errorText = e.getMessage();
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            errorText = e.getMessage();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
            errorText = e.getMessage();
        } catch (BadPaddingException e) {
            e.printStackTrace();
            errorText = e.getMessage();
        }


        return errorText;
    }

    public static boolean encryptFile(String filePath)
    {

        try {
            SecretKeySpec secretKey = new SecretKeySpec(Password.getBytes("ASCII"), "AES");
            ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            ecipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(InitialVector.getBytes("ASCII")));

            //create input stream to read in file that needs to be encrypted
            FileInputStream inputStream = new FileInputStream(filePath);
            //create output stream to write out the encrypted results, append .vault to out encrypted files
            FileOutputStream outputStream = new FileOutputStream(filePath + ".vault");
            //wrap the output stream
            CipherOutputStream encryptedOutputStream = new CipherOutputStream(outputStream, ecipher);

            // Encrypt the file
            int bytes;
            byte[] data = new byte[8];
            while((bytes = inputStream.read(data)) != -1)
            {
                encryptedOutputStream.write(data, 0, bytes);
            }

            // Flush and close streams.
            encryptedOutputStream.flush();
            encryptedOutputStream.close();
            inputStream.close();
            outputStream.flush();
            outputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            return false;
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
            return false;
        }catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return false;
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return false;
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } 
        return true;
    }

    public String decryptText(String cryptoText)
    {
        String errorText = "Error";

        try {
            SecretKeySpec secretKey = new SecretKeySpec(Password.getBytes("ASCII"), "AES");
            dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            dcipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(InitialVector.getBytes("ASCII")));

        // Decode base64 to get bytes
            byte[] dec = Base64.decode(cryptoText, Base64.DEFAULT);        
         // Decrypt
            byte[] utf8 = dcipher.doFinal(dec);        
         // Decode using utf-8
            return new String(utf8, "UTF8");    

        } catch (InvalidKeyException e) {
            e.printStackTrace();
            errorText = e.getMessage();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
            errorText = e.getMessage();
        }catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            errorText = e.getMessage();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            errorText = e.getMessage();
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            errorText = e.getMessage();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
            errorText = e.getMessage();
        } catch (BadPaddingException e) {
            e.printStackTrace();
            errorText = e.getMessage();
        }  
        return errorText;
    } 

    public boolean decryptFile(String filePath)
    {

        try {
            SecretKeySpec secretKey = new SecretKeySpec(Password.getBytes("ASCII"), "AES");
            dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            dcipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(InitialVector.getBytes("ASCII")));

            //create input stream to read in file that needs to be decrypted
            FileInputStream inputStream = new FileInputStream(filePath);
            //create output stream to write out the decrypted results, remove .vault to from file
            FileOutputStream outputStream = new FileOutputStream(filePath.replace(".vault", filePath));
            //wrap the output stream
            CipherInputStream encryptedInputStream = new CipherInputStream(inputStream, dcipher);

            //Decrypt the file
            int bytes;
            byte[] data = new byte[8];
            while((bytes = encryptedInputStream.read(data)) != -1)
            {
                outputStream.write(data, 0, bytes);
            }

            // Flush and close streams.
            outputStream.flush();
            outputStream.close();
            inputStream.close();
            encryptedInputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            return false;
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
            return false;
        }catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return false;
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return false;
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } 
        return true;
    }
}

文件探索。爪哇:

public class FileExplore extends Activity {

// Stores names of traversed directories
ArrayList<String> str = new ArrayList<String>();

// Check if the first level of the directory structure is the one showing
private Boolean firstLvl = true;

private static final String TAG = "F_PATH";

private Item[] fileList;
private File path = new File(Environment.getExternalStorageDirectory() + "");
private String chosenFile;
private static final int DIALOG_LOAD_FILE = 1000;

ListAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    loadFileList();
    showDialog(DIALOG_LOAD_FILE);
    Log.d(TAG, path.getAbsolutePath());




}

private void loadFileList() {
    try {
        path.mkdirs();
    } catch (SecurityException e) {
        Log.e(TAG, "unable to write on the sd card ");
    }

    // Checks whether path exists
    if (path.exists()) {
        FilenameFilter filter = new FilenameFilter() {
            @Override
            public boolean accept(File dir, String filename) {
                File sel = new File(dir, filename);
                // Filters based on whether the file is hidden or not
                return (sel.isFile() || sel.isDirectory())
                        && !sel.isHidden();

            }
        };

        String[] fList = path.list(filter);
        fileList = new Item[fList.length];
        for (int i = 0; i < fList.length; i++) {
            fileList[i] = new Item(fList[i], R.drawable.file_icon);

            // Convert into file path
            File sel = new File(path, fList[i]);

            // Set drawables
            if (sel.isDirectory()) {
                fileList[i].icon = R.drawable.directory_icon;
                Log.d("DIRECTORY", fileList[i].file);
            } else {
                Log.d("FILE", fileList[i].file);
            }
        }

        if (!firstLvl) {
            Item temp[] = new Item[fileList.length + 1];
            for (int i = 0; i < fileList.length; i++) {
                temp[i + 1] = fileList[i];
            }
            temp[0] = new Item("Up", R.drawable.directory_up);
            fileList = temp;
        }
    } else {
        Log.e(TAG, "path does not exist");
    }

    adapter = new ArrayAdapter<Item>(this,
            安卓.R.layout.select_dialog_item, 安卓.R.id.text1,
            fileList) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // creates view
            View view = super.getView(position, convertView, parent);
            TextView textView = (TextView) view
                    .findViewById(安卓.R.id.text1);

            // put the image on the text view
            textView.setCompoundDrawablesWithIntrinsicBounds(
                    fileList[position].icon, 0, 0, 0);

            // add margin between image and text (support various screen
            // densities)
            int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
            textView.setCompoundDrawablePadding(dp5);

            return view;
        }
    };

}

private class Item {
    public String file;
    public int icon;

    public Item(String file, Integer icon) {
        this.file = file;
        this.icon = icon;
    }

    @Override
    public String toString() {
        return file;
    }
}

@Override
protected Dialog onCreateDialog(int id)
{
    Dialog dialog = null;
    AlertDialog.Builder builder = new Builder(this);

    if (fileList == null) {
        Log.e(TAG, "No files loaded");
        dialog = builder.create();
        return dialog;
    }

    switch (id) {
    case DIALOG_LOAD_FILE:
        builder.setTitle("Choose your file");
        builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                chosenFile = fileList[which].file;
                File sel = new File(path + "/" + chosenFile);
                if (sel.isDirectory()) {
                    firstLvl = false;

                    // Adds chosen directory to list
                    str.add(chosenFile);
                    fileList = null;
                    path = new File(sel + "");

                    loadFileList();

                    removeDialog(DIALOG_LOAD_FILE);
                    showDialog(DIALOG_LOAD_FILE);
                    Log.d(TAG, path.getAbsolutePath());
                    Log.d(TAG,(chosenFile!=null)?chosenFile:"chosenFile is null");
                    boolean encryptedString = mySecurity.encryptFile(chosenFile);

                }

                // Checks if 'up' was clicked
                else if (chosenFile.equalsIgnoreCase("up") && !sel.exists()) {

                    // present directory removed from list
                    String s = str.remove(str.size() - 1);

                    // path modified to exclude present directory
                    path = new File(path.toString().substring(0,
                            path.toString().lastIndexOf(s)));
                    fileList = null;

                    // if there are no more directories in the list, then
                    // its the first level
                    if (str.isEmpty()) {
                        firstLvl = true;
                    }
                    loadFileList();

                    removeDialog(DIALOG_LOAD_FILE);
                    showDialog(DIALOG_LOAD_FILE);
                    Log.d(TAG, path.getAbsolutePath());
                    Log.d(TAG,(chosenFile!=null)?chosenFile:"chosenFile is null");
                    boolean encryptedString = mySecurity.encryptFile(chosenFile);
                }
                // File picked
                else {
                    // Perform action with file picked
                }

            }
        });
        break;
    }
    dialog = builder.show();
    return dialog;
}

}

下载链接:

http://www.sendspace.com/file/den6ue


共 (1) 个答案

  1. # 1 楼答案

    FileInputStream()构造函数的文档中

    FileInputStream(File file)

    Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.

    所以,如果你想创建一个FileInputStream的实例,那么你必须把一个File对象传递给FileInputStream()。但在下一行中,您传递的是文件路径,而不是文件对象

    FileInputStream inputStream = new FileInputStream(filePath);
    

    另一个问题是,你的filePath不正确。它只包含以下路径

    /DICM
    

    这不是一个正确的路径,它不是一个实际的文件路径,而是一个文件夹路径。正确的路径应该如下所示

    /mnt/sdcard/DICM
    

    现在,如果你想解决你的问题,那么你必须遵循这些

    1. 使用实际文件名和路径创建File对象
    2. 通过将File对象传递给FileInputStream()构造函数来创建FileInputStream对象

    现在,比方说,你的文件名是Text.txt,然后你更正的代码片段将是

    public boolean decryptFile(String filePath)
        {
    
            try {
                SecretKeySpec secretKey = new SecretKeySpec(Password.getBytes("ASCII"), "AES");
                dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                dcipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(InitialVector.getBytes("ASCII")));
    
                //Creating File object to into FileInputStream() constructor
                String fileDirectory = Environment.getExternalStorageDirectory().getPath() + filePath;
                String actualFilePath = fileDirectory + "/" + "Text.txt";
                File actualFile = new File(actualFilePath);
    
                //create input stream to read in file that needs to be decrypted
                FileInputStream inputStream = new FileInputStream(actualFile);
    
                //create output stream to write out the decrypted results, remove .vault to from file
                FileOutputStream outputStream = new FileOutputStream(filePath.replace(".vault", filePath));
                //wrap the output stream
                CipherInputStream encryptedInputStream = new CipherInputStream(inputStream, dcipher);
    
                //Decrypt the file
                int bytes;
                byte[] data = new byte[8];
                while((bytes = encryptedInputStream.read(data)) != -1)
                {
                    outputStream.write(data, 0, bytes);
                }
    
                // Flush and close streams.
                outputStream.flush();
                outputStream.close();
                inputStream.close();
                encryptedInputStream.close();
    
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return false;
            } catch (InvalidKeyException e) {
                e.printStackTrace();
                return false;
            } catch (InvalidAlgorithmParameterException e) {
                e.printStackTrace();
                return false;
            }catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
                return false;
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
                return false;
            }catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            } 
            return true;
        }