in ioXt/uraniborg/AndroidStudioProject/Hubble/app/src/main/java/com/uraniborg/hubble/Utilities.java [58:109]
public static String computeSHA256DigestOfFile(Context context, String pathToFile) {
final String TAG = "SHA256-File";
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA256");
md.reset();
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "SHA256 isn't implemented on this device.");
return null;
}
File f = new File(pathToFile);
FileInputStream fis;
try {
fis = new FileInputStream(f);
} catch (FileNotFoundException e) {
Log.e(TAG, String.format("File %s is not found on the system!", f.getAbsolutePath()));
return null;
}
DigestInputStream dis = new DigestInputStream(fis, md);
long filesize = f.length();
if (filesize == 0) {
Log.e(TAG, String.format("%s is an empty file", pathToFile));
return null;
}
// decide on buffer size based on device's memory class
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (am == null) {
Log.e(TAG, String.format("Error obtaining ActivityManager"));
return null;
}
int bufferSize = (int) (am.isLowRamDevice() ? 512 : 8 * Kilobyte);
bufferSize = (int) Math.min(filesize, bufferSize);
byte[] buffer = new byte[bufferSize];
try {
while (dis.read(buffer) != -1) {}
} catch (IOException e) {
Log.e(TAG, String.format("Failed to read from %s due to %s", pathToFile, e.getMessage()));
return null;
}
try {
dis.close();
} catch (IOException e) {
Log.w(TAG, String.format("Failed to close DigestInputStream"));
}
return convertBytesToHexString(md.digest());
}