-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVerifies.java
More file actions
45 lines (35 loc) · 1.6 KB
/
Verifies.java
File metadata and controls
45 lines (35 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashFileTest {
public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
boolean result = verifyChecksum("/home/eclipse-jee-indigo-SR2-linux-gtk-x86_64.tar.gz", "177750b65a21a9043105fd0820b85b58cf148ae4");
System.out.println("Does the file's checksum matches the expected one? " + result);
}
/**
* Verifies file's SHA1 checksum
* @param Filepath and name of a file that is to be verified
* @param testChecksum the expected checksum
* @return true if the expeceted SHA1 checksum matches the file's SHA1 checksum; false otherwise.
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public static boolean verifyChecksum(String file, String testChecksum) throws NoSuchAlgorithmException, IOException
{
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[1024];
int read = 0;
while ((read = fis.read(data)) != -1) {
sha1.update(data, 0, read);
};
byte[] hashBytes = sha1.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < hashBytes.length; i++) {
sb.append(Integer.toString((hashBytes[i] & 0xff) + 0x100, 16).substring(1));
}
String fileHash = sb.toString();
return fileHash.equals(testChecksum);
}