Reputation: 133
I'm developing a video player app. It downloads some video onto an sd card using Storage Access Framework. I downloaded the video successfully but I want it to be encrypted after downloading so I'm using the code below:-
import java.io.RandomAccessFile;
public class VideoCrypt {
public static final int REVERSE_BYTE_COUNT = 1024;
public static boolean decrypt(String path) {
try {
if (path == null) return false;
File source = new File(path);
int byteToReverse = source.length() < REVERSE_BYTE_COUNT ? ((int) source.length()) : REVERSE_BYTE_COUNT;
RandomAccessFile f = new RandomAccessFile(source, "rw");
f.seek(0);
byte b[] = new byte[byteToReverse];
f.read(b);
f.seek(0);
reverseBytes(b);
f.write(b);
f.seek(0);
b = new byte[byteToReverse];
f.read(b);
f.close();
return true;
} catch (Exception e) {
return false;
}
}
public static boolean encrypt(String path) {
try {
if (path == null) return false;
File source = new File(path);
RandomAccessFile f = new RandomAccessFile(source, "rw");
f.seek(0);
int byteToReverse = source.length() < REVERSE_BYTE_COUNT ? ((int) source.length()) : REVERSE_BYTE_COUNT;
byte b[] = new byte[byteToReverse];
f.read(b);
f.seek(0);
reverseBytes(b);
f.write(b);
f.seek(0);
b = new byte[byteToReverse];
f.read(b);
f.close();
return true;
} catch (Exception e) {
return false;
}
}
private static void reverseBytes(byte[] array) {
if (array == null) return;
int i = 0;
int j = array.length - 1;
byte tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}
Code is working fine with internal storage but in the case of theSD Card I'm getting this permission error:
ava.io.FileNotFoundException: /storage/0C69-1809/Android/tersjwafuh/ALongWa Down.@7&259: open failed: EACCES (Permission denied)
Upvotes: 0
Views: 70
Reputation: 9292
So your encryption is just reversing all bytes of the file?
For that you do not need a RandomAccessFile especially because you load all bytes (the complete file) in a bytearray.
You can as well use the saf uri to load all bytes in a byte array. Then reverse them and then write the byte array back to saf uri.
What you did not tell us is that you converted a nice saf uri to a file path. Dont do such nasty and dirty things. Not needed. Use the uri!
A removable micro sd card is read only with classic file means since Android 4 KitKat.
Only with SAF you have write access. (Well not completely true.. on an Android 11 device you have classic file write access if you obtain 'all files access'.)
Upvotes: 1