Как сохранить файл большого размера на локальном устройстве Android в зашифрованном формате - PullRequest
0 голосов
/ 21 декабря 2018

Я работаю над Android-приложением, которое работает в автономном режиме.Для этого мы храним видео на устройстве Android, что является лучшим способом сохранить данные (видеофайл) на устройстве, и оно будет открываться и запускаться только в моем приложении.

Я пытался зашифровать видеофайл и сохранитьв устройстве, но сталкивается со следующей проблемой: -

размер видео превышает 300 МБ, и для шифрования и дешифрования требуется слишком много времени (примерно время составляет более 1 - 2 минут)
, но мне нужно минимизироватьна этот раз до 2-3 секунд.Каков наилучший способ сделать это

Я использую следующие два способа шифрования и дешифрования

1. whole file at one time  

 public static byte[] encode(SecretKey yourKey, byte[] fileData)
        throws Exception {
    byte[] data = yourKey.getEncoded();
    SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length, EncoDecode.KEY_SPEC_ALGORITHM);
    Cipher cipher = Cipher.getInstance(EncoDecode.CIPHER_ALGORITHM);//, EncoDecode.PROVIDER
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
    return cipher.doFinal(fileData);


}

public static byte[] decode(SecretKey yourKey, byte[] fileData)
        throws Exception {
    byte[] decrypted;
    Cipher cipher = Cipher.getInstance(EncoDecode.CIPHER_ALGORITHM);//, EncoDecode.PROVIDER
    Log.d("", "decode() returned: " + cipher.getBlockSize());
    Utility.checkmemory(mContext);
    cipher.init(Cipher.DECRYPT_MODE, yourKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));
    Utility.checkmemory(mContext);
    decrypted = cipher.doFinal(fileData);
    return decrypted;
}
#
 2. byte -to byto encrytion or decrytion
  /**
 * Encrypt and save to disk
 *
 * @return
 */
private boolean encrypt() {
    updateUI("Encrypting file...");
    pDialog.setMessage("Encrypt start..");
    pDialog.show();
    try {

        Log.e(TAG, "encrypt: starting.... " );
        Encryptor encryptor = new Encryptor(EncryptDecryptUtils.getInstance(this).getSecretKey(), CIPHER_ALGORITHM, 16);

        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(path);
            os = encryptor.wrapOutputStream(new FileOutputStream(pathEnc));
            byte[] buffer = new byte[8192];// change in low memory device 4096
            int nRead;
            while((nRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, nRead);
                Log.e(TAG, "encrypt in process.... " );
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pDialog.setMessage("Encrypt in process...");
                    }
                });
            }
            os.flush();
        } finally {
            pDialog.setMessage("Encrypt complete...");
            pDialog.dismiss();
            Log.e(TAG, "encrypt complete.... " );
            if(is != null) {
                is.close();
            }
            if(os != null) {
                os.close();
            }
        }

        return true;
    } catch (Exception e) {
        e.printStackTrace();

        updateUI("File Encryption failed.\nException: " + e.getMessage());
    }
    return false;
}

/**
 * Decrypt and return the decoded bytes
 *
 * @return
 */
private byte[] decrypt() {
    updateUI("Decrypting file...");
    pDialog.setMessage("Decrypt start..");
    pDialog.show();
    try {
  Log.e(TAG, "decrypt start !!! " );
        Encryptor encryptor = new Encryptor(EncryptDecryptUtils.getInstance(this).getSecretKey(), CIPHER_ALGORITHM, 16);
        InputStream is = null;
        OutputStream os = null;

        try {
            is = encryptor.wrapInputStream(new FileInputStream(pathEnc));
            os = new FileOutputStream(pathDec);
            byte[] buffer = new byte[8192];
            int nRead;
            while((nRead = is.read(buffer)) != -1) {
                Log.e(TAG, "decrypt in porocess.... " );
                os.write(buffer, 0, nRead);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pDialog.setMessage("Decrypt in process...");
                    }
                });
            }
            os.flush();
        } finally {
            pDialog.setMessage("Decrypt complete...");
            pDialog.dismiss();
            Log.e(TAG, "decrypt complete !!! " );
            if(is != null) {
                is.close();
            }
            if(os != null) {
                os.close();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        updateUI("File Decryption failed.\nException: " + e.getMessage());
    }
    return null;
}
...