Skip to content

Instantly share code, notes, and snippets.

@decnorton
Last active August 22, 2016 08:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save decnorton/5835420 to your computer and use it in GitHub Desktop.
Save decnorton/5835420 to your computer and use it in GitHub Desktop.
Android. Check the SHA1 of a file against a string
public static boolean testSHA1(String sha1, File file) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "Exception while getting Digest", e);
return false;
}
InputStream is;
try {
is = new FileInputStream(file);
} catch (FileNotFoundException e) {
Log.e(TAG, "Exception while getting FileInputStream", e);
return false;
}
byte[] buffer = new byte[8192];
int read;
try {
while ((read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
byte[] md5sum = digest.digest();
BigInteger bigInt = new BigInteger(1, md5sum);
String output = bigInt.toString(16);
// Fill to 40 chars
output = String.format("%40s", output).replace(' ', '0');
Log.i(TAG, "Test: " + sha1);
Log.i(TAG, "Generated: " + output);
return (sha1.equals(output));
} catch (IOException e) {
throw new RuntimeException("Unable to process file for MD5", e);
} finally {
try {
is.close();
} catch (IOException e) {
Log.e(TAG, "Exception on closing MD5 input stream", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment