How to encrypt and decrypt images in android?

后端 未结 3 1012
一生所求
一生所求 2021-02-11 03:33

I am new to android and now i\'m building an android app to encrypt and hide the data,as part of my mini project.Could you please tell me the code to encrypt and decrypt tha ima

3条回答
  •  眼角桃花
    2021-02-11 03:40

    Here is static methods for encryption and decryption with AES hope this will help.

    public static void encrypt (final byte[] key,
            final String filename,
            final String newFilename,
            final Context context,
            final EncryptionActionListener listener) {
    
        final Handler uiHandler = new Handler();
        final ProgressDialog progressDialog = new ProgressDialog(context);
        progressDialog.setMessage(context.getString(R.string.encrypt_progress_message));
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(100);
        progressDialog.setProgress(0);
        progressDialog.show();
    
        Thread task = new Thread("Encrypt thread") {
            public void run() {
                boolean deleteSuccess = true;
                boolean outOfMem = false;
                boolean exception = false;
    
                try {
                    File file = new File(filename);
                    int length = (int)file.length();
    
                    byte fileBytes[] = new byte[1024*100];
    
                    if (!createLeadingFolders(newFilename)) {
                        throw new IOException("Could not create folders in path " + newFilename);
                    }
    
                    InputStream is = new FileInputStream(filename);
                    OutputStream os = new FileOutputStream(newFilename);    
                    AESOutputStream aos = new AESOutputStream(os, key, length);
    
                    int totalRead = 0;
                    int partialRead = 0;
                    while (true) {
                        partialRead = is.read(fileBytes);
                        if (partialRead == -1) {
                            break;
                        } else {
                            totalRead += partialRead;
                            aos.write(fileBytes, 0, partialRead);
                            final int percentage = (totalRead * 100) / length;
                            uiHandler.post(new Runnable() {
                                public void run() {
                                    progressDialog.setProgress(percentage);
                                }
                            });
                        }
                    }
    
                    is.close();
                    aos.close();
                    os.close();
    
                    deleteSuccess = file.delete();
    
                    AESImageAdapter.delete(context, filename);
    
                    if (listener != null)
                        listener.onActionComplete();
    
                    Intent i = new Intent(ACTION_ENCRYPTED_FILES_CHANGED);
                    context.sendBroadcast(i);
    
                } catch (OutOfMemoryError e) {
                    e.printStackTrace();
                    outOfMem = true;
                } catch (Exception e) {
                    e.printStackTrace();
                    exception = true;
                } finally {
                    progressDialog.dismiss();
                    if (exception) {
                        errorDialog(uiHandler, context.getString(R.string.encrypt_error), context);
                    } else if (outOfMem) {
                        errorDialog(uiHandler, context.getString(R.string.memory_error), context);
                    } else if (!deleteSuccess) {
                        errorDialog(uiHandler, context.getString(R.string.encrypt_delete_error), context);
                    }
                }
            }
        };
    
        task.start();
    }
    
    
    
    
    /**
     * Asynchronously decrypt the chosen file.
     * @param keyString Key to decrypt with
     * @param filename Name of file to decrypt
     * @param newFilename Name to save newly decrypted file
     * @param dialog An optional progress dialog to update with progress
     * @param adapter An optional adapter to notify when the encryption is finished
     * @param context Must supply context
     * @return
     */
    public static void decrypt (final byte[] key,
            final String filename,
            final String newFilename,
            final Context context,
            final EncryptionActionListener listener) {
    
        final Handler uiHandler = new Handler();
        final ProgressDialog progressDialog = new ProgressDialog(context);
        progressDialog.setMessage(context.getString(R.string.decrypt_progress_message));
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(100);
        progressDialog.setProgress(0);
        progressDialog.show();
    
        Thread task = new Thread("Decrypt thread") {
            public void run() {
                boolean deleteSuccess = true;
                boolean outOfMem = false;
                boolean exception = false;
    
                try {
                    File file = new File(filename);
                    int length = (int)file.length();
    
                    byte fileBytes[] = new byte[1024*100];
    
                    if (!createLeadingFolders(newFilename)) {
                        throw new IOException("Could not create folders in path " + newFilename);
                    }
    
                    InputStream is = new FileInputStream(filename);
                    OutputStream os = new FileOutputStream(newFilename);    
                    AESInputStream ais = new AESInputStream(is, key);
    
                    int totalRead = 0;
                    int partialRead = 0;
                    while (true) {
                        partialRead = ais.read(fileBytes);
                        if (partialRead == -1) {
                            break;
                        } else {
                            totalRead += partialRead;
                            os.write(fileBytes, 0, partialRead);
                            final int percentage = (totalRead * 100) / length;
                            uiHandler.post(new Runnable() {
                                public void run() {
                                    progressDialog.setProgress(percentage);
                                }
                            });
                        }
                    }
    
                    ais.close();
                    is.close();
                    os.close();
    
                    deleteSuccess = file.delete();
    
                    // Run the media scanner to discover the decrypted file exists
                    MediaScannerConnection.scanFile(context,
                            new String[] { newFilename },
                            null,
                            null);
    
                    if (listener != null)
                        listener.onActionComplete();
    
                    Intent i = new Intent(ACTION_ENCRYPTED_FILES_CHANGED);
                    context.sendBroadcast(i);
    
                } catch (OutOfMemoryError e) {
                    e.printStackTrace();
                    outOfMem = true;
                } catch (Exception e) {
                    e.printStackTrace();
                    exception = true;
                } finally {
                    progressDialog.dismiss();
                    if (exception) {
                        errorDialog(uiHandler, context.getString(R.string.decrypt_error), context);
                    } else if (outOfMem) {
                        errorDialog(uiHandler, context.getString(R.string.memory_error), context);
                    } else if (!deleteSuccess) {
                        errorDialog(uiHandler, context.getString(R.string.decrypt_delete_error), context);
                    }
                }
            }
        };
    
        task.start();
    }
    

    for more detailed example of encrypt or decrypt image file with AES you can follow this link https://github.com/charlesconnell/ImageHider/tree/master/src/com/connell/imagehider

提交回复
热议问题